Docfile commited on
Commit
e85cb9c
·
verified ·
1 Parent(s): 0ddde91

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +211 -121
app.py CHANGED
@@ -1,5 +1,5 @@
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
@@ -9,21 +9,25 @@ from docx.enum.table import WD_TABLE_ALIGNMENT, WD_ALIGN_VERTICAL, WD_ROW_HEIGHT
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()
 
27
  self.document.sections[0].page_height = Cm(29.7)
28
  self.document.sections[0].page_width = Cm(21)
29
  self.document.sections[0].left_margin = Cm(1.5)
@@ -31,6 +35,7 @@ class EvaluationGymnique:
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"
@@ -38,13 +43,18 @@ class EvaluationGymnique:
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
@@ -53,101 +63,120 @@ class EvaluationGymnique:
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])
@@ -156,68 +185,70 @@ class EvaluationGymnique:
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
@@ -230,19 +261,33 @@ class EvaluationGymnique:
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")
@@ -250,8 +295,13 @@ def index():
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()
@@ -267,58 +317,97 @@ def index():
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")
@@ -327,6 +416,7 @@ 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 ---
 
1
+ # --- START OF FLASK APP SCRIPT (v5 - Final) ---
2
+ from flask import Flask, render_template, request, send_file, flash, redirect, url_for
3
  import os
4
  import convertapi # For PDF conversion
5
  from docx import Document
 
9
  from docx.oxml.ns import nsdecls
10
  from docx.oxml import parse_xml
11
  import math
12
+ import uuid # For unique filenames
13
 
14
  # --- Configuration ---
15
  # IMPORTANT: Replace 'YOUR_SECRET' with your actual ConvertAPI secret
16
  # You can get one from https://www.convertapi.com/a
17
+ convertapi.api_secret = 'secret_8wCI6pgOP9AxLVJG'
18
+
19
+ # Define a temporary directory for generated files
20
+ BASE_DIR = os.path.abspath(os.path.dirname(__file__))
21
+ UPLOAD_FOLDER = os.path.join(BASE_DIR, 'temp_files')
22
  if not os.path.exists(UPLOAD_FOLDER):
23
  os.makedirs(UPLOAD_FOLDER)
24
 
25
 
26
+ # --- Classe de génération de document (Modifiée pour interligne standard) ---
27
  class EvaluationGymnique:
28
  def __init__(self):
29
  self.document = Document()
30
+ # --- Document Setup (Margins, etc.) ---
31
  self.document.sections[0].page_height = Cm(29.7)
32
  self.document.sections[0].page_width = Cm(21)
33
  self.document.sections[0].left_margin = Cm(1.5)
 
35
  self.document.sections[0].top_margin = Cm(1)
36
  self.document.sections[0].bottom_margin = Cm(1)
37
 
38
+ # --- Default Data ---
39
  self.centre_examen = "Centre d'examen"
40
  self.type_examen = "Bac Général"
41
  self.serie = "Série"
 
43
  self.session = "2025"
44
  self.nom_candidat = "Candidat"
45
  self.elements_techniques = []
46
+
47
+ # --- Layout Parameters ---
48
  self.base_font_size = 10
49
  self.base_header_font_size = 14
50
+ # Adjusted base row height slightly for single line break comfort
51
+ self.base_row_height = 1.0
52
  self.table_font_size = 9
53
  self.available_height = 27.7
54
+ # Adjusted fixed height estimate slightly
55
+ self.fixed_elements_height = 14
56
+
57
+ # --- Dynamic Parameters (initialized) ---
58
  self.dynamic_font_size = self.base_font_size
59
  self.dynamic_header_font_size = self.base_header_font_size
60
  self.dynamic_table_font_size = self.table_font_size
 
63
 
64
  def calculate_dynamic_sizing(self):
65
  num_elements = len(self.elements_techniques)
