Spaces:
Sleeping
Sleeping
File size: 18,077 Bytes
e8051be |
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 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 |
from fastapi import FastAPI, HTTPException, Depends, Query
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, HttpUrl
from typing import List, Dict, Any, Optional
import tempfile
import os
import hashlib
import asyncio
import aiohttp
import time
from contextlib import asynccontextmanager
from RAG.advanced_rag_processor import AdvancedRAGProcessor
from preprocessing.preprocessing import DocumentPreprocessor
from logger.logger import rag_logger
from LLM.llm_handler import llm_handler
from LLM.tabular_answer import get_answer_for_tabluar
from LLM.image_answerer import get_answer_for_image
from LLM.one_shotter import get_oneshot_answer
from config.config import *
import config.config as config
# Initialize security
security = HTTPBearer()
admin_security = HTTPBearer()
def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)):
"""Verify the bearer token for main API."""
if credentials.credentials != BEARER_TOKEN:
raise HTTPException(
status_code=401,
detail="Invalid authentication token"
)
return credentials.credentials
def verify_admin_token(credentials: HTTPAuthorizationCredentials = Depends(admin_security)):
"""Verify the bearer token for admin endpoints."""
if credentials.credentials != "9420689497":
raise HTTPException(
status_code=401,
detail="Invalid admin authentication token"
)
return credentials.credentials
# Pydantic models for request/response
class ProcessDocumentRequest(BaseModel):
documents: HttpUrl # URL to the PDF document
questions: List[str] # List of questions to answer
class ProcessDocumentResponse(BaseModel):
answers: List[str]
class HealthResponse(BaseModel):
status: str
message: str
class PreprocessingResponse(BaseModel):
status: str
message: str
doc_id: str
chunk_count: int
class LogsResponse(BaseModel):
export_timestamp: str
metadata: Dict[str, Any]
logs: List[Dict[str, Any]]
class LogsSummaryResponse(BaseModel):
summary: Dict[str, Any]
# Global instances
rag_processor: Optional[AdvancedRAGProcessor] = None
document_preprocessor: Optional[DocumentPreprocessor] = None
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Initialize and cleanup the RAG processor."""
global rag_processor, document_preprocessor
# Startup
print("π Initializing Advanced RAG System...")
rag_processor = AdvancedRAGProcessor() # Use advanced processor for better accuracy
document_preprocessor = DocumentPreprocessor()
print("β
Advanced RAG System initialized successfully")
yield
# Shutdown
print("π Shutting down RAG System...")
if rag_processor:
rag_processor.cleanup()
print("β
Cleanup completed")
# FastAPI app with lifespan management
app = FastAPI(
title="Advanced RAG API",
description="API for document processing and question answering using RAG",
version="1.0.0",
lifespan=lifespan
)
@app.get("/health", response_model=HealthResponse)
async def health_check():
"""Health check endpoint."""
return HealthResponse(
status="healthy",
message="RAG API is running successfully"
)
@app.post("/hackrx/run", response_model=ProcessDocumentResponse)
async def process_document(
request: ProcessDocumentRequest,
token: str = Depends(verify_token)
):
"""
Process a PDF document and answer questions about it.
This endpoint implements an optimized flow:
1. Check if the document is already processed (pre-computed embeddings)
2. If yes, use existing embeddings for fast retrieval + generation
3. If no, run full RAG pipeline (download + process + embed + store + answer)
Args:
request: Contains document URL and list of questions
token: Bearer token for authentication
Returns:
ProcessDocumentResponse: List of answers corresponding to the questions
"""
global rag_processor, document_preprocessor
if not rag_processor or not document_preprocessor:
raise HTTPException(
status_code=503,
detail="RAG system not initialized"
)
# Start timing and logging
start_time = time.time()
document_url = str(request.documents)
questions = request.questions
# Initialize answers for safe logging in finally
final_answers = []
status = "success"
error_message = None
doc_id = None
was_preprocessed = False
# Initialize enhanced logging
request_id = rag_logger.generate_request_id()
rag_logger.start_request_timing(request_id)
try:
print(f"π [{request_id}] Processing document: {document_url[:50]}...")
print(f"π€ [{request_id}] Number of questions: {len(questions)}")
print(f"")
print(f"π [{request_id}] ===== STARTING RAG PIPELINE =====")
print(f"π [{request_id}] PRIORITY 1: Checking stored embeddings database...")
# Generate document ID
doc_id = document_preprocessor.generate_doc_id(document_url)
# Step 1: Check if document is already processed (stored embeddings)
is_processed = document_preprocessor.is_document_processed(document_url)
was_preprocessed = is_processed
if is_processed:
print(f"β
[{request_id}] β
FOUND STORED EMBEDDINGS for {doc_id}")
print(f"β‘ [{request_id}] Using fast path with pre-computed embeddings")
# Fast path: Use existing embeddings
doc_info = document_preprocessor.get_document_info(document_url)
print(f"π [{request_id}] Using existing collection with {doc_info.get('chunk_count', 'N/A')} chunks")
else:
print(f"β [{request_id}] No stored embeddings found for {doc_id}")
print(f"π [{request_id}] PRIORITY 2: Running full RAG pipeline (download + process + embed)...")
# Full path: Download and process document
resp = await document_preprocessor.process_document(document_url)
# Handle different return formats: [content, type] or [content, type, no_cleanup_flag]
if isinstance(resp, list):
content, _type = resp[0], resp[1]
if content == 'unsupported':
# Unsupported file type: respond gracefully without throwing server error
msg = f"Unsupported file type: {_type.lstrip('.')}"
final_answers = [msg]
status = "success" # ensure no 500 is raised in the finally block
return ProcessDocumentResponse(answers=final_answers)
if _type == "image":
try:
final_answers = get_answer_for_image(content, questions)
status = "success"
return ProcessDocumentResponse(answers=final_answers)
finally:
# Clean up the image file after processing
if os.path.exists(content):
os.unlink(content)
print(f"ποΈ Cleaned up image file: {content}")
if _type == "tabular":
final_answers = get_answer_for_tabluar(content, questions)
status = "success"
return ProcessDocumentResponse(answers=final_answers)
if _type == "oneshot":
# Process questions in batches for oneshot
tasks = [
get_oneshot_answer(content, questions[i:i + 3])
for i in range(0, len(questions), 3)
]
# Run all batches in parallel
results = await asyncio.gather(*tasks)
# Flatten results
final_answers = [ans for batch in results for ans in batch]
status = "success"
return ProcessDocumentResponse(answers=final_answers)
else:
doc_id = resp
print(f"β
[{request_id}] Document {doc_id} processed and stored")
# Answer all questions using parallel processing for better latency
print(f"π [{request_id}] Processing {len(questions)} questions in parallel...")
async def answer_single_question(question: str, index: int) -> tuple[str, Dict[str, float]]:
"""Answer a single question with error handling and timing."""
try:
question_start = time.time()
print(f"β [{request_id}] Q{index+1}: {question[:50]}...")
answer, pipeline_timings = await rag_processor.answer_question(
question=question,
doc_id=doc_id,
logger=rag_logger,
request_id=request_id
)
question_time = time.time() - question_start
# Log question timing
rag_logger.log_question_timing(
request_id, index, question, answer, question_time, pipeline_timings
)
print(f"β
[{request_id}] Q{index+1} completed in {question_time:.4f}s")
return answer, pipeline_timings
except Exception as e:
print(f"β [{request_id}] Q{index+1} Error: {str(e)}")
return f"I encountered an error while processing this question: {str(e)}", {}
# Process questions in parallel with controlled concurrency
semaphore = asyncio.Semaphore(3) # Reduced concurrency for better logging visibility
async def bounded_answer(question: str, index: int) -> tuple[str, Dict[str, float]]:
async with semaphore:
return await answer_single_question(question, index)
# Execute all questions concurrently
tasks = [
bounded_answer(question, i)
for i, question in enumerate(questions)
]
results = await asyncio.gather(*tasks, return_exceptions=True)
# Handle any exceptions in answers
final_answers = []
error_count = 0
for i, result in enumerate(results):
if isinstance(result, Exception):
error_count += 1
final_answers.append(f"Error processing question {i+1}: {str(result)}")
else:
answer, _ = result
final_answers.append(answer)
# Determine final status
if error_count == 0:
status = "success"
elif error_count == len(questions):
status = "error"
else:
status = "partial"
print(f"β
[{request_id}] Successfully processed {len(questions) - error_count}/{len(questions)} questions")
except Exception as e:
print(f"β [{request_id}] Error processing request: {str(e)}")
status = "error"
error_message = str(e)
final_answers = [f"Error: {str(e)}" for _ in questions]
finally:
# End request timing and get detailed timing data
timing_data = rag_logger.end_request_timing(request_id)
# Log the request with enhanced timing
processing_time = time.time() - start_time
logged_request_id = rag_logger.log_request(
document_url=document_url,
questions=questions,
answers=final_answers,
processing_time=processing_time,
status=status,
error_message=error_message,
document_id=doc_id,
was_preprocessed=was_preprocessed,
timing_data=timing_data
)
print(f"π Request logged with ID: {logged_request_id} (Status: {status}, Time: {processing_time:.2f}s)")
if status == "error":
raise HTTPException(
status_code=500,
detail=f"Failed to process document: {error_message}"
)
return ProcessDocumentResponse(answers=final_answers)
@app.post("/preprocess", response_model=PreprocessingResponse)
async def preprocess_document(document_url: str, force: bool = False, token: str = Depends(verify_admin_token)):
"""
Preprocess a document (for batch preprocessing).
Args:
document_url: URL of the PDF to preprocess
force: Whether to reprocess if already processed
Returns:
PreprocessingResponse: Status and document info
"""
global document_preprocessor
if not document_preprocessor:
raise HTTPException(
status_code=503,
detail="Document preprocessor not initialized"
)
try:
doc_id = await document_preprocessor.process_document(document_url, force)
doc_info = document_preprocessor.get_document_info(document_url)
return PreprocessingResponse(
status="success",
message=f"Document processed successfully",
doc_id=doc_id,
chunk_count=doc_info.get("chunk_count", 0)
)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Failed to preprocess document: {str(e)}"
)
@app.get("/collections")
async def list_collections(token: str = Depends(verify_admin_token)):
"""List all available document collections."""
global document_preprocessor
if not document_preprocessor:
raise HTTPException(
status_code=503,
detail="Document preprocessor not initialized"
)
try:
processed_docs = document_preprocessor.list_processed_documents()
return {"collections": processed_docs}
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Failed to list collections: {str(e)}"
)
@app.get("/collections/stats")
async def get_collection_stats(token: str = Depends(verify_admin_token)):
"""Get statistics about all collections."""
global document_preprocessor
if not document_preprocessor:
raise HTTPException(
status_code=503,
detail="Document preprocessor not initialized"
)
try:
stats = document_preprocessor.get_collection_stats()
return stats
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Failed to get collection stats: {str(e)}"
)
# Logging Endpoints
@app.get("/logs", response_model=LogsResponse)
async def get_logs(
token: str = Depends(verify_admin_token),
limit: Optional[int] = Query(None, description="Maximum number of logs to return"),
minutes: Optional[int] = Query(None, description="Get logs from last N minutes"),
document_url: Optional[str] = Query(None, description="Filter logs by document URL")
):
"""
Export all API request logs as JSON.
Query Parameters:
limit: Maximum number of recent logs to return
minutes: Get logs from the last N minutes
document_url: Filter logs for a specific document URL
Returns:
LogsResponse: Complete logs export with metadata
"""
try:
if document_url:
# Get logs for specific document
logs = rag_logger.get_logs_by_document(document_url)
metadata = {
"filtered_by": "document_url",
"document_url": document_url,
"total_logs": len(logs)
}
return LogsResponse(
export_timestamp=rag_logger.export_logs()["export_timestamp"],
metadata=metadata,
logs=logs
)
elif minutes:
# Get recent logs
logs = rag_logger.get_recent_logs(minutes)
metadata = {
"filtered_by": "time_range",
"minutes": minutes,
"total_logs": len(logs)
}
return LogsResponse(
export_timestamp=rag_logger.export_logs()["export_timestamp"],
metadata=metadata,
logs=logs
)
else:
# Get all logs (with optional limit)
if limit:
logs = rag_logger.get_logs(limit)
metadata = rag_logger.get_logs_summary()
metadata["limited_to"] = limit
else:
logs_export = rag_logger.export_logs()
return LogsResponse(**logs_export)
return LogsResponse(
export_timestamp=rag_logger.export_logs()["export_timestamp"],
metadata=metadata,
logs=logs
)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Failed to export logs: {str(e)}"
)
@app.get("/logs/summary", response_model=LogsSummaryResponse)
async def get_logs_summary(token: str = Depends(verify_admin_token)):
"""
Get summary statistics of all logs.
Returns:
LogsSummaryResponse: Summary statistics
"""
try:
summary = rag_logger.get_logs_summary()
return LogsSummaryResponse(summary=summary)
except Exception as e:
raise HTTPException(
status_code=500,
detail=f"Failed to get logs summary: {str(e)}"
)
if __name__ == "__main__":
import uvicorn
# Run the FastAPI server
uvicorn.run(
"api:app",
host=API_HOST,
port=API_PORT,
reload=API_RELOAD,
log_level="info"
)
|