triflix commited on
Commit
1ccf566
·
verified ·
1 Parent(s): d859282

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +40 -58
main.py CHANGED
@@ -1,81 +1,63 @@
1
- import os
2
- import shutil
3
- import tempfile
4
- from typing import List
5
-
6
- from fastapi import FastAPI, File, UploadFile, Form, HTTPException, Request
7
  from fastapi.responses import JSONResponse, HTMLResponse
8
  from fastapi.templating import Jinja2Templates
9
 
10
  import google.generativeai as genai
 
11
 
12
- # Configure the API key from environment variables.
13
- if not os.environ.get("GOOGLE_API_KEY"):
14
- raise Exception("GOOGLE_API_KEY environment variable not set.")
15
- genai.configure(api_key=os.environ.get("GOOGLE_API_KEY"))
16
-
17
- # Choose the Gemini model.
18
- model = genai.GenerativeModel(model_name="gemini-1.5-pro-latest")
19
 
20
  app = FastAPI()
21
  templates = Jinja2Templates(directory="templates")
22
 
23
-
24
- def generate_content(file_paths: List[str], prompt: str) -> str:
25
- """
26
- Given a list of image file paths and a prompt, call the Gemini model
27
- to generate content. The list provided to generate_content will contain
28
- the image file paths followed by the prompt.
29
- """
30
- # Build the contents list: first the file paths, then the prompt.
31
- contents = file_paths.copy()
32
- contents.append(prompt)
33
 
34
- try:
35
- response = model.generate_content(contents)
36
- if not response or not response.text:
37
- raise Exception("No response text received.")
38
- return response.text
39
- except Exception as e:
40
- print("Error generating content:", e)
41
- raise e
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  @app.get("/", response_class=HTMLResponse)
45
  async def index(request: Request):
46
  return templates.TemplateResponse("index.html", {"request": request})
47
 
48
-
49
  @app.post("/upload", response_class=JSONResponse)
50
- async def upload_images(
51
- prompt: str = Form(...),
52
- files: List[UploadFile] = File(...),
53
- ):
54
- # Validate that each uploaded file is an image.
55
- for file in files:
56
- if not file.content_type.startswith("image/"):
57
- raise HTTPException(status_code=400, detail="Only image files are accepted.")
58
-
59
- temp_dir = tempfile.mkdtemp()
60
- saved_paths = []
61
-
62
  try:
63
- # Save each uploaded image temporarily.
64
- for file in files:
65
- file_path = os.path.join(temp_dir, file.filename)
66
- with open(file_path, "wb") as buffer:
67
- shutil.copyfileobj(file.file, buffer)
68
- saved_paths.append(file_path)
69
-
70
- # Generate the content using the images and prompt.
71
- result = generate_content(saved_paths, prompt)
72
  return {"result": result}
73
  except Exception as e:
74
- return JSONResponse(status_code=500, content={"detail": f"Error processing the image(s): {str(e)}"})
75
- finally:
76
- # Clean up temporary files.
77
- shutil.rmtree(temp_dir, ignore_errors=True)
78
-
79
 
80
  if __name__ == "__main__":
81
  import uvicorn
 
1
+ import base64
2
+ from fastapi import FastAPI, UploadFile, File, HTTPException, Request
 
 
 
 
3
  from fastapi.responses import JSONResponse, HTMLResponse
4
  from fastapi.templating import Jinja2Templates
5
 
6
  import google.generativeai as genai
7
+ import httpx
8
 
9
+ # Configure the Google Generative AI API key.
10
+ genai.configure(api_key="AIzaSyDcYyq3w21iwipYn17wCAQo3AYWhUIGDSI")
 
 
 
 
 
11
 
12
  app = FastAPI()
13
  templates = Jinja2Templates(directory="templates")
14
 
15
+ def generate_content_from_image(image_bytes: bytes) -> str:
16
+ # Encode the image as base64.
17
+ image_data = base64.b64encode(image_bytes).decode("utf-8")
 
 
 
 
 
 
 
18
 
19
+ # Create a prompt
20
+ prompt = """analyse question , analyse option , and give me question , it's options and answer in json format
21
+
22
+ fixed json format
23
+
24
+ below is example of json format ,the json structure is same like below
 
 
25
 
26
+ {
27
+ \"question\": \"What is the capital of France?\",
28
+ \"options\": [
29
+ \"a. Berlin\",
30
+ \"b. Madrid\",
31
+ \"c. Paris\",
32
+ \"d. Rome\"
33
+ ],
34
+ \"answer\": \"c\"
35
+ }
36
+
37
+ only json format nothing else"""
38
+
39
+ # Use the exact code you provided.
40
+ model = genai.GenerativeModel(model_name="gemini-2.0-flash")
41
+ response = model.generate_content([
42
+ {'mime_type': 'image/jpeg', 'data': image_data},
43
+ prompt
44
+ ])
45
+ return response.text
46
 
47
  @app.get("/", response_class=HTMLResponse)
48
  async def index(request: Request):
49
  return templates.TemplateResponse("index.html", {"request": request})
50
 
 
51
  @app.post("/upload", response_class=JSONResponse)
52
+ async def upload_image(file: UploadFile = File(...)):
53
+ if not file.content_type.startswith("image/"):
54
+ raise HTTPException(status_code=400, detail="Only image files are accepted.")
 
 
 
 
 
 
 
 
 
55
  try:
56
+ image_bytes = await file.read()
57
+ result = generate_content_from_image(image_bytes)
 
 
 
 
 
 
 
58
  return {"result": result}
59
  except Exception as e:
60
+ return JSONResponse(status_code=500, content={"detail": f"Error processing the image: {str(e)}"})
 
 
 
 
61
 
62
  if __name__ == "__main__":
63
  import uvicorn