Docfile commited on
Commit
e28d5a2
·
verified ·
1 Parent(s): 9f7873d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +256 -417
app.py CHANGED
@@ -1,18 +1,26 @@
 
1
  from flask import Flask, render_template, request, send_file
2
  import os
3
- import convertapi
4
  from docx import Document
5
  from docx.shared import Pt, Cm, RGBColor
6
  from docx.enum.text import WD_ALIGN_PARAGRAPH
7
- from docx.enum.table import WD_TABLE_ALIGNMENT
8
  from docx.oxml.ns import nsdecls
9
  from docx.oxml import parse_xml
10
  import math
11
 
12
- # Configuration des identifiants ConvertAPI
13
- convertapi.api_credentials = 'secret_8wCI6pgOP9AxLVJG'
 
 
 
 
 
 
14
 
15
- # --- Classe de génération de document ---
 
16
  class EvaluationGymnique:
17
  def __init__(self):
18
  self.document = Document()
@@ -22,472 +30,303 @@ class EvaluationGymnique:
22
  self.document.sections[0].right_margin = Cm(1.5)
23
  self.document.sections[0].top_margin = Cm(1)
24
  self.document.sections[0].bottom_margin = Cm(1)
25
-
26
- # Informations d'en-tête par défaut
27
  self.centre_examen = "Centre d'examen"
28
  self.type_examen = "Bac Général"
29
  self.serie = "Série"
30
  self.etablissement = "Établissement"
31
  self.session = "2025"
32
  self.nom_candidat = "Candidat"
33
-
34
- # Liste vide pour les éléments techniques
35
  self.elements_techniques = []
36
  self.appreciations = ["M", "PM", "NM", "NR"]
37
-
38
- # Paramètres dynamiques pour la mise en page
39
- self.base_font_size = 10 # Taille de base pour les polices
40
- self.base_header_font_size = 14 # Taille de base pour l'en-tête
41
- self.base_row_height = 1 # Hauteur de base pour les lignes en cm
42
- self.table_font_size = 9 # Taille de base pour les tableaux
43
-
44
- # Espace disponible sur une page A4 (en cm)
45
- self.available_height = 27.7 # 29.7 - marges
46
-
47
- # Estimation de l'espace fixe occupé par les éléments autres que le tableau principal
48
- self.fixed_elements_height = 14 # Estimation en cm
49
-
50
  def calculate_dynamic_sizing(self):
51
- """Calcule les tailles dynamiques en fonction du nombre d'éléments techniques"""
52
- # Nombre d'éléments techniques
53
  num_elements = len(self.elements_techniques)
54
-
55
- # Calcul de l'espace nécessaire pour le tableau principal
56
- # Chaque élément nécessite une ligne + une ligne d'en-tête
57
- required_table_height = (num_elements + 1) * self.base_row_height
58
-
59
- # Espace disponible pour le tableau principal
60
- available_space = self.available_height - self.fixed_elements_height
61
-
62
- # Facteur d'ajustement
63
- if required_table_height > available_space and num_elements > 0:
64
- adjustment_factor = available_space / required_table_height
65
- # Ajuster les tailles en fonction du nombre d'éléments
66
- if num_elements <= 5:
67
- # Ajustements mineurs pour peu d'éléments
68
- self.dynamic_font_size = max(self.base_font_size - 1, 7)
69
- self.dynamic_header_font_size = max(self.base_header_font_size - 1, 12)
70
- self.dynamic_table_font_size = max(self.table_font_size - 1, 7)
71
- self.dynamic_row_height = self.base_row_height * 0.9
72
- self.spacing_factor = 0.9
73
- elif num_elements <= 10:
74
- # Ajustements moyens
75
- self.dynamic_font_size = max(self.base_font_size - 2, 6.5)
76
- self.dynamic_header_font_size = max(self.base_header_font_size - 2, 11)
77
- self.dynamic_table_font_size = max(self.table_font_size - 2, 6.5)
78
- self.dynamic_row_height = self.base_row_height * 0.75
79
- self.spacing_factor = 0.7
80
- elif num_elements <= 15:
81
- # Ajustements significatifs
82
- self.dynamic_font_size = max(self.base_font_size - 3, 6)
83
- self.dynamic_header_font_size = max(self.base_header_font_size - 3, 10)
84
- self.dynamic_table_font_size = max(self.table_font_size - 3, 6)
85
- self.dynamic_row_height = self.base_row_height * 0.6
86
- self.spacing_factor = 0.5
87
- else:
88
- # Ajustements maximaux pour beaucoup d'éléments
89
- self.dynamic_font_size = max(self.base_font_size - 4, 5.5)
90
- self.dynamic_header_font_size = max(self.base_header_font_size - 4, 9)
91
- self.dynamic_table_font_size = max(self.table_font_size - 4, 5.5)
92
- self.dynamic_row_height = max(self.base_row_height * 0.5, 0.4) # Minimum 0.4 cm
93
- self.spacing_factor = 0.3
94
  else:
95
- # Aucun ajustement nécessaire
96
  self.dynamic_font_size = self.base_font_size
97
  self.dynamic_header_font_size = self.base_header_font_size
98
  self.dynamic_table_font_size = self.table_font_size
99
  self.dynamic_row_height = self.base_row_height
100
  self.spacing_factor = 1.0
101
-
 
102
  def ajouter_entete_colore(self):
