Update medgemma_api.py
Browse files- medgemma_api.py +25 -13
medgemma_api.py
CHANGED
|
@@ -2,19 +2,31 @@ import os
|
|
| 2 |
import requests
|
| 3 |
import base64
|
| 4 |
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
|
|
|
| 2 |
import requests
|
| 3 |
import base64
|
| 4 |
|
| 5 |
+
# 获取 Hugging Face Token(已通过 Secrets 设置)
|
| 6 |
+
HUGGINGFACE_API_TOKEN = os.getenv("HUGGINGFACE_TOKEN")
|
| 7 |
+
API_URL = "https://api-inference.huggingface.co/models/google/medgemma-4b-it"
|
| 8 |
+
HEADERS = {"Authorization": f"Bearer {HUGGINGFACE_API_TOKEN}"}
|
| 9 |
|
| 10 |
+
def query_medgemma(image_path, question):
|
| 11 |
+
with open(image_path, "rb") as f:
|
| 12 |
+
image_bytes = f.read()
|
| 13 |
+
encoded_image = base64.b64encode(image_bytes).decode("utf-8")
|
| 14 |
|
| 15 |
+
payload = {
|
| 16 |
+
"inputs": [
|
| 17 |
+
{
|
| 18 |
+
"role": "user",
|
| 19 |
+
"content": [
|
| 20 |
+
{"type": "image", "image": encoded_image},
|
| 21 |
+
{"type": "text", "text": question}
|
| 22 |
+
]
|
| 23 |
+
}
|
| 24 |
+
]
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
response = requests.post(API_URL, headers=HEADERS, json=payload)
|
| 28 |
+
if response.ok:
|
| 29 |
+
return response.json()[0]["generated_text"]
|
| 30 |
+
else:
|
| 31 |
+
return f"Error: {response.text}"
|
| 32 |
|