Update app.py
Browse files
app.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
from flask import Flask, render_template, request, jsonify, Response, stream_with_context
|
| 2 |
-
from google import genai
|
| 3 |
import os
|
| 4 |
from PIL import Image
|
| 5 |
import io
|
|
@@ -9,18 +9,31 @@ import requests
|
|
| 9 |
import threading
|
| 10 |
import uuid
|
| 11 |
import time
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
app = Flask(__name__)
|
| 14 |
|
| 15 |
# API Keys
|
| 16 |
GOOGLE_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 17 |
-
|
|
|
|
| 18 |
TELEGRAM_CHAT_ID = "-1002497861230"
|
| 19 |
|
| 20 |
# Initialize Gemini client
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
|
| 26 |
ppmqth = r"""
|
|
@@ -132,96 +145,285 @@ rend le très espacer. Ça doit être très aéré
|
|
| 132 |
|
| 133 |
"""
|
| 134 |
|
| 135 |
-
|
| 136 |
# Dictionnaire pour stocker les résultats des tâches en cours
|
| 137 |
task_results = {}
|
| 138 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 139 |
def send_to_telegram(image_data, caption="Nouvelle image uploadée"):
|
| 140 |
"""Envoie l'image à un chat Telegram spécifié"""
|
| 141 |
try:
|
| 142 |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendPhoto"
|
| 143 |
files = {'photo': ('image.png', image_data)}
|
| 144 |
data = {'chat_id': TELEGRAM_CHAT_ID, 'caption': caption}
|
| 145 |
-
response = requests.post(url, files=files, data=data)
|
| 146 |
|
| 147 |
if response.status_code == 200:
|
| 148 |
print("Image envoyée avec succès à Telegram")
|
| 149 |
return True
|
| 150 |
else:
|
| 151 |
-
print(f"Erreur lors de l'envoi à Telegram: {response.text}")
|
| 152 |
return False
|
|
|
|
|
|
|
|
|
|
| 153 |
except Exception as e:
|
| 154 |
-
print(f"Exception lors de l'envoi à Telegram: {e}")
|
| 155 |
return False
|
| 156 |
|
| 157 |
-
def send_document_to_telegram(
|
| 158 |
-
"""Envoie un fichier texte à un chat Telegram spécifié"""
|
| 159 |
try:
|
| 160 |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendDocument"
|
| 161 |
-
files =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
data = {'chat_id': TELEGRAM_CHAT_ID, 'caption': caption}
|
| 163 |
-
response = requests.post(url, files=files, data=data)
|
| 164 |
|
| 165 |
if response.status_code == 200:
|
| 166 |
-
print("Document envoyé avec succès
|
| 167 |
return True
|
| 168 |
else:
|
| 169 |
-
print(f"Erreur lors de l'envoi du document à Telegram: {response.text}")
|
| 170 |
return False
|
|
|
|
|
|
|
|
|
|
| 171 |
except Exception as e:
|
| 172 |
-
print(f"Exception lors de l'envoi du document à Telegram: {e}")
|
| 173 |
return False
|
| 174 |
|
|
|
|
| 175 |
def process_image_background(task_id, image_data):
|
| 176 |
-
"""Traite l'image
|
|
|
|
| 177 |
try:
|
| 178 |
-
# Mettre à jour le statut
|
| 179 |
task_results[task_id]['status'] = 'processing'
|
| 180 |
|
| 181 |
-
|
|
|
|
|
|
|
| 182 |
img = Image.open(io.BytesIO(image_data))
|
| 183 |
-
|
| 184 |
-
# Traitement pour Gemini
|
| 185 |
buffered = io.BytesIO()
|
| 186 |
-
img.save(buffered, format="PNG")
|
| 187 |
-
|
| 188 |
|
| 189 |
-
|
| 190 |
-
full_response = ""
|
| 191 |
|
| 192 |
try:
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
contents=[
|
| 196 |
-
{'inline_data': {'mime_type': 'image/png', 'data': img_str}},
|
| 197 |
-
ppmqth
|
| 198 |
-
])
|
| 199 |
-
|
| 200 |
-
# Extraire le texte complet
|
| 201 |
-
for part in response.candidates[0].content.parts:
|
| 202 |
-
full_response += part.text
|
| 203 |
|
| 204 |
-
#
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
task_results[task_id]['response'] = full_response
|
| 214 |
|
| 215 |
-
|
| 216 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
task_results[task_id]['status'] = 'error'
|
| 218 |
-
task_results[task_id]['error'] = str(
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
|
|
|
|
|
|
|
|
|
| 224 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
@app.route('/')
|
| 226 |
def index():
|
| 227 |
return render_template('index.html')
|
|
@@ -229,105 +431,115 @@ def index():
|
|
| 229 |
@app.route('/solve', methods=['POST'])
|
| 230 |
def solve():
|
| 231 |
try:
|
| 232 |
-
|
| 233 |
-
|
| 234 |
|
| 235 |
-
|
| 236 |
-
|
|
|
|
|
|
|
|
|
|
| 237 |
|
| 238 |
-
#
|
| 239 |
-
|
| 240 |
|
| 241 |
-
|
| 242 |
task_results[task_id] = {
|
| 243 |
'status': 'pending',
|
| 244 |
'response': '',
|
|
|
|
| 245 |
'time_started': time.time()
|
| 246 |
}
|
| 247 |
|
| 248 |
-
# Lancer le traitement en arrière-plan
|
| 249 |
threading.Thread(
|
| 250 |
target=process_image_background,
|
| 251 |
args=(task_id, image_data)
|
| 252 |
).start()
|
| 253 |
|
| 254 |
-
# Retourner immédiatement l'ID de la tâche
|
| 255 |
return jsonify({
|
| 256 |
'task_id': task_id,
|
| 257 |
'status': 'pending'
|
| 258 |
})
|
| 259 |
|
| 260 |
except Exception as e:
|
| 261 |
-
print(f"Exception
|
| 262 |
-
return jsonify({'error': 'Une erreur
|
| 263 |
|
| 264 |
@app.route('/task/<task_id>', methods=['GET'])
|
| 265 |
def get_task_status(task_id):
|
| 266 |
-
"""Récupère le statut d'une tâche en cours"""
|
| 267 |
if task_id not in task_results:
|
| 268 |
return jsonify({'error': 'Tâche introuvable'}), 404
|
| 269 |
|
| 270 |
task = task_results[task_id]
|
| 271 |
|
| 272 |
-
#
|
| 273 |
current_time = time.time()
|
| 274 |
-
if
|
| 275 |
-
|
| 276 |
-
#
|
| 277 |
-
|
|
|
|
| 278 |
|
| 279 |
-
|
| 280 |
-
'status': task['status']
|
|
|
|
|
|
|
| 281 |
}
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
response['error'] = task.get('error', 'Une erreur inconnue est survenue')
|
| 287 |
-
|
| 288 |
-
return jsonify(response)
|
| 289 |
|
| 290 |
@app.route('/stream/<task_id>', methods=['GET'])
|
| 291 |
def stream_task_progress(task_id):
|
| 292 |
-
"""Stream les mises à jour de progression d'une tâche"""
|
| 293 |
def generate():
|
| 294 |
if task_id not in task_results:
|
| 295 |
-
yield f'data: {json.dumps({"error": "Tâche introuvable"})}\n\n'
|
| 296 |
return
|
| 297 |
|
| 298 |
-
|
| 299 |
while True:
|
| 300 |
task = task_results.get(task_id)
|
| 301 |
-
if not task:
|
| 302 |
-
yield f'data: {json.dumps({"error": "Tâche
|
| 303 |
break
|
| 304 |
|
| 305 |
current_status = task['status']
|
| 306 |
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
yield f'data: {json.dumps({"status": "completed", "response": task["response"]})}\n\n'
|
| 315 |
-
break
|
| 316 |
-
elif current_status == 'error':
|
| 317 |
-
yield f'data: {json.dumps({"status": "error", "error": task.get("error", "Une erreur est survenue")})}\n\n'
|
| 318 |
-
break
|
| 319 |
|
| 320 |
-
#
|
| 321 |
-
time.sleep(0.5)
|
| 322 |
|
| 323 |
return Response(
|
| 324 |
stream_with_context(generate()),
|
| 325 |
mimetype='text/event-stream',
|
| 326 |
headers={
|
| 327 |
'Cache-Control': 'no-cache',
|
| 328 |
-
'X-Accel-Buffering': 'no'
|
|
|
|
| 329 |
}
|
| 330 |
)
|
| 331 |
|
| 332 |
if __name__ == '__main__':
|
| 333 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from flask import Flask, render_template, request, jsonify, Response, stream_with_context
|
| 2 |
+
from google import genai # User's import
|
| 3 |
import os
|
| 4 |
from PIL import Image
|
| 5 |
import io
|
|
|
|
| 9 |
import threading
|
| 10 |
import uuid
|
| 11 |
import time
|
| 12 |
+
import tempfile # Added
|
| 13 |
+
import subprocess # Added
|
| 14 |
+
import shutil # Added
|
| 15 |
+
# import platform # Not strictly needed for app.py modifications
|
| 16 |
+
import re # Added
|
| 17 |
|
| 18 |
app = Flask(__name__)
|
| 19 |
|
| 20 |
# API Keys
|
| 21 |
GOOGLE_API_KEY = os.environ.get("GEMINI_API_KEY")
|
| 22 |
+
# IMPORTANT: For production, move these to environment variables or a secure config
|
| 23 |
+
TELEGRAM_BOT_TOKEN = "8004545342:AAGcZaoDjYg8dmbbXRsR1N3TfSSbEiAGz88"
|
| 24 |
TELEGRAM_CHAT_ID = "-1002497861230"
|
| 25 |
|
| 26 |
# Initialize Gemini client
|
| 27 |
+
# Assuming genai.Client and client.models.generate_content are part of user's specific library setup
|
| 28 |
+
if GOOGLE_API_KEY:
|
| 29 |
+
try:
|
| 30 |
+
client = genai.Client(api_key=GOOGLE_API_KEY)
|
| 31 |
+
except Exception as e:
|
| 32 |
+
print(f"Erreur lors de l'initialisation du client Gemini: {e}")
|
| 33 |
+
client = None
|
| 34 |
+
else:
|
| 35 |
+
print("GEMINI_API_KEY non trouvé. Le client Gemini ne sera pas initialisé.")
|
| 36 |
+
client = None
|
| 37 |
|
| 38 |
|
| 39 |
ppmqth = r"""
|
|
|
|
| 145 |
|
| 146 |
"""
|
| 147 |
|
|
|
|
| 148 |
# Dictionnaire pour stocker les résultats des tâches en cours
|
| 149 |
task_results = {}
|
| 150 |
|
| 151 |
+
# --- LaTeX Helper Functions ---
|
| 152 |
+
def check_latex_installation():
|
| 153 |
+
"""Vérifie si pdflatex est installé sur le système"""
|
| 154 |
+
try:
|
| 155 |
+
# Using timeout to prevent hanging if pdflatex is unresponsive
|
| 156 |
+
subprocess.run(["pdflatex", "-version"], capture_output=True, check=True, timeout=10)
|
| 157 |
+
print("INFO: pdflatex est installé et accessible.")
|
| 158 |
+
return True
|
| 159 |
+
except (FileNotFoundError, subprocess.TimeoutExpired, subprocess.CalledProcessError) as e:
|
| 160 |
+
print(f"AVERTISSEMENT: pdflatex n'est pas installé ou ne fonctionne pas correctement: {e}")
|
| 161 |
+
print("AVERTISSEMENT: La génération de PDF sera désactivée. Seuls les fichiers .tex seront envoyés.")
|
| 162 |
+
return False
|
| 163 |
+
|
| 164 |
+
IS_LATEX_INSTALLED = check_latex_installation()
|
| 165 |
+
|
| 166 |
+
def clean_latex_code(latex_code):
|
| 167 |
+
"""Removes markdown code block fences (```latex ... ``` or ``` ... ```) if present."""
|
| 168 |
+
# Pattern for ```latex ... ```
|
| 169 |
+
match_latex = re.search(r"```(?:latex|tex)\s*(.*?)\s*```", latex_code, re.DOTALL | re.IGNORECASE)
|
| 170 |
+
if match_latex:
|
| 171 |
+
return match_latex.group(1).strip()
|
| 172 |
+
|
| 173 |
+
# Pattern for generic ``` ... ```, checking if it likely contains LaTeX
|
| 174 |
+
match_generic = re.search(r"```\s*(\\documentclass.*?)\s*```", latex_code, re.DOTALL | re.IGNORECASE)
|
| 175 |
+
if match_generic:
|
| 176 |
+
return match_generic.group(1).strip()
|
| 177 |
+
|
| 178 |
+
return latex_code.strip() # Default to stripping whitespace if no fences found
|
| 179 |
+
|
| 180 |
+
def latex_to_pdf(latex_code, output_filename_base="document"):
|
| 181 |
+
"""
|
| 182 |
+
Converts LaTeX code to PDF.
|
| 183 |
+
Returns: path_to_final_pdf (str) or None if error, message (str)
|
| 184 |
+
The returned path_to_final_pdf is a temporary file that the caller is responsible for deleting.
|
| 185 |
+
"""
|
| 186 |
+
if not IS_LATEX_INSTALLED:
|
| 187 |
+
return None, "pdflatex n'est pas disponible sur le système."
|
| 188 |
+
|
| 189 |
+
# Create a temporary directory for LaTeX compilation files
|
| 190 |
+
with tempfile.TemporaryDirectory() as temp_dir_compile:
|
| 191 |
+
tex_filename = f"{output_filename_base}.tex"
|
| 192 |
+
tex_path = os.path.join(temp_dir_compile, tex_filename)
|
| 193 |
+
pdf_path_in_compile_dir = os.path.join(temp_dir_compile, f"{output_filename_base}.pdf")
|
| 194 |
+
|
| 195 |
+
try:
|
| 196 |
+
with open(tex_path, "w", encoding="utf-8") as tex_file:
|
| 197 |
+
tex_file.write(latex_code)
|
| 198 |
+
|
| 199 |
+
my_env = os.environ.copy()
|
| 200 |
+
my_env["LC_ALL"] = "C.UTF-8" # Ensure UTF-8 locale for pdflatex
|
| 201 |
+
my_env["LANG"] = "C.UTF-8"
|
| 202 |
+
|
| 203 |
+
last_result = None
|
| 204 |
+
for i in range(2): # Run pdflatex twice for references, TOC, etc.
|
| 205 |
+
# Added -file-line-error for more precise error messages
|
| 206 |
+
# Added -halt-on-error to stop on first error (more efficient)
|
| 207 |
+
# Note: -halt-on-error might prevent a second pass that could fix some issues.
|
| 208 |
+
# For robustness, -interaction=nonstopmode is often preferred to try to complete.
|
| 209 |
+
process = subprocess.run(
|
| 210 |
+
["pdflatex", "-interaction=nonstopmode", "-output-directory", temp_dir_compile, tex_path],
|
| 211 |
+
capture_output=True, # Capture stdout and stderr
|
| 212 |
+
text=True, # Decode output as text
|
| 213 |
+
check=False, # Do not raise exception on non-zero exit code
|
| 214 |
+
encoding="utf-8", # Specify encoding for output decoding
|
| 215 |
+
errors="replace", # Replace undecodable characters
|
| 216 |
+
env=my_env,
|
| 217 |
+
timeout=120 # Timeout for pdflatex execution (e.g., 2 minutes)
|
| 218 |
+
)
|
| 219 |
+
last_result = process
|
| 220 |
+
if not os.path.exists(pdf_path_in_compile_dir) and process.returncode != 0:
|
| 221 |
+
# If PDF not created and there was an error, no point in second pass
|
| 222 |
+
break
|
| 223 |
+
|
| 224 |
+
if os.path.exists(pdf_path_in_compile_dir):
|
| 225 |
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as temp_pdf_out_file:
|
| 226 |
+
shutil.copy(pdf_path_in_compile_dir, temp_pdf_out_file.name)
|
| 227 |
+
final_pdf_path = temp_pdf_out_file.name
|
| 228 |
+
return final_pdf_path, f"PDF généré avec succès: {os.path.basename(final_pdf_path)}"
|
| 229 |
+
else:
|
| 230 |
+
error_log = last_result.stdout + "\n" + last_result.stderr if last_result else "Aucun résultat de compilation."
|
| 231 |
+
|
| 232 |
+
# Try to extract more specific error messages
|
| 233 |
+
if "LaTeX Error: File `" in error_log:
|
| 234 |
+
match = re.search(r"LaTeX Error: File `(.*?)' not found.", error_log)
|
| 235 |
+
if match:
|
| 236 |
+
return None, f"Erreur de compilation PDF: Fichier LaTeX manquant '{match.group(1)}'. Assurez-vous que tous les packages nécessaires (comme fontawesome5) sont installés."
|
| 237 |
+
|
| 238 |
+
if "! Undefined control sequence." in error_log:
|
| 239 |
+
return None, "Erreur de compilation PDF: Commande LaTeX non définie. Vérifiez le code LaTeX pour des erreurs de syntaxe."
|
| 240 |
+
|
| 241 |
+
if "! LaTeX Error:" in error_log:
|
| 242 |
+
match = re.search(r"! LaTeX Error: (.*?)\n", error_log) # Get first line of error
|
| 243 |
+
if match:
|
| 244 |
+
return None, f"Erreur de compilation PDF: {match.group(1).strip()}"
|
| 245 |
+
|
| 246 |
+
# Generic error if specific parsing fails
|
| 247 |
+
log_preview = error_log[-1000:] # Last 1000 characters of log for preview
|
| 248 |
+
print(f"Erreur de compilation PDF complète pour {output_filename_base}:\n{error_log}")
|
| 249 |
+
return None, f"Erreur lors de la compilation du PDF. Détails dans les logs du serveur. Aperçu: ...{log_preview}"
|
| 250 |
+
|
| 251 |
+
except subprocess.TimeoutExpired:
|
| 252 |
+
print(f"Timeout lors de la compilation de {output_filename_base}.tex")
|
| 253 |
+
return None, "Timeout lors de la compilation du PDF. Le document est peut-être trop complexe ou contient une boucle infinie."
|
| 254 |
+
except Exception as e:
|
| 255 |
+
print(f"Exception inattendue lors de la génération du PDF ({output_filename_base}): {e}")
|
| 256 |
+
return None, f"Exception inattendue lors de la génération du PDF: {str(e)}"
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
# --- Telegram Functions ---
|
| 260 |
def send_to_telegram(image_data, caption="Nouvelle image uploadée"):
|
| 261 |
"""Envoie l'image à un chat Telegram spécifié"""
|
| 262 |
try:
|
| 263 |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendPhoto"
|
| 264 |
files = {'photo': ('image.png', image_data)}
|
| 265 |
data = {'chat_id': TELEGRAM_CHAT_ID, 'caption': caption}
|
| 266 |
+
response = requests.post(url, files=files, data=data, timeout=30)
|
| 267 |
|
| 268 |
if response.status_code == 200:
|
| 269 |
print("Image envoyée avec succès à Telegram")
|
| 270 |
return True
|
| 271 |
else:
|
| 272 |
+
print(f"Erreur lors de l'envoi à Telegram: {response.status_code} - {response.text}")
|
| 273 |
return False
|
| 274 |
+
except requests.exceptions.RequestException as e:
|
| 275 |
+
print(f"Exception Request lors de l'envoi à Telegram: {e}")
|
| 276 |
+
return False
|
| 277 |
except Exception as e:
|
| 278 |
+
print(f"Exception générale lors de l'envoi à Telegram: {e}")
|
| 279 |
return False
|
| 280 |
|
| 281 |
+
def send_document_to_telegram(content_or_path, filename="reponse.txt", caption="Réponse", is_pdf=False):
|
| 282 |
+
"""Envoie un fichier (texte ou PDF) à un chat Telegram spécifié"""
|
| 283 |
try:
|
| 284 |
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendDocument"
|
| 285 |
+
files = None
|
| 286 |
+
|
| 287 |
+
if is_pdf:
|
| 288 |
+
with open(content_or_path, 'rb') as f_pdf:
|
| 289 |
+
files = {'document': (filename, f_pdf.read(), 'application/pdf')}
|
| 290 |
+
else: # Assuming text content
|
| 291 |
+
files = {'document': (filename, content_or_path.encode('utf-8'), 'text/plain')}
|
| 292 |
+
|
| 293 |
data = {'chat_id': TELEGRAM_CHAT_ID, 'caption': caption}
|
| 294 |
+
response = requests.post(url, files=files, data=data, timeout=60) # Increased timeout for larger files
|
| 295 |
|
| 296 |
if response.status_code == 200:
|
| 297 |
+
print(f"Document '{filename}' envoyé avec succès à Telegram.")
|
| 298 |
return True
|
| 299 |
else:
|
| 300 |
+
print(f"Erreur lors de l'envoi du document '{filename}' à Telegram: {response.status_code} - {response.text}")
|
| 301 |
return False
|
| 302 |
+
except requests.exceptions.RequestException as e:
|
| 303 |
+
print(f"Exception Request lors de l'envoi du document '{filename}' à Telegram: {e}")
|
| 304 |
+
return False
|
| 305 |
except Exception as e:
|
| 306 |
+
print(f"Exception générale lors de l'envoi du document '{filename}' à Telegram: {e}")
|
| 307 |
return False
|
| 308 |
|
| 309 |
+
# --- Background Image Processing ---
|
| 310 |
def process_image_background(task_id, image_data):
|
| 311 |
+
"""Traite l'image, génère LaTeX, convertit en PDF (si possible), et envoie via Telegram."""
|
| 312 |
+
pdf_file_to_clean = None
|
| 313 |
try:
|
|
|
|
| 314 |
task_results[task_id]['status'] = 'processing'
|
| 315 |
|
| 316 |
+
if not client:
|
| 317 |
+
raise ConnectionError("Client Gemini non initialisé. Vérifiez la clé API et la configuration.")
|
| 318 |
+
|
| 319 |
img = Image.open(io.BytesIO(image_data))
|
|
|
|
|
|
|
| 320 |
buffered = io.BytesIO()
|
| 321 |
+
img.save(buffered, format="PNG") # Gemini prefers PNG or JPEG
|
| 322 |
+
img_base64_str = base64.b64encode(buffered.getvalue()).decode()
|
| 323 |
|
| 324 |
+
full_latex_response = ""
|
|
|
|
| 325 |
|
| 326 |
try:
|
| 327 |
+
task_results[task_id]['status'] = 'generating_latex'
|
| 328 |
+
print(f"Task {task_id}: Génération LaTeX par Gemini...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
|
| 330 |
+
# User's original model: "gemini-2.5-pro-exp-03-25"
|
| 331 |
+
# Using "gemini-1.5-pro-latest" as a robust alternative. User can change if needed.
|
| 332 |
+
# The user's original Gemini call structure:
|
| 333 |
+
gemini_response = client.models.generate_content(
|
| 334 |
+
model="gemini-1.5-pro-latest",
|
| 335 |
+
contents=[
|
| 336 |
+
{'inline_data': {'mime_type': 'image/png', 'data': img_base64_str}},
|
| 337 |
+
ppmqth
|
| 338 |
+
]
|
| 339 |
+
# Consider adding generation_config for token limits, temperature if needed
|
| 340 |
+
# generation_config=genai.types.GenerationConfig(max_output_tokens=8192)
|
| 341 |
)
|
| 342 |
+
|
| 343 |
+
if gemini_response.candidates:
|
| 344 |
+
candidate = gemini_response.candidates[0]
|
| 345 |
+
if candidate.content and candidate.content.parts:
|
| 346 |
+
for part in candidate.content.parts:
|
| 347 |
+
if hasattr(part, 'text') and part.text:
|
| 348 |
+
full_latex_response += part.text
|
| 349 |
+
elif hasattr(candidate, 'text') and candidate.text: # Fallback for simpler candidate structure
|
| 350 |
+
full_latex_response = candidate.text
|
| 351 |
+
elif hasattr(gemini_response, 'text') and gemini_response.text: # Fallback for direct response.text
|
| 352 |
+
full_latex_response = gemini_response.text
|
| 353 |
|
| 354 |
+
if not full_latex_response.strip():
|
| 355 |
+
raise ValueError("Gemini a retourné une réponse vide ou sans contenu textuel.")
|
|
|
|
| 356 |
|
| 357 |
+
print(f"Task {task_id}: LaTeX brut reçu de Gemini (longueur: {len(full_latex_response)}).")
|
| 358 |
+
|
| 359 |
+
task_results[task_id]['status'] = 'cleaning_latex'
|
| 360 |
+
cleaned_latex = clean_latex_code(full_latex_response)
|
| 361 |
+
print(f"Task {task_id}: LaTeX nettoyé (longueur: {len(cleaned_latex)}).")
|
| 362 |
+
|
| 363 |
+
if not IS_LATEX_INSTALLED:
|
| 364 |
+
print(f"Task {task_id}: pdflatex non disponible. Envoi du .tex uniquement.")
|
| 365 |
+
send_document_to_telegram(
|
| 366 |
+
cleaned_latex,
|
| 367 |
+
filename=f"solution_{task_id}.tex",
|
| 368 |
+
caption=f"Code LaTeX pour tâche {task_id} (pdflatex non disponible)"
|
| 369 |
+
)
|
| 370 |
+
task_results[task_id]['status'] = 'completed_tex_only'
|
| 371 |
+
task_results[task_id]['response'] = cleaned_latex
|
| 372 |
+
return
|
| 373 |
+
|
| 374 |
+
task_results[task_id]['status'] = 'generating_pdf'
|
| 375 |
+
print(f"Task {task_id}: Génération du PDF...")
|
| 376 |
+
pdf_filename_base = f"solution_{task_id}"
|
| 377 |
+
pdf_file_to_clean, pdf_message = latex_to_pdf(cleaned_latex, output_filename_base=pdf_filename_base)
|
| 378 |
+
|
| 379 |
+
if pdf_file_to_clean:
|
| 380 |
+
print(f"Task {task_id}: PDF généré: {pdf_file_to_clean}. Envoi à Telegram...")
|
| 381 |
+
send_document_to_telegram(
|
| 382 |
+
pdf_file_to_clean,
|
| 383 |
+
filename=f"{pdf_filename_base}.pdf",
|
| 384 |
+
caption=f"Solution PDF pour tâche {task_id}",
|
| 385 |
+
is_pdf=True
|
| 386 |
+
)
|
| 387 |
+
task_results[task_id]['status'] = 'completed'
|
| 388 |
+
task_results[task_id]['response'] = cleaned_latex # Web UI still gets LaTeX source
|
| 389 |
+
else:
|
| 390 |
+
print(f"Task {task_id}: Échec de la génération PDF: {pdf_message}. Envoi du .tex en fallback.")
|
| 391 |
+
task_results[task_id]['status'] = 'pdf_error'
|
| 392 |
+
task_results[task_id]['error_detail'] = f"Erreur PDF: {pdf_message}" # Store PDF specific error
|
| 393 |
+
send_document_to_telegram(
|
| 394 |
+
cleaned_latex,
|
| 395 |
+
filename=f"solution_{task_id}.tex",
|
| 396 |
+
caption=f"Code LaTeX pour tâche {task_id} (Erreur PDF: {pdf_message[:150]})"
|
| 397 |
+
)
|
| 398 |
+
task_results[task_id]['response'] = cleaned_latex # Web UI gets LaTeX source
|
| 399 |
+
|
| 400 |
+
except Exception as e_gen:
|
| 401 |
+
print(f"Task {task_id}: Erreur lors de la génération Gemini ou traitement PDF: {e_gen}")
|
| 402 |
task_results[task_id]['status'] = 'error'
|
| 403 |
+
task_results[task_id]['error'] = f"Erreur de traitement: {str(e_gen)}"
|
| 404 |
+
# Optionally send a simple text error to Telegram
|
| 405 |
+
send_document_to_telegram(
|
| 406 |
+
f"Erreur lors du traitement de la tâche {task_id}: {str(e_gen)}",
|
| 407 |
+
filename=f"error_{task_id}.txt",
|
| 408 |
+
caption=f"Erreur Tâche {task_id}"
|
| 409 |
+
)
|
| 410 |
+
task_results[task_id]['response'] = f"Erreur: {str(e_gen)}"
|
| 411 |
+
|
| 412 |
|
| 413 |
+
except Exception as e_outer:
|
| 414 |
+
print(f"Task {task_id}: Exception majeure dans la tâche de fond: {e_outer}")
|
| 415 |
+
task_results[task_id]['status'] = 'error'
|
| 416 |
+
task_results[task_id]['error'] = f"Erreur système: {str(e_outer)}"
|
| 417 |
+
task_results[task_id]['response'] = f"Erreur système: {str(e_outer)}"
|
| 418 |
+
finally:
|
| 419 |
+
if pdf_file_to_clean and os.path.exists(pdf_file_to_clean):
|
| 420 |
+
try:
|
| 421 |
+
os.remove(pdf_file_to_clean)
|
| 422 |
+
print(f"Task {task_id}: Fichier PDF temporaire '{pdf_file_to_clean}' supprimé.")
|
| 423 |
+
except Exception as e_clean:
|
| 424 |
+
print(f"Task {task_id}: Erreur lors de la suppression du PDF temporaire '{pdf_file_to_clean}': {e_clean}")
|
| 425 |
+
|
| 426 |
+
# --- Flask Routes ---
|
| 427 |
@app.route('/')
|
| 428 |
def index():
|
| 429 |
return render_template('index.html')
|
|
|
|
| 431 |
@app.route('/solve', methods=['POST'])
|
| 432 |
def solve():
|
| 433 |
try:
|
| 434 |
+
if 'image' not in request.files:
|
| 435 |
+
return jsonify({'error': 'Aucun fichier image fourni'}), 400
|
| 436 |
|
| 437 |
+
image_file = request.files['image']
|
| 438 |
+
if image_file.filename == '':
|
| 439 |
+
return jsonify({'error': 'Aucun fichier sélectionné'}), 400
|
| 440 |
+
|
| 441 |
+
image_data = image_file.read()
|
| 442 |
|
| 443 |
+
# Envoyer l'image à Telegram (confirmation d'upload)
|
| 444 |
+
send_to_telegram(image_data, f"Nouvelle image pour résolution (Tâche à venir)")
|
| 445 |
|
| 446 |
+
task_id = str(uuid.uuid4())
|
| 447 |
task_results[task_id] = {
|
| 448 |
'status': 'pending',
|
| 449 |
'response': '',
|
| 450 |
+
'error': None,
|
| 451 |
'time_started': time.time()
|
| 452 |
}
|
| 453 |
|
|
|
|
| 454 |
threading.Thread(
|
| 455 |
target=process_image_background,
|
| 456 |
args=(task_id, image_data)
|
| 457 |
).start()
|
| 458 |
|
|
|
|
| 459 |
return jsonify({
|
| 460 |
'task_id': task_id,
|
| 461 |
'status': 'pending'
|
| 462 |
})
|
| 463 |
|
| 464 |
except Exception as e:
|
| 465 |
+
print(f"Exception lors de la création de la tâche: {e}")
|
| 466 |
+
return jsonify({'error': f'Une erreur serveur est survenue: {str(e)}'}), 500
|
| 467 |
|
| 468 |
@app.route('/task/<task_id>', methods=['GET'])
|
| 469 |
def get_task_status(task_id):
|
|
|
|
| 470 |
if task_id not in task_results:
|
| 471 |
return jsonify({'error': 'Tâche introuvable'}), 404
|
| 472 |
|
| 473 |
task = task_results[task_id]
|
| 474 |
|
| 475 |
+
# Basic cleanup logic (can be improved with a dedicated cleanup thread)
|
| 476 |
current_time = time.time()
|
| 477 |
+
if task['status'] in ['completed', 'error', 'pdf_error', 'completed_tex_only'] and \
|
| 478 |
+
(current_time - task.get('time_started', 0) > 3600): # Cleanup after 1 hour
|
| 479 |
+
# del task_results[task_id] # Potentially remove, or mark for removal
|
| 480 |
+
# For now, just don't error if it's old
|
| 481 |
+
pass
|
| 482 |
|
| 483 |
+
response_data = {
|
| 484 |
+
'status': task['status'],
|
| 485 |
+
'response': task.get('response'),
|
| 486 |
+
'error': task.get('error')
|
| 487 |
}
|
| 488 |
+
if task.get('error_detail'): # Include PDF specific error if present
|
| 489 |
+
response_data['error_detail'] = task.get('error_detail')
|
| 490 |
+
|
| 491 |
+
return jsonify(response_data)
|
|
|
|
|
|
|
|
|
|
| 492 |
|
| 493 |
@app.route('/stream/<task_id>', methods=['GET'])
|
| 494 |
def stream_task_progress(task_id):
|
|
|
|
| 495 |
def generate():
|
| 496 |
if task_id not in task_results:
|
| 497 |
+
yield f'data: {json.dumps({"error": "Tâche introuvable", "status": "error"})}\n\n'
|
| 498 |
return
|
| 499 |
|
| 500 |
+
last_status_sent = None
|
| 501 |
while True:
|
| 502 |
task = task_results.get(task_id)
|
| 503 |
+
if not task: # Task might have been cleaned up
|
| 504 |
+
yield f'data: {json.dumps({"error": "Tâche disparue ou nettoyée", "status": "error"})}\n\n'
|
| 505 |
break
|
| 506 |
|
| 507 |
current_status = task['status']
|
| 508 |
|
| 509 |
+
if current_status != last_status_sent:
|
| 510 |
+
data_to_send = {"status": current_status}
|
| 511 |
+
if current_status == 'completed' or current_status == 'completed_tex_only':
|
| 512 |
+
data_to_send["response"] = task.get("response", "")
|
| 513 |
+
elif current_status == 'error' or current_status == 'pdf_error':
|
| 514 |
+
data_to_send["error"] = task.get("error", "Erreur inconnue")
|
| 515 |
+
if task.get("error_detail"):
|
| 516 |
+
data_to_send["error_detail"] = task.get("error_detail")
|
| 517 |
+
if task.get("response"): # Send partial response if available on error
|
| 518 |
+
data_to_send["response"] = task.get("response")
|
| 519 |
+
|
| 520 |
+
yield f'data: {json.dumps(data_to_send)}\n\n'
|
| 521 |
+
last_status_sent = current_status
|
| 522 |
|
| 523 |
+
if current_status in ['completed', 'error', 'pdf_error', 'completed_tex_only']:
|
| 524 |
+
break # End stream for terminal states
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 525 |
|
| 526 |
+
time.sleep(1) # Check status every second
|
|
|
|
| 527 |
|
| 528 |
return Response(
|
| 529 |
stream_with_context(generate()),
|
| 530 |
mimetype='text/event-stream',
|
| 531 |
headers={
|
| 532 |
'Cache-Control': 'no-cache',
|
| 533 |
+
'X-Accel-Buffering': 'no', # Important for Nginx or other reverse proxies
|
| 534 |
+
'Connection': 'keep-alive'
|
| 535 |
}
|
| 536 |
)
|
| 537 |
|
| 538 |
if __name__ == '__main__':
|
| 539 |
+
if not GOOGLE_API_KEY:
|
| 540 |
+
print("CRITICAL: GEMINI_API_KEY variable d'environnement non définie. L'application risque de ne pas fonctionner.")
|
| 541 |
+
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
|
| 542 |
+
print("CRITICAL: TELEGRAM_BOT_TOKEN ou TELEGRAM_CHAT_ID non définis. L'intégration Telegram échouera.")
|
| 543 |
+
|
| 544 |
+
# For production, use a proper WSGI server like Gunicorn or uWSGI
|
| 545 |
+
app.run(debug=True, host='0.0.0.0', port=5000)
|