Spaces:
Sleeping
Sleeping
should work
Browse files15 unmodified lines16171819202122232425262728293031323334353637383940414243444546474849505152535455565758591 unmodified line6162636465666768697071727374757677787980818223 unmodified lines1061071081091101111 unmodified line1131141151161171181191201211221231241251261271281291301311321331341351364 unmodified lines1411421431441451461473 unmodified lines1511521531541551561571581599 unmodified lines16917017117217317420 unmodified lines1951961971981992002012022032042052062071 unmodified line2092102112122132142152162172182192202212222232242252262273 unmodified lines2312322332342352361 unmodified line23823924024115 unmodified linesmodel = Noneprocessor = Nonedevice = Nonedef load_model():"""Load the AI model once at startup"""global model, processor, devicelogger.info("Loading AI model...")# Get Hugging Face token from environmenthf_token = os.environ.get('HF_TOKEN')model_id = "mychen76/paligemma-3b-mix-448-med_30k-ct-brain"device = torch.device("cuda" if torch.cuda.is_available() else "cpu")dtype = torch.float16 if torch.cuda.is_available() else torch.float32logger.info(f"Using device: {device}")try:# Load processor and model with authentication tokenprocessor = AutoProcessor.from_pretrained(model_id,token=hf_token)model = PaliGemmaForConditionalGeneration.from_pretrained(model_id,torch_dtype=dtype,token=hf_token).to(device).eval()logger.info("Model loaded successfully!")return Trueexcept Exception as e:logger.error(f"Error loading model: {e}")return Falsedef analyze_brain_scan(image, patient_name="", patient_age="", symptoms=""):"""Analyze brain scan image and return medical findings"""try:if image is None:return "Please upload a brain scan image."1 unmodified lineif not isinstance(image, Image.Image):image = Image.fromarray(image).convert("RGB")# Run AI inferenceprompt = "<image> Findings:"inputs = processor(images=image,text=prompt,return_tensors="pt").to(device, dtype=torch.float16 if torch.cuda.is_available() else torch.float32)with torch.no_grad():generated_ids = model.generate(**inputs, max_new_tokens=100)result = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]# Clean up the resultif result.startswith(prompt):result = result[len(prompt):].strip()# Format the responsetimestamp = time.strftime("%Y-%m-%d %H:%M:%S")23 unmodified linesdef create_api_response(image, patient_name="", patient_age="", symptoms=""):"""Create API-compatible response for integration"""try:if image is None:return {"error": "No image provided"}1 unmodified lineif not isinstance(image, Image.Image):image = Image.fromarray(image).convert("RGB")# Run AI inferenceprompt = "<image> Findings:"inputs = processor(images=image,text=prompt,return_tensors="pt").to(device, dtype=torch.float16 if torch.cuda.is_available() else torch.float32)with torch.no_grad():generated_ids = model.generate(**inputs, max_new_tokens=100)result = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]# Clean up the resultif result.startswith(prompt):result = result[len(prompt):].strip()# Create API responseresponse = {"prediction": result,"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),4 unmodified lines},"model_info": {"model_id": "mychen76/paligemma-3b-mix-448-med_30k-ct-brain","device": str(device)}}3 unmodified lineslogger.error(f"API error: {e}")return {"error": f"Analysis failed: {str(e)}"}# Load model at startuplogger.info("Initializing Brain CT Analyzer...")if load_model():logger.info("Model loaded successfully!")else:logger.error("Failed to load model!")9 unmodified lines**β οΈ Important:** This is for educational/research purposes only. Always consult qualified medical professionals.""")with gr.Row():with gr.Column(scale=1):image_input = gr.Image(20 unmodified linesanalyze_btn = gr.Button("π Analyze Brain Scan",variant="primary",size="lg")with gr.Column(scale=1):result_output = gr.Markdown(label="Analysis Results",value="Upload an image and click 'Analyze Brain Scan' to see results.")# API endpoint simulation1 unmodified lineapi_output = gr.JSON(label="API Response Format")# Event handlersanalyze_btn.click(fn=analyze_brain_scan,inputs=[image_input, patient_name, patient_age, symptoms],outputs=result_output)analyze_btn.click(fn=create_api_response,inputs=[image_input, patient_name, patient_age, symptoms],outputs=api_output)# Example images (if you have any)gr.Markdown("""## π Usage Instructions:1. Upload a brain CT scan image (JPEG or PNG)3 unmodified lines## π Integration:This interface can be integrated with your medical app using the Gradio API.""")if __name__ == "__main__":1 unmodified lineserver_name="0.0.0.0",server_port=7860,share=True)15 unmodified lines161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081821 unmodified line848586878889909123 unmodified lines1151161171181191201211221231 unmodified line1251261271281291301311321331344 unmodified lines1391401411421431441451463 unmodified lines1501511521531541551561571581591601611621631641651661671681691701711729 unmodified lines18218318418518618718818919019119219320 unmodified lines2142152162172182192202212222232242252262271 unmodified line2292302312322332342352362372382392402412422432442452462472483 unmodified lines2522532542552562572582592601 unmodified line26226326426515 unmodified linesmodel = Noneprocessor = Nonedevice = Nonemodel_loaded = Falsedef load_model():"""Load the AI model exactly like in Colab"""global model, processor, device, model_loadedlogger.info("Loading AI model (Colab style)...")# === Load AI Model === (exactly like Colab)model_id = "mychen76/paligemma-3b-mix-448-med_30k-ct-brain"device = torch.device("cuda" if torch.cuda.is_available() else "cpu")dtype = torch.float16 if torch.cuda.is_available() else torch.float32logger.info(f"Using device: {device}")logger.info(f"Using dtype: {dtype}")logger.info(f"CUDA available: {torch.cuda.is_available()}")try:# Load exactly like Colab (no token, no trust_remote_code)logger.info("Loading processor...")processor = AutoProcessor.from_pretrained(model_id)logger.info("Loading model...")model = PaliGemmaForConditionalGeneration.from_pretrained(model_id,torch_dtype=dtype).to(device).eval()logger.info("Model loaded successfully!")model_loaded = Truereturn Trueexcept Exception as e:logger.error(f"Error loading model: {e}")logger.error(f"Error type: {type(e)}")model_loaded = Falsereturn Falsedef run_model(img):"""Run model inference exactly like Colab"""prompt = "<image> Findings:"inputs = processor(images=img, text=prompt, return_tensors="pt").to(device, dtype=torch.float16 if torch.cuda.is_available() else torch.float32)generated_ids = model.generate(**inputs, max_new_tokens=100)result = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]return resultdef analyze_brain_scan(image, patient_name="", patient_age="", symptoms=""):"""Analyze brain scan image and return medical findings"""try:if not model_loaded or model is None:return """## β οΈ Model Loading ErrorThe AI model is not available. This could be due to:- Model loading issues- Memory limitations- Network connectivityPlease check the logs or try refreshing."""if image is None:return "Please upload a brain scan image."1 unmodified lineif not isinstance(image, Image.Image):image = Image.fromarray(image).convert("RGB")# Run AI inference using Colab methodresult = run_model(image)# Format the responsetimestamp = time.strftime("%Y-%m-%d %H:%M:%S")23 unmodified linesdef create_api_response(image, patient_name="", patient_age="", symptoms=""):"""Create API-compatible response for integration"""try:if not model_loaded or model is None:return {"error": "Model not loaded"}if image is None:return {"error": "No image provided"}1 unmodified lineif not isinstance(image, Image.Image):image = Image.fromarray(image).convert("RGB")# Run AI inference using Colab methodresult = run_model(image)# Create API response (matching your original format)response = {"prediction": result,"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),4 unmodified lines},"model_info": {"model_id": "mychen76/paligemma-3b-mix-448-med_30k-ct-brain","device": str(device),"model_loaded": model_loaded}}3 unmodified lineslogger.error(f"API error: {e}")return {"error": f"Analysis failed: {str(e)}"}def get_model_status():"""Get current model status"""return f"""## π€ Model Status- **Model Loaded**: {model_loaded}- **Device**: {device}- **CUDA Available**: {torch.cuda.is_available()}- **Model Object**: {type(model).__name__ if model else 'None'}- **Processor Object**: {type(processor).__name__ if processor else 'None'}- **PyTorch Version**: {torch.__version__}"""# Load model at startuplogger.info("Initializing Brain CT Analyzer (Colab Style)...")load_success = load_model()if load_success:logger.info("Model loaded successfully!")else:logger.error("Failed to load model!")9 unmodified lines**β οΈ Important:** This is for educational/research purposes only. Always consult qualified medical professionals.""")# Model status sectionwith gr.Accordion("π§ Model Status", open=not model_loaded):status_output = gr.Markdown(value=get_model_status())refresh_btn = gr.Button("π Refresh Status")refresh_btn.click(fn=get_model_status, outputs=status_output)with gr.Row():with gr.Column(scale=1):image_input = gr.Image(20 unmodified linesanalyze_btn = gr.Button("π Analyze Brain Scan",variant="primary",size="lg",interactive=model_loaded)with gr.Column(scale=1):result_output = gr.Markdown(label="Analysis Results",value="Upload an image and click 'Analyze Brain Scan' to see results." if model_loaded else "β οΈ Model not loaded. Check status above.")# API endpoint simulation1 unmodified lineapi_output = gr.JSON(label="API Response Format")# Event handlersif model_loaded:analyze_btn.click(fn=analyze_brain_scan,inputs=[image_input, patient_name, patient_age, symptoms],outputs=result_output)analyze_btn.click(fn=create_api_response,inputs=[image_input, patient_name, patient_age, symptoms],outputs=api_output)# Instructionsgr.Markdown("""## π Usage Instructions:1. Upload a brain CT scan image (JPEG or PNG)3 unmodified lines## π Integration:This interface can be integrated with your medical app using the Gradio API.## β Based on Working Colab Code:This version uses the exact same model loading and inference code as your working Google Colab notebook.""")if __name__ == "__main__":1 unmodified lineserver_name="0.0.0.0",server_port=7860,share=True)
app.py+88-64