66
+ # Estimate accounts for single line break now
67
+ estimated_table_height = (num_elements + 1) * self.base_row_height * 1.3 # Reduced multiplier
68
+
69
  available_space_for_table = self.available_height - self.fixed_elements_height
70
  if estimated_table_height > available_space_for_table and num_elements > 0:
71
+ reduction_factor = max(0.6, 1 - (max(0, num_elements - 10) * 0.04)) # Adjusted factor/threshold
72
  self.dynamic_font_size = max(self.base_font_size * reduction_factor, 6)
73
  self.dynamic_header_font_size = max(self.base_header_font_size * reduction_factor, 9)
74
  self.dynamic_table_font_size = max(self.table_font_size * reduction_factor, 6)
75
+ self.dynamic_row_height = max(self.base_row_height * (reduction_factor + 0.1), 0.7) # Min 0.7cm
76
+ self.spacing_factor = max(reduction_factor, 0.4)
77
+ print(f"Adjusting sizes for {num_elements} elements. Factor: {reduction_factor:.2f}") # Optional debug
78
  else:
79
  self.dynamic_font_size = self.base_font_size
80
  self.dynamic_header_font_size = self.base_header_font_size
81
  self.dynamic_table_font_size = self.table_font_size
82
  self.dynamic_row_height = self.base_row_height
83
  self.spacing_factor = 1.0
84
+ print(f"Using base sizes for {num_elements} elements.") # Optional debug
85
+
86
+ def set_paragraph_format(self, paragraph, size=None, bold=False, italic=False, color_rgb=None, align=None, space_before=0, space_after=0):
87
+ """Helper to format paragraphs and their first run."""
88
+ paragraph.paragraph_format.space_before = Pt(space_before)
89
+ paragraph.paragraph_format.space_after = Pt(space_after)
90
+ if align is not None:
91
+ paragraph.alignment = align
92
+ if paragraph.runs:
93
+ run = paragraph.runs[0]
94
+ if size: run.font.size = Pt(size)
95
+ run.bold = bold
96
+ run.italic = italic
97
+ if color_rgb: run.font.color.rgb = color_rgb
98
+ # Consider adding a run if none exists, though setting text usually creates one.
99
 
100
  def ajouter_entete_colore(self):
101
+ p = self.document.add_paragraph(); p.add_run("ÉVALUATION GYMNASTIQUE")
102
+ self.set_paragraph_format(p, size=self.dynamic_header_font_size, bold=True, color_rgb=RGBColor(0, 32, 96), align=WD_ALIGN_PARAGRAPH.CENTER, space_after=6 * self.spacing_factor)
103
  header_table = self.document.add_table(rows=3, cols=2); header_table.style = 'Table Grid'; header_table.autofit = False
104
  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
105
+ available_table_width = page_width_cm - left_margin_cm - right_margin_cm; col_widths = [available_table_width * 0.55, available_table_width * 0.45]
 
106
  for i, width in enumerate(col_widths):
107
  for cell in header_table.columns[i].cells: cell.width = Cm(width)
108
+ row_height_cm = max(0.6, 0.8 * self.spacing_factor);
109
  for row in header_table.rows: row.height = Cm(row_height_cm)
110
+ shading_fill = "D9E2F3"
111
  for row in header_table.rows:
112
  for cell in row.cells:
113
+ cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER; shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{shading_fill}"/>'); cell._tc.get_or_add_tcPr().append(shading_elm)
114
+ for p in cell.paragraphs: self.set_paragraph_format(p) # Ensure 0 spacing inside cells
115
+ # Fill header data using helper
116
+ def fill_header_cell(cell, label, value):
117
+ p = cell.paragraphs[0]; p.clear(); run = p.add_run(label); run.bold = True; run.font.size = Pt(self.dynamic_font_size); run.font.color.rgb = RGBColor(0, 32, 96); p.add_run(value).font.size = Pt(self.dynamic_font_size)
118
+ fill_header_cell(header_table.cell(0, 0), "Centre d'examen: ", self.centre_examen); fill_header_cell(header_table.cell(0, 1), "Examen: ", self.type_examen)
119
+ fill_header_cell(header_table.cell(1, 0), "Série: ", self.serie); fill_header_cell(header_table.cell(1, 1), "Établissement: ", self.etablissement)
120
+ fill_header_cell(header_table.cell(2, 0), "Session: ", self.session); fill_header_cell(header_table.cell(2, 1), "Candidat: ", self.nom_candidat)
121
  self.document.add_paragraph().paragraph_format.space_after = Pt(4 * self.spacing_factor)
