Spaces:
Runtime error
Runtime error
Rivalcoder
commited on
Commit
·
862446b
1
Parent(s):
0589d55
[Edit] Update Of Size Of Questions
Browse files
app.py
CHANGED
|
@@ -4,6 +4,7 @@ import logging
|
|
| 4 |
import time
|
| 5 |
import json
|
| 6 |
from datetime import datetime
|
|
|
|
| 7 |
|
| 8 |
# Set up cache directory for HuggingFace models
|
| 9 |
cache_dir = os.path.join(os.getcwd(), ".cache")
|
|
@@ -17,11 +18,10 @@ os.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'
|
|
| 17 |
os.environ['TF_LOGGING_LEVEL'] = 'ERROR'
|
| 18 |
os.environ['TF_ENABLE_DEPRECATION_WARNINGS'] = '0'
|
| 19 |
|
| 20 |
-
# Suppress specific TensorFlow deprecation warnings
|
| 21 |
warnings.filterwarnings('ignore', category=DeprecationWarning, module='tensorflow')
|
| 22 |
logging.getLogger('tensorflow').setLevel(logging.ERROR)
|
| 23 |
|
| 24 |
-
from fastapi import FastAPI,
|
| 25 |
from fastapi.middleware.cors import CORSMiddleware
|
| 26 |
from pydantic import BaseModel
|
| 27 |
from pdf_parser import parse_pdf_from_url_multithreaded as parse_pdf_from_url, parse_pdf_from_file_multithreaded as parse_pdf_from_file
|
|
@@ -32,7 +32,6 @@ import uvicorn
|
|
| 32 |
|
| 33 |
app = FastAPI(title="HackRx Insurance Policy Assistant", version="1.0.0")
|
| 34 |
|
| 35 |
-
# Add CORS middleware
|
| 36 |
app.add_middleware(
|
| 37 |
CORSMiddleware,
|
| 38 |
allow_origins=["*"],
|
|
@@ -41,7 +40,6 @@ app.add_middleware(
|
|
| 41 |
allow_headers=["*"],
|
| 42 |
)
|
| 43 |
|
| 44 |
-
# Preload the model at startup
|
| 45 |
@app.on_event("startup")
|
| 46 |
async def startup_event():
|
| 47 |
print("Starting up HackRx Insurance Policy Assistant...")
|
|
@@ -55,7 +53,7 @@ async def root():
|
|
| 55 |
|
| 56 |
@app.get("/health")
|
| 57 |
async def health_check():
|
| 58 |
-
return {"status": "healthy"
|
| 59 |
|
| 60 |
class QueryRequest(BaseModel):
|
| 61 |
documents: str
|
|
@@ -68,201 +66,152 @@ class LocalQueryRequest(BaseModel):
|
|
| 68 |
def verify_token(authorization: str = Header(None)):
|
| 69 |
if not authorization or not authorization.startswith("Bearer "):
|
| 70 |
raise HTTPException(status_code=401, detail="Invalid authorization header")
|
| 71 |
-
|
| 72 |
token = authorization.replace("Bearer ", "")
|
| 73 |
-
# For demo purposes, accept any token. In production, validate against a database
|
| 74 |
if not token:
|
| 75 |
raise HTTPException(status_code=401, detail="Invalid token")
|
| 76 |
-
|
| 77 |
return token
|
| 78 |
|
|
|
|
|
|
|
|
|
|
| 79 |
@app.post("/api/v1/hackrx/run")
|
| 80 |
async def run_query(request: QueryRequest, token: str = Depends(verify_token)):
|
| 81 |
start_time = time.time()
|
| 82 |
timing_data = {}
|
| 83 |
-
|
| 84 |
try:
|
| 85 |
print("=== INPUT JSON ===")
|
| 86 |
-
print(json.dumps({
|
| 87 |
-
"documents": request.documents,
|
| 88 |
-
"questions": request.questions
|
| 89 |
-
}, indent=2))
|
| 90 |
print("==================\n")
|
| 91 |
-
|
| 92 |
print(f"Processing {len(request.questions)} questions...")
|
| 93 |
-
|
| 94 |
-
# Time PDF parsing
|
| 95 |
pdf_start = time.time()
|
| 96 |
text_chunks = parse_pdf_from_url(request.documents)
|
| 97 |
-
|
| 98 |
-
timing_data['pdf_parsing'] = round(pdf_time, 2)
|
| 99 |
print(f"Extracted {len(text_chunks)} text chunks from PDF")
|
| 100 |
-
|
| 101 |
-
# Time FAISS index building
|
| 102 |
index_start = time.time()
|
| 103 |
index, texts = build_faiss_index(text_chunks)
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
# Time chunk retrieval for all questions
|
| 108 |
retrieval_start = time.time()
|
| 109 |
all_chunks = set()
|
| 110 |
-
for
|
| 111 |
-
question_start = time.time()
|
| 112 |
top_chunks = retrieve_chunks(index, texts, question)
|
| 113 |
-
question_time = time.time() - question_start
|
| 114 |
all_chunks.update(top_chunks)
|
| 115 |
-
|
| 116 |
-
retrieval_time = time.time() - retrieval_start
|
| 117 |
-
timing_data['chunk_retrieval'] = round(retrieval_time, 2)
|
| 118 |
print(f"Retrieved {len(all_chunks)} unique chunks")
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
llm_start = time.time()
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
answers = answers[:len(request.questions)]
|
| 143 |
-
|
| 144 |
-
response_time = time.time() - response_start
|
| 145 |
-
timing_data['response_processing'] = round(response_time, 2)
|
| 146 |
-
print(f"Generated {len(answers)} answers")
|
| 147 |
-
|
| 148 |
-
# Calculate total time
|
| 149 |
-
total_time = time.time() - start_time
|
| 150 |
-
timing_data['total_time'] = round(total_time, 2)
|
| 151 |
-
|
| 152 |
print(f"\n=== TIMING BREAKDOWN ===")
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
print(f"Chunk Retrieval: {timing_data['chunk_retrieval']}s")
|
| 156 |
-
print(f"LLM Processing: {timing_data['llm_processing']}s")
|
| 157 |
-
print(f"Response Processing: {timing_data['response_processing']}s")
|
| 158 |
-
print(f"TOTAL TIME: {timing_data['total_time']}s")
|
| 159 |
print(f"=======================\n")
|
| 160 |
-
|
| 161 |
-
result = {"answers": answers}
|
| 162 |
print(f"=== OUTPUT JSON ===")
|
| 163 |
-
print(
|
| 164 |
print(f"==================\n")
|
| 165 |
-
|
| 166 |
-
return
|
| 167 |
-
|
| 168 |
except Exception as e:
|
| 169 |
-
|
| 170 |
-
print(f"Error after {total_time:.2f} seconds: {str(e)}")
|
| 171 |
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
|
| 172 |
|
| 173 |
@app.post("/api/v1/hackrx/local")
|
| 174 |
async def run_local_query(request: LocalQueryRequest):
|
| 175 |
start_time = time.time()
|
| 176 |
timing_data = {}
|
| 177 |
-
|
| 178 |
try:
|
| 179 |
-
print(
|
| 180 |
-
print(
|
| 181 |
-
print(
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
print(f"Processing {len(request.questions)} questions...")
|
| 186 |
-
|
| 187 |
-
# Time local PDF parsing
|
| 188 |
pdf_start = time.time()
|
| 189 |
text_chunks = parse_pdf_from_file(request.document_path)
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
# Time FAISS index building
|
| 195 |
index_start = time.time()
|
| 196 |
index, texts = build_faiss_index(text_chunks)
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
# Time chunk retrieval for all questions
|
| 201 |
retrieval_start = time.time()
|
| 202 |
all_chunks = set()
|
| 203 |
-
for
|
| 204 |
-
question_start = time.time()
|
| 205 |
top_chunks = retrieve_chunks(index, texts, question)
|
| 206 |
-
question_time = time.time() - question_start
|
| 207 |
all_chunks.update(top_chunks)
|
| 208 |
-
|
| 209 |
-
retrieval_time = time.time() - retrieval_start
|
| 210 |
-
timing_data['chunk_retrieval'] = round(retrieval_time, 2)
|
| 211 |
print(f"Retrieved {len(all_chunks)} unique chunks")
|
| 212 |
-
|
| 213 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 214 |
llm_start = time.time()
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
|
| 235 |
-
answers = answers[:len(request.questions)]
|
| 236 |
-
|
| 237 |
-
response_time = time.time() - response_start
|
| 238 |
-
timing_data['response_processing'] = round(response_time, 2)
|
| 239 |
-
print(f"Generated {len(answers)} answers")
|
| 240 |
-
|
| 241 |
-
# Calculate total time
|
| 242 |
-
total_time = time.time() - start_time
|
| 243 |
-
timing_data['total_time'] = round(total_time, 2)
|
| 244 |
-
|
| 245 |
print(f"\n=== TIMING BREAKDOWN ===")
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
print(f"Chunk Retrieval: {timing_data['chunk_retrieval']}s")
|
| 249 |
-
print(f"LLM Processing: {timing_data['llm_processing']}s")
|
| 250 |
-
print(f"Response Processing: {timing_data['response_processing']}s")
|
| 251 |
-
print(f"TOTAL TIME: {timing_data['total_time']}s")
|
| 252 |
print(f"=======================\n")
|
| 253 |
-
|
| 254 |
-
result = {"answers": answers}
|
| 255 |
print(f"=== OUTPUT JSON ===")
|
| 256 |
-
print(
|
| 257 |
print(f"==================\n")
|
| 258 |
-
|
| 259 |
-
return
|
| 260 |
-
|
| 261 |
except Exception as e:
|
| 262 |
-
|
| 263 |
-
print(f"Error after {total_time:.2f} seconds: {str(e)}")
|
| 264 |
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
|
| 265 |
|
| 266 |
if __name__ == "__main__":
|
| 267 |
port = int(os.environ.get("PORT", 7860))
|
| 268 |
-
uvicorn.run("app:app", host="0.0.0.0", port=port)
|
|
|
|
| 4 |
import time
|
| 5 |
import json
|
| 6 |
from datetime import datetime
|
| 7 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 8 |
|
| 9 |
# Set up cache directory for HuggingFace models
|
| 10 |
cache_dir = os.path.join(os.getcwd(), ".cache")
|
|
|
|
| 18 |
os.environ['TF_LOGGING_LEVEL'] = 'ERROR'
|
| 19 |
os.environ['TF_ENABLE_DEPRECATION_WARNINGS'] = '0'
|
| 20 |
|
|
|
|
| 21 |
warnings.filterwarnings('ignore', category=DeprecationWarning, module='tensorflow')
|
| 22 |
logging.getLogger('tensorflow').setLevel(logging.ERROR)
|
| 23 |
|
| 24 |
+
from fastapi import FastAPI, HTTPException, Depends, Header
|
| 25 |
from fastapi.middleware.cors import CORSMiddleware
|
| 26 |
from pydantic import BaseModel
|
| 27 |
from pdf_parser import parse_pdf_from_url_multithreaded as parse_pdf_from_url, parse_pdf_from_file_multithreaded as parse_pdf_from_file
|
|
|
|
| 32 |
|
| 33 |
app = FastAPI(title="HackRx Insurance Policy Assistant", version="1.0.0")
|
| 34 |
|
|
|
|
| 35 |
app.add_middleware(
|
| 36 |
CORSMiddleware,
|
| 37 |
allow_origins=["*"],
|
|
|
|
| 40 |
allow_headers=["*"],
|
| 41 |
)
|
| 42 |
|
|
|
|
| 43 |
@app.on_event("startup")
|
| 44 |
async def startup_event():
|
| 45 |
print("Starting up HackRx Insurance Policy Assistant...")
|
|
|
|
| 53 |
|
| 54 |
@app.get("/health")
|
| 55 |
async def health_check():
|
| 56 |
+
return {"status": "healthy"}
|
| 57 |
|
| 58 |
class QueryRequest(BaseModel):
|
| 59 |
documents: str
|
|
|
|
| 66 |
def verify_token(authorization: str = Header(None)):
|
| 67 |
if not authorization or not authorization.startswith("Bearer "):
|
| 68 |
raise HTTPException(status_code=401, detail="Invalid authorization header")
|
|
|
|
| 69 |
token = authorization.replace("Bearer ", "")
|
|
|
|
| 70 |
if not token:
|
| 71 |
raise HTTPException(status_code=401, detail="Invalid token")
|
|
|
|
| 72 |
return token
|
| 73 |
|
| 74 |
+
def process_batch(batch_questions, context_chunks):
|
| 75 |
+
return query_gemini(batch_questions, context_chunks)
|
| 76 |
+
|
| 77 |
@app.post("/api/v1/hackrx/run")
|
| 78 |
async def run_query(request: QueryRequest, token: str = Depends(verify_token)):
|
| 79 |
start_time = time.time()
|
| 80 |
timing_data = {}
|
|
|
|
| 81 |
try:
|
| 82 |
print("=== INPUT JSON ===")
|
| 83 |
+
print(json.dumps({"documents": request.documents, "questions": request.questions}, indent=2))
|
|
|
|
|
|
|
|
|
|
| 84 |
print("==================\n")
|
| 85 |
+
|
| 86 |
print(f"Processing {len(request.questions)} questions...")
|
| 87 |
+
|
|
|
|
| 88 |
pdf_start = time.time()
|
| 89 |
text_chunks = parse_pdf_from_url(request.documents)
|
| 90 |
+
timing_data['pdf_parsing'] = round(time.time() - pdf_start, 2)
|
|
|
|
| 91 |
print(f"Extracted {len(text_chunks)} text chunks from PDF")
|
| 92 |
+
|
|
|
|
| 93 |
index_start = time.time()
|
| 94 |
index, texts = build_faiss_index(text_chunks)
|
| 95 |
+
timing_data['faiss_index_building'] = round(time.time() - index_start, 2)
|
| 96 |
+
|
|
|
|
|
|
|
| 97 |
retrieval_start = time.time()
|
| 98 |
all_chunks = set()
|
| 99 |
+
for question in request.questions:
|
|
|
|
| 100 |
top_chunks = retrieve_chunks(index, texts, question)
|
|
|
|
| 101 |
all_chunks.update(top_chunks)
|
| 102 |
+
timing_data['chunk_retrieval'] = round(time.time() - retrieval_start, 2)
|
|
|
|
|
|
|
| 103 |
print(f"Retrieved {len(all_chunks)} unique chunks")
|
| 104 |
+
|
| 105 |
+
questions = request.questions
|
| 106 |
+
context_chunks = list(all_chunks)
|
| 107 |
+
batch_size = 10
|
| 108 |
+
batches = [(i, questions[i:i + batch_size]) for i in range(0, len(questions), batch_size)]
|
| 109 |
+
|
| 110 |
llm_start = time.time()
|
| 111 |
+
results_dict = {}
|
| 112 |
+
with ThreadPoolExecutor(max_workers=min(5, len(batches))) as executor:
|
| 113 |
+
futures = [executor.submit(process_batch, batch, context_chunks) for _, batch in batches]
|
| 114 |
+
for (start_idx, batch), future in zip(batches, futures):
|
| 115 |
+
try:
|
| 116 |
+
result = future.result()
|
| 117 |
+
if isinstance(result, dict) and "answers" in result:
|
| 118 |
+
for j, answer in enumerate(result["answers"]):
|
| 119 |
+
results_dict[start_idx + j] = answer
|
| 120 |
+
else:
|
| 121 |
+
for j in range(len(batch)):
|
| 122 |
+
results_dict[start_idx + j] = "Error in response"
|
| 123 |
+
except Exception as e:
|
| 124 |
+
for j in range(len(batch)):
|
| 125 |
+
results_dict[start_idx + j] = f"Error: {str(e)}"
|
| 126 |
+
timing_data['llm_processing'] = round(time.time() - llm_start, 2)
|
| 127 |
+
|
| 128 |
+
responses = [results_dict.get(i, "Not Found") for i in range(len(questions))]
|
| 129 |
+
|
| 130 |
+
timing_data['total_time'] = round(time.time() - start_time, 2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
print(f"\n=== TIMING BREAKDOWN ===")
|
| 132 |
+
for k, v in timing_data.items():
|
| 133 |
+
print(f"{k}: {v}s")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
print(f"=======================\n")
|
| 135 |
+
|
|
|
|
| 136 |
print(f"=== OUTPUT JSON ===")
|
| 137 |
+
print(json.dumps({"answers": responses}, indent=2))
|
| 138 |
print(f"==================\n")
|
| 139 |
+
|
| 140 |
+
return {"answers": responses}
|
| 141 |
+
|
| 142 |
except Exception as e:
|
| 143 |
+
print(f"Error: {str(e)}")
|
|
|
|
| 144 |
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
|
| 145 |
|
| 146 |
@app.post("/api/v1/hackrx/local")
|
| 147 |
async def run_local_query(request: LocalQueryRequest):
|
| 148 |
start_time = time.time()
|
| 149 |
timing_data = {}
|
|
|
|
| 150 |
try:
|
| 151 |
+
print("=== INPUT JSON ===")
|
| 152 |
+
print(json.dumps({"document_path": request.document_path, "questions": request.questions}, indent=2))
|
| 153 |
+
print("==================\n")
|
| 154 |
+
|
| 155 |
+
print(f"Processing {len(request.questions)} questions locally...")
|
| 156 |
+
|
|
|
|
|
|
|
|
|
|
| 157 |
pdf_start = time.time()
|
| 158 |
text_chunks = parse_pdf_from_file(request.document_path)
|
| 159 |
+
timing_data['pdf_parsing'] = round(time.time() - pdf_start, 2)
|
| 160 |
+
print(f"Extracted {len(text_chunks)} text chunks from PDF")
|
| 161 |
+
|
|
|
|
|
|
|
| 162 |
index_start = time.time()
|
| 163 |
index, texts = build_faiss_index(text_chunks)
|
| 164 |
+
timing_data['faiss_index_building'] = round(time.time() - index_start, 2)
|
| 165 |
+
|
|
|
|
|
|
|
| 166 |
retrieval_start = time.time()
|
| 167 |
all_chunks = set()
|
| 168 |
+
for question in request.questions:
|
|
|
|
| 169 |
top_chunks = retrieve_chunks(index, texts, question)
|
|
|
|
| 170 |
all_chunks.update(top_chunks)
|
| 171 |
+
timing_data['chunk_retrieval'] = round(time.time() - retrieval_start, 2)
|
|
|
|
|
|
|
| 172 |
print(f"Retrieved {len(all_chunks)} unique chunks")
|
| 173 |
+
|
| 174 |
+
questions = request.questions
|
| 175 |
+
context_chunks = list(all_chunks)
|
| 176 |
+
batch_size = 20
|
| 177 |
+
batches = [(i, questions[i:i + batch_size]) for i in range(0, len(questions), batch_size)]
|
| 178 |
+
|
| 179 |
llm_start = time.time()
|
| 180 |
+
results_dict = {}
|
| 181 |
+
with ThreadPoolExecutor(max_workers=min(5, len(batches))) as executor:
|
| 182 |
+
futures = [executor.submit(process_batch, batch, context_chunks) for _, batch in batches]
|
| 183 |
+
for (start_idx, batch), future in zip(batches, futures):
|
| 184 |
+
try:
|
| 185 |
+
result = future.result()
|
| 186 |
+
if isinstance(result, dict) and "answers" in result:
|
| 187 |
+
for j, answer in enumerate(result["answers"]):
|
| 188 |
+
results_dict[start_idx + j] = answer
|
| 189 |
+
else:
|
| 190 |
+
for j in range(len(batch)):
|
| 191 |
+
results_dict[start_idx + j] = "Error in response"
|
| 192 |
+
except Exception as e:
|
| 193 |
+
for j in range(len(batch)):
|
| 194 |
+
results_dict[start_idx + j] = f"Error: {str(e)}"
|
| 195 |
+
timing_data['llm_processing'] = round(time.time() - llm_start, 2)
|
| 196 |
+
|
| 197 |
+
responses = [results_dict.get(i, "Not Found") for i in range(len(questions))]
|
| 198 |
+
|
| 199 |
+
timing_data['total_time'] = round(time.time() - start_time, 2)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 200 |
print(f"\n=== TIMING BREAKDOWN ===")
|
| 201 |
+
for k, v in timing_data.items():
|
| 202 |
+
print(f"{k}: {v}s")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 203 |
print(f"=======================\n")
|
| 204 |
+
|
|
|
|
| 205 |
print(f"=== OUTPUT JSON ===")
|
| 206 |
+
print(json.dumps({"answers": responses}, indent=2))
|
| 207 |
print(f"==================\n")
|
| 208 |
+
|
| 209 |
+
return {"answers": responses}
|
| 210 |
+
|
| 211 |
except Exception as e:
|
| 212 |
+
print(f"Error: {str(e)}")
|
|
|
|
| 213 |
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
|
| 214 |
|
| 215 |
if __name__ == "__main__":
|
| 216 |
port = int(os.environ.get("PORT", 7860))
|
| 217 |
+
uvicorn.run("app:app", host="0.0.0.0", port=port)
|