Spaces:
Configuration error
Configuration error
File size: 6,718 Bytes
1a27ebc 48f8549 1a27ebc 48f8549 | 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 | import asyncio
import hashlib
import logging
import time
from typing import List, Dict, Any, Optional
from contextlib import asynccontextmanager
from fastapi import FastAPI, HTTPException, BackgroundTasks
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from src.models import QuestionRequest, AnswerResponse, ProcessingResult
from src.document_processor import AdvancedDocumentProcessor
from src.vector_store import VectorStoreManager
from src.llm_service import LLMService
from src.query_processor import QueryProcessor
from src.cache_manager import CacheManager
from src.monitoring import PerformanceMonitor
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# Global components
doc_processor = None
vector_store = None
llm_service = None
query_processor = None
cache_manager = None
monitor = None
@asynccontextmanager
async def lifespan(app: FastAPI):
"""Initialize and cleanup application resources"""
global doc_processor, vector_store, llm_service, query_processor, cache_manager, monitor
logger.info("π Starting HackRx 6.0 Application...")
# Initialize components
doc_processor = AdvancedDocumentProcessor()
vector_store = VectorStoreManager()
llm_service = LLMService()
cache_manager = CacheManager()
monitor = PerformanceMonitor()
# Initialize vector store
await vector_store.initialize()
# Initialize query processor with all components
query_processor = QueryProcessor(
doc_processor=doc_processor,
vector_store=vector_store,
llm_service=llm_service,
cache_manager=cache_manager,
monitor=monitor
)
logger.info("β
Application initialized successfully")
yield
# Cleanup
logger.info("π Shutting down application...")
await vector_store.close()
await cache_manager.close()
logger.info("β
Application shutdown complete")
# Initialize FastAPI app
app = FastAPI(
title="HackRx 6.0 - Intelligent Query-Retrieval System",
description="LLM-Powered document processing and question answering system",
version="1.0.0",
lifespan=lifespan
)
# Add CORS middleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def root():
"""Root endpoint with API information"""
return {
"message": "HackRx 6.0 - Intelligent Query-Retrieval System",
"version": "1.0.0",
"status": "active",
"endpoints": {
"main": "/hackrx/run",
"health": "/health",
"metrics": "/metrics"
}
}
@app.get("/health")
async def health_check():
"""Health check endpoint"""
return {
"status": "healthy",
"timestamp": time.time(),
"components": {
"document_processor": "active",
"vector_store": "active" if vector_store else "inactive",
"llm_service": "active" if llm_service else "inactive",
"cache": "active" if cache_manager else "inactive"
}
}
@app.post("/hackrx/run", response_model=AnswerResponse)
async def process_questions(
request: QuestionRequest,
background_tasks: BackgroundTasks
) -> AnswerResponse:
"""
Main endpoint for processing documents and answering questions
Args:
request: QuestionRequest containing document URL and questions
background_tasks: FastAPI background tasks
Returns:
AnswerResponse with answers to all questions
"""
start_time = time.time()
request_id = hashlib.md5(f"{request.documents}{len(request.questions)}{start_time}".encode()).hexdigest()[:8]
logger.info(f"π [{request_id}] Processing request with {len(request.questions)} questions")
logger.info(f"π [{request_id}] Document: {request.documents[:100]}...")
try:
# Process questions using the query processor
results = await query_processor.process_questions(
document_url=request.documents,
questions=request.questions,
request_id=request_id
)
# Extract answers from results
answers = [result.answer for result in results]
# Calculate processing time
processing_time = time.time() - start_time
# Log performance metrics
logger.info(f"β
[{request_id}] Completed in {processing_time:.2f}s")
logger.info(f"π [{request_id}] Average confidence: {sum(r.confidence for r in results) / len(results):.2f}")
# Background task for cleanup and optimization
background_tasks.add_task(
_post_processing_cleanup,
request_id,
processing_time,
results
)
return AnswerResponse(answers=answers)
except Exception as e:
logger.error(f"β [{request_id}] Processing failed: {str(e)}")
raise HTTPException(
status_code=500,
detail={
"error": "Processing failed",
"message": str(e),
"request_id": request_id
}
)
async def _post_processing_cleanup(
request_id: str,
processing_time: float,
results: List[ProcessingResult]
):
"""Background task for post-processing cleanup and optimization"""
try:
# Update performance metrics
if monitor:
await monitor.record_request(
request_id=request_id,
processing_time=processing_time,
question_count=len(results),
avg_confidence=sum(r.confidence for r in results) / len(results)
)
# Cache optimization
if cache_manager:
await cache_manager.optimize_cache()
logger.info(f"π§Ή [{request_id}] Post-processing cleanup completed")
except Exception as e:
logger.warning(f"β οΈ [{request_id}] Post-processing cleanup failed: {e}")
@app.get("/metrics")
async def get_metrics():
"""Get system performance metrics"""
try:
# Example: Return basic system performance data
return {
"uptime": time.time() - monitor.start_time,
"total_requests": monitor.total_requests,
"average_processing_time": monitor.average_processing_time()
}
except Exception as e:
logger.error(f"β Error fetching metrics: {e}")
raise HTTPException(status_code=500, detail="Failed to fetch metrics")
|