Spaces:
Sleeping
Sleeping
| # ============================================================================ | |
| # π AI TEST CASE GENERATOR API | |
| # FastAPI + Groq + PM Tool Integration | |
| # MVC Architecture Implementation | |
| # ============================================================================ | |
| import os | |
| import traceback | |
| from contextlib import asynccontextmanager | |
| from datetime import datetime | |
| from fastapi import FastAPI, HTTPException | |
| from fastapi.responses import JSONResponse | |
| from fastapi.middleware.cors import CORSMiddleware | |
| # Third-party imports | |
| try: | |
| from groq import Groq | |
| import pandas as pd | |
| from openpyxl import Workbook | |
| from openpyxl.styles import Font, PatternFill, Alignment | |
| except ImportError as e: | |
| print(f"β οΈ Missing dependency: {e}") | |
| print("Run: pip install groq pandas openpyxl aiohttp python-jose[cryptography]") | |
| exit(1) | |
| from app.config import Config | |
| from app.models.schemas import ErrorResponse | |
| from app.views.routes import router | |
| from app.utils.logger import logger | |
| from app.utils.http_client import http_client | |
| # ============================================================================ | |
| # FASTAPI APP INITIALIZATION | |
| # ============================================================================ | |
| async def lifespan(app: FastAPI): | |
| """Startup and shutdown events""" | |
| # Startup | |
| logger.info("π Starting AI Test Case Generator API...") | |
| await http_client.start() | |
| # Validate Groq API key | |
| if not Config.GROQ_API_KEY: | |
| logger.error("β GROQ_API_KEY not set! Set it via environment variable.") | |
| else: | |
| logger.info("β Groq API key configured") | |
| yield | |
| # Shutdown | |
| logger.info("π Shutting down API...") | |
| await http_client.close() | |
| app = FastAPI( | |
| title=Config.API_TITLE, | |
| version=Config.API_VERSION, | |
| description=Config.API_DESCRIPTION, | |
| lifespan=lifespan | |
| ) | |
| # CORS Middleware | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], # Configure appropriately for production | |
| allow_credentials=True, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Include API routes | |
| app.include_router(router) | |
| # ============================================================================ | |
| # EXCEPTION HANDLERS | |
| # ============================================================================ | |
| async def http_exception_handler(request, exc): | |
| return JSONResponse( | |
| status_code=exc.status_code, | |
| content=ErrorResponse( | |
| error=exc.detail, | |
| message=str(exc), | |
| timestamp=datetime.now().isoformat() | |
| ).dict() | |
| ) | |
| async def general_exception_handler(request, exc): | |
| logger.error(f"Unhandled exception: {exc}\n{traceback.format_exc()}") | |
| return JSONResponse( | |
| status_code=500, | |
| content=ErrorResponse( | |
| error="Internal Server Error", | |
| message=str(exc), | |
| details={"traceback": traceback.format_exc()}, | |
| timestamp=datetime.now().isoformat() | |
| ).dict() | |
| ) | |
| # ============================================================================ | |
| # MAIN ENTRY POINT | |
| # ============================================================================ | |
| if __name__ == "__main__": | |
| import uvicorn | |
| # Configuration | |
| HOST = os.getenv("HOST", "0.0.0.0") | |
| PORT = int(os.getenv("PORT", 8000)) | |
| WORKERS = int(os.getenv("WORKERS", 1)) | |
| logger.info(f""" | |
| ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| β π AI TEST CASE GENERATOR API β | |
| β Version: {Config.API_VERSION} β | |
| β Starting on http://{HOST}:{PORT} β | |
| β Docs: http://{HOST}:{PORT}/docs β | |
| ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ | |
| """) | |
| uvicorn.run( | |
| "main:app", | |
| host=HOST, | |
| port=PORT, | |
| workers=WORKERS, | |
| log_level=Config.LOG_LEVEL.lower(), | |
| access_log=True | |
| ) | |