103
- header_paragraph = self.document.add_paragraph()
104
- header_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
105
- header_paragraph.space_after = Pt(6 * self.spacing_factor)
106
- header_run = header_paragraph.add_run("ÉVALUATION GYMNASTIQUE")
107
- header_run.bold = True
108
- header_run.font.size = Pt(self.dynamic_header_font_size)
109
- header_run.font.color.rgb = RGBColor(0, 32, 96)
110
-
111
- header_table = self.document.add_table(rows=3, cols=2)
112
- header_table.style = 'Table Grid'
113
- header_table.autofit = False
114
-
115
- # Ajustement dynamique de la hauteur des lignes
116
- row_height = Cm(0.8 * (self.dynamic_row_height / self.base_row_height))
117
- for row in header_table.rows:
118
- row.height = row_height
119
-
120
  for row in header_table.rows:
121
  for cell in row.cells:
122
- shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="D9E2F3"/>')
123
- cell._tc.get_or_add_tcPr().append(shading_elm)
124
-
125
- # Première ligne
126
- cell = header_table.cell(0, 0)
127
- paragraph = cell.paragraphs[0]
128
- run = paragraph.add_run("Centre d'examen: ")
129
- run.bold = True
130
- run.font.size = Pt(self.dynamic_font_size)
131
- run.font.color.rgb = RGBColor(0, 32, 96)
132
- paragraph.add_run(self.centre_examen).font.size = Pt(self.dynamic_font_size)
133
-
134
- cell = header_table.cell(0, 1)
135
- paragraph = cell.paragraphs[0]
136
- run = paragraph.add_run("Examen: ")
137
- run.bold = True
138
- run.font.size = Pt(self.dynamic_font_size)
139
- run.font.color.rgb = RGBColor(0, 32, 96)
140
- paragraph.add_run(self.type_examen).font.size = Pt(self.dynamic_font_size)
141
-
142
- # Deuxième ligne
143
- cell = header_table.cell(1, 0)
144
- paragraph = cell.paragraphs[0]
145
- run = paragraph.add_run("Série: ")
146
- run.bold = True
147
- run.font.size = Pt(self.dynamic_font_size)
148
- run.font.color.rgb = RGBColor(0, 32, 96)
149
- paragraph.add_run(self.serie).font.size = Pt(self.dynamic_font_size)
150
-
151
- cell = header_table.cell(1, 1)
152
- paragraph = cell.paragraphs[0]
153
- run = paragraph.add_run("Établissement: ")
154
- run.bold = True
155
- run.font.size = Pt(self.dynamic_font_size)
156
- run.font.color.rgb = RGBColor(0, 32, 96)
157
- paragraph.add_run(self.etablissement).font.size = Pt(self.dynamic_font_size)
158
-
159
- # Troisième ligne
160
- cell = header_table.cell(2, 0)
161
- paragraph = cell.paragraphs[0]
162
- run = paragraph.add_run("Session: ")
163
- run.bold = True
164
- run.font.size = Pt(self.dynamic_font_size)
165
- run.font.color.rgb = RGBColor(0, 32, 96)
166
- paragraph.add_run(self.session).font.size = Pt(self.dynamic_font_size)
167
-
168
- cell = header_table.cell(2, 1)
169
- paragraph = cell.paragraphs[0]
170
- run = paragraph.add_run("Candidat: ")
171
- run.bold = True
172
- run.font.size = Pt(self.dynamic_font_size)
173
- run.font.color.rgb = RGBColor(0, 32, 96)
174
- paragraph.add_run(self.nom_candidat).font.size = Pt(self.dynamic_font_size)
175
-
176
- # Espace après l'en-tête ajusté dynamiquement
177
- self.document.add_paragraph().space_after = Pt(4 * self.spacing_factor)
178
-
179
  def creer_tableau_elements(self):
180
- table = self.document.add_table(rows=len(self.elements_techniques) + 1, cols=5)
181
- table.style = 'Table Grid'
182
- table.alignment = WD_TABLE_ALIGNMENT.CENTER
183
-
184
- # Configuration des largeurs de colonnes (proportionnelle)
185
- total_width = 18 # Largeur totale approximative en cm
186
-
187
- # Configuration des largeurs de colonnes
188
- col_widths = [8, 3, 2, 2.5, 2.5] # Largeurs originales
189
- for i, width in enumerate(col_widths):
190
- for cell in table.columns[i].cells:
191
- cell.width = Cm(width)
192
-
193
- # Ajustement dynamique de la hauteur des lignes
194
  for row in table.rows:
195
- row.height = Cm(self.dynamic_row_height)
196
-
197
- # En-tête du tableau
 
198
  header_row = table.rows[0]
199
- for cell in header_row.cells:
200
- shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="BDD7EE"/>')
201
- cell._tc.get_or_add_tcPr().append(shading_elm)
202
-
203
  headers = ["ELEMENTS TECHNIQUES", "CATEGORIES D'ELEMENTS TECHNIQUES ET PONDERATION", "", "APPRECIATIONS", "POINTS Accordés"]
204
  for i, header in enumerate(headers):
205
- cell = table.cell(0, i)
206
- cell.text = header
207
- cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
208
- run = cell.paragraphs[0].runs[0]
209
- run.bold = True
210
- run.font.size = Pt(self.dynamic_table_font_size)
211
- run.font.color.rgb = RGBColor(0, 32, 96)
212
- table.cell(0, 1).merge(table.cell(0, 2))
213
-
214
- # Ajout des éléments techniques
215
  for i, element in enumerate(self.elements_techniques, 1):