122
 
123
+ # --- MODIFIED METHOD for Line Breaks ---
124
  def creer_tableau_elements(self):
125
  num_elements = len(self.elements_techniques);
126
  if num_elements == 0: return
127
  table = self.document.add_table(rows=num_elements + 1, cols=5); table.style = 'Table Grid'; table.alignment = WD_TABLE_ALIGNMENT.CENTER; table.autofit = False
128
  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
129
+ available_table_width = page_width_cm - left_margin_cm - right_margin_cm; total_prop = 8 + 3 + 2 + 2.5 + 2.5
 
130
  col_widths_cm = [available_table_width * (p / total_prop) for p in [8, 3, 2, 2.5, 2.5]]
131
  for i, width in enumerate(col_widths_cm):
132
  for cell in table.columns[i].cells: cell.width = Cm(width)
133
+ min_row_height_cm = max(0.7, self.dynamic_row_height) # Adjusted min height
134
  for row in table.rows:
135
  row.height_rule = WD_ROW_HEIGHT_RULE.AT_LEAST; row.height = Cm(min_row_height_cm)
136
  for cell in row.cells:
137
  cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
138
+ # Ensure default paragraph spacing is 0 unless overridden
139
+ for p in cell.paragraphs: self.set_paragraph_format(p)
140
  header_row = table.rows[0]
141
+ shading_fill = "BDD7EE"
142
+ for cell in header_row.cells: shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{shading_fill}"/>'); cell._tc.get_or_add_tcPr().append(shading_elm)
143
  headers = ["ELEMENTS TECHNIQUES", "CATEGORIES D'ELEMENTS TECHNIQUES ET PONDERATION", "", "APPRECIATIONS", "POINTS Accordés"]
144
  for i, header in enumerate(headers):
145
+ cell = table.cell(0, i); p = cell.paragraphs[0]; p.clear(); p.add_run(header)
146
+ self.set_paragraph_format(p, size=self.dynamic_table_font_size, bold=True, color_rgb=RGBColor(0, 32, 96), align=WD_ALIGN_PARAGRAPH.CENTER)
147
  try: table.cell(0, 1).merge(table.cell(0, 2))
148
+ except Exception as e: print(f"Error merging cells: {e}")
149
  for i, element in enumerate(self.elements_techniques, 1):
150
  if i >= len(table.rows): continue
151
+ # --- Element Name Cell ---
152
+ element_cell = table.cell(i, 0)
153
+ # Set text with a single newline
154
+ element_cell.text = f'{element["nom"]}\n'
155
+ element_cell.vertical_alignment = WD_ALIGN_VERTICAL.TOP # Align text to top
156
+ # Format the paragraph containing the name and newline
157
+ if element_cell.paragraphs:
158
+ self.set_paragraph_format(element_cell.paragraphs[0], size=self.dynamic_table_font_size, bold=False, space_before=Pt(1), space_after=Pt(1)) # Minimal spacing
159
+
160
+ # --- Other Cells ---
161
+ def fill_element_cell(cell_index, text, align, is_bold=True, is_italic=True):
162
+ cell = table.cell(i, cell_index); cell.text = str(text) # Ensure text is string
163
+ if cell.paragraphs: self.set_paragraph_format(cell.paragraphs[0], size=self.dynamic_table_font_size, bold=is_bold, italic=is_italic, align=align)
164
+ fill_element_cell(1, element["categorie"], WD_ALIGN_PARAGRAPH.CENTER)
165
+ fill_element_cell(2, element["points"], WD_ALIGN_PARAGRAPH.CENTER)
166
+ fill_element_cell(3, "", WD_ALIGN_PARAGRAPH.CENTER, is_bold=False, is_italic=False) # Appreciation
167
+ fill_element_cell(4, "", WD_ALIGN_PARAGRAPH.CENTER, is_bold=False, is_italic=False) # Points Accordés
168
+
169
  self.document.add_paragraph().paragraph_format.space_after = Pt(6 * self.spacing_factor)
