WebashalarForML commited on
Commit
92d3c39
·
verified ·
1 Parent(s): e6ce96f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -103
app.py CHANGED
@@ -240,118 +240,100 @@ def create_agent_app(db_path: str):
240
  # create_app: The application factory.
241
  # =============================================================================
242
 
243
- def create_app():
244
- flask_app = Flask(__name__, static_url_path='/uploads', static_folder='uploads')
245
- socketio = SocketIO(flask_app, cors_allowed_origins="*")
 
246
 
247
- # Ensure uploads folder exists.
248
- if not os.path.exists(UPLOAD_FOLDER):
249
- os.makedirs(UPLOAD_FOLDER)
250
- flask_app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
251
 
252
- # -------------------------------------------------------------------------
253
- # Serve uploaded files via a custom route.
254
- # -------------------------------------------------------------------------
255
-
256
- @flask_app.route("/files/<path:filename>")
257
- def uploaded_file(filename):
258
- return send_from_directory(flask_app.config['UPLOAD_FOLDER'], filename)
259
 
260
- # -------------------------------------------------------------------------
261
- # Helper: run_agent runs the agent with the given prompt.
262
- # -------------------------------------------------------------------------
263
-
264
- def run_agent(prompt, socketio):
265
- global agent_app, abs_file_path, db_path
266
- if not abs_file_path:
267
- socketio.emit("log", {"message": "[ERROR]: No DB file uploaded."})
268
- socketio.emit("final", {"message": "No database available. Please upload one and try again."})
269
- return
270
 
271
- try:
272
- # Lazy agent initialization: use the previously uploaded DB.
273
- if agent_app is None:
274
- print("[INFO]: Initializing agent for the first time...")
275
- agent_app = create_agent_app(abs_file_path)
276
- socketio.emit("log", {"message": "[INFO]: Agent initialized."})
277
-
278
- query = {"messages": [("user", prompt)]}
279
- result = agent_app.invoke(query)
280
- try:
281
- result = result["messages"][-1].tool_calls[0]["args"]["final_answer"]
282
- except Exception:
283
- result = "Query failed or no valid answer found."
284
-
285
- print("final_answer------>", result)
286
- socketio.emit("final", {"message": result})
287
- except Exception as e:
288
- print(f"[ERROR]: {str(e)}")
289
- socketio.emit("log", {"message": f"[ERROR]: {str(e)}"})
290
- socketio.emit("final", {"message": "Generation failed."})
291
 
292
- # -------------------------------------------------------------------------
293
- # Route: index page.
294
- # -------------------------------------------------------------------------
295
-
296
- @flask_app.route("/")
297
- def index():
298
- return render_template("index.html")
 
299
 
300
- # -------------------------------------------------------------------------
301
- # Route: generate (POST) – receives a prompt and runs the agent.
302
- # -------------------------------------------------------------------------
303
-
304
- @flask_app.route("/generate", methods=["POST"])
305
- def generate():
306
- try:
307
- socketio.emit("log", {"message": "[STEP]: Entering query_gen..."})
308
- data = request.json
309
- prompt = data.get("prompt", "")
310
- socketio.emit("log", {"message": f"[INFO]: Received prompt: {prompt}"})
311
- thread = threading.Thread(target=run_agent, args=(prompt, socketio))
312
- socketio.emit("log", {"message": f"[INFO]: Starting thread: {thread}"})
313
- thread.start()
314
- return "OK", 200
315
- except Exception as e:
316
- print(f"[ERROR]: {str(e)}")
317
- socketio.emit("log", {"message": f"[ERROR]: {str(e)}"})
318
- return "ERROR", 500
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
319
 
320
- # -------------------------------------------------------------------------
321
- # Route: upload (GET/POST) – handles uploading the SQLite DB file.
322
- # -------------------------------------------------------------------------
323
-
324
- @flask_app.route("/upload", methods=["GET", "POST"])
325
- def upload():
326
- global abs_file_path, agent_app, db_path
327
  try:
328
- if request.method == "POST":
329
- file = request.files.get("file")
330
- if not file:
331
- print("No file uploaded")
332
- return "No file uploaded", 400
333
- filename = secure_filename(file.filename)
334
- if filename.endswith('.db'):
335
- db_path = os.path.join(flask_app.config['UPLOAD_FOLDER'], "uploaded.db")
336
- print("Saving file to:", db_path)
337
- file.save(db_path)
338
- abs_file_path = os.path.abspath(db_path) # Save it here; agent init will occur on first query.
339
- print(f"[INFO]: File '{filename}' uploaded. Agent will be initialized on first query.")
340
- socketio.emit("log", {"message": f"[INFO]: Database file '{filename}' uploaded."})
341
- return redirect(url_for("index"))
342
- return render_template("upload.html")
343
- except Exception as e:
344
- print(f"[ERROR]: {str(e)}")
345
- socketio.emit("log", {"message": f"[ERROR]: {str(e)}"})
346
- return render_template("upload.html")
347
-
348
- return flask_app, socketio
349
 
