-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
358 lines (281 loc) · 12.7 KB
/
Copy pathapp.py
File metadata and controls
358 lines (281 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import json
import gc
import jwt
from flask import Flask, g, jsonify, request
from flask_cors import CORS
from agents.sample_promtps_generator import SamplePromptsGenerator
import config
from config import JWT_SECRET
from controllers.checklist_controller import ChecklistController
from controllers.checklist_from_document_direct_text import ChecklistFromDocumentDirectText
from controllers.checklist_using_agent_controller import ChecklistUsingAgentController
from controllers.checklist_metadata_controller import ChecklistMetadataController
from controllers.checklist_from_document import ChecklistFromDocument
from controllers.checklist_status_indicators_controller import ChecklistStatusIndicatorsController
from utils.agent_utils import get_agent_by_id
from utils.utils import is_valid_url
from werkzeug.exceptions import RequestEntityTooLarge
# from memory_profiler import profile
app = Flask(__name__)
CORS(app)
# Set the maximum allowed content length to 50MB
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024
@app.before_request
def token_required():
if request.method != 'OPTIONS':
# Exclude some routes from token verification, for example the login route
# if request.path == '/login':
# return None
auth_header = request.headers.get('Authorization')
if not auth_header:
return jsonify({'error': {'message': 'Token is missing!'}}), 400
jwtSecretObject = json.loads(JWT_SECRET)
try:
token = auth_header.split(' ')[1]
payload = jwt.decode(
token, jwtSecretObject['key'], algorithms=['HS256'])
# Store the decoded payload in the 'g' object
g.jwt_session = payload
except jwt.ExpiredSignatureError:
return jsonify({'error': {'message': 'Token has expired!'}}), 401
except jwt.InvalidTokenError:
return jsonify({'error': {'message': 'Invalid token!'}}), 401
@app.route('/generate-checklist', methods=['POST'])
def generate_checklist_api():
# Generate a checklist and it will not be persisted in database
payload = request.get_json()
prompt = payload.get("prompt", None)
# Null validation
if (prompt is None or prompt == ""):
return jsonify({'error': {'message': 'Checklist prompt cannot be null'}}), 400
checklist = ChecklistController()
result = checklist.generate_checklist(
prompt)
response = {
"data": {
"result": result
}
}
return jsonify(response)
@app.route('/generate-checklist-using-agent', methods=['POST'])
def generate_checklist_using_agent_api():
payload = request.get_json()
org_id = payload.get("orgId", None)
project_id = payload.get("projectId", None)
name = payload.get("name", None)
project = payload.get("project", None)
organization = payload.get("organization", None)
agent_manager_id = payload.get("id", None)
role = payload.get("role", None)
# Null validation
if ((org_id is None or org_id == "") or
(project_id is None or project_id == "") or
(name is None or name == "") or
(project is None or project == "") or
(agent_manager_id is None or agent_manager_id == "")):
return jsonify({'error': {'message': 'Missing parameters'}}), 400
try:
checklist = ChecklistUsingAgentController(
org_id, project_id, name, project, organization, agent_manager_id, role)
checklist.generate_checklist()
return jsonify({
"data": {
"message": "Checklist generated successfully",
}
}), 200
except ValueError as error:
print("An error occurred:", error)
return jsonify({'error': {'message': str(error)}}), 500
finally:
gc.collect()
@app.route('/generate-sample-prompts', methods=['POST'])
def generate_sample_prompts_api():
body = request.get_json() or {}
role = body.get("jobRole")
industry = body.get("industry")
if not role or not industry:
return jsonify(error="Missing jobRole or industry"), 400
try:
gen = SamplePromptsGenerator(agent_id="sample-prompts")
prompts = gen.generate(role, industry)
return jsonify({ "prompts": prompts }), 200
except Exception as e:
return jsonify(error=str(e)), 500
@app.route('/generate-checklist-metadata', methods=['POST'])
def generate_checklist_metadata():
payload = request.get_json()
checklist = payload.get("checklist", None)
tasks = payload.get("tasks", None)
if (checklist is None or checklist == ""):
return jsonify({'error': {'message': 'Checklist cannot be null'}}), 400
if (tasks is None or len(tasks) == 0):
return jsonify({'error': {'message': 'Tasks cannot be null'}}), 400
try:
checklist_metadata_generator = ChecklistMetadataController()
result = checklist_metadata_generator.generate_checklist_metadata(
checklist,
tasks)
return jsonify({"data": {
"metadata": result
}})
except ValueError as error:
print("An error occurred:", error)
return jsonify({'error': {'message': str(error)}}), 500
finally:
gc.collect()
@app.route('/generate-checklist-from-document', methods=['POST'])
# @profile
def generate_checklist_from_document():
if 'file' not in request.files:
return jsonify({'error': {'message': 'Missing parameters'}}), 400
file = request.files['file']
# Fetch payload data (form data)
org_id = request.form.get('orgId', default=None)
project_id = request.form.get('projectId', default=None)
prompt = request.form.get('prompt', default=None)
# Validation
if ((org_id is None or org_id == "") or (project_id is None or project_id == "") or (file.filename == '')):
return jsonify({"error": {"message": "Missing parameters"}}), 400
ALLOWED_CONTENT_TYPES = {'application/pdf', 'text/plain', 'text/csv',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'}
if (file.content_type not in ALLOWED_CONTENT_TYPES):
return jsonify({"error": {"message": "File type not allowed. Allowed types are .txt, .pdf, .xlsx, .docx"}}), 400
try:
checklist_from_document = ChecklistFromDocument(org_id, project_id)
result = checklist_from_document.generate_checklist_from_document(
file, file.content_type, file.filename, prompt)
return jsonify({"data": {
"checklistId": result
}})
except ValueError as error:
print("An error occurred:", error)
return jsonify({'error': {'message': str(error)}}), 500
finally:
gc.collect()
# Example Usage
@app.route('/generate-checklist-from-document-text', methods=['POST'])
def generate_checklist_from_document_text():
if 'file' not in request.files:
return jsonify({'error': {'message': 'Missing parameters'}}), 400
file = request.files['file']
org_id = request.form.get('orgId', default=None)
project_id = request.form.get('projectId', default=None)
if not org_id or not project_id or not file.filename:
return jsonify({"error": {"message": "Missing parameters"}}), 400
ALLOWED_CONTENT_TYPES = {
'application/pdf', 'text/plain', 'text/csv',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-excel',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
}
if file.content_type not in ALLOWED_CONTENT_TYPES:
return jsonify({"error": {"message": "File type not allowed. Allowed types are .txt, .pdf, .xlsx, .docx"}}), 400
try:
checklist_from_document_text = ChecklistFromDocumentDirectText(org_id, project_id)
checklist_id = checklist_from_document_text.generate_checklist_from_document(file, file.content_type, file.filename)
return jsonify({"data": {"checklistId": checklist_id}})
except ValueError as error:
return jsonify({'error': {'message': str(error)}}), 500
finally:
gc.collect()
@app.route('/generate-checklist-from-url', methods=['POST'])
def generate_checklist_from_url():
payload = request.get_json()
org_id = payload.get("orgId", None)
project_id = payload.get("projectId", None)
url = payload.get("url", None)
prompt = payload.get("prompt", None)
if ((org_id is None or org_id == "") or (project_id is None or project_id == "") or (url is None or url == "")):
return jsonify({'error': {'message': 'Missing parameters'}}), 400
if (is_valid_url(url) == False):
return jsonify({'error': {'message': 'Invalid URL'}}), 400
try:
checklist_from_document = ChecklistFromDocument(org_id, project_id)
result = checklist_from_document.generate_checklist_from_url(url, prompt)
return jsonify({"data": {
"checklistId": result
}})
except ValueError as error:
print("An error occurred:", error)
return jsonify({'error': {'message': str(error)}}), 500
finally:
gc.collect()
@app.route('/generate-checklist-from-text', methods=['POST'])
def generate_checklist_from_text():
payload = request.get_json()
org_id = payload.get("orgId", None)
project_id = payload.get("projectId", None)
text = payload.get("text", None)
if ((org_id is None or org_id == "") or (project_id is None or project_id == "") or (text is None or text == "")):
return jsonify({'error': {'message': 'Missing parameters'}}), 400
words = text.split()
if (len(words) < 100):
return jsonify({'error': {'message': 'Text should contain minimum of 100 words'}}), 400
elif len(words) > 5000:
return jsonify({'error': {'message': 'Text should contain maximum of 5000 words'}}), 400
try:
checklist_from_document = ChecklistFromDocument(org_id, project_id)
result = checklist_from_document.generate_checklist_from_text(
text, " ".join(words[0:10]))
return jsonify({"data": {
"checklistId": result
}})
except ValueError as error:
print("An error occurred:", error)
return jsonify({'error': {'message': str(error)}}), 500
finally:
gc.collect()
@app.route('/generate-checklist-using-prompt', methods=['POST'])
def generate_checklist_using_prompt():
payload = request.get_json()
org_id = payload.get("orgId", None)
project_id = payload.get("projectId", None)
prompt = payload.get("prompt", None)
is_detailed_checklist = payload.get("isDetailedChecklist", None)
if ((org_id is None or org_id == "") or (project_id is None or project_id == "") or (prompt is None or prompt == "")):
return jsonify({'error': {'message': 'Missing parameters'}}), 400
words = prompt.split()
if (len(words) < 3):
return jsonify({'error': {'message': 'Prompt should contain minimum of 3 words'}}), 400
elif len(words) > 100:
return jsonify({'error': {'message': 'Text should contain maximum of 100 words'}}), 400
try:
checklist_from_document = ChecklistFromDocument(org_id, project_id)
result = checklist_from_document.generate_checklist_using_given_prompt(
prompt, is_detailed_checklist)
return jsonify({"data": {
"checklistId": result
}})
except ValueError as error:
print("An error occurred:", error)
return jsonify({'error': {'message': str(error)}}), 500
finally:
gc.collect()
@app.route('/generate-checklist-status-indicators', methods=['POST'])
def generate_checklist_status_indicators():
payload = request.get_json()
checklist_title = payload.get("title", None)
tasks = payload.get("tasks", None)
if (checklist_title is None or checklist_title == ""):
return jsonify({'error': {'message': 'Checklist title cannot be null'}}), 400
if (tasks is None or len(tasks) == 0):
return jsonify({'error': {'message': 'Tasks cannot be null'}}), 400
try:
checklist_metadata_generator = ChecklistStatusIndicatorsController()
result = checklist_metadata_generator.generate_status_indicators(
checklist_title, tasks)
return jsonify({"data": result})
except ValueError as error:
print("An error occurred:", error)
return jsonify({'error': {'message': str(error)}}), 500
finally:
gc.collect()
@app.errorhandler(RequestEntityTooLarge)
def file_too_large(e):
return jsonify({'error': {'message': str("File is too large")}}), 413
@app.route('/')
def root_path():
return 'It is working...'
# if __name__ == '__main__':
# app.run(host='localhost', port=8080, debug=True, threaded=True)