Spaces:
Build error
Build error
| import json | |
| import logging | |
| from fastapi import FastAPI, HTTPException, Query | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from pydantic import BaseModel | |
| from typing import Optional, List | |
| from core.database import ( | |
| get_all_documents, | |
| get_document_by_id, | |
| search_documents, | |
| get_stats, | |
| init_db | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # FastAPI app instance | |
| api_app = FastAPI( | |
| title="Arabic Document Intelligence API", | |
| description="Query and retrieve processed Arabic documents", | |
| version="1.0.0" | |
| ) | |
| api_app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_methods=["GET", "POST"], | |
| allow_headers=["*"] | |
| ) | |
| class SearchRequest(BaseModel): | |
| query: str | |
| language: Optional[str] = None | |
| async def startup(): | |
| init_db() | |
| logger.info("API started, DB initialized") | |
| async def root(): | |
| return { | |
| "service": "Arabic Document Intelligence API", | |
| "version": "1.0.0", | |
| "endpoints": ["/docs", "/stats", "/documents", "/documents/{id}", "/search"] | |
| } | |
| async def stats(): | |
| """Get database statistics.""" | |
| data = get_stats() | |
| if not data: | |
| raise HTTPException(status_code=500, detail="Could not retrieve stats") | |
| return data | |
| async def list_documents( | |
| limit: int = Query(default=20, ge=1, le=100), | |
| offset: int = Query(default=0, ge=0) | |
| ): | |
| """List all processed documents.""" | |
| docs = get_all_documents(limit=limit, offset=offset) | |
| return { | |
| "total_returned": len(docs), | |
| "limit": limit, | |
| "offset": offset, | |
| "documents": docs | |
| } | |
| async def get_document(document_id: str): | |
| """Get a specific document by ID.""" | |
| doc = get_document_by_id(document_id) | |
| if not doc: | |
| raise HTTPException(status_code=404, detail=f"Document {document_id} not found") | |
| return doc | |
| async def search(request: SearchRequest): | |
| """Search documents by text content.""" | |
| if not request.query or len(request.query) < 2: | |
| raise HTTPException(status_code=400, detail="Query must be at least 2 characters") | |
| results = search_documents(request.query, request.language) | |
| return { | |
| "query": request.query, | |
| "language_filter": request.language, | |
| "total_results": len(results), | |
| "results": results | |
| } | |
| async def get_document_json(document_id: str): | |
| """Get the full structured JSON of a document.""" | |
| doc = get_document_by_id(document_id) | |
| if not doc: | |
| raise HTTPException(status_code=404, detail=f"Document {document_id} not found") | |
| structured = doc.get("structured_data") | |
| if not structured: | |
| raise HTTPException(status_code=404, detail="Structured JSON not available") | |
| return structured |