File size: 24,643 Bytes
e28d5a2
662cf94
 
e28d5a2
662cf94
 
 
e28d5a2
662cf94
 
9f7873d
662cf94
e28d5a2
 
 
 
 
 
 
 
662cf94
e28d5a2
 
662cf94
 
 
 
 
 
 
 
 
e28d5a2
662cf94
 
 
 
 
 
 
 
e28d5a2
 
 
 
 
 
 
 
 
 
 
 
9f7873d
 
e28d5a2
 
 
 
 
 
 
 
 
 
9f7873d
 
 
 
 
 
e28d5a2
 
662cf94
e28d5a2
 
 
 
 
 
 
 
 
 
662cf94
 
e28d5a2
 
 
 
 
 
 
 
 
 
662cf94
e28d5a2
 
 
 
 
 
 
 
 
 
662cf94
e28d5a2
 
 
 
662cf94
e28d5a2
662cf94
 
e28d5a2
 
 
 
662cf94
e28d5a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
662cf94
e28d5a2
662cf94
e28d5a2
 
662cf94
e28d5a2
 
 
 
 
 
 
 
 
 
 
 
662cf94
e28d5a2
 
 
 
9f7873d
e28d5a2
 
662cf94
 
 
e28d5a2
 
 
 
 
 
 
662cf94
e28d5a2
 
662cf94
 
 
e28d5a2
 
662cf94
 
e28d5a2
 
 
662cf94
e28d5a2
 
 
9f7873d
662cf94
e28d5a2
 
 
662cf94
e28d5a2
 
 
 
 
 
 
 
662cf94
e28d5a2
 
 
 
9f7873d
e28d5a2
 
 
 
 
9f7873d
e28d5a2
 
 
 
 
 
 
662cf94
e28d5a2
 
 
 
662cf94
e28d5a2
 
 
 
662cf94
 
e28d5a2
662cf94
e28d5a2
662cf94
e28d5a2
662cf94
 
e28d5a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
662cf94
 
 
e28d5a2
 
 
 
 
 
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
# --- START OF FLASK APP SCRIPT ---
from flask import Flask, render_template, request, send_file
import os
import convertapi # For PDF conversion
from docx import Document
from docx.shared import Pt, Cm, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL, WD_ROW_HEIGHT_RULE
from docx.oxml.ns import nsdecls
from docx.oxml import parse_xml
import math

# --- Configuration ---
# IMPORTANT: Replace 'YOUR_SECRET' with your actual ConvertAPI secret
# You can get one from https://www.convertapi.com/a
convertapi.api_secret = 'YOUR_SECRET'
# Define a temporary directory for generated files (optional, adjust as needed)
UPLOAD_FOLDER = 'temp_files'
if not os.path.exists(UPLOAD_FOLDER):
    os.makedirs(UPLOAD_FOLDER)


