File size: 7,746 Bytes
271b2e1
3ff3018
271b2e1
 
 
3ff3018
271b2e1
 
 
 
 
 
 
 
8f9af28
271b2e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ff3018
 
 
271b2e1
3ff3018
 
 
 
 
271b2e1
3ff3018
4231f17
271b2e1
3ff3018
 
 
 
 
 
 
271b2e1
3ff3018
 
 
 
271b2e1
3ff3018
271b2e1
 
3ff3018
271b2e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ff3018
271b2e1
 
3ff3018
 
271b2e1
 
 
 
3ff3018
271b2e1
 
3ff3018
271b2e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ff3018
 
 
271b2e1
 
3ff3018
271b2e1
 
 
 
 
 
 
3ff3018
271b2e1
 
 
 
82cf12e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271b2e1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ff3018
271b2e1
 
3ff3018
271b2e1
 
3ff3018
4231f17
271b2e1
 
 
 
3ff3018
 
271b2e1
 
 
 
3ff3018
271b2e1
 
 
 
3ff3018
 
271b2e1
 
 
 
 
 
 
 
 
 
 
 
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
# ==========================================
# app_fixed.py - Calcul OCR v3.0 - Sessions isolées
# ==========================================

"""
Application principale avec isolation des sessions utilisateurs
"""

import gradio as gr
import warnings
import os
import gc
import numpy as np
from PIL import Image
import simple_gpu

warnings.filterwarnings("ignore")

# Import avec structure claire : GPU ou CPU uniquement
try:
    import torch
    if torch.cuda.is_available():
        from image_processing_gpu import init_ocr_model, create_white_canvas, cleanup_memory
        print("📱 Interface: Mode GPU détecté - TrOCR")
    else:
        from image_processing_cpu import init_ocr_model, create_white_canvas, cleanup_memory
        print("📱 Interface: Mode CPU détecté - EasyOCR")
except ImportError:
    from image_processing_cpu import init_ocr_model, create_white_canvas, cleanup_memory
    print("📱 Interface: Mode CPU détecté - EasyOCR")

from game_engine import MathGame, export_to_clean_dataset

print("🚀 Initialisation Calcul OCR v3.0...")
print("🔄 Chargement modèle OCR...")
init_ocr_model()
print("✅ Modèle OCR prêt")

def create_new_game_session():
    """Crée une nouvelle instance de jeu pour chaque session"""
    return MathGame()

def start_game_wrapper(duration: str, operation: str, difficulty: str, game_state) -> tuple:
    """Wrapper avec isolation de session"""
    if game_state is None:
        game_state = create_new_game_session()
    
    cleanup_memory()
    result = game_state.start_game(duration, operation, difficulty)
    return result + (game_state, "")  # Retourner l'état mis à jour

def next_question_wrapper(image_data, game_state) -> tuple:
    """Wrapper avec isolation de session"""
    if game_state is None:
        game_state = create_new_game_session()
    
    result = game_state.next_question(image_data)
    return result + (game_state,)  # Retourner l'état mis à jour

def export_current_session(game_state) -> str:
    """Export avec isolation de session"""
    if game_state is None:
        return "❌ Aucune session active"
    
    if not hasattr(game_state, 'session_data') or not game_state.session_data:
        return "❌ Aucune donnée de session à exporter"
    
    export_info = game_state.get_export_status()
    
    if export_info["status"] == "exported":
        return f"""✅ Session déjà exportée !
        
📅 Exporté le: {export_info['timestamp'][:19].replace('T', ' ')}
📊 Résultat: {export_info['result'][:100]}...

💡 Jouez une nouvelle session pour contribuer davantage !"""
    
    if export_info["status"] == "exporting":
        return "⏳ Export en cours..."
    
    if not export_info["can_export"]:
        return "❌ Aucune donnée à exporter"
    
    game_state.mark_export_in_progress()
    
    try:
        result = export_to_clean_dataset(game_state.session_data)
        game_state.mark_export_completed(result)
        cleanup_memory()
        return result
        
    except Exception as e:
        game_state.export_status = "not_exported"
        return f"❌ Erreur export: {str(e)}"

