Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, File, UploadFile, Form
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
from transformers import pipeline
|
| 4 |
+
from io import BytesIO
|
| 5 |
+
from PIL import Image
|
| 6 |
+
|
| 7 |
+
app = FastAPI()
|
| 8 |
+
|
| 9 |
+
# Load pipeline once
|
| 10 |
+
pipe = pipeline("image-text-to-text", model="google/medgemma-27b-it")
|
| 11 |
+
|
| 12 |
+
@app.get("/")
|
| 13 |
+
def root():
|
| 14 |
+
return {"message": "MedGemma Image-to-Text API running"}
|
| 15 |
+
|
| 16 |
+
@app.post("/analyze/")
|
| 17 |
+
async def analyze_image(prompt: str = Form(...), file: UploadFile = File(...)):
|
| 18 |
+
try:
|
| 19 |
+
image_data = await file.read()
|
| 20 |
+
image = Image.open(BytesIO(image_data)).convert("RGB")
|
| 21 |
+
|
| 22 |
+
response = pipe([
|
| 23 |
+
{
|
| 24 |
+
"role": "user",
|
| 25 |
+
"content": [
|
| 26 |
+
{"type": "image", "image": image},
|
| 27 |
+
{"type": "text", "text": prompt}
|
| 28 |
+
]
|
| 29 |
+
}
|
| 30 |
+
])
|
| 31 |
+
|
| 32 |
+
return {"result": response[0]['generated_text']}
|
| 33 |
+
|
| 34 |
+
except Exception as e:
|
| 35 |
+
return JSONResponse(status_code=500, content={"error": str(e)})
|