350
- # =============================================================================
351
- # Create the app for Gunicorn compatibility.
352
- # =============================================================================
353
 
354
- app, socketio_instance = create_app()
 
 
355
 
356
  if __name__ == "__main__":
357
- socketio_instance.run(app, debug=True)
 
240
  # create_app: The application factory.
241
  # =============================================================================
242
 
243
+ # Flask and SocketIO setup
244
+ flask_app = Flask(__name__)
245
+ flask_app.config['UPLOAD_FOLDER'] = "uploaded_files"
246
+ os.makedirs(flask_app.config['UPLOAD_FOLDER'], exist_ok=True)
247
 
248
+ socketio = SocketIO(flask_app, cors_allowed_origins="*")
 
 
 
249
 
250
+ # Global variables to manage state
251
+ agent_app = None
252
+ db_path = None
253
+ abs_file_path = None
 
 
 
254
 
255
+ # ----------------------------
256
+ # ROUTES
257
+ # ----------------------------
 
 
 
 
 
 
 
258
 
259
+ @flask_app.route("/", methods=["GET"])
260
+ def index():
261
+ return render_template("index.html")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
262
 
263
+ @flask_app.route("/upload", methods=["GET", "POST"])
264
+ def upload():
265
+ global abs_file_path, db_path, agent_app
266
+ try:
267
+ if request.method == "POST":
268
+ file = request.files.get("file")
269
+ if not file:
270
+ return "No file uploaded", 400
271
 
272
+ filename = secure_filename(file.filename)
273
+ if filename.endswith('.db'):
274
+ db_path = os.path.join(flask_app.config['UPLOAD_FOLDER'], "uploaded.db")
275
+ file.save(db_path)
276
+
277
+ abs_file_path = os.path.abspath(db_path)
278
+ agent_app = None # reset agent so it gets re-initialized on next query
279
+
280
+ print(f"[INFO]: File '{filename}' uploaded. Agent will be initialized on first query.")
281
+ socketio.emit("log", {"message": f"[INFO]: Database file '{filename}' uploaded."})
282
+
283
+ return redirect(url_for("index"))
284
+ return render_template("upload.html")
285
+ except Exception as e:
286
+ print(f"[ERROR]: {str(e)}")
287
+ socketio.emit("log", {"message": f"[ERROR]: {str(e)}"})
288
+ return render_template("upload.html")
289
+
290
+
291
+ # ----------------------------
292
+ # AGENT INVOCATION
293
+ # ----------------------------
294
+
295
+ @socketio.on("user_input")
296
+ def handle_user_input(data):
297
+ prompt = data.get("message")
298
+ if not prompt:
299
+ socketio.emit("log", {"message": "[ERROR]: Empty prompt received."})
300
+ return
301
+
302
+ run_agent(prompt)
303
+
304
+
305
+ def run_agent(prompt):
306
+ global agent_app, abs_file_path
307
+ if not abs_file_path:
308
+ socketio.emit("log", {"message": "[ERROR]: No DB file uploaded."})
309
+ socketio.emit("final", {"message": "No database available. Please upload one and try again."})
310
+ return
311
+
312
+ try:
313
+ if agent_app is None:
314
+ print("[INFO]: Initializing agent for the first time...")
315
+ agent_app = create_agent_app(abs_file_path)
316
+ socketio.emit("log", {"message": "[INFO]: Agent initialized."})
317
+
318
+ query = {"messages": [("user", prompt)]}
319
+ result = agent_app.invoke(query)
320
 
 
 
 
 
 
 
 
321
  try:
322
+ result = result["messages"][-1].tool_calls[0]["args"]["final_answer"]
323
+ except Exception:
324
+ result = "Query failed or no valid answer found."
325
+
326
+ print("final_answer------>", result)
327
+ socketio.emit("final", {"message": result})
328
+ except Exception as e:
329
+ print(f"[ERROR]: {str(e)}")
330
+ socketio.emit("log", {"message": f"[ERROR]: {str(e)}"})
331
+ socketio.emit("final", {"message": "Generation failed."})
 
 
 
 
 
 
 
 
 
 
 
332
 
 
 
 
333
 
334
+ # ----------------------------
335
+ # MAIN
336
+ # ----------------------------
337
 
338
  if __name__ == "__main__":
339
+ socketio.run(flask_app, debug=True)