File size: 14,263 Bytes
dc9fc1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79b1a5a
 
fc53ab2
 
79b1a5a
 
 
 
 
dc9fc1f
 
 
 
43f84cb
79b1a5a
dc9fc1f
 
 
 
43f84cb
79b1a5a
 
dc9fc1f
 
 
 
43f84cb
 
79b1a5a
fc53ab2
dc9fc1f
 
79b1a5a
dc9fc1f
79b1a5a
dc9fc1f
79b1a5a
 
 
 
 
 
dc9fc1f
79b1a5a
 
 
 
 
 
 
 
 
 
 
 
 
 
8a641ea
79b1a5a
 
 
 
dc9fc1f
79b1a5a
 
dc9fc1f
79b1a5a
 
dc9fc1f
79b1a5a
 
 
 
 
 
 
 
dc9fc1f
79b1a5a
 
 
 
43f84cb
79b1a5a
dc9fc1f
 
 
 
79b1a5a
8a641ea
dc9fc1f
79b1a5a
 
 
 
 
dc9fc1f
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
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 json

# --- Configuration ---
GOOGLE_API_KEY = os.environ.get("GEMINI_API_KEY")

if not GOOGLE_API_KEY:
    raise ValueError("La variable d'environnement GEMINI_API_KEY n'est pas définie.")

app = Flask(__name__)

# --- Initialisation client Gemini ---
def initialize_gemini_client():
    try:
        return genai.GenerativeModel(
            model_name="gemini-1.5-flash-latest",  # Modèle par défaut
            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}")
        return None

client = initialize_gemini_client()

# --- 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);
                            }
                        }
                    }
                }
                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 pour les navigateurs plus anciens
                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>
"""

# --- Fonctions d'utilitaires pour le traitement d'images ---
def process_image(image_bytes):
    """Traite une image pour l'envoyer à Gemini"""
    try:
        img = Image.open(io.BytesIO(image_bytes))
        # Assurez-vous que le format est supporté par Gemini
        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)
        return buffered.getvalue(), output_format.lower()
    except Exception as e:
        print(f"Erreur lors du traitement de l'image: {e}")
        raise

# --- 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()
        
        # Préparer l'image pour Gemini
        processed_image, output_format = process_image(image_data)

        # Le prompt pour Gemini
        prompt_parts = [
            types.Part.from_data(data=processed_image, mime_type=f'image/{output_format}'),
            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
                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',  # Important pour Nginx
                '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__':
    # 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("Serveur démarré. Accédez à http://localhost:5000 pour utiliser l'application.")
        app.run(debug=True, host='0.0.0.0', port=5000)