Spaces:
Sleeping
Sleeping
File size: 2,501 Bytes
1ccf566 39aa5c5 1ccf566 d0bddfc d859282 d0bddfc 1ccf566 19b05ea d0bddfc d859282 d0bddfc 39aa5c5 d859282 1ccf566 d0bddfc 1ccf566 39aa5c5 1ccf566 39aa5c5 1ccf566 d0bddfc 39aa5c5 1ccf566 39aa5c5 d859282 39aa5c5 d0bddfc d2c9a27 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
import base64
from typing import List, Tuple
from fastapi import FastAPI, UploadFile, File, HTTPException, Request
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.templating import Jinja2Templates
import google.generativeai as genai
# Configure the Google Generative AI API key.
genai.configure(api_key="")
app = FastAPI()
templates = Jinja2Templates(directory="templates")
def generate_content_from_images(images: List[Tuple[str, bytes]]) -> str:
"""
Given a list of tuples (mime_type, image_bytes), encode each image
in base64, build a list of image dicts, append the fixed prompt,
and call the Gemini model.
"""
image_data_list = []
for mime_type, image_bytes in images:
image_data = base64.b64encode(image_bytes).decode("utf-8")
image_data_list.append({'mime_type': mime_type, 'data': image_data})
prompt = """analyse question , analyse option , and give me question , it's options and answer in json format
fixed json format
below is example of json format ,the json structure is same like below
{
\"question\": \"What is the capital of France?\",
\"options\": [
\"a. Berlin\",
\"b. Madrid\",
\"c. Paris\",
\"d. Rome\"
],
\"answer\": \"c\"
}
only json format nothing else"""
payload = image_data_list.copy()
payload.append(prompt)
# Use your exact code snippet.
model = genai.GenerativeModel(model_name="gemini-2.0-flash")
response = model.generate_content(payload)
return response.text
@app.get("/", response_class=HTMLResponse)
async def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.post("/upload", response_class=JSONResponse)
async def upload_images(files: List[UploadFile] = File(...)):
if not files:
raise HTTPException(status_code=400, detail="No files uploaded.")
images = []
for file in files:
if not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="Only image files are accepted.")
image_bytes = await file.read()
images.append((file.content_type, image_bytes))
try:
result = generate_content_from_images(images)
return {"result": result}
except Exception as e:
return JSONResponse(status_code=500, content={"detail": f"Error processing the image(s): {str(e)}"})
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)
|