# Interface Gradio avec State management
with gr.Blocks(
    title="🧮 Calcul OCR - Entraînement mathématiques",
    theme=gr.themes.Soft(),
    css="""
    .gradio-container { max-width: 1200px !important; }
    .config-section { 
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 15px;
        border-radius: 10px;
        margin: 10px 0;
    }
    .dataset-info {
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        color: white;
        padding: 15px;
        border-radius: 10px;
        margin: 10px 0;
    }
    .radio-group {
        background: #f8f9fa;
        padding: 10px;
        border-radius: 8px;
        margin: 5px 0;
    }
    """,
    head="<meta name='viewport' content='width=device-width, initial-scale=1.0'>"
) as demo:

    # ✅ STATE MANAGEMENT - Chaque utilisateur a sa propre instance
    game_state = gr.State(value=None)

    gr.Markdown(
        """
        # 🧮 Entraînement au calcul mental avec OCR
               
        **Comment jouer :**
        1. **Configurez** votre session ci-dessous
        2. Cliquez sur **🚀 GO !** pour démarrer
        3. **Écrivez** ✏️ votre réponse sur le tableau 
        4. Cliquez sur **➡️ NEXT !** pour la question suivante
        
        À la fin, vous pourrez consulter vos résultats et contribuer au dataset ouvert !
        """
    )
    
    # Configuration de la session
    duration_choice = gr.Radio(
        choices=["30 secondes", "60 secondes"],
        value="30 secondes",
        label="**⏱️ Durée**"
    )

    operation_choice = gr.Radio(
        choices=["×", "+", "-", "÷", "Aléatoire"],
        value="×",
        label="**🔢 Opération**"
    )

    difficulty_choice = gr.Radio(
        choices=["Facile", "Difficile"],
        value="Facile",
        label="**🎯 Difficulté**"
    )
    
    with gr.Row():
        with gr.Column(scale=1):
            # Question
            question_display = gr.HTML(
                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>'
            )

            # Contrôles
            with gr.Row():
                go_button = gr.Button("🚀 GO !", variant="primary", size="lg")
                next_button = gr.Button("➡️ NEXT !", variant="secondary", size="lg", interactive=False)

            # Status
            status_display = gr.Markdown("### 🎯 Configurez votre session et cliquez sur GO !")
            timer_display = gr.Markdown("### ⏱️ --")

        with gr.Column(scale=1):
            # Zone de dessin
            canvas = gr.ImageEditor(
                label="✏️ Votre réponse",
                height=350,
                width=350,
                value=create_white_canvas(350, 350),
                brush=gr.Brush(default_size=8, default_color="#000000"),
                sources=[],
                layers=False,
                transforms=[],
                eraser=gr.Eraser(default_size=20)
            )

    # Résultats
    results_display = gr.HTML("")

    # Export vers dataset dédié
    export_button = gr.Button("📤 Exporter la série vers le dataset", variant="primary", size="lg")
    export_status = gr.Markdown("")

    # ✅ ÉVÉNEMENTS avec State management
    go_button.click(
        fn=start_game_wrapper,
        inputs=[duration_choice, operation_choice, difficulty_choice, game_state],
        outputs=[question_display, canvas, status_display, timer_display, go_button, next_button, results_display, game_state, export_status]
    )

    next_button.click(
        fn=next_question_wrapper,
        inputs=[canvas, game_state],
        outputs=[question_display, canvas, status_display, timer_display, go_button, next_button, results_display, game_state]
    )

    export_button.click(
        fn=export_current_session,
        inputs=[game_state],
        outputs=[export_status]
    )

if __name__ == "__main__":
    print("🚀 Lancement Calcul OCR v3.0 - Sessions isolées...")
    print("🔒 Isolation: Chaque utilisateur a sa propre instance")
    print("🎯 Dataset: calcul_ocr_dataset")
    print("📊 Opérations: ×, +, -, ÷, Aléatoire")
    print("⚙️ Durées: 30s, 60s")
    print("🎯 Difficultés: Facile, Difficile")
    demo.launch(
        share=False,
        show_error=True,
        server_name="0.0.0.0",
        server_port=7860,
        show_api=False,
        favicon_path=None
    )