170
+ # --- END OF MODIFIED METHOD ---
171
 
172
  def ajouter_note_jury(self):
173
+ p = self.document.add_paragraph(); p.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.")
174
+ self.set_paragraph_format(p, size=max(self.dynamic_font_size - 2, 5.5), bold=True, color_rgb=RGBColor(255, 0, 0), space_before=4 * self.spacing_factor, space_after=4 * self.spacing_factor)
 
175
 
176
  def creer_tableau_recapitulatif(self):
177
  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
178
  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
179
+ 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)
 
180
  col_widths_recap = [];
181
  for _ in range(5): col_widths_recap.extend([width_A_E_pair / 2, width_A_E_pair / 2])
182
  col_widths_recap.extend([width_final_single, width_final_single, width_final_single])
 
185
  adjusted_width = max(0.5, width + width_adjustment);
186
  for cell in note_table.columns[i].cells: cell.width = Cm(adjusted_width)
187
  row_height_cm = max(0.5, 0.6 * self.spacing_factor)
188
+ shading_fill = "BDD7EE"
189
  for row in note_table.rows:
190
  row.height = Cm(row_height_cm)
191
  for cell in row.cells: cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER;
192
+ for p in cell.paragraphs: self.set_paragraph_format(p)
193
+ for cell in note_table.rows[0].cells: shading_elm = parse_xml(f'<w:shd {nsdecls("w")} w:fill="{shading_fill}"/>'); cell._tc.get_or_add_tcPr().append(shading_elm)
194
  recap_font_size = max(self.dynamic_table_font_size - 1, 5)
195
+ header_color = RGBColor(0, 32, 96)
196
  type_data = [("A", "1pt"), ("B", "1,5pt"), ("C", "2pts"), ("D", "2,5pts"), ("E", "3pts")]
197
  for col, (type_lettre, points) in enumerate(type_data):
198
  idx = col * 2
199
  if idx + 1 < len(note_table.columns):
200
  cell = note_table.cell(0, idx)
201
  try:
202
+ cell.merge(note_table.cell(0, idx + 1)); p = cell.paragraphs[0]; p.clear(); p.add_run(f"Type {type_lettre}\n{points}")
203
+ self.set_paragraph_format(p, size=recap_font_size, bold=True, color_rgb=header_color, align=WD_ALIGN_PARAGRAPH.CENTER)
204
  except Exception as e: print(f"Error merging cells at index {idx}: {e}") # Optional logging
205
  final_headers = [("ROV", "2pts"), ("Projet", "2pts"), ("Réalisation", "16pts")]
206
  for col_offset, (titre, points) in enumerate(final_headers):
207
  col = 10 + col_offset
208
  if col < len(note_table.columns):
209
+ cell = note_table.cell(0, col); p = cell.paragraphs[0]; p.clear(); p.add_run(f"{titre}\n{points}")
210
+ self.set_paragraph_format(p, size=recap_font_size, bold=True, color_rgb=header_color, align=WD_ALIGN_PARAGRAPH.CENTER)
211
  for col in range(5):
212
  idx = col * 2
213
  if idx + 1 < len(note_table.columns):
