File size: 17,564 Bytes
79b1a5a
 
 
43f84cb
79b1a5a
 
 
 
 
9f15b41
79b1a5a
 
 
 
43f84cb
79b1a5a
 
 
 
 
43f84cb
 
79b1a5a
43f84cb
fc53ab2
79b1a5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47c91f3
79b1a5a
 
 
 
 
 
 
 
 
 
47c91f3
79b1a5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47c91f3
79b1a5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc53ab2
 
79b1a5a
 
 
 
 
 
 
 
 
43f84cb
79b1a5a
 
 
 
 
43f84cb
79b1a5a
 
 
 
 
 
43f84cb
 
79b1a5a
 
 
43f84cb
79b1a5a
 
 
 
 
 
 
 
 
 
 
 
fc53ab2
79b1a5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43f84cb
79b1a5a
 
 
 
 
 
 
fc53ab2
 
79b1a5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
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 # Pour les requêtes HTTP vers l'API Telegram

# --- Configuration ---
GOOGLE_API_KEY = os.environ.get("GEMINI_API_KEY")
TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") # Récupérer depuis les variables d'env
TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID")     # Récupérer depuis les variables d'env

if not GOOGLE_API_KEY:
    raise ValueError("La variable d'environnement GEMINI_API_KEY n'est pas définie.")
# Optionnel: vérifier aussi TELEGRAM_BOT_TOKEN et TELEGRAM_CHAT_ID si vous voulez forcer leur utilisation
# if not TELEGRAM_BOT_TOKEN or not TELEGRAM_CHAT_ID:
#     print("Attention: Les variables d'environnement Telegram ne sont pas toutes définies. L'envoi à Telegram pourrait échouer.")


app = Flask(__name__)

try:
    client = genai.GenerativeModel(
        model_name="gemini-1.5-flash-latest", # Ou "gemini-1.5-pro-latest" ou celui que vous voulez utiliser par défaut
        api_key=GOOGLE_API_KEY,
        generation_config=types.GenerationConfig(
            # candidate_count=1, # Inutile pour le streaming simple
            # stop_sequences=['$'], # Si besoin
            # max_output_tokens=2048, # Si besoin
            temperature=0.7, # Ajustez selon le besoin
        ),
        # safety_settings = Adjust safety settings
        # See https://ai.google.dev/gemini-api/docs/safety-settings
    )
except Exception as e:
    print(f"Erreur lors de l'initialisation du client GenAI : {e}")
    client = None # Pour éviter des erreurs si l'initialisation échoue

# --- Fonctions Utilitaires ---
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

# --- Code HTML/CSS/JS pour le Frontend ---
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>
"""

# --- Routes Flask ---
@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()
        # Pour réutiliser image_data, il faut le "rembobiner" si on le lit plusieurs fois
        # ou le stocker après la première lecture.
        
        # Envoyer l'image à Telegram (optionnel)
        # Note: send_to_telegram attend des bytes, image_data est déjà en bytes.
        send_to_telegram(image_data, "Image reçue pour résolution Gemini")

        # Préparer l'image pour Gemini
        img = Image.open(io.BytesIO(image_data))
        # Assurez-vous que le format est supporté par Gemini (PNG, JPEG, WEBP, HEIC, HEIF)
        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()

        # Le prompt pour Gemini
        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:
                # Utilisation de generate_content avec stream=True
                # Le modèle choisi est "gemini-1.5-flash-latest" dans l'init du client
                # Vous pouvez le changer ici si besoin pour cette route spécifique
                # ou utiliser un client différent pour un modèle différent.
                response_stream = client.generate_content(
                    contents=prompt_parts,
                    stream=True,
                    # generation_config peut être surchargé ici si besoin
                    # request_options={"timeout": 600} # Optionnel: timeout pour la requête
                )

                for chunk in response_stream:
                    # La structure de 'chunk' pour 1.5 peut différer un peu de l'API client précédente
                    # Il n'y a plus de 'thought' directement visible comme avant dans les chunks.
                    # La gestion "thinking" / "answering" devient moins directe.
                    # On va simplifier : on envoie le contenu dès qu'il arrive.
                    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: # Pour certains retours directs
                         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', # Important pour Nginx si utilisé comme reverse proxy
                'Connection': 'keep-alive'
            }
        )

    except Exception as e:
        print(f"Erreur générale dans /solve: {e}")
        # Renvoyer l'erreur en SSE pour que le client puisse l'afficher
        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__':
    # Assurez-vous que les variables d'environnement sont chargées
    # par exemple, si vous utilisez un fichier .env avec python-dotenv:
    # from dotenv import load_dotenv
    # load_dotenv()
    # 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")
    # (et réinitialisez le client si les clés sont chargées après l'init initiale)

    # Vérification finale avant de lancer
    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)