Spaces:
Sleeping
Sleeping
Add application file
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241import osimport torchimport timeimport gradio as grimport requestsfrom transformers import AutoProcessor, PaliGemmaForConditionalGenerationfrom PIL import Imagefrom io import BytesIOimport logging
# Configure logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)
# Global variables for modelmodel = Noneprocessor = Nonedevice = None
def load_model(): """Load the AI model once at startup""" global model, processor, device logger.info("Loading AI model...") # Get Hugging Face token from environment hf_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.float32 logger.info(f"Using device: {device}") try: # Load processor and model with authentication token processor = 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 True except Exception as e: logger.error(f"Error loading model: {e}") return False
def 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." # Convert to PIL Image if needed if not isinstance(image, Image.Image): image = Image.fromarray(image).convert("RGB") # Run AI inference prompt = "<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 result if result.startswith(prompt): result = result[len(prompt):].strip() # Format the response timestamp = time.strftime("%Y-%m-%d %H:%M:%S") formatted_result = f"""## Brain CT Analysis Results
**Patient Information:**- Name: {patient_name or 'Not provided'}- Age: {patient_age or 'Not provided'}- Symptoms: {symptoms or 'Not provided'}- Analysis Date: {timestamp}
**AI Findings:**{result}
**Note:** This is an AI-generated analysis for educational purposes only. Always consult with qualified medical professionals for actual diagnosis.""" return formatted_result except Exception as e: logger.error(f"Analysis error: {e}") return f"Error during analysis: {str(e)}"
def 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"} # Convert to PIL Image if needed if not isinstance(image, Image.Image): image = Image.fromarray(image).convert("RGB") # Run AI inference prompt = "<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 result if result.startswith(prompt): result = result[len(prompt):].strip() # Create API response response = { "prediction": result, "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), "patient_info": { "name": patient_name, "age": patient_age, "symptoms": symptoms }, "model_info": { "model_id": "mychen76/paligemma-3b-mix-448-med_30k-ct-brain", "device": str(device) } } return response except Exception as e: logger.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!")
# Create Gradio interfacewith gr.Blocks(title="Brain CT Analyzer", theme=gr.themes.Soft()) as demo: gr.Markdown(""" # π§ Brain CT Analyzer Upload a brain CT scan image for AI-powered analysis. This tool uses the PaliGemma medical model to provide preliminary findings. **β οΈ 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( label="Upload Brain CT Scan", type="pil", height=400 ) with gr.Group(): patient_name = gr.Textbox( label="Patient Name (Optional)", placeholder="Enter patient name" ) patient_age = gr.Textbox( label="Patient Age (Optional)", placeholder="Enter patient age" ) symptoms = gr.Textbox( label="Symptoms (Optional)", placeholder="Describe symptoms", lines=3 ) analyze_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 simulation with gr.Accordion("π API Response (for developers)", open=False): api_output = gr.JSON(label="API Response Format") # Event handlers 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 ) # Example images (if you have any) gr.Markdown(""" ## π Usage Instructions: 1. Upload a brain CT scan image (JPEG or PNG) 2. Optionally fill in patient information 3. Click "Analyze Brain Scan" to get AI findings 4. Review the results in the output panel ## π Integration: This interface can be integrated with your medical app using the Gradio API. """)
if __name__ == "__main__": demo.launch( server_name="0.0.0.0", server_port=7860, share=True ) app.pyAdded+241