# --- Classe de génération de document (Version 4 - Finalized) ---
class EvaluationGymnique:
    def __init__(self):
        self.document = Document()
        self.document.sections[0].page_height = Cm(29.7)
        self.document.sections[0].page_width = Cm(21)
        self.document.sections[0].left_margin = Cm(1.5)
        self.document.sections[0].right_margin = Cm(1.5)
        self.document.sections[0].top_margin = Cm(1)
        self.document.sections[0].bottom_margin = Cm(1)

        self.centre_examen = "Centre d'examen"
        self.type_examen = "Bac Général"
        self.serie = "Série"
        self.etablissement = "Établissement"
        self.session = "2025"
        self.nom_candidat = "Candidat"
        self.elements_techniques = []
        self.appreciations = ["M", "PM", "NM", "NR"]
        self.base_font_size = 10
        self.base_header_font_size = 14
        self.base_row_height = 1.2
        self.table_font_size = 9
        self.available_height = 27.7
        self.fixed_elements_height = 15
        self.dynamic_font_size = self.base_font_size
        self.dynamic_header_font_size = self.base_header_font_size
        self.dynamic_table_font_size = self.table_font_size
        self.dynamic_row_height = self.base_row_height
        self.spacing_factor = 1.0

    def calculate_dynamic_sizing(self):
        num_elements = len(self.elements_techniques)
        estimated_table_height = (num_elements + 1) * self.base_row_height * 1.8
        available_space_for_table = self.available_height - self.fixed_elements_height
        if estimated_table_height > available_space_for_table and num_elements > 0:
            reduction_factor = max(0.5, 1 - (max(0, num_elements - 8) * 0.05))
            self.dynamic_font_size = max(self.base_font_size * reduction_factor, 6)
            self.dynamic_header_font_size = max(self.base_header_font_size * reduction_factor, 9)
            self.dynamic_table_font_size = max(self.table_font_size * reduction_factor, 6)
            self.dynamic_row_height = max(self.base_row_height * (reduction_factor + 0.2), 0.9)
            self.spacing_factor = max(reduction_factor, 0.3)
            # print(f"Adjusting sizes for {num_elements} elements. Factor: {reduction_factor:.2f}") # Optional debug
        else:
            self.dynamic_font_size = self.base_font_size
            self.dynamic_header_font_size = self.base_header_font_size
            self.dynamic_table_font_size = self.table_font_size
            self.dynamic_row_height = self.base_row_height
            self.spacing_factor = 1.0
            # print(f"Using base sizes for {num_elements} elements.") # Optional debug

    def ajouter_entete_colore(self):
        header_paragraph = self.document.add_paragraph(); header_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER; header_paragraph.space_after = Pt(6 * self.spacing_factor)
        header_run = header_paragraph.add_run("ÉVALUATION GYMNASTIQUE"); header_run.bold = True; header_run.font.size = Pt(self.dynamic_header_font_size); header_run.font.color.rgb = RGBColor(0, 32, 96)
        header_table = self.document.add_table(rows=3, cols=2); header_table.style = 'Table Grid'; header_table.autofit = False
        page_width_cm = self.document.sections[0].page_width.cm; left_margin_cm = self.document.sections[0].left_margin.cm; right_margin_cm = self.document.sections[0].right_margin.cm
        available_table_width = page_width_cm - left_margin_cm - right_margin_cm
        col_widths = [available_table_width * 0.55, available_table_width * 0.45]
        for i, width in enumerate(col_widths):
            for cell in header_table.columns[i].cells: cell.width = Cm(width)
        row_height_cm = max(0.6, 0.8 * self.spacing_factor)
        for row in header_table.rows: row.height = Cm(row_height_cm)
        for row in header_table.rows:
            for cell in row.cells:
                cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER; shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="D9E2F3"/>'); cell._tc.get_or_add_tcPr().append(shading_elm)
                for paragraph in cell.paragraphs: paragraph.paragraph_format.space_before = Pt(0); paragraph.paragraph_format.space_after = Pt(0)
        cell = header_table.cell(0, 0); p = cell.paragraphs[0]; run = p.add_run("Centre d'examen: "); run.bold = True; run.font.size = Pt(self.dynamic_font_size); run.font.color.rgb = RGBColor(0, 32, 96); p.add_run(self.centre_examen).font.size = Pt(self.dynamic_font_size)
        cell = header_table.cell(0, 1); p = cell.paragraphs[0]; run = p.add_run("Examen: "); run.bold = True; run.font.size = Pt(self.dynamic_font_size); run.font.color.rgb = RGBColor(0, 32, 96); p.add_run(self.type_examen).font.size = Pt(self.dynamic_font_size)
        cell = header_table.cell(1, 0); p = cell.paragraphs[0]; run = p.add_run("Série: "); run.bold = True; run.font.size = Pt(self.dynamic_font_size); run.font.color.rgb = RGBColor(0, 32, 96); p.add_run(self.serie).font.size = Pt(self.dynamic_font_size)
        cell = header_table.cell(1, 1); p = cell.paragraphs[0]; run = p.add_run("Établissement: "); run.bold = True; run.font.size = Pt(self.dynamic_font_size); run.font.color.rgb = RGBColor(0, 32, 96); p.add_run(self.etablissement).font.size = Pt(self.dynamic_font_size)
        cell = header_table.cell(2, 0); p = cell.paragraphs[0]; run = p.add_run("Session: "); run.bold = True; run.font.size = Pt(self.dynamic_font_size); run.font.color.rgb = RGBColor(0, 32, 96); p.add_run(self.session).font.size = Pt(self.dynamic_font_size)
        cell = header_table.cell(2, 1); p = cell.paragraphs[0]; run = p.add_run("Candidat: "); run.bold = True; run.font.size = Pt(self.dynamic_font_size); run.font.color.rgb = RGBColor(0, 32, 96); p.add_run(self.nom_candidat).font.size = Pt(self.dynamic_font_size)
        self.document.add_paragraph().paragraph_format.space_after = Pt(4 * self.spacing_factor)

    def creer_tableau_elements(self):
        num_elements = len(self.elements_techniques);
        if num_elements == 0: return
        table = self.document.add_table(rows=num_elements + 1, cols=5); table.style = 'Table Grid'; table.alignment = WD_TABLE_ALIGNMENT.CENTER; table.autofit = False
        page_width_cm = self.document.sections[0].page_width.cm; left_margin_cm = self.document.sections[0].left_margin.cm; right_margin_cm = self.document.sections[0].right_margin.cm
        available_table_width = page_width_cm - left_margin_cm - right_margin_cm
        total_prop = 8 + 3 + 2 + 2.5 + 2.5
        col_widths_cm = [available_table_width * (p / total_prop) for p in [8, 3, 2, 2.5, 2.5]]
        for i, width in enumerate(col_widths_cm):
            for cell in table.columns[i].cells: cell.width = Cm(width)
        min_row_height_cm = max(0.9, self.dynamic_row_height)
        for row in table.rows:
            row.height_rule = WD_ROW_HEIGHT_RULE.AT_LEAST; row.height = Cm(min_row_height_cm)
            for cell in row.cells:
                 cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
                 for p in cell.paragraphs: p.paragraph_format.space_before = Pt(0); p.paragraph_format.space_after = Pt(0)
        header_row = table.rows[0]
        for cell in header_row.cells: shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="BDD7EE"/>'); cell._tc.get_or_add_tcPr().append(shading_elm)
        headers = ["ELEMENTS TECHNIQUES", "CATEGORIES D'ELEMENTS TECHNIQUES ET PONDERATION", "", "APPRECIATIONS", "POINTS Accordés"]
        for i, header in enumerate(headers):
            cell = table.cell(0, i); p = cell.paragraphs[0]; p.clear(); p.add_run(header); p.alignment = WD_ALIGN_PARAGRAPH.CENTER
            run = p.runs[0]; run.bold = True; run.font.size = Pt(self.dynamic_table_font_size); run.font.color.rgb = RGBColor(0, 32, 96)
        try: table.cell(0, 1).merge(table.cell(0, 2))
        except Exception as e: print(f"Error merging cells: {e}") # Optional logging
        for i, element in enumerate(self.elements_techniques, 1):
            if i >= len(table.rows): continue
            element_cell = table.cell(i, 0); supplementary_text = "\nExécution:\nAmplitude:\nRéception:"
            element_cell.text = f'{element["nom"]}{supplementary_text}'; element_cell.vertical_alignment = WD_ALIGN_VERTICAL.TOP
            if element_cell.paragraphs and element_cell.paragraphs[0].runs: run = element_cell.paragraphs[0].runs[0]
            else: run = element_cell.paragraphs[0].add_run(f'{element["nom"]}{supplementary_text}')
            run.bold = False; run.font.size = Pt(self.dynamic_table_font_size)
            for p in element_cell.paragraphs: p.paragraph_format.space_before = Pt(0); p.paragraph_format.space_after = Pt(0)
            categorie_cell = table.cell(i, 1); categorie_cell.text = element["categorie"]; categorie_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
            if categorie_cell.paragraphs[0].runs: run = categorie_cell.paragraphs[0].runs[0]
            else: run = categorie_cell.paragraphs[0].add_run(element["categorie"])
            run.bold = True; run.font.size = Pt(self.dynamic_table_font_size); run.italic = True
            points_cell = table.cell(i, 2); points_cell.text = str(element["points"]); points_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
            if points_cell.paragraphs[0].runs: run = points_cell.paragraphs[0].runs[0]
            else: run = points_cell.paragraphs[0].add_run(str(element["points"]))
            run.bold = True; run.font.size = Pt(self.dynamic_table_font_size); run.italic = True
            appreciation_cell = table.cell(i, 3); appreciation_cell.text = ""
            points_accordes_cell = table.cell(i, 4); points_accordes_cell.text = ""
        self.document.add_paragraph().paragraph_format.space_after = Pt(6 * self.spacing_factor)

    def ajouter_note_jury(self):
        para = self.document.add_paragraph(); para.paragraph_format.space_before = Pt(4 * self.spacing_factor); para.paragraph_format.space_after = Pt(4 * self.spacing_factor)
        run = para.add_run("NB1 : Zone réservée aux membres du jury ! Le jury cochera le point correspondant au niveau de réalisation de l'élément gymnique par le candidat.")
        run.bold = True; run.font.color.rgb = RGBColor(255, 0, 0); run.font.size = Pt(max(self.dynamic_font_size - 2, 5.5))

    def creer_tableau_recapitulatif(self):
        note_table = self.document.add_table(rows=3, cols=13); note_table.style = 'Table Grid'; note_table.alignment = WD_TABLE_ALIGNMENT.CENTER; note_table.autofit = False
        page_width_cm = self.document.sections[0].page_width.cm; left_margin_cm = self.document.sections[0].left_margin.cm; right_margin_cm = self.document.sections[0].right_margin.cm
        available_recap_width = page_width_cm - left_margin_cm - right_margin_cm
        width_A_E_pair = available_recap_width * (1.2 / 13.0); width_final_single = available_recap_width * (1.0 / 13.0)
        col_widths_recap = [];
        for _ in range(5): col_widths_recap.extend([width_A_E_pair / 2, width_A_E_pair / 2])
        col_widths_recap.extend([width_final_single, width_final_single, width_final_single])
        current_total_width = sum(col_widths_recap); width_adjustment = (available_recap_width - current_total_width) / len(col_widths_recap)
        for i, width in enumerate(col_widths_recap):
            adjusted_width = max(0.5, width + width_adjustment);
            for cell in note_table.columns[i].cells: cell.width = Cm(adjusted_width)
        row_height_cm = max(0.5, 0.6 * self.spacing_factor)
        for row in note_table.rows:
            row.height = Cm(row_height_cm)
            for cell in row.cells: cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER;
            for p in cell.paragraphs: p.paragraph_format.space_before = Pt(0); p.paragraph_format.space_after = Pt(0)
        for cell in note_table.rows[0].cells: shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="BDD7EE"/>'); cell._tc.get_or_add_tcPr().append(shading_elm)
        recap_font_size = max(self.dynamic_table_font_size - 1, 5)
        type_data = [("A", "1pt"), ("B", "1,5pt"), ("C", "2pts"), ("D", "2,5pts"), ("E", "3pts")]
        for col, (type_lettre, points) in enumerate(type_data):
            idx = col * 2
            if idx + 1 < len(note_table.columns):
                cell = note_table.cell(0, idx)
                try:
                    cell.merge(note_table.cell(0, idx + 1)); p = cell.paragraphs[0]; p.clear(); p.add_run(f"Type {type_lettre}\n{points}"); p.alignment = WD_ALIGN_PARAGRAPH.CENTER
                    for run in p.runs: run.bold = True; run.font.size = Pt(recap_font_size); run.font.color.rgb = RGBColor(0, 32, 96)
                except Exception as e: print(f"Error merging cells at index {idx}: {e}") # Optional logging
        final_headers = [("ROV", "2pts"), ("Projet", "2pts"), ("Réalisation", "16pts")]
        for col_offset, (titre, points) in enumerate(final_headers):
            col = 10 + col_offset
            if col < len(note_table.columns):
                cell = note_table.cell(0, col); p = cell.paragraphs[0]; p.clear(); p.add_run(f"{titre}\n{points}"); p.alignment = WD_ALIGN_PARAGRAPH.CENTER
                for run in p.runs: run.bold = True; run.font.size = Pt(recap_font_size); run.font.color.rgb = RGBColor(0, 32, 96)
        for col in range(5):
            idx = col * 2
            if idx + 1 < len(note_table.columns):
                neg_cell = note_table.cell(1, idx); p_neg = neg_cell.paragraphs[0]; p_neg.clear(); run_neg = p_neg.add_run("NEG"); run_neg.italic = True; run_neg.font.size = Pt(recap_font_size); p_neg.alignment = WD_ALIGN_PARAGRAPH.CENTER
                note_cell = note_table.cell(1, idx + 1); p_note = note_cell.paragraphs[0]; p_note.clear(); run_note = p_note.add_run("Note"); run_note.italic = True; run_note.font.size = Pt(recap_font_size); p_note.alignment = WD_ALIGN_PARAGRAPH.CENTER
        for col in range(10, 13):
            if col < len(note_table.columns):
                cell = note_table.cell(1, col); p = cell.paragraphs[0]; p.clear(); run = p.add_run("Note"); run.italic = True; run.font.size = Pt(recap_font_size); p.alignment = WD_ALIGN_PARAGRAPH.CENTER
        self.document.add_paragraph().paragraph_format.space_after = Pt(6 * self.spacing_factor)

    def ajouter_note_candidat_avec_cadre(self):
        note_table = self.document.add_table(rows=1, cols=1); note_table.style = 'Table Grid'; note_table.alignment = WD_TABLE_ALIGNMENT.CENTER; note_table.autofit = True
        cell = note_table.cell(0, 0); shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="C6E0B4"/>'); cell._tc.get_or_add_tcPr().append(shading_elm)
        p = cell.paragraphs[0]; p.paragraph_format.space_before = Pt(2); p.paragraph_format.space_after = Pt(2)
        font_size = max(6 * self.spacing_factor, 5)
        run = p.add_run("NB2: Après le choix des catégories d'éléments gymniques par le candidat, ce dernier remplira la colonne de pointage selon l'orientation suivante: A (0.25; 0.5; 0.75; 1) B (0.25; 0.5; 0.75; 1; 1.25; 1.5) C (0.5; 0.75; 1; 1.25; 1.5; 2) D (0.75; 1; 1.25; 1.5; 2; 2.5) et E (0.75; 1; 1.5; 2; 2.5; 3) également, le candidat devra fournir 2 copies de son projet sur une page! (appréciations: NR, NM, PM, M).")
        run.italic = True; run.font.size = Pt(font_size)
        self.document.add_paragraph().paragraph_format.space_after = Pt(8 * self.spacing_factor)

    def ajouter_zone_note(self):
        para_note_label = self.document.add_paragraph(); para_note_label.alignment = WD_ALIGN_PARAGRAPH.RIGHT; para_note_label.paragraph_format.space_after = Pt(1); para_note_label.paragraph_format.space_before = Pt(4 * self.spacing_factor)
        run = para_note_label.add_run("Note finale/20"); run.bold = True; run.font.size = Pt(self.dynamic_table_font_size + 1); run.font.color.rgb = RGBColor(0, 32, 96)
        box_table = self.document.add_table(rows=1, cols=1); box_table.style = 'Table Grid'; box_table.alignment = WD_TABLE_ALIGNMENT.RIGHT
        box_size = Cm(1.5); cell = box_table.cell(0, 0); cell.width = box_size; box_table.rows[0].height = box_size
        cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER; cell.text = ""
        if cell.paragraphs: cell.paragraphs[0].text = ""; cell.paragraphs[0].paragraph_format.space_before = Pt(0); cell.paragraphs[0].paragraph_format.space_after = Pt(0)
        self.document.add_paragraph().paragraph_format.space_after = Pt(8 * self.spacing_factor)

    def ajouter_lignes_correcteurs(self):
        num_elements = len(self.elements_techniques); use_compact_mode = num_elements > 12
        if use_compact_mode:
            para = self.document.add_paragraph(); para.paragraph_format.space_before = Pt(4 * self.spacing_factor); para.paragraph_format.space_after = Pt(4 * self.spacing_factor)
            run = para.add_run("Correcteurs: "); run.bold = True; run.font.size = Pt(self.dynamic_font_size); para.add_run("Projet / Principal / ROV").font.size = Pt(self.dynamic_font_size); para.add_run("\n" + "." * 30)
        else:
            for role in ["Projet", "Principal", "ROV"]:
                para = self.document.add_paragraph(); para.paragraph_format.space_before = Pt(3 * self.spacing_factor); para.paragraph_format.space_after = Pt(1 * self.spacing_factor)
                run = para.add_run(f"Correcteur {role} : "); run.bold = True; run.font.size = Pt(self.dynamic_font_size)
                chars_per_cm_estimate = 3; line_length_cm = 10; points_count = int(line_length_cm * chars_per_cm_estimate)
                points_count = max(20, points_count); points_count = int(points_count * (self.dynamic_font_size / 10.0) * self.spacing_factor); points_count = max(15, points_count)
                para.add_run("." * points_count).font.size = Pt(self.dynamic_font_size)

    def modifier_centre_examen(self, nom): self.centre_examen = nom
    def modifier_type_examen(self, type_examen): self.type_examen = type_examen
    def modifier_serie(self, serie): self.serie = serie
    def modifier_etablissement(self, nom): self.etablissement = nom
    def modifier_session(self, annee): self.session = annee
    def modifier_candidat(self, nom): self.nom_candidat = nom
    def ajouter_element(self, nom, categorie, points):
        try: point_value = float(points)
        except (ValueError, TypeError): print(f"Warning: Invalid points value '{points}' for element '{nom}'. Using 0.0."); point_value = 0.0
        self.elements_techniques.append({"nom": nom, "categorie": categorie, "points": point_value})

    def generer_document(self, nom_fichier="evaluation_gymnastique.docx"):
        self.calculate_dynamic_sizing(); self.ajouter_entete_colore(); self.creer_tableau_elements(); self.ajouter_note_jury(); self.creer_tableau_recapitulatif(); self.ajouter_lignes_correcteurs(); self.ajouter_zone_note(); self.ajouter_note_candidat_avec_cadre()
        try:
            self.document.save(nom_fichier); print(f"Document '{nom_fichier}' generated successfully.")
        except Exception as e: print(f"Error saving document: {e}")
        return nom_fichier

