File size: 8,833 Bytes
ca9f82a
f388c93
 
 
 
 
 
6b10944
1e4539a
12d4886
f388c93
 
12d4886
e7761b5
ca9f82a
 
 
f388c93
ca9f82a
 
 
8071ff2
ca9f82a
 
 
2ef19ee
1e4539a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca9f82a
 
f388c93
ca9f82a
 
 
f388c93
 
949f8bc
451d8eb
ca9f82a
 
 
 
 
 
 
1e4539a
ca9f82a
 
b6bd995
1e4539a
ca9f82a
b88caed
ca9f82a
 
 
 
 
 
 
 
b88caed
ca9f82a
1e4539a
ca9f82a
b88caed
ca9f82a
b88caed
1e4539a
 
 
b88caed
1e4539a
 
b88caed
1e4539a
 
 
 
 
 
ca9f82a
 
 
b88caed
ca9f82a
 
 
 
 
 
 
 
451d8eb
8071ff2
 
ca9f82a
e7761b5
2ef19ee
93f4a81
2ef19ee
ca9f82a
 
8071ff2
ca9f82a
 
 
8071ff2
ca9f82a
 
 
 
 
 
 
c9c813b
ca9f82a
 
b6bd995
 
 
1e4539a
ca9f82a
b88caed
ca9f82a
 
 
 
 
 
 
 
b88caed
ca9f82a
1e4539a
ca9f82a
b88caed
ca9f82a
b88caed
1e4539a
 
 
b88caed
1e4539a
 
b88caed
1e4539a
 
 
 
 
 
ca9f82a
 
 
b88caed
ca9f82a
 
 
 
 
 
 
 
 
8071ff2
ca9f82a
 
2ef19ee
f388c93
ca9f82a
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
from flask import Flask, render_template, request, jsonify, Response, 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 re

app = Flask(__name__)

GOOGLE_API_KEY = os.environ.get("GEMINI_API_KEY")

client = genai.Client(
    api_key=GOOGLE_API_KEY,
)

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/free')
def indexx():
    return render_template('maj.html')

def process_markdown_and_code(text):
    """Traite le texte pour identifier et formater le code et le markdown"""
    # Convertit le texte en HTML formaté
    # Cette fonction pourrait être étendue pour utiliser une bibliothèque de markdown
    return text

def format_code_execution_result(response_parts):
    """Formate les résultats d'exécution de code pour l'affichage HTML"""
    result = []
    
    for part in response_parts:
        # Traitement du texte (équivalent à display(Markdown(part.text)))
        if hasattr(part, 'text') and part.text is not None:
            result.append({
                'type': 'markdown',
                'content': part.text
            })
        
        # Traitement du code exécutable
        if hasattr(part, 'executable_code') and part.executable_code is not None:
            result.append({
                'type': 'code',
                'content': part.executable_code.code
            })
        
        # Traitement des résultats d'exécution
        if hasattr(part, 'code_execution_result') and part.code_execution_result is not None:
            result.append({
                'type': 'execution_result',
                'content': part.code_execution_result.output
            })
        
        # Traitement des images (équivalent à display(Image(data=part.inline_data.data)))
        if hasattr(part, 'inline_data') and part.inline_data is not None:
            # Encodage de l'image en base64 pour l'affichage HTML
            img_data = base64.b64encode(part.inline_data.data).decode('utf-8')
            result.append({
                'type': 'image',
                'content': img_data,
                'format': 'png'  # Supposé comme png par défaut
            })
    
    return result

