File size: 6,258 Bytes
2dcfe74 |
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 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 |
```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
@app.get("/")
async def root():
return {"message": "Healthcare AI API - HIPAA Compliant"}
@app.post("/api/generate-education", response_model=APIResponse)
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")
@app.post("/api/predict-health", response_model=APIResponse)
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
)
``` |