216
- element_cell = table.cell(i, 0)
217
- element_cell.text = element["nom"]
218
- element_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.LEFT
219
- run = element_cell.paragraphs[0].runs[0]
220
- run.bold = True
221
- run.font.size = Pt(self.dynamic_table_font_size)
222
-
223
- categorie_cell = table.cell(i, 1)
224
- categorie_cell.text = element["categorie"]
225
- categorie_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
226
- run = categorie_cell.paragraphs[0].runs[0]
227
- run.bold = True
228
- run.font.size = Pt(self.dynamic_table_font_size)
229
- run.italic = True
230
-
231
- points_cell = table.cell(i, 2)
232
- points_cell.text = str(element["points"])
233
- points_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
234
- run = points_cell.paragraphs[0].runs[0]
235
- run.bold = True
236
- run.font.size = Pt(self.dynamic_table_font_size)
237
- run.italic = True
238
-
239
  def ajouter_note_jury(self):
240
- para = self.document.add_paragraph()
241
- para.space_before = Pt(4 * self.spacing_factor)
242
- para.space_after = Pt(4 * self.spacing_factor)
243
  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.")
244
- run.bold = True
245
- run.font.color.rgb = RGBColor(255, 0, 0)
246
- run.font.size = Pt(max(self.dynamic_font_size - 2, 5.5)) # Minimum 5.5pt
247
-
248
  def creer_tableau_recapitulatif(self):
249
- note_table = self.document.add_table(rows=3, cols=13)
250
- note_table.style = 'Table Grid'
251
- note_table.alignment = WD_TABLE_ALIGNMENT.CENTER
252
-
253
- # Ajuster la hauteur des lignes
 
 
 
 
 
 
 
254
  for row in note_table.rows:
255
- row.height = Cm(0.6 * (self.dynamic_row_height / self.base_row_height))
256
-
257
- for cell in note_table.rows[0].cells:
258
- shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="BDD7EE"/>')
259
- cell._tc.get_or_add_tcPr().append(shading_elm)
260
-
261
- # Taille de police pour le tableau récapitulatif (légèrement plus petite)
262
  recap_font_size = max(self.dynamic_table_font_size - 1, 5)
263
-
264
- for col, (type_lettre, points) in enumerate([("A", "1pt"), ("B", "1,5pt"), ("C", "2pts"), ("D", "2,5pts"), ("E", "3pts")]):
265
  idx = col * 2
266
  if idx + 1 < len(note_table.columns):
267
  cell = note_table.cell(0, idx)
268
- cell.merge(note_table.cell(0, idx + 1))
269
- cell.text = f"Type {type_lettre}\n{points}"
270
- cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
271
- for run in cell.paragraphs[0].runs:
272
- run.bold = True
273
- run.font.size = Pt(recap_font_size)
274
- run.font.color.rgb = RGBColor(0, 32, 96)
275
-
276
- for col, (titre, points) in enumerate([("ROV", "2pts"), ("Projet", "2pts"), ("Réalisation", "16pts")], 10):
277
  if col < len(note_table.columns):
278
- cell = note_table.cell(0, col)
279
- cell.text = f"{titre}\n{points}"
280
- cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
281
- for run in cell.paragraphs[0].runs:
282
- run.bold = True
283
- run.font.size = Pt(recap_font_size)
284
- run.font.color.rgb = RGBColor(0, 32, 96)
285
-
286
  for col in range(5):
287
  idx = col * 2
288
  if idx + 1 < len(note_table.columns):
289
- neg_cell = note_table.cell(1, idx)
290
- neg_cell.text = "NEG"
291
- neg_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
292
- for run in neg_cell.paragraphs[0].runs:
293
- run.italic = True
294
- run.font.size = Pt(recap_font_size)
295
-
296
- note_cell = note_table.cell(1, idx + 1)
297
- note_cell.text = "Note"
298
- note_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
299
- for run in note_cell.paragraphs[0].runs:
300
- run.italic = True
301
- run.font.size = Pt(recap_font_size)
302
-
303
  for col in range(10, 13):
304
  if col < len(note_table.columns):
305
- cell = note_table.cell(1, col)
306
- cell.text = "Note"
307
- cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
308
- for run in cell.paragraphs[0].runs:
309
- run.italic = True
310
- run.font.size = Pt(recap_font_size)
311
-
312
  def ajouter_note_candidat_avec_cadre(self):
313
- note_table = self.document.add_table(rows=1, cols=1)
314
- note_table.style = 'Table Grid'
315
- note_table.alignment = WD_TABLE_ALIGNMENT.CENTER
316
-
317
- cell = note_table.cell(0, 0)
318
- shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="E2EFDA"/>')
319
- cell._tc.get_or_add_tcPr().append(shading_elm)
320
-
321
- p = cell.paragraphs[0]
322
-
323
- # Pour les notes de bas, on adapte encore plus la taille si nécessaire
324
  font_size = max(6 * self.spacing_factor, 5)
325
-
326
  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).")
327
- run.italic = True
328
- run.font.size = Pt(font_size)
329
-
330
  def ajouter_zone_note(self):
