Update app.py
Browse files
app.py
CHANGED
@@ -1,57 +1,105 @@
|
|
1 |
-
from flask import Flask, request, render_template, jsonify
|
2 |
-
import
|
3 |
import google.generativeai as genai
|
4 |
import os
|
5 |
-
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
app = Flask(__name__)
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
safety_settings
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
]
|
22 |
-
|
23 |
-
GOOGLE_API_KEY = os.environ.get("TOKEN")
|
24 |
-
|
25 |
-
genai.configure(api_key=GOOGLE_API_KEY)
|
26 |
-
|
27 |
-
# Fonction pour interroger Gemini
|
28 |
-
def query_gemini(image_path,prompt_gemini):
|
29 |
-
img = PIL.Image.open(image_path)
|
30 |
-
model = genai.GenerativeModel(
|
31 |
-
model_name="gemini-exp-1206",
|
32 |
-
generation_config=generation_config,
|
33 |
-
safety_settings=safety_settings
|
34 |
-
)
|
35 |
-
try:
|
36 |
-
response = model.generate_content([prompt_gemini, img], request_options={"timeout": 600})
|
37 |
-
#response = "Non disponible pour l'instant"
|
38 |
-
return response.text
|
39 |
-
except Exception as e:
|
40 |
-
return "Non disponible pour l'instant"
|
41 |
|
42 |
-
|
43 |
-
def query_qwen2(image_path, question):
|
44 |
-
try:
|
45 |
-
client = Client("Qwen/Qwen2.5-Math-Demo")
|
46 |
-
result = client.predict(
|
47 |
-
image=handle_file(image_path),
|
48 |
-
sketchpad=None,
|
49 |
-
question=question,
|
50 |
-
api_name="/math_chat_bot"
|
51 |
-
)
|
52 |
-
return result
|
53 |
-
except Exception as e:
|
54 |
-
return str(e)
|
55 |
|
56 |
@app.route('/')
|
57 |
def index():
|
@@ -60,30 +108,48 @@ def index():
|
|
60 |
@app.route('/upload', methods=['POST'])
|
61 |
def upload_image():
|
62 |
if 'image' not in request.files:
|
63 |
-
return jsonify({'error': '
|
64 |
|
65 |
file = request.files['image']
|
66 |
-
|
67 |
-
|
68 |
|
69 |
-
|
70 |
-
|
71 |
-
if file.filename == '':
|
72 |
-
return jsonify({'error': 'Aucun fichier sélectionné'}), 400
|
73 |
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
|
|
|
|
|
|
|
|
81 |
|
|
|
|
|
82 |
os.unlink(temp_file.name)
|
83 |
-
return jsonify({'result': result, 'model': model_choice})
|
84 |
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from flask import Flask, request, render_template, jsonify, send_from_directory
|
2 |
+
from PIL import Image
|
3 |
import google.generativeai as genai
|
4 |
import os
|
5 |
+
import re
|
6 |
+
import matplotlib.pyplot as plt
|
7 |
+
import tempfile
|
8 |
+
from gradio_client import Client, handle_file
|
9 |
+
# import subprocess # Not used
|
10 |
+
from dataclasses import dataclass
|
11 |
+
from typing import List, Optional
|
12 |
+
import logging
|
13 |
|
14 |
+
# Logging configuration
|
15 |
+
logging.basicConfig(level=logging.INFO)
|
16 |
+
logger = logging.getLogger(__name__)
|
17 |
+
|
18 |
+
@dataclass
|
19 |
+
class GeminiConfig:
|
20 |
+
api_key: str
|
21 |
+
generation_config: dict
|
22 |
+
safety_settings: List[dict]
|
23 |
+
model_name: str = "gemini-exp-1206"
|
24 |
+
|
25 |
+
class MathSolver:
|
26 |
+
def __init__(self, gemini_config: GeminiConfig):
|
27 |
+
self.gemini_config = gemini_config
|
28 |
+
genai.configure(api_key=gemini_config.api_key)
|
29 |
+
plt.switch_backend('Agg') # Non-interactive backend
|
30 |
+
|
31 |
+
def query_gemini(self, image_path: str, prompt: str) -> str:
|
32 |
+
try:
|
33 |
+
img = Image.open(image_path)
|
34 |
+
model = genai.GenerativeModel(
|
35 |
+
model_name=self.gemini_config.model_name,
|
36 |
+
generation_config=self.gemini_config.generation_config,
|
37 |
+
safety_settings=self.gemini_config.safety_settings
|
38 |
+
)
|
39 |
+
response = model.generate_content([prompt, img], request_options={"timeout": 600})
|
40 |
+
return response.text
|
41 |
+
except Exception as e:
|
42 |
+
logger.error(f"Gemini Error: {str(e)}")
|
43 |
+
raise
|
44 |
+
|
45 |
+
@staticmethod
|
46 |
+
def query_qwen2(image_path: str, question: str) -> str:
|
47 |
+
try:
|
48 |
+
client = Client("Qwen/Qwen2.5-Math-Demo")
|
49 |
+
return client.predict(
|
50 |
+
image=handle_file(image_path),
|
51 |
+
sketchpad=None,
|
52 |
+
question=question,
|
53 |
+
api_name="/math_chat_bot"
|
54 |
+
)
|
55 |
+
except Exception as e:
|
56 |
+
logger.error(f"Qwen2 Error: {str(e)}")
|
57 |
+
raise
|
58 |
+
|
59 |
+
@staticmethod
|
60 |
+
def extract_and_execute_python_code(text: str) -> Optional[List[str]]:
|
61 |
+
code_blocks = re.findall(r'```python\n(.*?)```', text, re.DOTALL)
|
62 |
+
if not code_blocks:
|
63 |
+
return None
|
64 |
+
|
65 |
+
image_paths = []
|
66 |
+
for code in code_blocks:
|
67 |
+
try:
|
68 |
+
code = "import numpy as np\n" + code
|
69 |
+
# Replace single backslashes with double backslashes
|
70 |
+
code = code.replace("\\", "\\\\")
|
71 |
+
|
72 |
+
with tempfile.NamedTemporaryFile(suffix=".png", delete=False) as tmpfile:
|
73 |
+
plt.figure()
|
74 |
+
exec(code)
|
75 |
+
plt.savefig(tmpfile.name)
|
76 |
+
plt.close()
|
77 |
+
relative_path = os.path.basename(tmpfile.name)
|
78 |
+
image_paths.append(relative_path)
|
79 |
+
except Exception as e:
|
80 |
+
logger.error(f"Error generating graph: {str(e)}")
|
81 |
+
continue
|
82 |
+
|
83 |
+
return image_paths if image_paths else None
|
84 |
+
|
85 |
+
# Application configuration
|
86 |
app = Flask(__name__)
|
87 |
|
88 |
+
gemini_config = GeminiConfig(
|
89 |
+
api_key="AIzaSyD6yZxfVOnh63GXBJjakAupk9aP4CZrgrQ", # Replace with your actual API key
|
90 |
+
generation_config={
|
91 |
+
"temperature": 1,
|
92 |
+
"max_output_tokens": 8192,
|
93 |
+
},
|
94 |
+
safety_settings=[
|
95 |
+
{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_NONE"},
|
96 |
+
{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"},
|
97 |
+
{"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_NONE"},
|
98 |
+
{"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_NONE"},
|
99 |
+
]
|
100 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
101 |
|
102 |
+
math_solver = MathSolver(gemini_config)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
|
104 |
@app.route('/')
|
105 |
def index():
|
|
|
108 |
@app.route('/upload', methods=['POST'])
|
109 |
def upload_image():
|
110 |
if 'image' not in request.files:
|
111 |
+
return jsonify({'error': 'No image provided'}), 400
|
112 |
|
113 |
file = request.files['image']
|
114 |
+
if not file.filename:
|
115 |
+
return jsonify({'error': 'No file selected'}), 400
|
116 |
|
117 |
+
model_choice = request.form.get('model_choice', 'gemini')
|
118 |
+
custom_instruction = request.form.get('custom_instruction', '')
|
|
|
|
|
119 |
|
120 |
+
prompt = f"Solve this math problem. Provide a complete solution using LaTeX. {custom_instruction}"
|
121 |
+
|
122 |
+
try:
|
123 |
+
with tempfile.NamedTemporaryFile(delete=False) as temp_file:
|
124 |
+
file.save(temp_file.name)
|
125 |
+
|
126 |
+
result = (
|
127 |
+
math_solver.query_gemini(temp_file.name, prompt)
|
128 |
+
if model_choice == "mariam's"
|
129 |
+
else math_solver.query_qwen2(temp_file.name, prompt)
|
130 |
+
)
|
131 |
|
132 |
+
# Extract and generate graphs
|
133 |
+
image_paths = math_solver.extract_and_execute_python_code(result)
|
134 |
os.unlink(temp_file.name)
|
|
|
135 |
|
136 |
+
return jsonify({
|
137 |
+
'result': result,
|
138 |
+
'model': model_choice,
|
139 |
+
'image_paths': image_paths,
|
140 |
+
'temp_dir': tempfile.gettempdir()
|
141 |
+
})
|
142 |
+
except Exception as e:
|
143 |
+
logger.error(f"Error processing: {str(e)}")
|
144 |
+
return jsonify({'error': str(e)}), 500
|
145 |
+
|
146 |
+
@app.route('/temp/<path:filename>')
|
147 |
+
def serve_temp_image(filename):
|
148 |
+
try:
|
149 |
+
return send_from_directory(tempfile.gettempdir(), filename)
|
150 |
+
except Exception as e:
|
151 |
+
logger.error(f"Error sending image: {str(e)}")
|
152 |
+
return jsonify({'error': 'Image not found'}), 404
|
153 |
+
|
154 |
+
if __name__ == '__main__':
|
155 |
+
app.run(debug=True)
|