Spaces:
Sleeping
Sleeping
from fastapi import FastAPI, HTTPException | |
from fastapi.middleware.cors import CORSMiddleware | |
from pydantic import BaseModel | |
from typing import List, Optional, Dict, Any | |
import uvicorn | |
import sys | |
import os | |
from pathlib import Path | |
from fastapi.responses import FileResponse | |
# Add src directory to Python path | |
sys.path.append(os.path.join(os.path.dirname(__file__), 'src')) | |
# Import the medical generator and data analyzer | |
from src.generation.medical_generator import MedicalTextGenerator, DEFAULT_GEMINI_API_KEY | |
from analyze_data_quality import DataQualityAnalyzer | |
app = FastAPI( | |
title="Synthex Medical Text Generator API", | |
description="API for generating synthetic medical records and analyzing data quality", | |
version="1.0.0" | |
) | |
# Add CORS middleware | |
app.add_middleware( | |
CORSMiddleware, | |
allow_origins=["*"], # Allows all origins | |
allow_credentials=True, | |
allow_methods=["*"], # Allows all methods | |
allow_headers=["*"], # Allows all headers | |
) | |
# Initialize the generator and analyzer | |
generator = None | |
analyzer = None | |
class GenerationRequest(BaseModel): | |
record_type: str | |
quantity: int = 1 | |
use_gemini: bool = False | |
gemini_api_key: Optional[str] = None | |
include_metadata: bool = True | |
class GenerationResponse(BaseModel): | |
records: List[dict] | |
total_generated: int | |
class AnalysisResponse(BaseModel): | |
summary: Dict[str, Any] | |
datasets: Dict[str, Dict[str, Any]] | |
plots_available: List[str] | |
async def startup_event(): | |
global generator, analyzer | |
try: | |
generator = MedicalTextGenerator() | |
analyzer = DataQualityAnalyzer() | |
except Exception as e: | |
print(f"Error initializing services: {str(e)}") | |
async def root(): | |
return {"message": "Welcome to Synthex Medical Text Generator API"} | |
async def generate_records(request: GenerationRequest): | |
global generator | |
if generator is None: | |
try: | |
generator = MedicalTextGenerator(gemini_api_key=request.gemini_api_key) | |
except Exception as e: | |
raise HTTPException(status_code=500, detail=f"Failed to initialize generator: {str(e)}") | |
try: | |
generated_records = [] | |
for _ in range(request.quantity): | |
record = generator.generate_record( | |
request.record_type, | |
use_gemini=request.use_gemini | |
) | |
generated_records.append(record) | |
return GenerationResponse( | |
records=generated_records, | |
total_generated=len(generated_records) | |
) | |
except Exception as e: | |
raise HTTPException(status_code=500, detail=f"Generation failed: {str(e)}") | |
async def get_record_types(): | |
return { | |
"record_types": [ | |
"clinical_note", | |
"discharge_summary", | |
"lab_report", | |
"prescription", | |
"patient_intake" | |
] | |
} | |
async def analyze_data(): | |
global analyzer | |
if analyzer is None: | |
try: | |
analyzer = DataQualityAnalyzer() | |
except Exception as e: | |
raise HTTPException(status_code=500, detail=f"Failed to initialize analyzer: {str(e)}") | |
try: | |
# Run analysis | |
analyzer.analyze_all_datasets() | |
report = analyzer.generate_report() | |
analyzer.plot_metrics() | |
# Get list of generated plots | |
plots_dir = analyzer.data_dir.parent / "reports" / "plots" | |
plots_available = [f.name for f in plots_dir.glob("*.png")] | |
return AnalysisResponse( | |
summary=report["summary"], | |
datasets=report["datasets"], | |
plots_available=plots_available | |
) | |
except Exception as e: | |
raise HTTPException(status_code=500, detail=f"Analysis failed: {str(e)}") | |
async def get_plot(plot_name: str): | |
plots_dir = Path("data/reports/plots") | |
plot_path = plots_dir / plot_name | |
if not plot_path.exists(): | |
raise HTTPException(status_code=404, detail=f"Plot {plot_name} not found") | |
return FileResponse(plot_path) | |
if __name__ == "__main__": | |
uvicorn.run("api:app", host="0.0.0.0", port=8000, reload=True) |