Download src/engine/__init__.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 13.3 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/engine/__init__.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/engine/__init__.py
-
curl -L -o __init__.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/engine/__init__.py
13.3 kB
| """ | |
| YAZ AI Engine - Core AI/ML Services | |
| Provides predictive analytics, clinical decision support, and medical image analysis | |
| """ | |
| from typing import Dict, List, Any, Optional | |
| from datetime import datetime | |
| import numpy as np | |
| from sklearn.base import BaseEstimator | |
| from sklearn.ensemble import RandomForestClassifier | |
| import joblib | |
| import structlog | |
| logger = structlog.get_logger(__name__) | |
| class ClinicalRiskPredictor: | |
| """AI model for clinical risk assessment.""" | |
| def __init__(self, model_path: Optional[str] = None): | |
| self.model = None | |
| self.feature_names = [ | |
| "age", | |
| "bmi", | |
| "systolic_bp", | |
| "diastolic_bp", | |
| "glucose_level", | |
| "cholesterol", | |
| "smoking_status", | |
| "diabetes", | |
| "hypertension", | |
| "cardiac_history", | |
| ] | |
| if model_path: | |
| self.load_model(model_path) | |
| else: | |
| self._create_default_model() | |
| def _create_default_model(self): | |
| """Create a default model for demonstration.""" | |
| self.model = RandomForestClassifier(n_estimators=100, max_depth=10, random_state=42) | |
| logger.info("Created default clinical risk prediction model") | |
| def load_model(self, model_path: str): | |
| """Load trained model from file.""" | |
| try: | |
| self.model = joblib.load(model_path) | |
| logger.info(f"Loaded clinical risk model from {model_path}") | |
| except Exception as e: | |
| logger.error(f"Failed to load model: {e}") | |
| self._create_default_model() | |
| def predict_risk(self, patient_data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Predict clinical risk for a patient.""" | |
| try: | |
| # Extract features from patient data | |
| features = self._extract_features(patient_data) | |
| # Make prediction (placeholder logic for demo) | |
| risk_score = self._calculate_risk_score(features) | |
| risk_level = self._classify_risk_level(risk_score) | |
| return { | |
| "risk_score": risk_score, | |
| "risk_level": risk_level, | |
| "confidence": 0.85, | |
| "factors": self._identify_risk_factors(features), | |
| "recommendations": self._generate_recommendations(risk_level, features), | |
| } | |
| except Exception as e: | |
| logger.error(f"Risk prediction failed: {e}") | |
| return { | |
| "risk_score": 0.0, | |
| "risk_level": "unknown", | |
| "confidence": 0.0, | |
| "factors": [], | |
| "recommendations": ["Consult healthcare provider"], | |
| } | |
| def _extract_features(self, patient_data: Dict[str, Any]) -> np.ndarray: | |
| """Extract features from patient data.""" | |
| features = [] | |
| for feature in self.feature_names: | |
| value = patient_data.get(feature, 0) | |
| if isinstance(value, bool): | |
| value = int(value) | |
| features.append(value) | |
| return np.array(features).reshape(1, -1) | |
| def _calculate_risk_score(self, features: np.ndarray) -> float: | |
| """Calculate risk score (0-100).""" | |
| # Simplified risk calculation for demo | |
| age_factor = features[0, 0] / 100.0 | |
| bp_factor = (features[0, 2] + features[0, 3]) / 200.0 | |
| condition_factor = sum(features[0, 7:]) / 3.0 | |
| risk_score = (age_factor + bp_factor + condition_factor) * 33.33 | |
| return min(max(risk_score, 0.0), 100.0) | |
| def _classify_risk_level(self, risk_score: float) -> str: | |
| """Classify risk level based on score.""" | |
| if risk_score < 25: | |
| return "low" | |
| elif risk_score < 50: | |
| return "medium" | |
| elif risk_score < 75: | |
| return "high" | |
| else: | |
| return "critical" | |
| def _identify_risk_factors(self, features: np.ndarray) -> List[str]: | |
| """Identify primary risk factors.""" | |
| factors = [] | |
| if features[0, 0] > 65: | |
| factors.append("advanced_age") | |
| if features[0, 2] > 140 or features[0, 3] > 90: | |
| factors.append("hypertension") | |
| if features[0, 4] > 126: | |
| factors.append("elevated_glucose") | |
| if features[0, 5] > 240: | |
| factors.append("high_cholesterol") | |
| if features[0, 6] == 1: | |
| factors.append("smoking") | |
| return factors | |
| def _generate_recommendations(self, risk_level: str, features: np.ndarray) -> List[str]: | |
| """Generate personalized recommendations.""" | |
| recommendations = [] | |
| if risk_level in ["high", "critical"]: | |
| recommendations.append("Schedule immediate cardiology consultation") | |
| recommendations.append("Consider medication review") | |
| if features[0, 2] > 140: | |
| recommendations.append("Monitor blood pressure daily") | |
| if features[0, 6] == 1: | |
| recommendations.append("Smoking cessation program") | |
| recommendations.append("Regular follow-up appointments") | |
| recommendations.append("Lifestyle modifications") | |
| return recommendations | |
| class SurgicalOutcomePredictor: | |
| """AI model for surgical outcome prediction.""" | |
| def __init__(self): | |
| self.model = None | |
| self._initialize_model() | |
| def _initialize_model(self): | |
| """Initialize the surgical outcome prediction model.""" | |
| # Placeholder for actual model | |
| self.model = RandomForestClassifier(n_estimators=50, random_state=42) | |
| logger.info("Initialized surgical outcome prediction model") | |
| def predict_outcome(self, surgery_data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Predict surgical outcomes.""" | |
| try: | |
| # Extract relevant features | |
| age = surgery_data.get("patient_age", 50) | |
| procedure_complexity = surgery_data.get("complexity_score", 5) | |
| asa_score = surgery_data.get("asa_score", 2) | |
| duration = surgery_data.get("estimated_duration", 120) | |
| # Calculate complication probability | |
| complication_risk = self._calculate_complication_risk( | |
| age, procedure_complexity, asa_score, duration | |
| ) | |
| return { | |
| "success_probability": 1.0 - complication_risk, | |
| "complication_probability": complication_risk, | |
| "estimated_los": self._estimate_length_of_stay(age, procedure_complexity), | |
| "risk_factors": self._identify_surgical_risks(surgery_data), | |
| "recommendations": self._generate_surgical_recommendations(complication_risk), | |
| } | |
| except Exception as e: | |
| logger.error(f"Surgical outcome prediction failed: {e}") | |
| return self._default_prediction() | |
| def _calculate_complication_risk( | |
| self, age: int, complexity: int, asa: int, duration: int | |
| ) -> float: | |
| """Calculate complication risk based on factors.""" | |
| age_risk = min(age / 100.0, 0.3) | |
| complexity_risk = min(complexity / 20.0, 0.2) | |
| asa_risk = min(asa / 10.0, 0.2) | |
| duration_risk = min(duration / 600.0, 0.1) | |
| total_risk = age_risk + complexity_risk + asa_risk + duration_risk | |
| return min(total_risk, 0.8) | |
| def _estimate_length_of_stay(self, age: int, complexity: int) -> int: | |
| """Estimate post-operative length of stay.""" | |
| base_los = 2 | |
| age_factor = max(0, (age - 60) // 10) | |
| complexity_factor = complexity // 3 | |
| return base_los + age_factor + complexity_factor | |
| def _identify_surgical_risks(self, surgery_data: Dict[str, Any]) -> List[str]: | |
| """Identify surgical risk factors.""" | |
| risks = [] | |
| if surgery_data.get("patient_age", 0) > 75: | |
| risks.append("advanced_age") | |
| if surgery_data.get("asa_score", 1) > 3: | |
| risks.append("high_anesthesia_risk") | |
| if surgery_data.get("complexity_score", 1) > 7: | |
| risks.append("complex_procedure") | |
| if surgery_data.get("emergency", False): | |
| risks.append("emergency_surgery") | |
| return risks | |
| def _generate_surgical_recommendations(self, risk: float) -> List[str]: | |
| """Generate surgical recommendations.""" | |
| recommendations = [] | |
| if risk > 0.3: | |
| recommendations.extend( | |
| [ | |
| "Consider pre-operative optimization", | |
| "Enhanced post-operative monitoring", | |
| "ICU bed availability", | |
| ] | |
| ) | |
| if risk > 0.5: | |
| recommendations.extend( | |
| [ | |
| "Multidisciplinary team consultation", | |
| "Family discussion about risks", | |
| "Consider alternative approaches", | |
| ] | |
| ) | |
| return recommendations | |
| def _default_prediction(self) -> Dict[str, Any]: | |
| """Return default prediction on error.""" | |
| return { | |
| "success_probability": 0.85, | |
| "complication_probability": 0.15, | |
| "estimated_los": 2, | |
| "risk_factors": [], | |
| "recommendations": ["Standard surgical protocol"], | |
| } | |
| class MedicalImageAnalyzer: | |
| """AI for medical image analysis.""" | |
| def __init__(self): | |
| self.models = {} | |
| self._initialize_models() | |
| def _initialize_models(self): | |
| """Initialize image analysis models.""" | |
| # Placeholder for actual medical imaging models | |
| self.models = { | |
| "chest_xray": "ChestXRayClassifier", | |
| "ct_scan": "CTScanAnalyzer", | |
| "mri": "MRIAnalyzer", | |
| "pathology": "PathologyClassifier", | |
| } | |
| logger.info("Initialized medical image analysis models") | |
| def analyze_image(self, image_data: bytes, image_type: str) -> Dict[str, Any]: | |
| """Analyze medical image.""" | |
| try: | |
| if image_type not in self.models: | |
| raise ValueError(f"Unsupported image type: {image_type}") | |
| # Placeholder analysis results | |
| return { | |
| "image_type": image_type, | |
| "findings": self._generate_findings(image_type), | |
| "abnormalities": self._detect_abnormalities(image_type), | |
| "confidence": 0.87, | |
| "recommendations": self._generate_image_recommendations(image_type), | |
| "processed_at": datetime.now().isoformat(), | |
| } | |
| except Exception as e: | |
| logger.error(f"Image analysis failed: {e}") | |
| return self._default_image_analysis() | |
| def _generate_findings(self, image_type: str) -> List[str]: | |
| """Generate image findings based on type.""" | |
| findings_map = { | |
| "chest_xray": ["Clear lung fields", "Normal cardiac silhouette"], | |
| "ct_scan": ["No acute findings", "Normal enhancement pattern"], | |
| "mri": ["Normal signal intensity", "No mass lesions"], | |
| "pathology": ["Benign tissue architecture", "No malignant features"], | |
| } | |
| return findings_map.get(image_type, ["Analysis completed"]) | |
| def _detect_abnormalities(self, image_type: str) -> List[Dict[str, Any]]: | |
| """Detect potential abnormalities.""" | |
| # Placeholder abnormality detection | |
| return [] | |
| def _generate_image_recommendations(self, image_type: str) -> List[str]: | |
| """Generate recommendations based on image analysis.""" | |
| return [ | |
| "Clinical correlation recommended", | |
| "Follow-up as clinically indicated", | |
| "Compare with prior studies if available", | |
| ] | |
| def _default_image_analysis(self) -> Dict[str, Any]: | |
| """Return default analysis on error.""" | |
| return { | |
| "image_type": "unknown", | |
| "findings": ["Analysis unavailable"], | |
| "abnormalities": [], | |
| "confidence": 0.0, | |
| "recommendations": ["Manual review required"], | |
| "processed_at": datetime.now().isoformat(), | |
| } | |
| class AIEngine: | |
| """Main AI engine orchestrating all AI services.""" | |
| def __init__(self): | |
| self.clinical_predictor = ClinicalRiskPredictor() | |
| self.surgical_predictor = SurgicalOutcomePredictor() | |
| self.image_analyzer = MedicalImageAnalyzer() | |
| logger.info("YAZ AI Engine initialized successfully") | |
| def get_clinical_insights(self, patient_data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Get comprehensive clinical insights for a patient.""" | |
| return { | |
| "risk_assessment": self.clinical_predictor.predict_risk(patient_data), | |
| "timestamp": datetime.now().isoformat(), | |
| "version": "1.0.0", | |
| } | |
| def get_surgical_prediction(self, surgery_data: Dict[str, Any]) -> Dict[str, Any]: | |
| """Get surgical outcome predictions.""" | |
| return { | |
| "prediction": self.surgical_predictor.predict_outcome(surgery_data), | |
| "timestamp": datetime.now().isoformat(), | |
| "version": "1.0.0", | |
| } | |
| def analyze_medical_image(self, image_data: bytes, image_type: str) -> Dict[str, Any]: | |
| """Analyze medical images.""" | |
| return self.image_analyzer.analyze_image(image_data, image_type) | |
| # Global AI engine instance | |
| ai_engine = AIEngine() | |