Spaces:
Sleeping
Sleeping
updated the code ✅✅
Browse files
app.py
CHANGED
|
@@ -1,60 +1,136 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
-
from transformers import
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
# Gradio Interface
|
| 26 |
-
with gr.Blocks() as app:
|
| 27 |
-
gr.Markdown("
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
)
|
| 32 |
|
| 33 |
with gr.Row():
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
interactive=False
|
| 49 |
-
)
|
| 50 |
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
-
|
|
|
|
| 54 |
fn=generate_response,
|
| 55 |
-
inputs=[image_input, text_input, specialization],
|
| 56 |
-
outputs=[
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
)
|
| 58 |
|
| 59 |
-
|
| 60 |
-
app.launch()
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
|
| 3 |
+
import torch
|
| 4 |
+
import logging
|
| 5 |
+
|
| 6 |
+
# Configure logging
|
| 7 |
+
logging.basicConfig(level=logging.INFO)
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
# Load model and processor with cache
|
| 11 |
+
@gr.Cache()
|
| 12 |
+
def load_model():
|
| 13 |
+
try:
|
| 14 |
+
model = Qwen2VLForConditionalGeneration.from_pretrained(
|
| 15 |
+
"prithivMLmods/Radiology-Infer-Mini",
|
| 16 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 17 |
+
device_map="auto"
|
| 18 |
+
)
|
| 19 |
+
processor = AutoProcessor.from_pretrained("prithivMLmods/Radiology-Infer-Mini")
|
| 20 |
+
return model, processor
|
| 21 |
+
except Exception as e:
|
| 22 |
+
logger.error(f"Error loading model: {e}")
|
| 23 |
+
raise
|
| 24 |
+
|
| 25 |
+
model, processor = load_model()
|
| 26 |
+
|
| 27 |
+
def generate_response(image, text, specialization, history=None):
|
| 28 |
+
"""Generate response combining image and text inputs with proper error handling."""
|
| 29 |
+
try:
|
| 30 |
+
# Validate inputs
|
| 31 |
+
if not image and not text.strip():
|
| 32 |
+
return "⚠️ Please provide either an image or a text query.", history
|
| 33 |
+
|
| 34 |
+
# Prepare messages with specialization context
|
| 35 |
+
messages = [{
|
| 36 |
+
"role": "system",
|
| 37 |
+
"content": f"You are a {specialization} medical assistant. Provide professional, accurate analysis in clear language."
|
| 38 |
+
}]
|
| 39 |
+
|
| 40 |
+
content = []
|
| 41 |
+
if image:
|
| 42 |
+
content.append({"type": "image", "image": image})
|
| 43 |
+
if text.strip():
|
| 44 |
+
content.append({"type": "text", "text": text})
|
| 45 |
+
|
| 46 |
+
messages.append({"role": "user", "content": content})
|
| 47 |
+
|
| 48 |
+
# Process inputs
|
| 49 |
+
inputs = processor(
|
| 50 |
+
text=processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True),
|
| 51 |
+
images=[image] if image else None,
|
| 52 |
+
return_tensors="pt"
|
| 53 |
+
).to(model.device)
|
| 54 |
+
|
| 55 |
+
# Generate response
|
| 56 |
+
generated_ids = model.generate(
|
| 57 |
+
**inputs,
|
| 58 |
+
max_new_tokens=256,
|
| 59 |
+
temperature=0.7,
|
| 60 |
+
repetition_penalty=1.1,
|
| 61 |
+
eos_token_id=processor.tokenizer.eos_token_id
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
response = processor.batch_decode(
|
| 65 |
+
generated_ids[:, inputs.input_ids.shape[1]:],
|
| 66 |
+
skip_special_tokens=True,
|
| 67 |
+
clean_up_tokenization_spaces=False
|
| 68 |
+
)[0]
|
| 69 |
+
|
| 70 |
+
# Format history
|
| 71 |
+
formatted_history = (history or []) + [(text, response)]
|
| 72 |
+
return response, formatted_history
|
| 73 |
+
|
| 74 |
+
except Exception as e:
|
| 75 |
+
logger.error(f"Generation error: {e}")
|
| 76 |
+
return f"❌ Error processing request: {str(e)}", history
|
| 77 |
|
| 78 |
# Gradio Interface
|
| 79 |
+
with gr.Blocks(theme=gr.themes.Soft()) as app:
|
| 80 |
+
gr.Markdown("""
|
| 81 |
+
# 🩺 AI Medical Assistant
|
| 82 |
+
**Upload medical images and ask questions** for analysis in various specialties.
|
| 83 |
+
""")
|
|
|
|
| 84 |
|
| 85 |
with gr.Row():
|
| 86 |
+
with gr.Column(scale=1):
|
| 87 |
+
specialization = gr.Dropdown(
|
| 88 |
+
label="Medical Specialty",
|
| 89 |
+
choices=["General Practice", "Radiology", "Cardiology", "Neurology", "Pediatrics"],
|
| 90 |
+
value="General Practice"
|
| 91 |
+
)
|
| 92 |
+
image_input = gr.Image(type="pil", label="Upload Medical Image", sources=["upload", "clipboard"])
|
| 93 |
+
|
| 94 |
+
with gr.Column(scale=2):
|
| 95 |
+
chatbot = gr.Chatbot(height=400, label="Consultation History")
|
| 96 |
+
text_input = gr.Textbox(
|
| 97 |
+
label="Patient Query",
|
| 98 |
+
placeholder="Describe symptoms or ask about the image...",
|
| 99 |
+
lines=3
|
| 100 |
+
)
|
| 101 |
+
submit_btn = gr.Button("Submit", variant="primary")
|
| 102 |
|
| 103 |
+
# Examples
|
| 104 |
+
gr.Examples(
|
| 105 |
+
examples=[
|
| 106 |
+
["Radiology", "Explain this chest X-ray finding.", "
|
| 107 |
|
| 108 |
+
"],
|
| 109 |
+
["Cardiology", "Interpret these ECG results.", "
|
|
|
|
|
|
|
| 110 |
|
| 111 |
+
"]
|
| 112 |
+
],
|
| 113 |
+
inputs=[specialization, text_input, image_input]
|
| 114 |
+
)
|
| 115 |
|
| 116 |
+
# Event handling
|
| 117 |
+
submit_event = text_input.submit(
|
| 118 |
fn=generate_response,
|
| 119 |
+
inputs=[image_input, text_input, specialization, chatbot],
|
| 120 |
+
outputs=[text_input, chatbot]
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
submit_btn.click(
|
| 124 |
+
fn=generate_response,
|
| 125 |
+
inputs=[image_input, text_input, specialization, chatbot],
|
| 126 |
+
outputs=[text_input, chatbot]
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# Clear inputs after submission
|
| 130 |
+
submit_event.then(
|
| 131 |
+
lambda: ("", None),
|
| 132 |
+
outputs=[text_input, image_input]
|
| 133 |
)
|
| 134 |
|
| 135 |
+
if __name__ == "__main__":
|
| 136 |
+
app.launch(server_name="0.0.0.0" if torch.cuda.is_available() else "127.0.0.0")
|