Spaces:
Running
Running
Commit
·
da736bd
1
Parent(s):
f672b04
GRADIO CLIENT MIGRATION:
Browse files
vlm.py
CHANGED
@@ -1,70 +1,54 @@
|
|
1 |
-
# vlm.py
|
2 |
import os, logging, traceback, json, base64
|
3 |
from io import BytesIO
|
4 |
from PIL import Image
|
5 |
-
from huggingface_hub import InferenceClient # Render model on HF hub
|
6 |
-
from transformers import pipeline # Render model on transformers
|
7 |
from translation import translate_query
|
8 |
-
|
9 |
-
|
10 |
-
HF_TOKEN = os.getenv("HF_TOKEN")
|
11 |
-
# client = InferenceClient(provider="auto", api_key=HF_TOKEN) # comment in back
|
12 |
|
13 |
logger = logging.getLogger("vlm-agent")
|
14 |
-
logging.basicConfig(level=logging.INFO, format="%(asctime)s — %(name)s — %(levelname)s — %(message)s", force=True)
|
15 |
|
16 |
-
# ✅ Load
|
17 |
-
|
18 |
-
def
|
19 |
-
global
|
20 |
-
if
|
21 |
-
logger.info("⏳
|
22 |
-
|
23 |
-
logger.info("
|
24 |
-
return
|
25 |
|
26 |
def process_medical_image(base64_image: str, prompt: str = None, lang: str = "EN") -> str:
|
27 |
-
"""
|
28 |
-
Send base64 image + prompt to MedGEMMA and return output.
|
29 |
-
"""
|
30 |
if not prompt:
|
31 |
prompt = "Describe and investigate any clinical findings from this medical image."
|
32 |
-
elif
|
33 |
-
|
34 |
-
|
35 |
try:
|
36 |
-
#
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
#
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
# Beautify
|
60 |
-
result = message.content.strip()
|
61 |
-
logger.info(f"[VLM] MedGemma returned {result}")
|
62 |
-
return result
|
63 |
except Exception as e:
|
64 |
logger.error(f"[VLM] ❌ Exception: {e}")
|
65 |
logger.error(f"[VLM] 🔍 Traceback:\n{traceback.format_exc()}")
|
66 |
-
|
67 |
-
logger.error(f"[VLM] ⚠️ Raw response: {json.dumps(response, default=str, indent=2)}")
|
68 |
-
except:
|
69 |
-
logger.warning("[VLM] ⚠️ Response not serializable.")
|
70 |
-
return f"[VLM] ⚠️ Image diagnosis failed: {str(e)}"
|
|
|
|
|
1 |
import os, logging, traceback, json, base64
|
2 |
from io import BytesIO
|
3 |
from PIL import Image
|
|
|
|
|
4 |
from translation import translate_query
|
5 |
+
from gradio_client import Client, handle_file
|
6 |
+
import tempfile
|
|
|
|
|
7 |
|
8 |
logger = logging.getLogger("vlm-agent")
|
9 |
+
logging.basicConfig(level=logging.INFO, format="%(asctime)s — %(name)s — %(levelname)s — %(message)s", force=True)
|
10 |
|
11 |
+
# ✅ Load Gradio client once
|
12 |
+
gr_client = None
|
13 |
+
def load_gradio_client():
|
14 |
+
global gr_client
|
15 |
+
if gr_client is None:
|
16 |
+
logger.info("[VLM] ⏳ Connecting to MedGEMMA Gradio Space...")
|
17 |
+
gr_client = Client("warshanks/medgemma-4b-it")
|
18 |
+
logger.info("[VLM] Gradio MedGEMMA client ready.")
|
19 |
+
return gr_client
|
20 |
|
21 |
def process_medical_image(base64_image: str, prompt: str = None, lang: str = "EN") -> str:
|
|
|
|
|
|
|
22 |
if not prompt:
|
23 |
prompt = "Describe and investigate any clinical findings from this medical image."
|
24 |
+
elif lang.upper() in {"VI", "ZH"}:
|
25 |
+
prompt = translate_query(prompt, lang.lower())
|
26 |
+
|
27 |
try:
|
28 |
+
# 1️⃣ Decode base64 image to temp file
|
29 |
+
image_data = base64.b64decode(base64_image)
|
30 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmp:
|
31 |
+
tmp.write(image_data)
|
32 |
+
tmp.flush()
|
33 |
+
image_path = tmp.name
|
34 |
+
|
35 |
+
# 2️⃣ Send to Gradio MedGEMMA
|
36 |
+
client = load_gradio_client()
|
37 |
+
logger.info(f"[VLM] Sending prompt: {prompt}")
|
38 |
+
result = client.predict(
|
39 |
+
message={"text": prompt, "files": [handle_file(image_path)]},
|
40 |
+
param_2 = "You analyze medical images and report abnormalities, diseases with clear diagnostic insight."
|
41 |
+
param_3=2048,
|
42 |
+
api_name="/chat"
|
43 |
+
)
|
44 |
+
if isinstance(result, str):
|
45 |
+
logger.info(f"[VLM] ✅ Response: {result}")
|
46 |
+
return result.strip()
|
47 |
+
else:
|
48 |
+
logger.warning(f"[VLM] ⚠️ Unexpected result type: {type(result)} — {result}")
|
49 |
+
return str(result)
|
50 |
+
|
|
|
|
|
|
|
|
|
51 |
except Exception as e:
|
52 |
logger.error(f"[VLM] ❌ Exception: {e}")
|
53 |
logger.error(f"[VLM] 🔍 Traceback:\n{traceback.format_exc()}")
|
54 |
+
return f"[VLM] ⚠️ Failed to process image: {e}"
|
|
|
|
|
|
|
|