331
- zone_note = self.document.add_table(rows=1, cols=2)
332
- zone_note.style = 'Table Grid'
333
- zone_note.alignment = WD_TABLE_ALIGNMENT.RIGHT
334
-
335
- # Ajuster la taille selon le nombre d'éléments
336
- cell_width = Cm(1.5 * self.spacing_factor)
337
-
338
- cell_libelle = zone_note.cell(0, 0)
339
- cell_libelle.width = cell_width
340
- cell_libelle.text = "Note finale"
341
- cell_libelle.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT
342
- run = cell_libelle.paragraphs[0].runs[0]
343
- run.bold = True
344
- run.font.size = Pt(self.dynamic_table_font_size)
345
- run.font.color.rgb = RGBColor(0, 32, 96)
346
-
347
- cell_saisie = zone_note.cell(0, 1)
348
- cell_saisie.width = cell_width
349
- zone_note.rows[0].height = cell_width
350
- shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="F2F2F2"/>')
351
- cell_saisie._tc.get_or_add_tcPr().append(shading_elm)
352
- cell_saisie.text = "/20"
353
- cell_saisie.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
354
- run = cell_saisie.paragraphs[0].runs[0]
355
- run.bold = True
356
- run.font.size = Pt(self.dynamic_table_font_size)
357
-
358
  def ajouter_lignes_correcteurs(self):
359
- # Si beaucoup d'éléments, fusionner tous les correcteurs sur une seule ligne
360
- if len(self.elements_techniques) > 12:
361
- para = self.document.add_paragraph()
362
- para.space_before = Pt(2 * self.spacing_factor)
363
- para.space_after = Pt(2 * self.spacing_factor)
364
- run = para.add_run("Correcteurs: ")
365
- run.bold = True
366
- run.font.size = Pt(self.dynamic_font_size)
367
- para.add_run("Projet / Principal / ROV").font.size = Pt(self.dynamic_font_size)
368
  else:
369
- # Format standard avec une ligne par correcteur
370
- para_intro = self.document.add_paragraph()
371
- para_intro.space_before = Pt(2 * self.spacing_factor)
372
-
373
- for role in ["Projet", "principal", "ROV"]:
374
- para = self.document.add_paragraph()
375
- para.space_before = Pt(2 * self.spacing_factor)
376
- para.space_after = Pt(2 * self.spacing_factor)
377
- run = para.add_run(f"Correcteur {role} : ")
378
- run.bold = True
379
- run.font.size = Pt(self.dynamic_font_size)
380
-
381
- # Ajuster le nombre de points en fonction du nombre d'éléments
382
- points_count = max(20, 50 - len(self.elements_techniques) * 2)
383
  para.add_run("." * points_count).font.size = Pt(self.dynamic_font_size)
384
-
385
- # Méthodes de modification des données
386
- def modifier_centre_examen(self, nom):
387
- self.centre_examen = nom
388
-
389
- def modifier_type_examen(self, type_examen):
390
- self.type_examen = type_examen
391
-
392
- def modifier_serie(self, serie):
393
- self.serie = serie
394
-
395
- def modifier_etablissement(self, nom):
396
- self.etablissement = nom
397
-
398
- def modifier_session(self, annee):
399
- self.session = annee
400
-
401
- def modifier_candidat(self, nom):
402
- self.nom_candidat = nom
403
-
404
  def ajouter_element(self, nom, categorie, points):
405
- self.elements_techniques.append({
406
- "nom": nom,
407
- "categorie": categorie,
408
- "points": float(points)
409
- })
410
-
411
  def generer_document(self, nom_fichier="evaluation_gymnastique.docx"):
412
- # Calculer les paramètres dynamiques en fonction du nombre d'éléments
413
- self.calculate_dynamic_sizing()
414
-
415
- # Générer le document avec les paramètres dynamiques
416
- self.ajouter_entete_colore()
417
- self.creer_tableau_elements()
418
-
419
- # Pour les documents très chargés, réorganiser les éléments
420
- if len(self.elements_techniques) > 15:
421
- # Version simplifiée et compacte
422
- self.ajouter_note_jury()
423
- self.creer_tableau_recapitulatif()
424
- self.ajouter_zone_note()
425
- self.ajouter_lignes_correcteurs() # Version compacte des correcteurs
426
- else:
427
- # Version standard
428
- self.ajouter_note_jury()
429
- self.creer_tableau_recapitulatif()
430
- self.ajouter_lignes_correcteurs()
431
- self.ajouter_zone_note()
432
-
433
- # Toujours inclure la note candidat
434
- self.ajouter_note_candidat_avec_cadre()
435
-
436
- self.document.save(nom_fichier)
437
  return nom_fichier
438
 
439
- # --- Application Flask ---
440
  app = Flask(__name__)
 
441
 
442
- @app.route("/eps", methods=["GET", "POST"])
443
  def index():
444
  if request.method == "POST":