# --- Flask Application ---
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route("/eps", methods=["GET", "POST"]) # Changed route back to /eps as in original
def index():
    if request.method == "POST":
        try:
            # --- Récupération des informations depuis le formulaire ---
            centre_examen = request.form.get("centre_examen", "Centre d'examen")
            type_examen = request.form.get("type_examen", "Bac Général")
            serie = request.form.get("serie", "Série")
            etablissement = request.form.get("etablissement", "Établissement")
            session_value = request.form.get("session", "2025")
            nom_candidat = request.form.get("nom_candidat", "Candidat")
            output_format = request.form.get("format", "docx") # Get format preference

            # --- Création et configuration du document ---
            evaluation = EvaluationGymnique()
            evaluation.modifier_centre_examen(centre_examen)
            evaluation.modifier_type_examen(type_examen)
            evaluation.modifier_serie(serie)
            evaluation.modifier_etablissement(etablissement)
            evaluation.modifier_session(session_value)
            evaluation.modifier_candidat(nom_candidat)

            # --- Récupération des éléments techniques ---
            element_names = request.form.getlist("new_element_name")
            element_categories = request.form.getlist("new_element_categorie")
            element_points = request.form.getlist("new_element_points")

            print(f"Received names: {element_names}") # Debug print
            print(f"Received categories: {element_categories}") # Debug print
            print(f"Received points: {element_points}") # Debug print


            for name, cat, pts in zip(element_names, element_categories, element_points):
                # Add element only if all three fields have some value
                if name and cat and pts:
                    evaluation.ajouter_element(name, cat, pts)
                else:
                    print(f"Skipping incomplete element: Name='{name}', Cat='{cat}', Pts='{pts}'") # Debug print


            # --- Génération du document DOCX ---
            # Use a unique filename in the temp folder to avoid conflicts
            base_filename = f"evaluation_{nom_candidat.replace(' ', '_')}_{session_value}"
            docx_filename = os.path.join(app.config['UPLOAD_FOLDER'], f"{base_filename}.docx")
            evaluation.generer_document(docx_filename)

            # --- Conversion et envoi ---
            if output_format == "pdf":
                 if convertapi.api_secret == 'YOUR_SECRET':
                      # Handle case where API secret is not set
                      return "Error: ConvertAPI secret not set in the script. Cannot generate PDF.", 500

                 print(f"Attempting PDF conversion for {docx_filename}...")
                 try:
                    result = convertapi.convert('pdf', { 'File': docx_filename }, from_format = 'docx')
                    pdf_filename_base = f"{base_filename}.pdf"
                    pdf_filepath = os.path.join(app.config['UPLOAD_FOLDER'], pdf_filename_base)
                    result.save_files(pdf_filepath)
                    print(f"PDF saved to {pdf_filepath}")
                    # Send the generated PDF
                    return send_file(pdf_filepath, as_attachment=True, download_name=pdf_filename_base)
                 except Exception as e:
                      print(f"Error during PDF conversion: {e}")
                      # Provide feedback to the user
                      return f"Error during PDF conversion: {e}. Check ConvertAPI credits or file.", 500
                 finally:
                      # Clean up the original docx file after attempting conversion
                      if os.path.exists(docx_filename):
                          os.remove(docx_filename)

            else: # Send the generated DOCX
                # Ensure the download name doesn't include the folder path
                return send_file(docx_filename, as_attachment=True, download_name=f"{base_filename}.docx")

        except Exception as e:
            # Log the general error
            print(f"An error occurred during POST request processing: {e}")
            # Provide generic error feedback
            return f"An internal error occurred: {e}", 500

    # --- Affichage du formulaire (GET request) ---
    return render_template("index.html")

if __name__ == "__main__":
    # Make sure the UPLOAD_FOLDER exists when running directly
    if not os.path.exists(UPLOAD_FOLDER):
        os.makedirs(UPLOAD_FOLDER)
    app.run(debug=True) # debug=True is helpful during development

# --- END OF FLASK APP SCRIPT ---