214
+ neg_cell = note_table.cell(1, idx); p_neg = neg_cell.paragraphs[0]; p_neg.clear(); p_neg.add_run("NEG"); self.set_paragraph_format(p_neg, size=recap_font_size, italic=True, align=WD_ALIGN_PARAGRAPH.CENTER)
215
+ note_cell = note_table.cell(1, idx + 1); p_note = note_cell.paragraphs[0]; p_note.clear(); p_note.add_run("Note"); self.set_paragraph_format(p_note, size=recap_font_size, italic=True, align=WD_ALIGN_PARAGRAPH.CENTER)
216
  for col in range(10, 13):
217
  if col < len(note_table.columns):
218
+ cell = note_table.cell(1, col); p = cell.paragraphs[0]; p.clear(); p.add_run("Note"); self.set_paragraph_format(p, size=recap_font_size, italic=True, align=WD_ALIGN_PARAGRAPH.CENTER)
219
  self.document.add_paragraph().paragraph_format.space_after = Pt(6 * self.spacing_factor)
220
 
221
  def ajouter_note_candidat_avec_cadre(self):
222
  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
223
  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)
224
+ p = cell.paragraphs[0]; p.clear()
 
225
  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).")
226
+ run.italic = True; run.font.size = Pt(max(6 * self.spacing_factor, 5))
227
+ p.paragraph_format.space_before = Pt(2); p.paragraph_format.space_after = Pt(2)
228
  self.document.add_paragraph().paragraph_format.space_after = Pt(8 * self.spacing_factor)
229
 
230
  def ajouter_zone_note(self):
231
+ p_label = self.document.add_paragraph(); p_label.add_run("Note finale/20")
232
+ self.set_paragraph_format(p_label, size=self.dynamic_table_font_size + 1, bold=True, color_rgb=RGBColor(0, 32, 96), align=WD_ALIGN_PARAGRAPH.RIGHT, space_before=4 * self.spacing_factor, space_after=1)
233
  box_table = self.document.add_table(rows=1, cols=1); box_table.style = 'Table Grid'; box_table.alignment = WD_TABLE_ALIGNMENT.RIGHT
234
  box_size = Cm(1.5); cell = box_table.cell(0, 0); cell.width = box_size; box_table.rows[0].height = box_size
235
+ cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER; cell.text = ""; self.set_paragraph_format(cell.paragraphs[0])
 
236
  self.document.add_paragraph().paragraph_format.space_after = Pt(8 * self.spacing_factor)
237
 
238
  def ajouter_lignes_correcteurs(self):
239
  num_elements = len(self.elements_techniques); use_compact_mode = num_elements > 12
240
  if use_compact_mode:
241
+ p = self.document.add_paragraph(); run = p.add_run("Correcteurs: "); run.bold = True; run.font.size = Pt(self.dynamic_font_size)
242
+ p.add_run("Projet / Principal / ROV").font.size = Pt(self.dynamic_font_size); p.add_run("\n" + "." * 30)
243
+ self.set_paragraph_format(p, space_before=4 * self.spacing_factor, space_after=4 * self.spacing_factor)
244
  else:
245
  for role in ["Projet", "Principal", "ROV"]:
246
+ p = self.document.add_paragraph(); run = p.add_run(f"Correcteur {role} : "); run.bold = True; run.font.size = Pt(self.dynamic_font_size)
247
+ chars_per_cm_estimate = 3; line_length_cm = 10; points_count = int(line_length_cm * chars_per_cm_estimate * (self.dynamic_font_size / 10.0) * self.spacing_factor); points_count = max(15, points_count)
248
+ p.add_run("." * points_count).font.size = Pt(self.dynamic_font_size)
249
+ self.set_paragraph_format(p, space_before=3 * self.spacing_factor, space_after=1 * self.spacing_factor)
 
250
 
251
+ # --- Data Modifiers ---
252
  def modifier_centre_examen(self, nom): self.centre_examen = nom
253
  def modifier_type_examen(self, type_examen): self.type_examen = type_examen
254
  def modifier_serie(self, serie): self.serie = serie
 
261
  self.elements_techniques.append({"nom": nom, "categorie": categorie, "points": point_value})
262
 
