Olivier commited on
Commit
a0fa517
·
verified ·
1 Parent(s): 2c7c9ef

Upload 4 files

Browse files
Files changed (4) hide show
  1. app.py +213 -0
  2. game_engine.py +580 -0
  3. image_processing.py +232 -0
  4. requirements.txt +10 -0
app.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ==========================================
2
+ # app.py - Calcul OCR v3.0
3
+ # ==========================================
4
+
5
+ """
6
+ Application principale - Entraînement aux calculs avec OCR
7
+ """
8
+
9
+ import gradio as gr
10
+ import warnings
11
+ import os
12
+ import gc
13
+ import numpy as np
14
+ from PIL import Image
15
+
16
+ warnings.filterwarnings("ignore")
17
+
18
+ from image_processing import init_ocr_model, create_white_canvas, cleanup_memory
19
+ from game_engine import MathGame, export_to_clean_dataset
20
+
21
+ print("🚀 Initialisation Calcul OCR v3.0...")
22
+
23
+ print("🔄 Chargement modèle OCR...")
24
+ init_ocr_model()
25
+ print("✅ Modèle OCR prêt")
26
+
27
+ game = MathGame()
28
+
29
+ def start_game_wrapper(duration: str, operation: str, difficulty: str) -> tuple:
30
+ cleanup_memory()
31
+ return game.start_game(duration, operation, difficulty)
32
+
33
+ def next_question_wrapper(image_data: dict | np.ndarray | Image.Image | None) -> tuple:
34
+ return game.next_question(image_data)
35
+
36
+ def export_current_session() -> str:
37
+ """Export vers le nouveau dataset calcul_ocr_dataset"""
38
+
39
+ if not hasattr(game, 'session_data') or not game.session_data:
40
+ return "❌ Aucune donnée de session à exporter"
41
+
42
+ export_info = game.get_export_status()
43
+
44
+ if export_info["status"] == "exported":
45
+ return f"""✅ Session déjà exportée !
46
+
47
+ 📅 Exporté le: {export_info['timestamp'][:19].replace('T', ' ')}
48
+ 📊 Résultat: {export_info['result'][:100]}...
49
+
50
+ 💡 Jouez une nouvelle session pour contribuer davantage !"""
51
+
52
+ if export_info["status"] == "exporting":
53
+ return "⏳ Export en cours..."
54
+
55
+ if not export_info["can_export"]:
56
+ return "❌ Aucune donnée à exporter"
57
+
58
+ game.mark_export_in_progress()
59
+
60
+ try:
61
+ result = export_to_clean_dataset(game.session_data)
62
+ game.mark_export_completed(result)
63
+ cleanup_memory()
64
+ return result
65
+
66
+ except Exception as e:
67
+ game.export_status = "not_exported"
68
+ return f"❌ Erreur export: {str(e)}"
69
+
70
+ # Interface Gradio
71
+ with gr.Blocks(
72
+ title="🧮 Calcul OCR - Entraînement mathématiques",
73
+ theme=gr.themes.Soft(),
74
+ css="""
75
+ .gradio-container { max-width: 1200px !important; }
76
+ .config-section {
77
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
78
+ color: white;
79
+ padding: 15px;
80
+ border-radius: 10px;
81
+ margin: 10px 0;
82
+ }
83
+ .dataset-info {
84
+ background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
85
+ color: white;
86
+ padding: 15px;
87
+ border-radius: 10px;
88
+ margin: 10px 0;
89
+ }
90
+ .radio-group {
91
+ background: #f8f9fa;
92
+ padding: 10px;
93
+ border-radius: 8px;
94
+ margin: 5px 0;
95
+ }
96
+ """,
97
+ head="<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
98
+ ) as demo:
99
+
100
+ gr.Markdown(
101
+ """
102
+ # 🧮 Entraînement aux calculs avec OCR
103
+
104
+ **Nouveau !** Choisissez votre configuration et entraînez-vous sur différents types de calculs !
105
+
106
+ **Comment jouer :**
107
+ 1. **Configurez** votre session ci-dessous
108
+ 2. Cliquez sur **🚀 GO !** pour démarrer
109
+ 3. **Écrivez** ✏️ votre réponse sur le tableau
110
+ 4. Cliquez sur **➡️ NEXT !** pour la question suivante
111
+
112
+ À la fin, vous pourrez contribuer au dataset ouvert pour améliorer l'OCR mathématique !
113
+
114
+ ---
115
+ """
116
+ )
117
+
118
+ # Configuration de la session
119
+ with gr.Group():
120
+ gr.Markdown("### ⚙️ Configuration de la session", elem_classes=["config-section"])
121
+
122
+ with gr.Row():
123
+ duration_choice = gr.Radio(
124
+ choices=["30 secondes", "60 secondes"],
125
+ value="30 secondes",
126
+ label="⏱️ Durée",
127
+ elem_classes=["radio-group"]
128
+ )
129
+
130
+ operation_choice = gr.Radio(
131
+ choices=["×", "+", "-", "÷", "Aléatoire"],
132
+ value="×",
133
+ label="🔢 Opération",
134
+ elem_classes=["radio-group"]
135
+ )
136
+
137
+ difficulty_choice = gr.Radio(
138
+ choices=["Facile", "Difficile"],
139
+ value="Facile",
140
+ label="🎯 Difficulté",
141
+ elem_classes=["radio-group"]
142
+ )
143
+
144
+ with gr.Row():
145
+ with gr.Column(scale=1):
146
+ # Question
147
+ question_display = gr.HTML(
148
+ value='<div style="font-size: 2.5em; font-weight: bold; text-align: center; padding: 20px; background: linear-gradient(45deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px;">Prêt à jouer ?</div>'
149
+ )
150
+
151
+ # Contrôles
152
+ with gr.Row():
153
+ go_button = gr.Button("🚀 GO !", variant="primary", size="lg")
154
+ next_button = gr.Button("➡️ NEXT !", variant="secondary", size="lg", interactive=False)
155
+
156
+ # Status
157
+ status_display = gr.Markdown("### 🎯 Configurez votre session et cliquez sur GO !")
158
+ timer_display = gr.Markdown("### ⏱️ --")
159
+
160
+ with gr.Column(scale=1):
161
+ # Zone de dessin
162
+ canvas = gr.ImageEditor(
163
+ label="✏️ Votre réponse",
164
+ height=350,
165
+ width=350,
166
+ value=create_white_canvas(350, 350),
167
+ brush=gr.Brush(default_size=8, default_color="#000000"),
168
+ sources=[],
169
+ layers=False,
170
+ transforms=[],
171
+ eraser=gr.Eraser(default_size=20)
172
+ )
173
+
174
+ # Résultats
175
+ results_display = gr.HTML("")
176
+
177
+ # Export vers dataset dédié
178
+ gr.Markdown("### 📤 Contribuer au dataset", elem_classes=["dataset-info"])
179
+ export_button = gr.Button("📤 Ajouter la série au dataset calcul_ocr", variant="primary", size="lg")
180
+ export_status = gr.Markdown("")
181
+
182
+ # Événements
183
+ go_button.click(
184
+ fn=start_game_wrapper,
185
+ inputs=[duration_choice, operation_choice, difficulty_choice],
186
+ outputs=[question_display, canvas, status_display, timer_display, go_button, next_button, results_display]
187
+ )
188
+
189
+ next_button.click(
190
+ fn=next_question_wrapper,
191
+ inputs=[canvas],
192
+ outputs=[question_display, canvas, status_display, timer_display, go_button, next_button, results_display]
193
+ )
194
+
195
+ export_button.click(
196
+ fn=export_current_session,
197
+ outputs=[export_status]
198
+ )
199
+
200
+ if __name__ == "__main__":
201
+ print("🚀 Lancement Calcul OCR v3.0...")
202
+ print("🎯 Dataset: calcul_ocr_dataset")
203
+ print("📊 Opérations: ×, +, -, ÷, Aléatoire")
204
+ print("⚙️ Durées: 30s, 60s")
205
+ print("🎯 Difficultés: Facile, Difficile")
206
+ demo.launch(
207
+ share=False,
208
+ show_error=True,
209
+ server_name="0.0.0.0",
210
+ server_port=7860,
211
+ show_api=False,
212
+ favicon_path=None
213
+ )
game_engine.py ADDED
@@ -0,0 +1,580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ==========================================
2
+ # game_engine.py - Calcul OCR v3.0
3
+ # ==========================================
4
+
5
+ """
6
+ Moteur de jeu mathématique complet
7
+ """
8
+
9
+ import random
10
+ import time
11
+ import datetime
12
+ import gradio as gr
13
+ import os
14
+ import uuid
15
+ import gc
16
+ import base64
17
+ from io import BytesIO
18
+ import numpy as np
19
+ from PIL import Image
20
+
21
+ # Import optimisé avec images
22
+ from image_processing import (
23
+ recognize_number_fast_with_image,
24
+ create_thumbnail_fast,
25
+ create_white_canvas,
26
+ cleanup_memory,
27
+ log_memory_usage
28
+ )
29
+
30
+ # Imports dataset avec gestion d'erreur
31
+ try:
32
+ from datasets import Dataset, load_dataset
33
+ DATASET_AVAILABLE = True
34
+ print("✅ Modules dataset disponibles")
35
+ except ImportError as e:
36
+ DATASET_AVAILABLE = False
37
+ print(f"⚠️ Modules dataset non disponibles: {e}")
38
+
39
+ # Nom du nouveau dataset
40
+ DATASET_NAME = "hoololi/calcul_ocr_dataset"
41
+
42
+ # Configuration des difficultés par opération
43
+ DIFFICULTY_RANGES = {
44
+ "×": {
45
+ "Facile": (2, 9),
46
+ "Difficile": (4, 12)
47
+ },
48
+ "+": {
49
+ "Facile": (1, 50),
50
+ "Difficile": (10, 100)
51
+ },
52
+ "-": {
53
+ "Facile": (1, 50),
54
+ "Difficile": (10, 100)
55
+ },
56
+ "÷": {
57
+ "Facile": (1, 10), # Pour les résultats
58
+ "Difficile": (2, 12) # Pour les résultats
59
+ }
60
+ }
61
+
62
+ def create_result_row_with_images(i: int, image: dict | np.ndarray | Image.Image, expected: int, operation_data: tuple[int, int, str, int]) -> dict:
63
+
64
+ # OCR optimisé
65
+ recognized, optimized_image, dataset_image_data = recognize_number_fast_with_image(image)
66
+
67
+ try:
68
+ recognized_num = int(recognized) if recognized.isdigit() else 0
69
+ except:
70
+ recognized_num = 0
71
+
72
+ is_correct = recognized_num == expected
73
+ a, b, operation, correct_result = operation_data
74
+
75
+ status_icon = "✅" if is_correct else "❌"
76
+ status_text = "Correct" if is_correct else "Incorrect"
77
+ row_color = "#e8f5e8" if is_correct else "#ffe8e8"
78
+
79
+ # Miniature
80
+ image_thumbnail = create_thumbnail_fast(optimized_image, size=(50, 50))
81
+
82
+ # Libérer mémoire
83
+ if optimized_image and hasattr(optimized_image, 'close'):
84
+ try:
85
+ optimized_image.close()
86
+ except:
87
+ pass
88
+
89
+ return {
90
+ 'html_row': f"""
91
+ <tr style="background-color: {row_color};">
92
+ <td style="text-align: center; padding: 8px; border: 1px solid #ddd; color: #333;">{i+1}</td>
93
+ <td style="text-align: center; padding: 8px; border: 1px solid #ddd; font-weight: bold; color: #333;">{a}</td>
94
+ <td style="text-align: center; padding: 8px; border: 1px solid #ddd; font-weight: bold; color: #333;">{operation}</td>
95
+ <td style="text-align: center; padding: 8px; border: 1px solid #ddd; font-weight: bold; color: #333;">{b}</td>
96
+ <td style="text-align: center; padding: 8px; border: 1px solid #ddd; font-weight: bold; color: #333;">{expected}</td>
97
+ <td style="text-align: center; padding: 8px; border: 1px solid #ddd;">{image_thumbnail}</td>
98
+ <td style="text-align: center; padding: 8px; border: 1px solid #ddd; font-weight: bold; color: #333;">{recognized_num}</td>
99
+ <td style="text-align: center; padding: 8px; border: 1px solid #ddd; color: #333;">{status_icon} {status_text}</td>
100
+ </tr>
101
+ """,
102
+ 'is_correct': is_correct,
103
+ 'recognized': recognized,
104
+ 'recognized_num': recognized_num,
105
+ 'dataset_image_data': dataset_image_data
106
+ }
107
+
108
+
109
+ class MathGame:
110
+ """Moteur de jeu mathématique complet"""
111
+
112
+ def __init__(self):
113
+ self.is_running = False
114
+ self.start_time = 0
115
+ self.current_operation = ""
116
+ self.correct_answer = 0
117
+ self.user_images = []
118
+ self.expected_answers = []
119
+ self.operations_history = []
120
+ self.question_count = 0
121
+ self.time_remaining = 30
122
+ self.session_data = []
123
+
124
+ # Configuration session
125
+ self.duration = 30
126
+ self.operation_type = "×"
127
+ self.difficulty = "Facile"
128
+
129
+ # Gestion export
130
+ self.export_status = "not_exported"
131
+ self.export_timestamp = None
132
+ self.export_result = None
133
+
134
+ def get_export_status(self) -> dict[str, str | bool | None]:
135
+ return {
136
+ "status": self.export_status,
137
+ "timestamp": self.export_timestamp,
138
+ "result": self.export_result,
139
+ "can_export": self.export_status == "not_exported" and len(self.session_data) > 0
140
+ }
141
+
142
+ def mark_export_in_progress(self) -> None:
143
+ self.export_status = "exporting"
144
+ self.export_timestamp = datetime.datetime.now().isoformat()
145
+
146
+ def mark_export_completed(self, result: str) -> None:
147
+ self.export_status = "exported"
148
+ self.export_result = result
149
+
150
+ def generate_multiplication(self, difficulty: str) -> tuple[str, int]:
151
+ """Génère une multiplication"""
152
+ min_val, max_val = DIFFICULTY_RANGES["×"][difficulty]
153
+ a = random.randint(min_val, max_val)
154
+ b = random.randint(min_val, max_val)
155
+ return f"{a} × {b}", a * b
156
+
157
+ def generate_addition(self, difficulty: str) -> tuple[str, int]:
158
+ """Génère une addition"""
159
+ min_val, max_val = DIFFICULTY_RANGES["+"][difficulty]
160
+ a = random.randint(min_val, max_val)
161
+ b = random.randint(min_val, max_val)
162
+ return f"{a} + {b}", a + b
163
+
164
+ def generate_subtraction(self, difficulty: str) -> tuple[str, int]:
165
+ """Génère une soustraction (résultat toujours positif)"""
166
+ min_val, max_val = DIFFICULTY_RANGES["-"][difficulty]
167
+ a = random.randint(min_val, max_val)
168
+ b = random.randint(min_val, a) # b <= a pour éviter les négatifs
169
+ return f"{a} - {b}", a - b
170
+
171
+ def generate_division(self, difficulty: str) -> tuple[str, int]:
172
+ """Génère une division exacte"""
173
+ min_result, max_result = DIFFICULTY_RANGES["÷"][difficulty]
174
+ result = random.randint(min_result, max_result)
175
+ if difficulty == "Facile":
176
+ divisor = random.randint(2, 9)
177
+ else:
178
+ divisor = random.randint(2, 12)
179
+ dividend = result * divisor
180
+ return f"{dividend} ÷ {divisor}", result
181
+
182
+ def generate_operation(self, operation_type: str, difficulty: str) -> tuple[str, int]:
183
+ """Génère une opération selon le type et la difficulté"""
184
+ if operation_type == "×":
185
+ return self.generate_multiplication(difficulty)
186
+ elif operation_type == "+":
187
+ return self.generate_addition(difficulty)
188
+ elif operation_type == "-":
189
+ return self.generate_subtraction(difficulty)
190
+ elif operation_type == "÷":
191
+ return self.generate_division(difficulty)
192
+ elif operation_type == "Aléatoire":
193
+ # Choisir aléatoirement une opération
194
+ random_op = random.choice(["×", "+", "-", "÷"])
195
+ return self.generate_operation(random_op, difficulty)
196
+ else:
197
+ # Par défaut, multiplication
198
+ return self.generate_multiplication(difficulty)
199
+
200
+ def start_game(self, duration: str, operation: str, difficulty: str) -> tuple[str, Image.Image, str, str, gr.update, gr.update, str]:
201
+ """Démarre le jeu avec la configuration choisie"""
202
+
203
+ log_memory_usage("avant nettoyage start_game")
204
+
205
+ # Configuration
206
+ self.duration = 60 if duration == "60 secondes" else 30
207
+ self.operation_type = operation
208
+ self.difficulty = difficulty
209
+
210
+ # Nettoyage
211
+ if hasattr(self, 'user_images') and self.user_images:
212
+ for img in self.user_images:
213
+ if hasattr(img, 'close'):
214
+ try:
215
+ img.close()
216
+ except:
217
+ pass
218
+
219
+ if hasattr(self, 'session_data') and self.session_data:
220
+ for entry in self.session_data:
221
+ if 'user_drawing' in entry and entry['user_drawing']:
222
+ entry['user_drawing'] = None
223
+ self.session_data.clear()
224
+
225
+ # Réinit
226
+ self.is_running = True
227
+ self.start_time = time.time()
228
+ self.user_images = []
229
+ self.expected_answers = []
230
+ self.operations_history = []
231
+ self.question_count = 0
232
+ self.time_remaining = self.duration
233
+ self.session_data = []
234
+
235
+ # Reset export
236
+ self.export_status = "not_exported"
237
+ self.export_timestamp = None
238
+ self.export_result = None
239
+
240
+ gc.collect()
241
+ log_memory_usage("après nettoyage start_game")
242
+
243
+ # Première opération
244
+ operation_str, answer = self.generate_operation(self.operation_type, self.difficulty)
245
+ self.current_operation = operation_str
246
+ self.correct_answer = answer
247
+
248
+ # Parser l'opération pour l'historique
249
+ parts = operation_str.split()
250
+ a, op, b = int(parts[0]), parts[1], int(parts[2])
251
+ self.operations_history.append((a, b, op, answer))
252
+
253
+ # Affichage adapté selon l'opération
254
+ operation_emoji = {
255
+ "×": "✖️", "+": "➕", "-": "➖", "÷": "➗", "Aléatoire": "🎲"
256
+ }
257
+ emoji = operation_emoji.get(self.operation_type, "🔢")
258
+
259
+ return (
260
+ f'<div style="font-size: 3em; font-weight: bold; text-align: center; padding: 20px; background: linear-gradient(45deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px;">{operation_str}</div>',
261
+ create_white_canvas(),
262
+ f"🎯 {emoji} {self.operation_type} • {self.difficulty} • Écrivez votre réponse !",
263
+ f"⏱️ Temps restant: {self.time_remaining}s",
264
+ gr.update(interactive=False),
265
+ gr.update(interactive=True),
266
+ ""
267
+ )
268
+
269
+ def next_question(self, image_data: dict | np.ndarray | Image.Image | None) -> tuple[str, Image.Image, str, str, gr.update, gr.update, str]:
270
+ if not self.is_running:
271
+ return (
272
+ f'<div style="font-size: 3em; font-weight: bold; text-align: center; padding: 20px; background: linear-gradient(45deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px;">{self.current_operation}</div>',
273
+ image_data,
274
+ "❌ Le jeu n'est pas en cours !",
275
+ "⏱️ Temps: 0s",
276
+ gr.update(interactive=True),
277
+ gr.update(interactive=False),
278
+ ""
279
+ )
280
+
281
+ elapsed_time = time.time() - self.start_time
282
+ if elapsed_time >= self.duration:
283
+ return self.end_game(image_data)
284
+
285
+ if image_data is not None:
286
+ self.user_images.append(image_data)
287
+ self.expected_answers.append(self.correct_answer)
288
+ self.question_count += 1
289
+
290
+ # Nouvelle opération
291
+ operation_str, answer = self.generate_operation(self.operation_type, self.difficulty)
292
+ self.current_operation = operation_str
293
+ self.correct_answer = answer
294
+
295
+ # Parser pour l'historique
296
+ parts = operation_str.split()
297
+ a, op, b = int(parts[0]), parts[1], int(parts[2])
298
+ self.operations_history.append((a, b, op, answer))
299
+
300
+ time_remaining = max(0, self.duration - int(elapsed_time))
301
+ self.time_remaining = time_remaining
302
+
303
+ if time_remaining <= 0:
304
+ return self.end_game(image_data)
305
+
306
+ # Emoji pour l'opération
307
+ operation_emoji = {
308
+ "×": "✖️", "+": "➕", "-": "➖", "÷": "➗", "Aléatoire": "🎲"
309
+ }
310
+ emoji = operation_emoji.get(self.operation_type, "🔢")
311
+
312
+ return (
313
+ f'<div style="font-size: 3em; font-weight: bold; text-align: center; padding: 20px; background: linear-gradient(45deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px;">{operation_str}</div>',
314
+ create_white_canvas(),
315
+ f"🎯 {emoji} Question {self.question_count + 1} • {self.difficulty}",
316
+ f"⏱️ Temps restant: {time_remaining}s",
317
+ gr.update(interactive=False),
318
+ gr.update(interactive=True),
319
+ ""
320
+ )
321
+
322
+ def end_game(self, final_image: dict | np.ndarray | Image.Image | None) -> tuple[str, Image.Image, str, str, gr.update, gr.update, str]:
323
+
324
+ self.is_running = False
325
+
326
+ log_memory_usage("début end_game")
327
+
328
+ if final_image is not None:
329
+ self.user_images.append(final_image)
330
+ self.expected_answers.append(self.correct_answer)
331
+ self.question_count += 1
332
+ if len(self.operations_history) < len(self.user_images):
333
+ parts = self.current_operation.split()
334
+ a, op, b = int(parts[0]), parts[1], int(parts[2])
335
+ self.operations_history.append((a, b, op, self.correct_answer))
336
+
337
+ correct_answers = 0
338
+ total_questions = len(self.user_images)
339
+ table_rows_html = ""
340
+
341
+ session_timestamp = datetime.datetime.now().isoformat()
342
+ session_id = f"session_{int(datetime.datetime.now().timestamp())}_{str(uuid.uuid4())[:8]}"
343
+
344
+ self.session_data = []
345
+ images_saved = 0
346
+ total_image_size_kb = 0
347
+
348
+ # Traitement optimisé
349
+ print(f"🔄 Traitement de {total_questions} images...")
350
+
351
+ for i, (image, expected, operation_data) in enumerate(zip(self.user_images, self.expected_answers, self.operations_history)):
352
+ row_data = create_result_row_with_images(i, image, expected, operation_data)
353
+ table_rows_html += row_data['html_row']
354
+
355
+ if row_data['is_correct']:
356
+ correct_answers += 1
357
+
358
+ # Structure pour NOUVEAU DATASET CALCUL OCR
359
+ a, b, operation, correct_result = operation_data
360
+
361
+ entry = {
362
+ "session_id": session_id,
363
+ "timestamp": session_timestamp,
364
+ "question_number": i + 1,
365
+
366
+ # Configuration session
367
+ "session_duration": self.duration,
368
+ "operation_type": self.operation_type,
369
+ "difficulty_level": self.difficulty,
370
+
371
+ # Mathématiques
372
+ "operand_a": a,
373
+ "operand_b": b,
374
+ "operation": operation,
375
+ "correct_answer": expected,
376
+
377
+ # OCR & Résultats
378
+ "user_answer_ocr": row_data['recognized'],
379
+ "user_answer_parsed": row_data['recognized_num'],
380
+ "is_correct": row_data['is_correct'],
381
+
382
+ # Métadonnées
383
+ "total_questions": total_questions,
384
+ "app_version": "3.0_calcul_ocr"
385
+ }
386
+
387
+ # Ajouter image si disponible
388
+ if row_data['dataset_image_data']:
389
+ entry["handwriting_image"] = row_data['dataset_image_data']["image_base64"]
390
+ entry["image_width"] = int(row_data['dataset_image_data']["compressed_size"][0])
391
+ entry["image_height"] = int(row_data['dataset_image_data']["compressed_size"][1])
392
+ entry["image_size_kb"] = float(row_data['dataset_image_data']["file_size_kb"])
393
+ entry["has_image"] = True
394
+ images_saved += 1
395
+ total_image_size_kb += row_data['dataset_image_data']["file_size_kb"]
396
+ else:
397
+ entry["has_image"] = False
398
+
399
+ self.session_data.append(entry)
400
+
401
+ accuracy = (correct_answers / total_questions * 100) if total_questions > 0 else 0
402
+
403
+ for entry in self.session_data:
404
+ entry["session_accuracy"] = accuracy
405
+
406
+ # Nettoyage mémoire
407
+ for img in self.user_images:
408
+ if hasattr(img, 'close'):
409
+ try:
410
+ img.close()
411
+ except:
412
+ pass
413
+
414
+ gc.collect()
415
+ log_memory_usage("après nettoyage end_game")
416
+
417
+ # HTML résultats
418
+ table_html = f"""
419
+ <div style="overflow-x: auto; margin: 20px 0;">
420
+ <table style="width: 100%; border-collapse: collapse; border: 2px solid #4a90e2;">
421
+ <thead>
422
+ <tr style="background: #4a90e2; color: white;">
423
+ <th style="padding: 8px;">Question</th>
424
+ <th style="padding: 8px;">A</th>
425
+ <th style="padding: 8px;">Op</th>
426
+ <th style="padding: 8px;">B</th>
427
+ <th style="padding: 8px;">Réponse</th>
428
+ <th style="padding: 8px;">Votre dessin</th>
429
+ <th style="padding: 8px;">OCR</th>
430
+ <th style="padding: 8px;">Statut</th>
431
+ </tr>
432
+ </thead>
433
+ <tbody>
434
+ {table_rows_html}
435
+ </tbody>
436
+ </table>
437
+ </div>
438
+ """
439
+
440
+ # Configuration session pour affichage
441
+ config_display = f"{self.operation_type} • {self.difficulty} • {self.duration}s"
442
+ operation_emoji = {
443
+ "×": "✖️", "+": "➕", "-": "➖", "÷": "➗", "Aléatoire": "🎲"
444
+ }
445
+ emoji = operation_emoji.get(self.operation_type, "🔢")
446
+
447
+ export_info = self.get_export_status()
448
+ if export_info["can_export"]:
449
+ export_section = f"""
450
+ <div style="margin-top: 20px; padding: 15px; background-color: #e8f5e8; border-radius: 8px;">
451
+ <h3 style="color: #2e7d32;">📤 Ajouter cette série au dataset ?</h3>
452
+ <p style="color: #2e7d32;">
453
+ ✅ {total_questions} réponses • 📊 {accuracy:.1f}% de précision<br>
454
+ 📸 {images_saved} opérations et images sauvegardées ({total_image_size_kb:.1f}KB)<br>
455
+ ⚙️ Configuration: {config_display}
456
+ </p>
457
+ </div>
458
+ """
459
+ else:
460
+ export_section = ""
461
+
462
+ final_results = f"""
463
+ <div style="margin: 20px 0;">
464
+ <h1 style="text-align: center; color: #4a90e2;">🎉 Session terminée !</h1>
465
+ <div style="background: linear-gradient(45deg, #667eea 0%, #764ba2 100%); color: white; padding: 20px; border-radius: 10px; margin: 20px 0;">
466
+ <h2>📈 Résultats</h2>
467
+ <div style="text-align: center; margin-bottom: 15px;">
468
+ <strong>{emoji} {config_display}</strong>
469
+ </div>
470
+ <div style="display: flex; justify-content: space-around; flex-wrap: wrap;">
471
+ <div style="text-align: center; margin: 10px;">
472
+ <div style="font-size: 2em; font-weight: bold; color: #90EE90;">{correct_answers}</div>
473
+ <div>Correctes</div>
474
+ </div>
475
+ <div style="text-align: center; margin: 10px;">
476
+ <div style="font-size: 2em; font-weight: bold; color: #FFB6C1;">{total_questions - correct_answers}</div>
477
+ <div>Incorrectes</div>
478
+ </div>
479
+ <div style="text-align: center; margin: 10px;">
480
+ <div style="font-size: 2em; font-weight: bold;">{accuracy:.1f}%</div>
481
+ <div>Précision</div>
482
+ </div>
483
+ </div>
484
+ </div>
485
+ <h2 style="color: #4a90e2;">📊 Détail des Réponses</h2>
486
+ {table_html}
487
+ {export_section}
488
+ </div>
489
+ """
490
+
491
+ return (
492
+ """<div style="font-size: 3em; font-weight: bold; text-align: center; padding: 20px; background: linear-gradient(45deg, #667eea 0%, #764ba2 100%); color: white; border-radius: 10px;">🏁 C'est fini !</div>""",
493
+ create_white_canvas(),
494
+ f"✨ Session {config_display} terminée !",
495
+ "⏱️ Temps écoulé !",
496
+ gr.update(interactive=True),
497
+ gr.update(interactive=False),
498
+ final_results
499
+ )
500
+
501
+
502
+ def export_to_clean_dataset(session_data: list[dict], dataset_name: str = DATASET_NAME) -> str:
503
+ """Export vers le nouveau dataset calcul_ocr_dataset"""
504
+ if not DATASET_AVAILABLE:
505
+ return "❌ Modules dataset non disponibles"
506
+
507
+ hf_token = os.getenv("HF_TOKEN")
508
+ if not hf_token:
509
+ return "❌ Token HuggingFace manquant"
510
+
511
+ try:
512
+ print(f"\n🚀 === EXPORT VERS DATASET CALCUL OCR ===")
513
+ print(f"📊 Dataset: {dataset_name}")
514
+
515
+ # Filtrer les entrées avec images
516
+ clean_entries = []
517
+
518
+ for entry in session_data:
519
+ if entry.get('has_image', False):
520
+ clean_entries.append(entry)
521
+
522
+ print(f"✅ {len(clean_entries)} entrées avec images converties")
523
+
524
+ if len(clean_entries) == 0:
525
+ return "❌ Aucune entrée avec image à exporter"
526
+
527
+ # Charger dataset existant OU créer nouveau
528
+ try:
529
+ existing_dataset = load_dataset(dataset_name, split="train")
530
+ existing_data = existing_dataset.to_list()
531
+ print(f"📊 {len(existing_data)} entrées existantes")
532
+ except:
533
+ existing_data = []
534
+ print("📊 Création nouveau dataset calcul_ocr")
535
+
536
+ # Combiner
537
+ combined_data = existing_data + clean_entries
538
+ clean_dataset = Dataset.from_list(combined_data)
539
+
540
+ print(f"✅ Dataset créé - Features:")
541
+ for feature_name in clean_dataset.features:
542
+ print(f" - {feature_name}: {clean_dataset.features[feature_name]}")
543
+
544
+ # Statistiques par opération
545
+ operations_count = {}
546
+ for entry in clean_entries:
547
+ op = entry.get('operation_type', 'unknown')
548
+ operations_count[op] = operations_count.get(op, 0) + 1
549
+
550
+ operations_summary = ", ".join([f"{op}: {count}" for op, count in operations_count.items()])
551
+
552
+ # Push vers HuggingFace
553
+ print(f"📤 Push vers {dataset_name}...")
554
+ clean_dataset.push_to_hub(
555
+ dataset_name,
556
+ private=False,
557
+ token=hf_token,
558
+ commit_message=f"Add {len(clean_entries)} handwriting samples for math OCR ({operations_summary})"
559
+ )
560
+
561
+ cleanup_memory()
562
+
563
+ return f"""✅ Session ajoutée au dataset avec succès !
564
+
565
+ 📊 **Dataset:** {dataset_name}
566
+ 📸 **Images:** {len(clean_entries)}
567
+ 🔢 **Opérations:** {operations_summary}
568
+ 📈 **Total:** {len(clean_dataset)}
569
+
570
+ 🔗 Le dataset est consultable ici : https://huggingface.co/datasets/{dataset_name}"""
571
+
572
+ except Exception as e:
573
+ print(f"❌ ERREUR: {e}")
574
+ import traceback
575
+ traceback.print_exc()
576
+ return f"❌ Erreur: {str(e)}": bold;">{total_questions}</div>
577
+ <div>Questions</div>
578
+ </div>
579
+ <div style="text-align: center; margin: 10px;">
580
+ <div style="font-size: 2em; font-weight
image_processing.py ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ==========================================
2
+ # image_processing.py - Calcul OCR v3.0
3
+ # ==========================================
4
+
5
+ """
6
+ Module de traitement d'images pour calculs mathématiques
7
+ """
8
+
9
+ from PIL import Image, ImageEnhance
10
+ import numpy as np
11
+ import base64
12
+ from io import BytesIO
13
+ import gc
14
+ import os
15
+
16
+ # Variables globales pour le modèle OCR
17
+ processor = None
18
+ model = None
19
+
20
+ def init_ocr_model() -> bool:
21
+ """Initialise le modèle OCR pour les calculs"""
22
+ global processor, model
23
+
24
+ try:
25
+ print("🔄 Chargement du modèle TrOCR pour calculs...")
26
+ from transformers import TrOCRProcessor, VisionEncoderDecoderModel
27
+
28
+ processor = TrOCRProcessor.from_pretrained('microsoft/trocr-base-handwritten')
29
+ model = VisionEncoderDecoderModel.from_pretrained('microsoft/trocr-base-handwritten')
30
+
31
+ print("✅ Modèle TrOCR chargé avec succès !")
32
+ return True
33
+
34
+ except Exception as e:
35
+ print(f"❌ Erreur lors du chargement du modèle: {e}")
36
+ return False
37
+
38
+ def create_white_canvas(width: int = 300, height: int = 300) -> Image.Image:
39
+ """Crée un canvas blanc pour le dessin de calculs"""
40
+ return Image.new('RGB', (width, height), 'white')
41
+
42
+ def log_memory_usage(context: str = "") -> None:
43
+ """Log l'usage mémoire actuel"""
44
+ try:
45
+ import psutil
46
+ process = psutil.Process(os.getpid())
47
+ memory_mb = process.memory_info().rss / 1024 / 1024
48
+ print(f"🔍 Mémoire {context}: {memory_mb:.1f}MB")
49
+ except:
50
+ pass
51
+
52
+ def cleanup_memory() -> None:
53
+ """Force le nettoyage mémoire"""
54
+ gc.collect()
55
+
56
+ def optimize_image_for_ocr(image_dict: dict | np.ndarray | Image.Image | None) -> Image.Image | None:
57
+ """Optimisation image pour reconnaissance de nombres"""
58
+ if image_dict is None:
59
+ return None
60
+
61
+ try:
62
+ # Gérer les formats Gradio
63
+ if isinstance(image_dict, dict):
64
+ if 'composite' in image_dict and image_dict['composite'] is not None:
65
+ image = image_dict['composite']
66
+ elif 'background' in image_dict and image_dict['background'] is not None:
67
+ image = image_dict['background']
68
+ else:
69
+ return None
70
+ elif isinstance(image_dict, np.ndarray):
71
+ image = image_dict
72
+ elif isinstance(image_dict, Image.Image):
73
+ image = image_dict
74
+ else:
75
+ return None
76
+
77
+ # Conversion
78
+ if isinstance(image, np.ndarray):
79
+ pil_image = Image.fromarray(image).convert('RGB')
80
+ else:
81
+ pil_image = image.convert('RGB')
82
+
83
+ # Redimensionner si nécessaire pour optimiser OCR
84
+ max_size = 300
85
+ if pil_image.size[0] > max_size or pil_image.size[1] > max_size:
86
+ pil_image.thumbnail((max_size, max_size), Image.Resampling.LANCZOS)
87
+
88
+ return pil_image
89
+
90
+ except Exception:
91
+ return None
92
+
93
+ def prepare_image_for_dataset(image: Image.Image, max_size: tuple[int, int] = (100, 100), quality: int = 60) -> dict[str, str | int | float | tuple] | None:
94
+ """Prépare image pour dataset calcul OCR"""
95
+ try:
96
+ if image is None:
97
+ return None
98
+
99
+ # Copier et redimensionner
100
+ dataset_image = image.copy()
101
+ dataset_image.thumbnail(max_size, Image.Resampling.LANCZOS)
102
+ compressed_size = dataset_image.size
103
+
104
+ # Convertir en base64
105
+ buffer = BytesIO()
106
+ dataset_image.save(buffer, format='PNG', optimize=True, quality=quality)
107
+
108
+ buffer_data = buffer.getvalue()
109
+ image_base64 = base64.b64encode(buffer_data).decode()
110
+ file_size_kb = len(image_base64) / 1024
111
+
112
+ # Structure propre pour dataset
113
+ result = {
114
+ "image_base64": image_base64,
115
+ "compressed_size": compressed_size,
116
+ "file_size_kb": round(file_size_kb, 1),
117
+ "format": "PNG",
118
+ "quality": quality
119
+ }
120
+
121
+ # Nettoyage
122
+ dataset_image.close()
123
+ buffer.close()
124
+
125
+ return result
126
+
127
+ except Exception as e:
128
+ print(f"❌ Erreur préparation image: {e}")
129
+ return None
130
+
131
+ def recognize_number_fast_with_image(image_dict: dict | np.ndarray | Image.Image | None) -> tuple[str, Image.Image | None, dict | None]:
132
+ """OCR pour calculs avec préparation image pour dataset"""
133
+ if image_dict is None or processor is None or model is None:
134
+ return "0", None, None
135
+
136
+ try:
137
+ # Optimiser image
138
+ optimized_image = optimize_image_for_ocr(image_dict)
139
+ if optimized_image is None:
140
+ return "0", None, None
141
+
142
+ # OCR rapide - optimisé pour les nombres de calculs
143
+ pixel_values = processor(images=optimized_image, return_tensors="pt").pixel_values
144
+
145
+ generated_ids = model.generate(
146
+ pixel_values,
147
+ max_length=5, # Augmenté pour les calculs plus complexes
148
+ num_beams=1,
149
+ do_sample=False,
150
+ pad_token_id=processor.tokenizer.pad_token_id
151
+ )
152
+
153
+ result = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
154
+
155
+ # Nettoyage spécialisé pour les calculs
156
+ cleaned_result = ''.join(filter(str.isdigit, result))
157
+
158
+ # Validation pour les résultats de calculs (plus large que multiplications)
159
+ if cleaned_result and len(cleaned_result) <= 4: # Jusqu'à 4 chiffres
160
+ final_result = cleaned_result
161
+ else:
162
+ final_result = "0"
163
+
164
+ # Préparer pour dataset
165
+ dataset_image_data = prepare_image_for_dataset(optimized_image)
166
+
167
+ return final_result, optimized_image, dataset_image_data
168
+
169
+ except Exception as e:
170
+ print(f"❌ Erreur OCR calcul: {e}")
171
+ return "0", None, None
172
+
173
+ def recognize_number_fast(image_dict: dict | np.ndarray | Image.Image | None) -> tuple[str, Image.Image | None]:
174
+ """Version rapide standard pour calculs"""
175
+ result, optimized_image, _ = recognize_number_fast_with_image(image_dict)
176
+ return result, optimized_image
177
+
178
+ def recognize_number(image_dict: dict | np.ndarray | Image.Image | None) -> str:
179
+ """Interface standard pour reconnaissance de calculs"""
180
+ result, _ = recognize_number_fast(image_dict)
181
+ return result
182
+
183
+ def create_thumbnail_fast(optimized_image: Image.Image | None, size: tuple[int, int] = (40, 40)) -> str:
184
+ """Création miniature rapide pour calculs"""
185
+ try:
186
+ if optimized_image is None:
187
+ return "📝"
188
+
189
+ thumbnail = optimized_image.copy()
190
+ thumbnail.thumbnail(size, Image.Resampling.LANCZOS)
191
+
192
+ buffer = BytesIO()
193
+ thumbnail.save(buffer, format='PNG', optimize=True, quality=70)
194
+ img_str = base64.b64encode(buffer.getvalue()).decode()
195
+
196
+ thumbnail.close()
197
+ buffer.close()
198
+
199
+ return f'<img src="data:image/png;base64,{img_str}" width="{size[0]}" height="{size[1]}" style="border: 1px solid #ccc; border-radius: 3px;" alt="Réponse calcul">'
200
+
201
+ except Exception:
202
+ return "📝"
203
+
204
+ # Fonction utilitaire pour fine-tuning calculs
205
+ def decode_image_from_dataset(base64_string: str) -> Image.Image | None:
206
+ """Décode une image depuis le dataset pour fine-tuning calculs"""
207
+ try:
208
+ image_bytes = base64.b64decode(base64_string)
209
+ image = Image.open(BytesIO(image_bytes))
210
+ return image
211
+ except Exception as e:
212
+ print(f"Erreur décodage calcul: {e}")
213
+ return None
214
+
215
+ # Fonctions d'analyse pour différents types de calculs
216
+ def analyze_calculation_complexity(operand_a: int, operand_b: int, operation: str) -> dict:
217
+ """Analyse la complexité d'un calcul pour le dataset"""
218
+ complexity_score = 0
219
+
220
+ if operation == "×":
221
+ complexity_score = max(operand_a, operand_b)
222
+ elif operation == "+":
223
+ complexity_score = (operand_a + operand_b) / 20
224
+ elif operation == "-":
225
+ complexity_score = max(operand_a, operand_b) / 10
226
+ elif operation == "÷":
227
+ complexity_score = operand_a / 10
228
+
229
+ return {
230
+ "complexity_score": round(complexity_score, 2),
231
+ "difficulty_category": "easy" if complexity_score < 5 else "medium" if complexity_score < 10 else "hard"
232
+ }
requirements.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ transformers>=4.30.0
3
+ torch>=2.0.0
4
+ torchvision>=0.15.0
5
+ pillow>=9.0.0
6
+ numpy>=1.21.0
7
+ datasets>=2.10.0
8
+ huggingface_hub>=0.16.0
9
+ pandas>=1.5.0
10
+ psutil>=5.8.0