|
from fastapi import FastAPI, HTTPException |
|
from pydantic import BaseModel |
|
import uvicorn |
|
from medical_simplifier import MedicalTextSimplifier |
|
import logging |
|
|
|
|
|
logging.basicConfig(level=logging.INFO) |
|
logger = logging.getLogger(__name__) |
|
|
|
app = FastAPI( |
|
title="Medical Text Simplifier API", |
|
description="API to simplify medical text by explaining medical terms in plain language", |
|
version="1.0.0" |
|
) |
|
|
|
|
|
try: |
|
simplifier = MedicalTextSimplifier() |
|
logger.info("Medical text simplifier initialized successfully") |
|
except Exception as e: |
|
logger.error(f"Failed to initialize simplifier: {e}") |
|
simplifier = None |
|
|
|
class TextInput(BaseModel): |
|
text: str |
|
|
|
class SimplificationResponse(BaseModel): |
|
original_text: str |
|
medical_terms_explained: dict |
|
|
|
@app.get("/") |
|
async def root(): |
|
return { |
|
"message": "Medical Text Simplifier API", |
|
"status": "running", |
|
"endpoints": ["/simplify", "/health"] |
|
} |
|
|
|
@app.get("/health") |
|
async def health_check(): |
|
if simplifier is None: |
|
raise HTTPException(status_code=503, detail="Model not loaded") |
|
return {"status": "healthy", "models_loaded": True} |
|
|
|
@app.post("/simplify", response_model=SimplificationResponse) |
|
async def simplify_text(input_data: TextInput): |
|
if simplifier is None: |
|
raise HTTPException(status_code=503, detail="Model not loaded") |
|
|
|
if not input_data.text.strip(): |
|
raise HTTPException(status_code=400, detail="Text input cannot be empty") |
|
|
|
try: |
|
|
|
medical_terms = simplifier.identify_medical_terms(input_data.text) |
|
|
|
|
|
unique_terms = {} |
|
|
|
for item in medical_terms: |
|
term = item['term'].lower() |
|
if term not in unique_terms: |
|
explanation = simplifier.generate_simplified_explanation(item['term'], input_data.text) |
|
unique_terms[term] = explanation |
|
|
|
return SimplificationResponse( |
|
original_text=input_data.text, |
|
medical_terms_explained=unique_terms |
|
) |
|
|
|
except Exception as e: |
|
logger.error(f"Error processing text: {e}") |
|
raise HTTPException(status_code=500, detail="Error processing text") |
|
|
|
if __name__ == "__main__": |
|
uvicorn.run(app, host="0.0.0.0", port=7860) |