263
  def generer_document(self, nom_fichier="evaluation_gymnastique.docx"):
264
+ """Generates the complete DOCX document."""
265
+ self.calculate_dynamic_sizing()
266
+ self.ajouter_entete_colore()
267
+ self.creer_tableau_elements()
268
+ self.ajouter_note_jury()
269
+ self.creer_tableau_recapitulatif()
270
+ # Reordered slightly for common layout flow
271
+ self.ajouter_note_candidat_avec_cadre() # Instructions often come before signatures/final score
272
+ self.ajouter_lignes_correcteurs()
273
+ self.ajouter_zone_note()
274
  try:
275
  self.document.save(nom_fichier); print(f"Document '{nom_fichier}' generated successfully.")
276
+ return nom_fichier
277
+ except Exception as e:
278
+ print(f"Error saving document: {e}")
279
+ raise # Re-raise the exception for Flask to handle
280
 
281
  # --- Flask Application ---
282
  app = Flask(__name__)
283
  app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
284
+ app.secret_key = os.urandom(24) # Needed for flash messages
285
 
286
+ @app.route("/eps", methods=["GET", "POST"])
287
  def index():
288
  if request.method == "POST":
289
+ docx_filepath = None # Initialize to None
290
+ pdf_filepath = None # Initialize to None
291
  try:
292
  # --- Récupération des informations depuis le formulaire ---
293
  centre_examen = request.form.get("centre_examen", "Centre d'examen")
 
295
  serie = request.form.get("serie", "Série")
296
  etablissement = request.form.get("etablissement", "Établissement")
297
  session_value = request.form.get("session", "2025")
298
+ nom_candidat = request.form.get("nom_candidat", "Candidat").strip()
299
+ output_format = request.form.get("format", "docx")
300
+
301
+ # Basic validation for candidate name
302
+ if not nom_candidat:
303
+ flash("Le nom du candidat ne peut pas être vide.", "error")
304
+ return redirect(url_for('index'))
305
 
306
  # --- Création et configuration du document ---
307
  evaluation = EvaluationGymnique()
 
317
  element_categories = request.form.getlist("new_element_categorie")
318
  element_points = request.form.getlist("new_element_points")
319
 
320
+ valid_elements_added = 0
 
 
 
 
321
  for name, cat, pts in zip(element_names, element_categories, element_points):
322
+ if name.strip() and cat.strip() and pts.strip():
323
+ try:
324
+ # Validate points format (allow dot or comma, convert to float)
325
+ pts_float = float(pts.replace(',', '.'))
326
+ evaluation.ajouter_element(name.strip(), cat.strip(), pts_float)
327
+ valid_elements_added += 1
328
+ except ValueError:
329
+ print(f"Skipping element due to invalid points format: Name='{name}', Pts='{pts}'")
330
  else:
331
+ print(f"Skipping incomplete element: Name='{name}', Cat='{cat}', Pts='{pts}'")
332
+
333
+ if valid_elements_added == 0:
334
+ flash("Aucun élément technique valide n'a été ajouté. Veuillez vérifier les entrées.", "error")
335
+ # Persist form data (more advanced, not implemented here simply)
336
+ return redirect(url_for('index'))
337
 
338
 
339
  # --- Génération du document DOCX ---
340
+ safe_candidat_name = "".join(c if c.isalnum() else "_" for c in nom_candidat)
341
+ unique_id = uuid.uuid4().hex[:6] # Short unique ID
342
+ base_filename = f"evaluation_{safe_candidat_name}_{session_value}_{unique_id}"
343
+ docx_filename = f"{base_filename}.docx"
344
+ docx_filepath = os.path.join(app.config['UPLOAD_FOLDER'], docx_filename)
345
+
346
+ # This might raise an exception if saving fails
347
+ evaluation.generer_document(docx_filepath)
348
 
349
  # --- Conversion et envoi ---
350
  if output_format == "pdf":