@app.route('/solve', methods=['POST'])
def solve():
    try:
        image_data = request.files['image'].read()
        img = Image.open(io.BytesIO(image_data))

        buffered = io.BytesIO()
        img.save(buffered, format="PNG")
        img_str = base64.b64encode(buffered.getvalue()).decode()

        def generate():
            mode = 'starting'
            try:
                response = client.models.generate_content_stream(
                    model="gemini-2.5-pro-exp-03-25",
                    contents=[
                        {'inline_data': {'mime_type': 'image/png', 'data': img_str}},
                        """Résous ça en français with rendering latex"""
                    ],
                    config=types.GenerateContentConfig(
                        
                        # Ajouter l'outil d'exécution de code
                        tools=[types.Tool(
                            code_execution=types.ToolCodeExecution
                        )]
                    )
                )

                for chunk in response:
                    for part in chunk.candidates[0].content.parts:
                        if hasattr(part, 'thought') and part.thought:
                            if mode != "thinking":
                                yield f'data: {json.dumps({"mode": "thinking"})}\n\n'
                                mode = "thinking"
                        else:
                            if mode != "answering":
                                yield f'data: {json.dumps({"mode": "answering"})}\n\n'
                                mode = "answering"
                        
                        # Gestion des différents types de contenu
                        if hasattr(part, 'text') and part.text is not None:
                            yield f'data: {json.dumps({"content": part.text, "type": "text"})}\n\n'
                        
                        if hasattr(part, 'executable_code') and part.executable_code is not None:
                            yield f'data: {json.dumps({"content": part.executable_code.code, "type": "code"})}\n\n'
                        
                        if hasattr(part, 'code_execution_result') and part.code_execution_result is not None:
                            yield f'data: {json.dumps({"content": part.code_execution_result.output, "type": "result"})}\n\n'
                        
                        if hasattr(part, 'inline_data') and part.inline_data is not None:
                            img_data = base64.b64encode(part.inline_data.data).decode('utf-8')
                            yield f'data: {json.dumps({"content": img_data, "type": "image"})}\n\n'

            except Exception as e:
                print(f"Error during generation: {e}")
                yield f'data: {json.dumps({"error": str(e)})}\n\n'

        return Response(
            stream_with_context(generate()),
            mimetype='text/event-stream',
            headers={
                'Cache-Control': 'no-cache',
                'X-Accel-Buffering': 'no'
            }
        )

    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/solved', methods=['POST'])
def solved():
    try:
        image_data = request.files['image'].read()
        img = Image.open(io.BytesIO(image_data))

        buffered = io.BytesIO()
        img.save(buffered, format="PNG")
        img_str = base64.b64encode(buffered.getvalue()).decode()

        def generate():
            mode = 'starting'
            try:
                response = client.models.generate_content_stream(
                    model="gemini-2.5-flash-preview-04-17",
                    contents=[
                        {'inline_data': {'mime_type': 'image/png', 'data': img_str}},
                        """Résous ça en français with rendering latex. utilise python pour les calculs et figures."""
                    ],
                    config=types.GenerateContentConfig(
                        thinking_config=types.ThinkingConfig(
                            thinking_budget=16000
                        ),
                        # Ajouter l'outil d'exécution de code
                        tools=[types.Tool(
                            code_execution=types.ToolCodeExecution
                        )]
                    )
                )

                for chunk in response:
                    for part in chunk.candidates[0].content.parts:
                        if hasattr(part, 'thought') and part.thought:
                            if mode != "thinking":
                                yield f'data: {json.dumps({"mode": "thinking"})}\n\n'
                                mode = "thinking"
                        else:
                            if mode != "answering":
                                yield f'data: {json.dumps({"mode": "answering"})}\n\n'
                                mode = "answering"
                        
                        # Gestion des différents types de contenu
                        if hasattr(part, 'text') and part.text is not None:
                            yield f'data: {json.dumps({"content": part.text, "type": "text"})}\n\n'
                        
                        if hasattr(part, 'executable_code') and part.executable_code is not None:
                            yield f'data: {json.dumps({"content": part.executable_code.code, "type": "code"})}\n\n'
                        
                        if hasattr(part, 'code_execution_result') and part.code_execution_result is not None:
                            yield f'data: {json.dumps({"content": part.code_execution_result.output, "type": "result"})}\n\n'
                        
                        if hasattr(part, 'inline_data') and part.inline_data is not None:
                            img_data = base64.b64encode(part.inline_data.data).decode('utf-8')
                            yield f'data: {json.dumps({"content": img_data, "type": "image"})}\n\n'

            except Exception as e:
                print(f"Error during generation: {e}")
                yield f'data: {json.dumps({"error": str(e)})}\n\n'

        return Response(
            stream_with_context(generate()),
            mimetype='text/event-stream',
            headers={
                'Cache-Control': 'no-cache',
                'X-Accel-Buffering': 'no'
            }
        )

    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    app.run(debug=True)