File size: 4,361 Bytes
32519eb
 
 
7271401
32519eb
 
 
7271401
 
32519eb
 
 
 
7271401
32519eb
7271401
32519eb
 
 
7271401
32519eb
 
 
 
 
 
 
 
 
 
 
 
7271401
32519eb
7271401
32519eb
 
 
 
 
 
 
 
 
 
 
 
7271401
 
 
 
 
32519eb
 
7271401
32519eb
 
7271401
32519eb
7271401
32519eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7271401
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32519eb
 
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
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]

@app.on_event("startup")
async def startup_event():
    global generator, analyzer
    try:
        generator = MedicalTextGenerator()
        analyzer = DataQualityAnalyzer()
    except Exception as e:
        print(f"Error initializing services: {str(e)}")

@app.get("/")
async def root():
    return {"message": "Welcome to Synthex Medical Text Generator API"}

@app.post("/generate", response_model=GenerationResponse)
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)}")

@app.get("/record-types")
async def get_record_types():
    return {
        "record_types": [
            "clinical_note",
            "discharge_summary",
            "lab_report",
            "prescription",
            "patient_intake"
        ]
    }

@app.post("/analyze", response_model=AnalysisResponse)
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)}")

@app.get("/analysis/plots/{plot_name}")
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)