445
- # Récupération des informations depuis le formulaire
446
- centre_examen = request.form.get("centre_examen", "Centre d'examen")
447
- type_examen = request.form.get("type_examen", "Bac Général")
448
- serie = request.form.get("serie", "Série")
449
- etablissement = request.form.get("etablissement", "Établissement")
450
- session_value = request.form.get("session", "2025")
451
- nom_candidat = request.form.get("nom_candidat", "Candidat")
452
-
453
- # Création et configuration du document
454
- evaluation = EvaluationGymnique()
455
- evaluation.modifier_centre_examen(centre_examen)
456
- evaluation.modifier_type_examen(type_examen)
457
- evaluation.modifier_serie(serie)
458
- evaluation.modifier_etablissement(etablissement)
459
- evaluation.modifier_session(session_value)
460
- evaluation.modifier_candidat(nom_candidat)
461
-
462
- # Récupération des éléments techniques ajoutés dynamiquement
463
- element_names = request.form.getlist("new_element_name")
464
- element_categories = request.form.getlist("new_element_categorie")
465
- element_points = request.form.getlist("new_element_points")
466
- for name, cat, pts in zip(element_names, element_categories, element_points):
467
- if name and cat and pts:
468
- evaluation.ajouter_element(name, cat, pts)
469
-
470
- # Génération du document DOCX
471
- filename = "evaluation_gymnastique.docx"
472
- evaluation.generer_document(filename)
473
-
474
- # Vérification du format de sortie demandé
475
- output_format = request.form.get("format", "docx")
476
- if output_format == "pdf":
477
- # Conversion en PDF via ConvertAPI
478
- result = convertapi.convert('pdf', {
479
- 'File': filename,
480
- 'FileName': 'evaluation_gymnastique',
481
- 'ConvertMetadata': 'false',
482
- 'ConvertHeadings': 'false'
483
- }, from_format='doc')
484
- pdf_filename = "evaluation_gymnastique.pdf"
485
- result.save_files(pdf_filename)
486
- return send_file(pdf_filename, as_attachment=True)
487
- else:
488
- return send_file(filename, as_attachment=True)
489
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
490
  return render_template("index.html")
491
 
492
  if __name__ == "__main__":
493
- app.run(debug=True)
 
 
 
 
 
 
1
+ # --- START OF FLASK APP SCRIPT ---
2
  from flask import Flask, render_template, request, send_file
3
  import os
4
+ import convertapi # For PDF conversion
5
  from docx import Document
6
  from docx.shared import Pt, Cm, RGBColor
7
  from docx.enum.text import WD_ALIGN_PARAGRAPH
8
+ from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL, WD_ROW_HEIGHT_RULE
9
  from docx.oxml.ns import nsdecls
10
  from docx.oxml import parse_xml
11
  import math
12
 
13
+ # --- Configuration ---
14
+ # IMPORTANT: Replace 'YOUR_SECRET' with your actual ConvertAPI secret
15
+ # You can get one from https://www.convertapi.com/a
16
+ convertapi.api_secret = 'YOUR_SECRET'
17
+ # Define a temporary directory for generated files (optional, adjust as needed)
18
+ UPLOAD_FOLDER = 'temp_files'
19
+ if not os.path.exists(UPLOAD_FOLDER):
20
+ os.makedirs(UPLOAD_FOLDER)
21
 
22
+
23
+ # --- Classe de génération de document (Version 4 - Finalized) ---
24
  class EvaluationGymnique:
25
  def __init__(self):
26
  self.document = Document()
 
30
  self.document.sections[0].right_margin = Cm(1.5)
31
  self.document.sections[0].top_margin = Cm(1)
32
  self.document.sections[0].bottom_margin = Cm(1)
33
+
 
34
  self.centre_examen = "Centre d'examen"
35
  self.type_examen = "Bac Général"
36
  self.serie = "Série"
37
  self.etablissement = "Établissement"
38
  self.session = "2025"
39
  self.nom_candidat = "Candidat"
 
 
40
  self.elements_techniques = []
41
  self.appreciations = ["M", "PM", "NM", "NR"]
42
+ self.base_font_size = 10
43
+ self.base_header_font_size = 14
44
+ self.base_row_height = 1.2
45
+ self.table_font_size = 9
46
+ self.available_height = 27.7
47
+ self.fixed_elements_height = 15
48
+ self.dynamic_font_size = self.base_font_size
49
+ self.dynamic_header_font_size = self.base_header_font_size
50
+ self.dynamic_table_font_size = self.table_font_size
51
+ self.dynamic_row_height = self.base_row_height
52
+ self.spacing_factor = 1.0
53
+
 
54
  def calculate_dynamic_sizing(self):
 
 
55
  num_elements = len(self.elements_techniques)
56
+ estimated_table_height = (num_elements + 1) * self.base_row_height * 1.8
57
+ available_space_for_table = self.available_height - self.fixed_elements_height
58
+ if estimated_table_height > available_space_for_table and num_elements > 0:
59
+ reduction_factor = max(0.5, 1 - (max(0, num_elements - 8) * 0.05))
60
+ self.dynamic_font_size = max(self.base_font_size * reduction_factor, 6)
61
+ self.dynamic_header_font_size = max(self.base_header_font_size * reduction_factor, 9)
62
+ self.dynamic_table_font_size = max(self.table_font_size * reduction_factor, 6)
63
+ self.dynamic_row_height = max(self.base_row_height * (reduction_factor + 0.2), 0.9)
64
+ self.spacing_factor = max(reduction_factor, 0.3)
65
+ # print(f"Adjusting sizes for {num_elements} elements. Factor: {reduction_factor:.2f}") # Optional debug
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  else:
 
67
  self.dynamic_font_size = self.base_font_size
68
  self.dynamic_header_font_size = self.base_header_font_size
69
  self.dynamic_table_font_size = self.table_font_size
70
  self.dynamic_row_height = self.base_row_height
71
  self.spacing_factor = 1.0
72
+ # print(f"Using base sizes for {num_elements} elements.") # Optional debug
73
+
74
  def ajouter_entete_colore(self):
