# app/main.py from fastapi import FastAPI, UploadFile, File, Request, Form from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse from app.backend import extract_text_from_pdf, build_faiss_index, generate_answer, generate_voice_response import os from markdown import markdown as md import re import faiss import numpy as np import zipfile import os zip_path = "app/nse_vector_base.zip" # path to your uploaded zip extract_path = "/tmp/nse_vector_base/" # folder to extract into # Extract only if not already extracted if not os.path.exists(extract_path): with zipfile.ZipFile(zip_path, 'r') as zip_ref: zip_ref.extractall(extract_path) print("✅ Unzipped to:", extract_path) print("📂 Files:", os.listdir(extract_path)) app = FastAPI() def protect_math(text): return re.sub(r'(\${2})(.+?)\1', r'@@\2@@', text, flags=re.DOTALL) def unprotect_math(html): return html.replace('@@', '$$') def auto_wrap_math_blocks(text): def wrap_if_needed(line): if re.search(r'\\text|\d+\s*[\+\-\*/=]\s*\d+', line) and not re.match(r'\s*\$\$', line): return f"$$\n{line.strip()}\n$$" return line return "\n".join(wrap_if_needed(l) for l in text.splitlines()) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"] ) # ----------- Load Static Banking Documents ------------ # ✅ Load saved FAISS index # ----------- Load Static Banking Documents ------------ BASE_DIR = os.path.dirname(__file__) # Banking KB bank_index = faiss.read_index(os.path.join(BASE_DIR, "vector_base", "faiss_index.bin")) bank_chunks = np.load(os.path.join(BASE_DIR, "vector_base", "chunks.npy"), allow_pickle=True).tolist() # NSE KB nse_index = faiss.read_index(os.path.join("/tmp/nse_vector_base/nse_vector_base/nse_index.bin")) nse_chunks = np.load(os.path.join("/tmp/nse_vector_base/nse_vector_base/nse_chunks.npy"), allow_pickle=True).tolist() @app.post("/logout") async def logout_user(session_id: str = Form(...)): if session_id in chat_sessions: del chat_sessions[session_id] print(f"[LOGOUT] Session '{session_id}' flushed.") return JSONResponse(content={"message": "Session cleared."}) chat_sessions = {} # -------------- Chat Endpoint ---------------- import time @app.post("/query") async def query_endpoint( request: Request, query: str = Form(...), user_data_text: str = Form(""), session_id: str = Form(...), kb_type: str = Form("bank") # ✅ New parameter, default is "bank" ): start_time = time.time() chat_history = chat_sessions.get(session_id, []) combined_user_data = user_data_text.strip() # ✅ Choose correct FAISS index & chunks if kb_type.lower() == "nse": index, chunks = nse_index, nse_chunks else: # default to banking index, chunks = bank_index, bank_chunks # Generate answer using the chosen KB answer = generate_answer( query=query, index=index, chunks=chunks, chat_history=chat_history, user_data_text=combined_user_data ) # Update chat history chat_history.append({"role": "user", "message": query}) chat_history.append({"role": "bot", "message": answer}) chat_sessions[session_id] = chat_history # Log for debugging input_context = "\n".join([c["message"] for c in chat_history]) + combined_user_data input_tokens = len(input_context.split()) output_tokens = len(answer.split()) time_taken = round(time.time() - start_time, 2) print(f"[QUERY LOG] Session: {session_id} | KB: {kb_type} | Input Tokens: {input_tokens} | Output Tokens: {output_tokens} | Time: {time_taken}s") return JSONResponse(content={"response": answer}) @app.post("/voice") async def voice_endpoint( request: Request, query: str = Form(...), user_data_text: str = Form(""), session_id: str = Form(...), kb_type: str = Form("bank") # ✅ default knowledge base ): start_time = time.time() chat_history = chat_sessions.get(session_id, []) combined_user_data = user_data_text.strip() # ✅ Choose the correct FAISS index & chunks if kb_type.lower() == "nse": index, chunks = nse_index, nse_chunks else: index, chunks = bank_index, bank_chunks # ✅ Generate natural voice-friendly answer answer = generate_voice_response( query=query, index=index, chunks=chunks, chat_history=chat_history ) # ✅ Update chat history chat_history.append({"role": "user", "message": query}) chat_history.append({"role": "bot", "message": answer}) chat_sessions[session_id] = chat_history # ✅ Log for monitoring input_context = "\n".join([c["message"] for c in chat_history]) + combined_user_data input_tokens = len(input_context.split()) output_tokens = len(answer.split()) time_taken = round(time.time() - start_time, 2) print(f"[VOICE LOG] Session: {session_id} | KB: {kb_type} | Input Tokens: {input_tokens} | Output Tokens: {output_tokens} | Time: {time_taken}s") # ✅ Return plain text (voice assistant will TTS it) return JSONResponse(content={"response": answer})