Spaces:
Runtime error
Runtime error
Upload agents/finding_interpreter.py with huggingface_hub
Browse files8 unmodified lines91011121314151617181920211 unmodified line232425262728292 unmodified lines32333435363738394041424344454647484950515253545556575859606162636465666768697071727324 unmodified lines989910010110210310410510610710810 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541558 unmodified linesfrom .base_agent import BaseAgent, AgentResult# Try to import torch and transformerstry:import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer, AutoProcessorTORCH_AVAILABLE = Trueexcept ImportError:TORCH_AVAILABLE = Falseclass FindingInterpreterAgent(BaseAgent):1 unmodified lineAgent 2: MedGemma Finding InterpreterTakes CXR analysis results and generates clinical interpretationsusing Google's MedGemma model."""def __init__(self, demo_mode: bool = False):2 unmodified linesmodel_name="google/medgemma-4b-it")self.demo_mode = demo_modeself.tokenizer = Nonedef load_model(self) -> bool:"""Load MedGemma model."""if self.demo_mode:self.is_loaded = Truereturn Trueif not TORCH_AVAILABLE:print("Warning: PyTorch not available. Running in demo mode.")self.demo_mode = Trueself.is_loaded = Truereturn Truetry:self.tokenizer = AutoTokenizer.from_pretrained(self.model_name,trust_remote_code=True)# Load with appropriate settings for memory efficiencyself.model = AutoModelForCausalLM.from_pretrained(self.model_name,trust_remote_code=True,torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32,device_map="auto" if torch.cuda.is_available() else None,low_cpu_mem_usage=True)self.model.eval()self.is_loaded = Truereturn Trueexcept Exception as e:print(f"Failed to load MedGemma model: {e}")print("Falling back to demo mode.")self.demo_mode = Trueself.is_loaded = Truereturn True24 unmodified linesfindings = input_data.get("findings", [])region_analysis = input_data.get("region_analysis", {})# Process based on modeif self.demo_mode:interpretation = self._simulate_interpretation(findings, region_analysis, context)else:interpretation = self._run_model_inference(findings, region_analysis, context)processing_time = (time.time() - start_time) * 100010 unmodified linesregion_analysis: Dict,context: Optional[Dict]) -> Dict:"""Run actual MedGemma inference."""try:# Prepare promptprompt = self._build_prompt(findings, region_analysis, context)# Tokenizeinputs = self.tokenizer(prompt, return_tensors="pt")if torch.cuda.is_available():inputs = {k: v.cuda() for k, v in inputs.items()}# Generatewith torch.no_grad():outputs = self.model.generate(**inputs,max_new_tokens=512,temperature=0.3,top_p=0.9,do_sample=True,pad_token_id=self.tokenizer.eos_token_id)# Decoderesponse = self.tokenizer.decode(outputs[0], skip_special_tokens=True)# Parse responsereturn self._parse_model_response(response, findings)except Exception as e:print(f"MedGemma inference error: {e}")return self._simulate_interpretation(findings, region_analysis, context)def _simulate_interpretation(self,findings: List[Dict],8 unmodified lines910111213141516171819201 unmodified line222324252627282 unmodified lines313233343536373839404142434445464748495024 unmodified lines757677787980818283848510 unmodified lines969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621638 unmodified linesfrom .base_agent import BaseAgent, AgentResult# Import the unified MedGemma enginetry:from .medgemma_engine import get_engine, MedGemmaEngineENGINE_AVAILABLE = Trueexcept ImportError:ENGINE_AVAILABLE = Falseclass FindingInterpreterAgent(BaseAgent):1 unmodified lineAgent 2: MedGemma Finding InterpreterTakes CXR analysis results and generates clinical interpretationsusing Google's MedGemma model via the unified engine."""def __init__(self, demo_mode: bool = False):2 unmodified linesmodel_name="google/medgemma-4b-it")self.demo_mode = demo_modeself.engine = Nonedef load_model(self) -> bool:"""Load MedGemma model via unified engine."""if self.demo_mode or not ENGINE_AVAILABLE:self.is_loaded = Truereturn Truetry:self.engine = get_engine(force_demo=self.demo_mode)self.is_loaded = self.engine.is_loadedreturn Trueexcept Exception as e:print(f"Failed to load MedGemma engine: {e}")self.demo_mode = Trueself.is_loaded = Truereturn True24 unmodified linesfindings = input_data.get("findings", [])region_analysis = input_data.get("region_analysis", {})# Process - always try to use real model if availableif self.engine and self.engine.is_loaded and self.engine.backend != "demo":interpretation = self._run_model_inference(findings, region_analysis, context)else:interpretation = self._simulate_interpretation(findings, region_analysis, context)processing_time = (time.time() - start_time) * 100010 unmodified linesregion_analysis: Dict,context: Optional[Dict]) -> Dict:"""Run actual MedGemma inference using the unified engine."""try:clinical_context = context.get("clinical_history", "Not provided") if context else "Not provided"# Generate interpretations for each finding using real MedGemmainterpreted_findings = []for finding in findings:prompt = f"""As a radiologist, interpret this chest X-ray finding:Finding: {finding.get('type', 'Unknown')}Region: {finding.get('region', 'Unknown')}Severity: {finding.get('severity', 'Unknown')}Description: {finding.get('description', 'No description')}Clinical History: {clinical_context}Provide:1. Clinical significance (1-2 sentences)2. Top 3 differential diagnoses3. Recommended follow-upBe concise and clinically relevant."""response = self.engine.generate(prompt, max_tokens=200)interpreted = {"original": finding,"clinical_significance": self._extract_significance(response, finding),"differential_diagnoses": self._get_differentials(finding),"recommended_followup": self._get_followup(finding),"medgemma_interpretation": response,"correlation_notes": f"MedGemma analysis: {response[:100]}..."}interpreted_findings.append(interpreted)# Generate clinical summaryclinical_summary = self._generate_clinical_summary(interpreted_findings, clinical_context)key_concerns = self._identify_key_concerns(interpreted_findings)return {"interpreted_findings": interpreted_findings,"clinical_summary": clinical_summary,"key_concerns": key_concerns,"abnormal_regions": [region for region, data in region_analysis.items()if data.get("status") == "abnormal"],"confidence_level": "high","model_used": f"MedGemma ({self.engine.backend})"}except Exception as e:print(f"MedGemma inference error: {e}")return self._simulate_interpretation(findings, region_analysis, context)def _extract_significance(self, response: str, finding: Dict) -> str:"""Extract clinical significance from MedGemma response."""# Take first meaningful sentencesentences = response.split('.')if sentences and len(sentences[0]) > 10:return sentences[0].strip() + "."return self._get_significance(finding)def _simulate_interpretation(self,findings: List[Dict],
agents/finding_interpreter.py+68-60