Spaces:
Sleeping
Sleeping
Update app/main.py
Browse files7 unmodified lines8910111213141516171819201 unmodified line22232425262718 unmodified lines464748495051525354555657585960616212 unmodified lines757677787980818283848586878889909192939495969798991001011021031041057 unmodified linesimport reimport faissimport numpy as npapp = FastAPI()import zipfileimport oszip_path = "app/nse_vector_base.zip" # path to your uploaded zipextract_path = "app/nse_vector_base/" # folder to extract into# Extract only if not already extractedif not os.path.exists(extract_path):with zipfile.ZipFile(zip_path, 'r') as zip_ref:1 unmodified lineprint("β Unzipped to:", extract_path)print("π Files:", os.listdir(extract_path))def protect_math(text):return re.sub(r'(\${2})(.+?)\1', r'@@\2@@', text, flags=re.DOTALL)18 unmodified lines# ----------- Load Static Banking Documents ------------# β Load saved FAISS indexBASE_DIR = os.path.dirname(__file__)index_path = os.path.join(BASE_DIR, "vector_base/faiss_index.bin")faiss_index = faiss.read_index(index_path)BASE_DIR = os.path.dirname(__file__)faiss_index = faiss.read_index(os.path.join(BASE_DIR, "vector_base", "faiss_index.bin"))document_chunks = np.load(os.path.join(BASE_DIR, "vector_base", "chunks.npy"), allow_pickle=True).tolist()@app.get("/")def root():return {"status": "FinBot awake!"}@app.post("/logout")async def logout_user(session_id: str = Form(...)):12 unmodified linesrequest: Request,query: str = Form(...),user_data_text: str = Form(""),session_id: str = Form(...)):start_time = time.time()# β Use session_id as the key instead of IPchat_history = chat_sessions.get(session_id, [])combined_user_data = user_data_text.strip()input_context = "\n".join([c["message"] for c in chat_history]) + combined_user_datainput_tokens = len(input_context.split())answer = generate_answer(query=query,index=faiss_index,chunks=document_chunks,chat_history=chat_history,user_data_text=combined_user_data)output_tokens = len(answer.split())time_taken = round(time.time() - start_time, 2)chat_history.append({"role": "user", "message": query})chat_history.append({"role": "bot", "message": answer})chat_sessions[session_id] = chat_history # β Correct usageprint(f"[QUERY LOG] Session: {session_id} | Input Tokens: {input_tokens} | Output Tokens: {output_tokens} | Time: {time_taken}s")return JSONResponse(content={"response": answer})7 unmodified lines89101112131415161718191 unmodified line2122232425262718 unmodified lines46474849505152535455565758596061626312 unmodified lines7677787980818283848586878889909192939495969798991001011021031041051061071081091101111121137 unmodified linesimport reimport faissimport numpy as npimport zipfileimport oszip_path = "app/nse_vector_base.zip" # path to your uploaded zipextract_path = "tmp/nse_vector_base/" # folder to extract into# Extract only if not already extractedif not os.path.exists(extract_path):with zipfile.ZipFile(zip_path, 'r') as zip_ref:1 unmodified lineprint("β 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)18 unmodified lines# ----------- Load Static Banking Documents ------------# β Load saved FAISS index# ----------- Load Static Banking Documents ------------BASE_DIR = os.path.dirname(__file__)# Banking KBbank_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 KBnse_index = faiss.read_index(os.path.join(BASE_DIR, "nse_vector_base", "nse_index.bin"))nse_chunks = np.load(os.path.join(BASE_DIR, "nse_vector_base", "nse_chunks.npy"), allow_pickle=True).tolist()@app.post("/logout")async def logout_user(session_id: str = Form(...)):12 unmodified linesrequest: 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 & chunksif kb_type.lower() == "nse":index, chunks = nse_index, nse_chunkselse: # default to bankingindex, chunks = bank_index, bank_chunks# Generate answer using the chosen KBanswer = generate_answer(query=query,index=index,chunks=chunks,chat_history=chat_history,user_data_text=combined_user_data)# Update chat historychat_history.append({"role": "user", "message": query})chat_history.append({"role": "bot", "message": answer})chat_sessions[session_id] = chat_history# Log for debugginginput_context = "\n".join([c["message"] for c in chat_history]) + combined_user_datainput_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/main.py+30-22