75
+ header_paragraph = self.document.add_paragraph(); header_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER; header_paragraph.space_after = Pt(6 * self.spacing_factor)
76
+ 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)
77
+ header_table = self.document.add_table(rows=3, cols=2); header_table.style = 'Table Grid'; header_table.autofit = False
78
+ 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
79
+ available_table_width = page_width_cm - left_margin_cm - right_margin_cm
80
+ col_widths = [available_table_width * 0.55, available_table_width * 0.45]
81
+ for i, width in enumerate(col_widths):
82
+ for cell in header_table.columns[i].cells: cell.width = Cm(width)
83
+ row_height_cm = max(0.6, 0.8 * self.spacing_factor)
84
+ for row in header_table.rows: row.height = Cm(row_height_cm)
 
 
 
 
 
 
 
85
  for row in header_table.rows:
86
  for cell in row.cells:
87
+ 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)
88
+ for paragraph in cell.paragraphs: paragraph.paragraph_format.space_before = Pt(0); paragraph.paragraph_format.space_after = Pt(0)
89
+ 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)
90
+ 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)
91
+ 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)
92
+ 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)
93
+ 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)
94
+ 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)
95
+ self.document.add_paragraph().paragraph_format.space_after = Pt(4 * self.spacing_factor)
96
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  def creer_tableau_elements(self):
98
+ num_elements = len(self.elements_techniques);
99
+ if num_elements == 0: return
100
+ table = self.document.add_table(rows=num_elements + 1, cols=5); table.style = 'Table Grid'; table.alignment = WD_TABLE_ALIGNMENT.CENTER; table.autofit = False
101
+ 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
102
+ available_table_width = page_width_cm - left_margin_cm - right_margin_cm
103
+ total_prop = 8 + 3 + 2 + 2.5 + 2.5
104
+ col_widths_cm = [available_table_width * (p / total_prop) for p in [8, 3, 2, 2.5, 2.5]]
105
+ for i, width in enumerate(col_widths_cm):
106
+ for cell in table.columns[i].cells: cell.width = Cm(width)
107
+ min_row_height_cm = max(0.9, self.dynamic_row_height)
 
 
 
 
108
  for row in table.rows:
109
+ row.height_rule = WD_ROW_HEIGHT_RULE.AT_LEAST; row.height = Cm(min_row_height_cm)
110
+ for cell in row.cells:
111
+ cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
112
+ for p in cell.paragraphs: p.paragraph_format.space_before = Pt(0); p.paragraph_format.space_after = Pt(0)
113
  header_row = table.rows[0]
114
+ 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)
 
 
 
115
  headers = ["ELEMENTS TECHNIQUES", "CATEGORIES D'ELEMENTS TECHNIQUES ET PONDERATION", "", "APPRECIATIONS", "POINTS Accordés"]
116
  for i, header in enumerate(headers):
117
+ cell = table.cell(0, i); p = cell.paragraphs[0]; p.clear(); p.add_run(header); p.alignment = WD_ALIGN_PARAGRAPH.CENTER
118
+ run = p.runs[0]; run.bold = True; run.font.size = Pt(self.dynamic_table_font_size); run.font.color.rgb = RGBColor(0, 32, 96)
119
+ try: table.cell(0, 1).merge(table.cell(0, 2))
120
+ except Exception as e: print(f"Error merging cells: {e}") # Optional logging
 
 
 
 
 
 
121
  for i, element in enumerate(self.elements_techniques, 1):
122
+ if i >= len(table.rows): continue
123
+ element_cell = table.cell(i, 0); supplementary_text = "\nExécution:\nAmplitude:\nRéception:"
124
+ element_cell.text = f'{element["nom"]}{supplementary_text}'; element_cell.vertical_alignment = WD_ALIGN_VERTICAL.TOP
125
+ if element_cell.paragraphs and element_cell.paragraphs[0].runs: run = element_cell.paragraphs[0].runs[0]
126
+ else: run = element_cell.paragraphs[0].add_run(f'{element["nom"]}{supplementary_text}')
127
+ run.bold = False; run.font.size = Pt(self.dynamic_table_font_size)
128
+ for p in element_cell.paragraphs: p.paragraph_format.space_before = Pt(0); p.paragraph_format.space_after = Pt(0)
129
+ categorie_cell = table.cell(i, 1); categorie_cell.text = element["categorie"]; categorie_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
130
+ if categorie_cell.paragraphs[0].runs: run = categorie_cell.paragraphs[0].runs[0]
131
+ else: run = categorie_cell.paragraphs[0].add_run(element["categorie"])
132
+ run.bold = True; run.font.size = Pt(self.dynamic_table_font_size); run.italic = True
133
+ points_cell = table.cell(i, 2); points_cell.text = str(element["points"]); points_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
134
+ if points_cell.paragraphs[0].runs: run = points_cell.paragraphs[0].runs[0]
135
+ else: run = points_cell.paragraphs[0].add_run(str(element["points"]))
136
+ run.bold = True; run.font.size = Pt(self.dynamic_table_font_size); run.italic = True
137
+ appreciation_cell = table.cell(i, 3); appreciation_cell.text = ""
138
+ points_accordes_cell = table.cell(i, 4); points_accordes_cell.text = ""
139
+ self.document.add_paragraph().paragraph_format.space_after = Pt(6 * self.spacing_factor)
140
+
 
 
 
 
141
  def ajouter_note_jury(self):
142
+ 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)
 
 
143
  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.")