351
+ if not convertapi.api_secret or convertapi.api_secret == 'YOUR_SECRET':
352
+ flash("La clé API pour ConvertAPI n'est pas configurée. Impossible de générer le PDF.", "error")
353
+ # Still have the DOCX, could offer that instead or redirect
354
+ # Let's redirect back for now
355
+ return redirect(url_for('index'))
356
 
357
+ print(f"Attempting PDF conversion for {docx_filepath}...")
358
  try:
359
+ # Explicitly set output path for saved PDF
360
+ pdf_filename = f"{base_filename}.pdf"
361
+ pdf_filepath = os.path.join(app.config['UPLOAD_FOLDER'], pdf_filename)
362
+
363
+ result = convertapi.convert('pdf', {'File': docx_filepath}, from_format = 'docx')
364
+
365
+ # Save the converted file(s)
366
+ saved_files = result.save_files(app.config['UPLOAD_FOLDER']) # Save to temp folder
367
+ print(f"ConvertAPI saved files: {saved_files}")
368
+
369
+ # Find the expected PDF file path (ConvertAPI might rename slightly)
370
+ # Let's assume the first saved file is the PDF we want if only one exists
371
+ if saved_files and len(saved_files) == 1:
372
+ actual_pdf_path = saved_files[0]
373
+ # Optionally rename it back to our desired name if needed, but sending works
374
+ print(f"PDF conversion successful: {actual_pdf_path}")
375
+ return send_file(actual_pdf_path, as_attachment=True, download_name=pdf_filename)
376
+ elif os.path.exists(pdf_filepath): # Check if it saved with exact name
377
+ print(f"PDF conversion successful (exact path): {pdf_filepath}")
378
+ return send_file(pdf_filepath, as_attachment=True, download_name=pdf_filename)
379
+ else:
380
+ flash(f"Erreur: Fichier PDF non trouvé après conversion. Fichiers sauvegardés: {saved_files}", "error")
381
+ return redirect(url_for('index'))
382
+
383
  except Exception as e:
384
  print(f"Error during PDF conversion: {e}")
385
+ flash(f"Erreur durant la conversion PDF: {e}. Vérifiez vos crédits ConvertAPI ou le fichier.", "error")
386
+ # Fallback: Offer the DOCX instead? Or just redirect.
387
+ return redirect(url_for('index'))
 
 
 
388
 
389
  else: # Send the generated DOCX
390
+ return send_file(docx_filepath, as_attachment=True, download_name=docx_filename)
 
391
 
392
  except Exception as e:
393
  # Log the general error
394
  print(f"An error occurred during POST request processing: {e}")
395
+ flash(f"Une erreur interne est survenue: {e}", "error")
396
+ return redirect(url_for('index'))
397
+
398
+ finally:
399
+ # --- Cleanup ---
400
+ # Clean up DOCX only if PDF was successfully sent or if DOCX was sent
401
+ # If PDF conversion failed but DOCX exists, maybe keep it?
402
+ # Let's clean up the DOCX if PDF was *attempted* regardless of success for simplicity
403
+ if output_format == 'pdf' and docx_filepath and os.path.exists(docx_filepath):
404
+ try:
405
+ os.remove(docx_filepath)
406
+ print(f"Cleaned up DOCX: {docx_filepath}")
407
+ except OSError as e:
408
+ print(f"Error cleaning up DOCX file {docx_filepath}: {e}")
409
+ # We don't explicitly clean the PDF here as send_file handles it (or it might fail before sending)
410
+
411
 
412
  # --- Affichage du formulaire (GET request) ---
413
  return render_template("index.html")
 
416
  # Make sure the UPLOAD_FOLDER exists when running directly
417
  if not os.path.exists(UPLOAD_FOLDER):
418
  os.makedirs(UPLOAD_FOLDER)
419
+ # Consider security implications of running debug=True in production
420
+ app.run(debug=True, host='0.0.0.0', port=5001) # Run on port 5001 for example
421
 
422
  # --- END OF FLASK APP SCRIPT ---