Spaces:
Sleeping
Sleeping
| 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 | |
| async def index(request: Request): | |
| return templates.TemplateResponse("index.html", {"request": request}) | |
| 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) | |