Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, HTTPException, Depends | |
| import os | |
| import logging | |
| import uvicorn | |
| from dotenv import load_dotenv | |
| from src.auth import get_api_key | |
| from src.schemas import DetectionRequest, DetectionResponse | |
| from src.services.ai_detector import ai_detector_service | |
| from src.services.language_detector import language_detector_service | |
| from src.middleware.request_logging import RequestLoggingMiddleware | |
| # Load environment variables | |
| load_dotenv() | |
| # Configure logging | |
| logging.basicConfig( | |
| level=logging.INFO, | |
| format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", | |
| datefmt="%Y-%m-%d %H:%M:%S" | |
| ) | |
| app = FastAPI(title="AI Text Detector API") | |
| app.add_middleware(RequestLoggingMiddleware) | |
| async def startup_event(): | |
| language_detector_service.initialize() | |
| ai_detector_service.initialize() | |
| def root(): | |
| return {"message": "AI Text Detector API is running. Visit /docs for documentation."} | |
| def health_check(): | |
| return ai_detector_service.get_status() | |
| async def detect(request: DetectionRequest, api_key: str = Depends(get_api_key)): | |
| try: | |
| # Detect language | |
| lang = language_detector_service.detect_language(request.text) | |
| if lang != "en": | |
| # Optional: Decide if we want to block non-English or just warn. | |
| # The requirements said "Keep the fasttext detector before passing to the AI text detector". | |
| # Assuming we should strict block like before. | |
| raise HTTPException(status_code=422, detail="Only English text is supported for accuracy") | |
| result = ai_detector_service.detect(request.text) | |
| return result | |
| except HTTPException as he: | |
| raise he | |
| except RuntimeError: | |
| raise HTTPException(status_code=503, detail="Model not initialized") | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| if __name__ == "__main__": | |
| port = int(os.environ.get("PORT", 8080)) | |
| uvicorn.run(app, host="0.0.0.0", port=port) | |