Develop a script in Python to fine-tune a text generation model (e.g., BioGPT) that creates patient education materials or reports, while incorporating a machine learning predictive layer (e.g., using XGBoost) to analyze health data (e.g., electronic records) and predict outcomes like disease progression. Ensure HIPAA compliance in data handling. Provide code for model training, inference, and integration into a web app, optimized for healthcare providers scrambling to integrate AI amid 220% demand growth.
2dcfe74
verified
| ```python | |
| #!/usr/bin/env python3 | |
| """ | |
| Healthcare AI API for Web Integration | |
| FastAPI backend for HIPAA-compliant AI services | |
| """ | |
| from fastapi import FastAPI, HTTPException, Depends, Security | |
| from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials | |
| from pydantic import BaseModel | |
| import uvicorn | |
| from healthcare_ai_finetune import HealthcareAIApp, HIPAACompliantDataHandler | |
| import json | |
| from typing import Optional, List | |
| import logging | |
| # Configure logging | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| # Initialize AI system | |
| healthcare_ai = HealthcareAIApp() | |
| healthcare_ai.initialize_models() | |
| app = FastAPI( | |
| title="Healthcare AI API", | |
| description="HIPAA-compliant AI services for patient education and predictive analytics", | |
| version="1.0.0" | |
| ) | |
| security = HTTPBearer() | |
| class PatientData(BaseModel): | |
| age: int | |
| bmi: float | |
| blood_pressure_systolic: int | |
| blood_pressure_diastolic: int | |
| gender: str | |
| smoking_status: str | |
| diabetes_status: str | |
| condition: str | |
| symptoms: str | |
| class PredictionRequest(BaseModel): | |
| patient_data: PatientData | |
| model_type: str = "both" # "education", "prediction", or "both" | |
| class HealthPrediction(BaseModel): | |
| risk_level: int | |
| confidence: float | |
| recommendations: List[str] | |
| class EducationMaterial(BaseModel): | |
| content: str | |
| condition: str | |
| generated_at: str | |
| class APIResponse(BaseModel): | |
| success: bool | |
| message: str | |
| data: Optional[dict] = None | |
| def verify_token(credentials: HTTPAuthorizationCredentials = Depends(security)): | |
| """Simple token verification - enhance for production""" | |
| valid_tokens = ["healthcare_provider_token_2024"] | |
| if credentials.credentials not in valid_tokens: | |
| raise HTTPException(status_code=401, detail="Invalid token") | |
| return credentials.credentials | |
| async def root(): | |
| return {"message": "Healthcare AI API - HIPAA Compliant"} | |
| async def generate_education_material( | |
| request: PredictionRequest, | |
| token: str = Depends(verify_token) | |
| ): | |
| """Generate patient education materials""" | |
| try: | |
| # Convert patient data to DataFrame format | |
| patient_df = pd.DataFrame([{ | |
| 'age': request.patient_data.age, | |
| 'bmi': request.patient_data.bmi, | |
| 'blood_pressure_systolic': request.patient_data.blood_pressure_systolic, | |
| 'blood_pressure_diastolic': request.patient_data.blood_pressure_diastolic, | |
| 'gender': request.patient_data.gender, | |
| 'smoking_status': request.patient_data.smoking_status, | |
| 'diabetes_status': request.patient_data.diabetes_status | |
| }]) | |
| result = healthcare_ai.process_patient_case( | |
| patient_df, | |
| request.patient_data.condition, | |
| request.patient_data.symptoms | |
| ) | |
| return APIResponse( | |
| success=True, | |
| message="Education material generated successfully", | |
| data={ | |
| "education_material": result["education_material"], | |
| "condition": request.patient_data.condition | |
| ) | |
| except Exception as e: | |
| logger.error(f"Error generating education material: {e}") | |
| raise HTTPException(status_code=500, detail="Internal server error") | |
| async def predict_health_outcomes( | |
| request: PredictionRequest, | |
| token: str = Depends(verify_token) | |
| ): | |
| """Predict health outcomes and risk levels""" | |
| try: | |
| patient_df = pd.DataFrame([{ | |
| 'age': request.patient_data.age, | |
| 'bmi': request.patient_data.bmi, | |
| 'blood_pressure_systolic': request.patient_data.blood_pressure_systolic, | |
| 'blood_pressure_diastolic': request.patient_data.blood_pressure_diastolic, | |
| 'gender': request.patient_data.gender, | |
| 'smoking_status': request.patient_data.smoking_status, | |
| 'diabetes_status': request.patient_data.diabetes_status | |
| }]) | |
| predictions, probabilities = healthcare_ai.health_predictor.predict_health_outcomes(patient_df) | |
| return APIResponse( | |
| success=True, | |
| message="Health prediction completed", | |
| data={ | |
| "risk_prediction": int(predictions[0]), | |
| "confidence_score': float(np.max(probabilities[0])), | |
| 'recommendations': result["treatment_recommendations"] | |
| ) | |
| except Exception as e: | |
| logger.error(f"Error predicting health outcomes: {e}") | |
| raise HTTPException(status_code=500, detail="Internal server error") | |
| @app.post("/api/comprehensive-analysis", response_model=APIResponse) | |
| async def comprehensive_health_analysis( | |
| request: PredictionRequest, | |
| token: str = Depends(verify_token) | |
| ): | |
| """Complete health analysis with education and predictions""" | |
| try: | |
| patient_df = pd.DataFrame([{ | |
| 'age': request.patient_data.age, | |
| 'bmi': request.patient_data.bmi, | |
| 'blood_pressure_systolic': request.patient_data.blood_pressure_systolic, | |
| 'blood_pressure_diastolic': request.patient_data.blood_pressure_diastolic, | |
| 'gender': request.patient_data.gender, | |
| 'smoking_status': request.patient_data.smoking_status, | |
| 'diabetes_status': request.patient_data.diabetes_status | |
| }]) | |
| result = healthcare_ai.process_patient_case( | |
| patient_df, | |
| request.patient_data.condition, | |
| request.patient_data.symptoms | |
| ) | |
| return APIResponse( | |
| success=True, | |
| message="Comprehensive health analysis completed", | |
| data=result | |
| ) | |
| except Exception as e: | |
| logger.error(f"Error in comprehensive analysis: {e}") | |
| raise HTTPException(status_code=500, detail="Internal server error") | |
| @app.get("/api/health") | |
| async def health_check(): | |
| return {"status": "healthy", "service": "healthcare_ai"} | |
| if __name__ == "__main__": | |
| uvicorn.run( | |
| "healthcare_api:app", | |
| host="0.0.0.0", | |
| port=8000, | |
| reload=True | |
| ) | |
| ``` |