144
+ run.bold = True; run.font.color.rgb = RGBColor(255, 0, 0); run.font.size = Pt(max(self.dynamic_font_size - 2, 5.5))
145
+
 
 
146
  def creer_tableau_recapitulatif(self):
147
+ 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
148
+ 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
149
+ available_recap_width = page_width_cm - left_margin_cm - right_margin_cm
150
+ width_A_E_pair = available_recap_width * (1.2 / 13.0); width_final_single = available_recap_width * (1.0 / 13.0)
151
+ col_widths_recap = [];
152
+ for _ in range(5): col_widths_recap.extend([width_A_E_pair / 2, width_A_E_pair / 2])
153
+ col_widths_recap.extend([width_final_single, width_final_single, width_final_single])
154
+ current_total_width = sum(col_widths_recap); width_adjustment = (available_recap_width - current_total_width) / len(col_widths_recap)
155
+ for i, width in enumerate(col_widths_recap):
156
+ adjusted_width = max(0.5, width + width_adjustment);
157
+ for cell in note_table.columns[i].cells: cell.width = Cm(adjusted_width)
158
+ row_height_cm = max(0.5, 0.6 * self.spacing_factor)
159
  for row in note_table.rows:
160
+ row.height = Cm(row_height_cm)
161
+ for cell in row.cells: cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER;
162
+ for p in cell.paragraphs: p.paragraph_format.space_before = Pt(0); p.paragraph_format.space_after = Pt(0)
163
+ 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)
 
 
 
164
  recap_font_size = max(self.dynamic_table_font_size - 1, 5)
165
+ type_data = [("A", "1pt"), ("B", "1,5pt"), ("C", "2pts"), ("D", "2,5pts"), ("E", "3pts")]
166
+ for col, (type_lettre, points) in enumerate(type_data):
167
  idx = col * 2
168
  if idx + 1 < len(note_table.columns):
169
  cell = note_table.cell(0, idx)
170
+ try:
171
+ 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
172
+ for run in p.runs: run.bold = True; run.font.size = Pt(recap_font_size); run.font.color.rgb = RGBColor(0, 32, 96)
173
+ except Exception as e: print(f"Error merging cells at index {idx}: {e}") # Optional logging
174
+ final_headers = [("ROV", "2pts"), ("Projet", "2pts"), ("Réalisation", "16pts")]
175
+ for col_offset, (titre, points) in enumerate(final_headers):
176
+ col = 10 + col_offset
 
 
177
  if col < len(note_table.columns):
178
+ 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
179
+ for run in p.runs: run.bold = True; run.font.size = Pt(recap_font_size); run.font.color.rgb = RGBColor(0, 32, 96)
 
 
 
 
 
 
180
  for col in range(5):
181
  idx = col * 2
182
  if idx + 1 < len(note_table.columns):
183
+ 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
184
+ 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
 
 
 
 
 
 
 
 
 
 
 
 
185
  for col in range(10, 13):
186
  if col < len(note_table.columns):
187
+ 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
188
+ self.document.add_paragraph().paragraph_format.space_after = Pt(6 * self.spacing_factor)
189
+
 
 
 
 
190
  def ajouter_note_candidat_avec_cadre(self):
191
+ 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
192
+ 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)
193
+ p = cell.paragraphs[0]; p.paragraph_format.space_before = Pt(2); p.paragraph_format.space_after = Pt(2)
 
 
 
 
 
 
 
 
194
  font_size = max(6 * self.spacing_factor, 5)
 
195
  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).")
196
+ run.italic = True; run.font.size = Pt(font_size)
197
+ self.document.add_paragraph().paragraph_format.space_after = Pt(8 * self.spacing_factor)
198
+
199
  def ajouter_zone_note(self):
200
+ 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)
201
+ 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)
202
+ box_table = self.document.add_table(rows=1, cols=1); box_table.style = 'Table Grid'; box_table.alignment = WD_TABLE_ALIGNMENT.RIGHT
203
+ box_size = Cm(1.5); cell = box_table.cell(0, 0); cell.width = box_size; box_table.rows[0].height = box_size
204
+ cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER; cell.text = ""
205
+ 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)
206
+ self.document.add_paragraph().paragraph_format.space_after = Pt(8 * self.spacing_factor)
207
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
  def ajouter_lignes_correcteurs(self):
209
+ num_elements = len(self.elements_techniques); use_compact_mode = num_elements > 12
210
+ if use_compact_mode:
211
+ 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)
212
+ 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)
 
 
 
 
 
213
  else:
214
+ for role in ["Projet", "Principal", "ROV"]:
215
+ 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)
216
+ run = para.add_run(f"Correcteur {role} : "); run.bold = True; run.font.size = Pt(self.dynamic_font_size)
217
+ chars_per_cm_estimate = 3; line_length_cm = 10; points_count = int(line_length_cm * chars_per_cm_estimate)
218
+ 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)
 
 
 
 
 
 
 
 
 
219
  para.add_run("." * points_count).font.size = Pt(self.dynamic_font_size)
