triflix commited on
Commit
d0bddfc
·
verified ·
1 Parent(s): 2ca30b9

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +129 -0
main.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ from fastapi import FastAPI, File, UploadFile, HTTPException, Request
4
+ from fastapi.responses import JSONResponse, HTMLResponse
5
+ from fastapi.templating import Jinja2Templates
6
+
7
+ # Import the required modules from google.genai
8
+ from google import genai
9
+ from google.genai import types
10
+
11
+ app = FastAPI()
12
+ templates = Jinja2Templates(directory="templates")
13
+
14
+ def generate_question(image_path: str) -> str:
15
+ # Initialize the client using your GEMINI_API_KEY environment variable.
16
+ client = genai.Client(api_key=os.environ.get("GEMINI_API_KEY"))
17
+
18
+ # Upload the image file
19
+ files = [client.files.upload(file=image_path)]
20
+ model = "gemini-2.0-flash"
21
+
22
+ # Prepare the content using the image URI and provided sample text
23
+ contents = [
24
+ types.Content(
25
+ role="user",
26
+ parts=[
27
+ types.Part.from_uri(
28
+ file_uri=files[0].uri,
29
+ mime_type=files[0].mime_type,
30
+ ),
31
+ ],
32
+ ),
33
+ types.Content(
34
+ role="model",
35
+ parts=[
36
+ types.Part.from_text(text="""You are absolutely correct! My apologies for the repeated errors. The correct answer is 24 degrees.
37
+
38
+ ```json
39
+ {
40
+ \"question\": \"This horizontal bar chart displays the average daily temperatures recorded for each day of the week. If the temperature on Thursday was increased by 1/4th times of the second highest temperature of the week, what temperature would be experienced on Thursday?\",
41
+ \"options\": [
42
+ \"a. 35°\",
43
+ \"b. 24°\",
44
+ \"c. 18°\",
45
+ \"d. 30°\"
46
+ ],
47
+ \"answer\": \"b\"
48
+ }
49
+ ```"""),
50
+ ],
51
+ ),
52
+ types.Content(
53
+ role="user",
54
+ parts=[
55
+ types.Part.from_text(text="INSERT_INPUT_HERE"),
56
+ ],
57
+ ),
58
+ ]
59
+ tools = [types.Tool(function_declarations=[])]
60
+ generate_content_config = types.GenerateContentConfig(
61
+ temperature=1,
62
+ top_p=0.95,
63
+ top_k=40,
64
+ max_output_tokens=8192,
65
+ tools=tools,
66
+ response_mime_type="text/plain",
67
+ system_instruction=[
68
+ types.Part.from_text(text="""analyse question , analyse option , and give me question , it's options and answer in json format
69
+
70
+ fixed json format
71
+
72
+ below is example of json format ,the json structure is same like below
73
+
74
+ {
75
+ \"question\": \"What is the capital of France?\",
76
+ \"options\": [
77
+ \"a. Berlin\",
78
+ \"b. Madrid\",
79
+ \"c. Paris\",
80
+ \"d. Rome\"
81
+ ],
82
+ \"answer\": \"c\"
83
+ }
84
+
85
+ only json format nothing else
86
+ """),
87
+ ],
88
+ )
89
+
90
+ # Generate content stream and collect the response
91
+ response_text = ""
92
+ for chunk in client.models.generate_content_stream(
93
+ model=model,
94
+ contents=contents,
95
+ config=generate_content_config,
96
+ ):
97
+ if chunk.text:
98
+ response_text += chunk.text
99
+ elif chunk.function_calls:
100
+ response_text += chunk.function_calls[0]
101
+
102
+ return response_text
103
+
104
+ @app.get("/", response_class=HTMLResponse)
105
+ async def index(request: Request):
106
+ return templates.TemplateResponse("index.html", {"request": request})
107
+
108
+ @app.post("/upload", response_class=JSONResponse)
109
+ async def upload_image(file: UploadFile = File(...)):
110
+ if not file.content_type.startswith("image/"):
111
+ raise HTTPException(status_code=400, detail="Only image files are accepted.")
112
+
113
+ # Save uploaded file temporarily
114
+ temp_dir = "temp"
115
+ os.makedirs(temp_dir, exist_ok=True)
116
+ file_path = os.path.join(temp_dir, file.filename)
117
+ with open(file_path, "wb") as buffer:
118
+ shutil.copyfileobj(file.file, buffer)
119
+
120
+ try:
121
+ result = generate_question(file_path)
122
+ finally:
123
+ os.remove(file_path)
124
+
125
+ return {"result": result}
126
+
127
+ if __name__ == "__main__":
128
+ import uvicorn
129
+ uvicorn.run(app, host="0.0.0.0", port=8000)