Spaces:
Sleeping
Sleeping
File size: 5,256 Bytes
772c108 f9ebc77 772c108 7e46c0f 30aca25 78197ef 915e18d 30aca25 7e46c0f 772c108 7e46c0f 772c108 7e46c0f e0baa68 4f8fe25 7e46c0f 772c108 bce8fcb 772c108 bce8fcb 772c108 bce8fcb 7e46c0f 772c108 bce8fcb 772c108 7e46c0f 772c108 7e46c0f 772c108 7e46c0f 772c108 bce8fcb 772c108 7e46c0f 772c108 7e46c0f bce8fcb 7e46c0f bce8fcb 772c108 20a4958 f9ebc77 20a4958 f9ebc77 20a4958 f9ebc77 20a4958 f9ebc77 20a4958 f9ebc77 20a4958 f9ebc77 20a4958 | 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 | # 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})
|