220
+
221
+ def modifier_centre_examen(self, nom): self.centre_examen = nom
222
+ def modifier_type_examen(self, type_examen): self.type_examen = type_examen
223
+ def modifier_serie(self, serie): self.serie = serie
224
+ def modifier_etablissement(self, nom): self.etablissement = nom
225
+ def modifier_session(self, annee): self.session = annee
226
+ def modifier_candidat(self, nom): self.nom_candidat = nom
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  def ajouter_element(self, nom, categorie, points):
228
+ try: point_value = float(points)
229
+ except (ValueError, TypeError): print(f"Warning: Invalid points value '{points}' for element '{nom}'. Using 0.0."); point_value = 0.0
230
+ self.elements_techniques.append({"nom": nom, "categorie": categorie, "points": point_value})
231
+
 
 
232
  def generer_document(self, nom_fichier="evaluation_gymnastique.docx"):
233
+ 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()
234
+ try:
235
+ self.document.save(nom_fichier); print(f"Document '{nom_fichier}' generated successfully.")
236
+ except Exception as e: print(f"Error saving document: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
  return nom_fichier
238
 
239
+ # --- Flask Application ---
240
  app = Flask(__name__)
241
+ app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
242
 
243
+ @app.route("/eps", methods=["GET", "POST"]) # Changed route back to /eps as in original
244
  def index():
245
  if request.method == "POST":
246
+ try:
247
+ # --- Récupération des informations depuis le formulaire ---
248
+ centre_examen = request.form.get("centre_examen", "Centre d'examen")
249
+ type_examen = request.form.get("type_examen", "Bac Général")
250
+ serie = request.form.get("serie", "Série")
251
+ etablissement = request.form.get("etablissement", "Établissement")
252
+ session_value = request.form.get("session", "2025")
253
+ nom_candidat = request.form.get("nom_candidat", "Candidat")
254
+ output_format = request.form.get("format", "docx") # Get format preference
255
+
256
+ # --- Création et configuration du document ---
257
+ evaluation = EvaluationGymnique()
258
+ evaluation.modifier_centre_examen(centre_examen)
259
+ evaluation.modifier_type_examen(type_examen)
260
+ evaluation.modifier_serie(serie)
261
+ evaluation.modifier_etablissement(etablissement)
262
+ evaluation.modifier_session(session_value)
263
+ evaluation.modifier_candidat(nom_candidat)
264
+
265
+ # --- Récupération des éléments techniques ---
266
+ element_names = request.form.getlist("new_element_name")
267
+ element_categories = request.form.getlist("new_element_categorie")
268
+ element_points = request.form.getlist("new_element_points")
269
+
270
+ print(f"Received names: {element_names}") # Debug print
271
+ print(f"Received categories: {element_categories}") # Debug print
272
+ print(f"Received points: {element_points}") # Debug print
273
+
274
+
275
+ for name, cat, pts in zip(element_names, element_categories, element_points):
276
+ # Add element only if all three fields have some value
277
+ if name and cat and pts:
278
+ evaluation.ajouter_element(name, cat, pts)
279
+ else:
280
+ print(f"Skipping incomplete element: Name='{name}', Cat='{cat}', Pts='{pts}'") # Debug print
281
+
282
+
283
+ # --- Génération du document DOCX ---
284
+ # Use a unique filename in the temp folder to avoid conflicts
285
+ base_filename = f"evaluation_{nom_candidat.replace(' ', '_')}_{session_value}"
286
+ docx_filename = os.path.join(app.config['UPLOAD_FOLDER'], f"{base_filename}.docx")
287
+ evaluation.generer_document(docx_filename)
288
+
289
+ # --- Conversion et envoi ---
290
+ if output_format == "pdf":
291
+ if convertapi.api_secret == 'YOUR_SECRET':
292
+ # Handle case where API secret is not set
293
+ return "Error: ConvertAPI secret not set in the script. Cannot generate PDF.", 500
294
+
295
+ print(f"Attempting PDF conversion for {docx_filename}...")
296
+ try:
297
+ result = convertapi.convert('pdf', { 'File': docx_filename }, from_format = 'docx')
298
+ pdf_filename_base = f"{base_filename}.pdf"
299
+ pdf_filepath = os.path.join(app.config['UPLOAD_FOLDER'], pdf_filename_base)
300
+ result.save_files(pdf_filepath)
301
+ print(f"PDF saved to {pdf_filepath}")
302
+ # Send the generated PDF
303
+ return send_file(pdf_filepath, as_attachment=True, download_name=pdf_filename_base)
304
+ except Exception as e:
305
+ print(f"Error during PDF conversion: {e}")
306
+ # Provide feedback to the user
307
+ return f"Error during PDF conversion: {e}. Check ConvertAPI credits or file.", 500
308
+ finally:
309
+ # Clean up the original docx file after attempting conversion
310
+ if os.path.exists(docx_filename):
311
+ os.remove(docx_filename)
312
+
313
+ else: # Send the generated DOCX
314
+ # Ensure the download name doesn't include the folder path
315
+ return send_file(docx_filename, as_attachment=True, download_name=f"{base_filename}.docx")
316
+
317
+ except Exception as e:
318
+ # Log the general error
319
+ print(f"An error occurred during POST request processing: {e}")
320
+ # Provide generic error feedback
321
+ return f"An internal error occurred: {e}", 500
322
+
323
+ # --- Affichage du formulaire (GET request) ---
324
  return render_template("index.html")
325
 
326
  if __name__ == "__main__":
327
+ # Make sure the UPLOAD_FOLDER exists when running directly
328
+ if not os.path.exists(UPLOAD_FOLDER):
329
+ os.makedirs(UPLOAD_FOLDER)
330
+ app.run(debug=True) # debug=True is helpful during development
331
+
332
+ # --- END OF FLASK APP SCRIPT ---