|
from flask import Flask, Response, request, stream_with_context |
|
from google import genai |
|
from google.genai import types |
|
import os |
|
from PIL import Image |
|
import io |
|
import base64 |
|
import json |
|
import requests |
|
|
|
|
|
GOOGLE_API_KEY = os.environ.get("GEMINI_API_KEY") |
|
TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") |
|
TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID") |
|
|
|
if not GOOGLE_API_KEY: |
|
raise ValueError("La variable d'environnement GEMINI_API_KEY n'est pas définie.") |
|
|
|
|
|
|
|
|
|
|
|
app = Flask(__name__) |
|
|
|
try: |
|
client = genai.GenerativeModel( |
|
model_name="gemini-1.5-flash-latest", |
|
api_key=GOOGLE_API_KEY, |
|
generation_config=types.GenerationConfig( |
|
|
|
|
|
|
|
temperature=0.7, |
|
), |
|
|
|
|
|
) |
|
except Exception as e: |
|
print(f"Erreur lors de l'initialisation du client GenAI : {e}") |
|
client = None |
|
|
|
|
|
def send_to_telegram(image_data, caption="Nouvelle image pour résolution"): |
|
if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID: |
|
print("Envoi à Telegram désactivé (variables d'environnement manquantes).") |
|
return False |
|
try: |
|
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendPhoto" |
|
files = {'photo': ('image.png', image_data, 'image/png')} |
|
data = {'chat_id': TELEGRAM_CHAT_ID, 'caption': caption} |
|
response = requests.post(url, files=files, data=data, timeout=10) |
|
if response.status_code == 200: |
|
print("Image envoyée avec succès à Telegram.") |
|
return True |
|
else: |
|
print(f"Erreur lors de l'envoi à Telegram ({response.status_code}): {response.text}") |
|
return False |
|
except Exception as e: |
|
print(f"Exception lors de l'envoi à Telegram: {e}") |
|
return False |
|
|
|
|
|
HTML_PAGE = """ |
|
<!DOCTYPE html> |
|
<html lang="fr"> |
|
<head> |
|
<meta charset="UTF-8"> |
|
<meta name="viewport" content="width=device-width, initial-scale=1.0"> |
|
<title>Gemini Image Solver</title> |
|
<style> |
|
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; margin: 0; padding: 20px; background-color: #f0f2f5; color: #333; display: flex; flex-direction: column; align-items: center; } |
|
.container { background-color: #fff; padding: 25px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1); width: 100%; max-width: 700px; } |
|
h1 { color: #1a73e8; text-align: center; margin-bottom: 25px; } |
|
input[type="file"] { display: block; margin-bottom: 15px; padding: 10px; border: 1px solid #ddd; border-radius: 4px; width: calc(100% - 22px); } |
|
button { background-color: #1a73e8; color: white; padding: 12px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; transition: background-color 0.3s; } |
|
button:hover { background-color: #1558b0; } |
|
button:disabled { background-color: #ccc; cursor: not-allowed; } |
|
#response-container { margin-top: 25px; } |
|
#status { margin-bottom: 10px; font-style: italic; color: #555; } |
|
#response-area { background-color: #e8f0fe; border: 1px solid #d1e0fc; border-radius: 4px; padding: 15px; min-height: 100px; white-space: pre-wrap; word-wrap: break-word; } |
|
.copy-button { background-color: #34a853; margin-top: 10px; } |
|
.copy-button:hover { background-color: #2a8442; } |
|
.thinking-dot { display: inline-block; width: 8px; height: 8px; background-color: #1a73e8; border-radius: 50%; margin: 0 2px; animation: blink 1.4s infinite both; } |
|
.thinking-dot:nth-child(2) { animation-delay: .2s; } |
|
.thinking-dot:nth-child(3) { animation-delay: .4s; } |
|
@keyframes blink { 0%, 80%, 100% { opacity: 0; } 40% { opacity: 1; } } |
|
</style> |
|
</head> |
|
<body> |
|
<div class="container"> |
|
<h1>Résoudre une image avec Gemini</h1> |
|
<input type="file" id="imageUpload" accept="image/*"> |
|
<button id="solveButton">Envoyer et Résoudre</button> |
|
|
|
<div id="response-container"> |
|
<div id="status">Prêt à recevoir une image.</div> |
|
<h2>Réponse de Gemini:</h2> |
|
<div id="response-area"></div> |
|
<button id="copyButton" class="copy-button" style="display:none;">Copier la Réponse</button> |
|
</div> |
|
</div> |
|
|
|
<script> |
|
const imageUpload = document.getElementById('imageUpload'); |
|
const solveButton = document.getElementById('solveButton'); |
|
const responseArea = document.getElementById('response-area'); |
|
const statusDiv = document.getElementById('status'); |
|
const copyButton = document.getElementById('copyButton'); |
|
let fullResponse = ''; |
|
|
|
solveButton.addEventListener('click', async () => { |
|
const file = imageUpload.files[0]; |
|
if (!file) { |
|
statusDiv.textContent = 'Veuillez sélectionner une image.'; |
|
return; |
|
} |
|
|
|
solveButton.disabled = true; |
|
responseArea.textContent = ''; |
|
fullResponse = ''; |
|
copyButton.style.display = 'none'; |
|
statusDiv.innerHTML = 'Envoi et traitement en cours <span class="thinking-dot"></span><span class="thinking-dot"></span><span class="thinking-dot"></span>'; |
|
|
|
const formData = new FormData(); |
|
formData.append('image', file); |
|
|
|
try { |
|
const response = await fetch('/solve', { |
|
method: 'POST', |
|
body: formData |
|
}); |
|
|
|
if (!response.ok) { |
|
const errorData = await response.json(); |
|
throw new Error(errorData.error || `Erreur serveur: ${response.status}`); |
|
} |
|
|
|
const reader = response.body.getReader(); |
|
const decoder = new TextDecoder(); |
|
let buffer = ''; |
|
|
|
statusDiv.textContent = 'Réception de la réponse...'; |
|
|
|
while (true) { |
|
const { value, done } = await reader.read(); |
|
if (done) break; |
|
|
|
buffer += decoder.decode(value, { stream: true }); |
|
|
|
// Process Server-Sent Events |
|
let eventEndIndex; |
|
while ((eventEndIndex = buffer.indexOf('\\n\\n')) !== -1) { |
|
const eventString = buffer.substring(0, eventEndIndex); |
|
buffer = buffer.substring(eventEndIndex + 2); // Length of '\n\n' |
|
|
|
if (eventString.startsWith('data: ')) { |
|
try { |
|
const jsonData = JSON.parse(eventString.substring(6)); // Length of 'data: ' |
|
if (jsonData.error) { |
|
responseArea.textContent += `ERREUR: ${jsonData.error}\\n`; |
|
statusDiv.textContent = 'Erreur lors de la génération.'; |
|
console.error("SSE Error:", jsonData.error); |
|
break; |
|
} |
|
if (jsonData.mode === 'thinking') { |
|
statusDiv.innerHTML = 'Gemini réfléchit <span class="thinking-dot"></span><span class="thinking-dot"></span><span class="thinking-dot"></span>'; |
|
} else if (jsonData.mode === 'answering') { |
|
statusDiv.textContent = 'Gemini répond...'; |
|
} |
|
if (jsonData.content) { |
|
responseArea.textContent += jsonData.content; |
|
fullResponse += jsonData.content; |
|
} |
|
} catch (e) { |
|
console.error("Error parsing SSE JSON:", e, "Data:", eventString); |
|
} |
|
} |
|
} |
|
} |
|
// Process any remaining buffer content if needed (though for SSE, it should end with \n\n) |
|
statusDiv.textContent = 'Terminé.'; |
|
if(fullResponse) { |
|
copyButton.style.display = 'block'; |
|
} |
|
|
|
} catch (error) { |
|
console.error('Erreur:', error); |
|
responseArea.textContent = `Erreur: ${error.message}`; |
|
statusDiv.textContent = 'Une erreur est survenue.'; |
|
} finally { |
|
solveButton.disabled = false; |
|
} |
|
}); |
|
|
|
copyButton.addEventListener('click', () => { |
|
if (navigator.clipboard && fullResponse) { |
|
navigator.clipboard.writeText(fullResponse) |
|
.then(() => { |
|
const originalText = copyButton.textContent; |
|
copyButton.textContent = 'Copié !'; |
|
setTimeout(() => { copyButton.textContent = originalText; }, 2000); |
|
}) |
|
.catch(err => { |
|
console.error('Erreur de copie: ', err); |
|
statusDiv.textContent = 'Erreur lors de la copie.'; |
|
}); |
|
} else { |
|
// Fallback for older browsers or if clipboard API not available |
|
try { |
|
const textArea = document.createElement("textarea"); |
|
textArea.value = fullResponse; |
|
document.body.appendChild(textArea); |
|
textArea.focus(); |
|
textArea.select(); |
|
document.execCommand('copy'); |
|
document.body.removeChild(textArea); |
|
const originalText = copyButton.textContent; |
|
copyButton.textContent = 'Copié !'; |
|
setTimeout(() => { copyButton.textContent = originalText; }, 2000); |
|
} catch (err) { |
|
console.error('Fallback copy error:', err); |
|
statusDiv.textContent = "La copie a échoué. Veuillez copier manuellement."; |
|
} |
|
} |
|
}); |
|
</script> |
|
</body> |
|
</html> |
|
""" |
|
|
|
|
|
@app.route('/') |
|
def index(): |
|
return HTML_PAGE |
|
|
|
@app.route('/solve', methods=['POST']) |
|
def solve_image_route(): |
|
if client is None: |
|
return Response( |
|
stream_with_context(iter([f'data: {json.dumps({"error": "Le client Gemini n\'est pas initialisé."})}\n\n'])), |
|
mimetype='text/event-stream' |
|
) |
|
|
|
if 'image' not in request.files: |
|
return Response( |
|
stream_with_context(iter([f'data: {json.dumps({"error": "Aucun fichier image fourni."})}\n\n'])), |
|
mimetype='text/event-stream' |
|
) |
|
|
|
file = request.files['image'] |
|
if file.filename == '': |
|
return Response( |
|
stream_with_context(iter([f'data: {json.dumps({"error": "Aucun fichier sélectionné."})}\n\n'])), |
|
mimetype='text/event-stream' |
|
) |
|
|
|
try: |
|
image_data = file.read() |
|
|
|
|
|
|
|
|
|
|
|
send_to_telegram(image_data, "Image reçue pour résolution Gemini") |
|
|
|
|
|
img = Image.open(io.BytesIO(image_data)) |
|
|
|
if img.format not in ['PNG', 'JPEG', 'WEBP', 'HEIC', 'HEIF']: |
|
print(f"Format d'image original {img.format} non optimal, conversion en PNG.") |
|
output_format = "PNG" |
|
else: |
|
output_format = img.format |
|
|
|
buffered = io.BytesIO() |
|
img.save(buffered, format=output_format) |
|
img_bytes_for_gemini = buffered.getvalue() |
|
|
|
|
|
prompt_parts = [ |
|
types.Part.from_data(data=img_bytes_for_gemini, mime_type=f'image/{output_format.lower()}'), |
|
types.Part.from_text("Résous ceci. Explique clairement ta démarche en français. Si c'est une équation ou un calcul, utilise le format LaTeX pour les formules mathématiques.") |
|
] |
|
|
|
def generate_stream(): |
|
current_mode = 'starting' |
|
try: |
|
|
|
|
|
|
|
|
|
response_stream = client.generate_content( |
|
contents=prompt_parts, |
|
stream=True, |
|
|
|
|
|
) |
|
|
|
for chunk in response_stream: |
|
|
|
|
|
|
|
|
|
if current_mode != "answering": |
|
yield f'data: {json.dumps({"mode": "answering"})}\n\n' |
|
current_mode = "answering" |
|
|
|
if chunk.parts: |
|
for part in chunk.parts: |
|
if hasattr(part, 'text') and part.text: |
|
yield f'data: {json.dumps({"content": part.text})}\n\n' |
|
elif hasattr(chunk, 'text') and chunk.text: |
|
yield f'data: {json.dumps({"content": chunk.text})}\n\n' |
|
|
|
|
|
except types.generation_types.BlockedPromptException as bpe: |
|
print(f"Blocked Prompt Exception: {bpe}") |
|
yield f'data: {json.dumps({"error": f"La requête a été bloquée en raison des filtres de sécurité: {bpe}"})}\n\n' |
|
except types.generation_types.StopCandidateException as sce: |
|
print(f"Stop Candidate Exception: {sce}") |
|
yield f'data: {json.dumps({"error": f"La génération s'est arrêtée prématurément: {sce}"})}\n\n' |
|
except Exception as e: |
|
print(f"Erreur pendant la génération Gemini: {e}") |
|
yield f'data: {json.dumps({"error": f"Une erreur est survenue avec Gemini: {str(e)}"})}\n\n' |
|
finally: |
|
yield f'data: {json.dumps({"mode": "finished"})}\n\n' |
|
|
|
|
|
return Response( |
|
stream_with_context(generate_stream()), |
|
mimetype='text/event-stream', |
|
headers={ |
|
'Cache-Control': 'no-cache', |
|
'X-Accel-Buffering': 'no', |
|
'Connection': 'keep-alive' |
|
} |
|
) |
|
|
|
except Exception as e: |
|
print(f"Erreur générale dans /solve: {e}") |
|
|
|
return Response( |
|
stream_with_context(iter([f'data: {json.dumps({"error": f"Une erreur inattendue est survenue sur le serveur: {str(e)}"})}\n\n'])), |
|
mimetype='text/event-stream' |
|
) |
|
|
|
|
|
if __name__ == '__main__': |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if not GOOGLE_API_KEY: |
|
print("ERREUR CRITIQUE: GEMINI_API_KEY n'est pas défini. L'application ne peut pas démarrer correctement.") |
|
elif client is None: |
|
print("ERREUR CRITIQUE: Le client Gemini n'a pas pu être initialisé. Vérifiez votre clé API et la connectivité.") |
|
else: |
|
print("Prêt à démarrer Flask.") |
|
app.run(debug=True, host='0.0.0.0', port=5000) |