triflix's picture
Update main.py
1ccf566 verified
raw
history blame
2.03 kB
import base64
from fastapi import FastAPI, UploadFile, File, HTTPException, Request
from fastapi.responses import JSONResponse, HTMLResponse
from fastapi.templating import Jinja2Templates
import google.generativeai as genai
import httpx
# Configure the Google Generative AI API key.
genai.configure(api_key="AIzaSyDcYyq3w21iwipYn17wCAQo3AYWhUIGDSI")
app = FastAPI()
templates = Jinja2Templates(directory="templates")
def generate_content_from_image(image_bytes: bytes) -> str:
# Encode the image as base64.
image_data = base64.b64encode(image_bytes).decode("utf-8")
# Create a prompt
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"""
# Use the exact code you provided.
model = genai.GenerativeModel(model_name="gemini-2.0-flash")
response = model.generate_content([
{'mime_type': 'image/jpeg', 'data': image_data},
prompt
])
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_image(file: UploadFile = File(...)):
if not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="Only image files are accepted.")
try:
image_bytes = await file.read()
result = generate_content_from_image(image_bytes)
return {"result": result}
except Exception as e:
return JSONResponse(status_code=500, content={"detail": f"Error processing the image: {str(e)}"})
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)