Nayohn commited on
Commit
5747165
·
1 Parent(s): 8c1f5b3

Add application file

Browse files
Files changed (1) hide show
  1. generate_resume.py +830 -0
generate_resume.py ADDED
@@ -0,0 +1,830 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import json
5
+ import subprocess
6
+ import shutil
7
+ import platform
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Any, Dict
11
+ import uuid
12
+
13
+ from jinja2 import Environment, FileSystemLoader
14
+ from pydantic import ValidationError
15
+
16
+ from pydantic_model import Resume
17
+
18
+ # Import conditionnel de gradio pour éviter les erreurs si non installé
19
+ try:
20
+ import gradio as gr
21
+ except ImportError:
22
+ gr = None
23
+
24
+ PROJECT_ROOT = Path(__file__).parent
25
+ TEMPLATES_DIR = PROJECT_ROOT / "templates"
26
+ # Par défaut, toujours utiliser le template classic
27
+ TEMPLATE_NAME = "classic.tex.j2"
28
+ OUTPUT_DIR = PROJECT_ROOT / "build"
29
+
30
+ # Activer explicitement le serveur MCP via variable d'environnement (équivalent à mcp_server=True)
31
+ os.environ["GRADIO_MCP_SERVER"] = "True"
32
+
33
+ def escape_latex_special_chars(text: str) -> str:
34
+ """Escape special LaTeX characters in text."""
35
+ if not isinstance(text, str):
36
+ return text
37
+
38
+ # Il faut traiter \ en premier pour éviter d'échapper les échappements
39
+ # Puis traiter les autres caractères spéciaux
40
+ text = text.replace('\\', r'\textbackslash{}')
41
+
42
+ latex_special_chars = {
43
+ '&': r'\&',
44
+ '%': r'\%',
45
+ '$': r'\$',
46
+ '#': r'\#',
47
+ '^': r'\textasciicircum{}',
48
+ '_': r'\_',
49
+ '{': r'\{',
50
+ '}': r'\}',
51
+ '~': r'\textasciitilde{}',
52
+ }
53
+
54
+ for char, escape in latex_special_chars.items():
55
+ text = text.replace(char, escape)
56
+
57
+ return text
58
+
59
+ def escape_resume_data(data: Dict[str, Any]) -> Dict[str, Any]:
60
+ """Recursively escape LaTeX special characters in resume data."""
61
+ if isinstance(data, dict):
62
+ return {k: escape_resume_data(v) for k, v in data.items()}
63
+ elif isinstance(data, list):
64
+ return [escape_resume_data(item) for item in data]
65
+ elif isinstance(data, str):
66
+ return escape_latex_special_chars(data)
67
+ else:
68
+ return data
69
+
70
+ def render_tex(resume_data: Dict[str, Any], output_tex_path: Path, template_name: str = TEMPLATE_NAME) -> None:
71
+ try:
72
+ resume = Resume.model_validate(resume_data)
73
+ except ValidationError as e:
74
+ # En mode serveur (Gradio/MCP), il ne faut pas quitter le process
75
+ # Propager une erreur explicite pour que l'UI / MCP l'affiche correctement
76
+ raise ValueError(f"Validation Pydantic échouée: {e}") from e
77
+
78
+ env = Environment(
79
+ loader=FileSystemLoader(str(TEMPLATES_DIR)),
80
+ autoescape=False,
81
+ trim_blocks=True,
82
+ lstrip_blocks=True,
83
+ )
84
+ # Configure custom delimiters to avoid clashes with LaTeX
85
+ env.block_start_string = "<<%"
86
+ env.block_end_string = "%>>"
87
+ env.variable_start_string = "<<"
88
+ env.variable_end_string = ">>"
89
+ env.comment_start_string = "<#!"
90
+ env.comment_end_string = "!#>"
91
+ template = env.get_template(template_name)
92
+
93
+ # Échapper les caractères spéciaux LaTeX dans les données
94
+ escaped_data = escape_resume_data(resume.model_dump())
95
+ rendered = template.render(resume=escaped_data)
96
+
97
+ output_tex_path.parent.mkdir(parents=True, exist_ok=True)
98
+ output_tex_path.write_text(rendered, encoding="utf-8")
99
+
100
+
101
+ def run_tectonic(tex_path: Path, outdir: Path) -> None:
102
+ cmd = [
103
+ "tectonic",
104
+ "--outdir",
105
+ str(outdir),
106
+ str(tex_path),
107
+ ]
108
+ subprocess.run(cmd, check=True)
109
+
110
+
111
+ def run_latexmk(tex_path: Path, outdir: Path, *, xelatex: bool = False) -> None:
112
+ # latexmk -pdf -synctex=1 -interaction=nonstopmode -output-directory=outdir tex
113
+ cmd = ["latexmk"]
114
+ if xelatex:
115
+ cmd.append("-xelatex")
116
+ else:
117
+ cmd.append("-pdf")
118
+ cmd += [
119
+ "-halt-on-error",
120
+ "-file-line-error",
121
+ "-synctex=1",
122
+ "-interaction=nonstopmode",
123
+ f"-output-directory={outdir}",
124
+ str(tex_path),
125
+ ]
126
+ subprocess.run(cmd, check=True)
127
+
128
+
129
+ def compile_pdf(output_tex_path: Path, output_pdf_path: Path, engine_preference: str = "tectonic") -> None:
130
+ outdir = output_pdf_path.parent
131
+ outdir.mkdir(parents=True, exist_ok=True)
132
+
133
+ def tool_available(cmd: str) -> bool:
134
+ return shutil.which(cmd) is not None
135
+
136
+ def read_latex_log_tail() -> str:
137
+ try:
138
+ base = output_tex_path.stem
139
+ log_path = outdir / f"{base}.log"
140
+ if log_path.exists():
141
+ content = log_path.read_text(errors="ignore")
142
+ tail = "\n".join(content.splitlines()[-120:])
143
+ return tail
144
+ # tenter aussi le .xdv log de xelatex
145
+ xdv_path = outdir / f"{base}.xdv"
146
+ if xdv_path.exists():
147
+ return "(fichier .xdv présent, pas de .log généré)"
148
+ except Exception:
149
+ pass
150
+ return "(pas de log disponible)"
151
+
152
+ if engine_preference == "latexmk":
153
+ try:
154
+ # Sur Linux (HF Spaces), privilégier XeLaTeX pour éviter les soucis de polices (lmodern)
155
+ use_xelatex = platform.system() == "Linux"
156
+ run_latexmk(output_tex_path, outdir, xelatex=use_xelatex)
157
+ except (FileNotFoundError, subprocess.CalledProcessError) as e:
158
+ if tool_available("tectonic"):
159
+ run_tectonic(output_tex_path, outdir)
160
+ else:
161
+ log_tail = read_latex_log_tail()
162
+ raise RuntimeError(
163
+ "Compilation LaTeX échouée avec latexmk et aucun fallback 'tectonic' disponible.\n"
164
+ f"Commande: {e}\n\nDernières lignes du .log:\n{log_tail}"
165
+ ) from e
166
+ else:
167
+ # default: try tectonic first, then fallback if available
168
+ try:
169
+ run_tectonic(output_tex_path, outdir)
170
+ except (FileNotFoundError, subprocess.CalledProcessError) as e:
171
+ if tool_available("latexmk"):
172
+ try:
173
+ run_latexmk(output_tex_path, outdir)
174
+ except subprocess.CalledProcessError as e2:
175
+ log_tail = read_latex_log_tail()
176
+ raise RuntimeError(
177
+ "Compilation LaTeX échouée avec tectonic puis latexmk.\n"
178
+ f"Erreur latexmk: {e2}\n\nDernières lignes du .log:\n{log_tail}"
179
+ ) from e2
180
+ else:
181
+ raise RuntimeError(
182
+ f"Compilation LaTeX échouée avec tectonic et aucun fallback 'latexmk' disponible. "
183
+ f"Erreur tectonic: {e}"
184
+ ) from e
185
+
186
+ if not output_pdf_path.exists():
187
+ raise RuntimeError(f"PDF introuvable après compilation: {output_pdf_path}")
188
+
189
+
190
+ @gr.mcp.prompt()
191
+ def resume_generation_system_prompt() -> str:
192
+ """
193
+ System prompt complet pour gérer tout le workflow de génération de CV professionnel.
194
+
195
+ Ce prompt système fournit des instructions détaillées à l'assistant IA pour gérer
196
+ efficacement tout le processus de création de CV, de la collecte d'informations
197
+ à la génération du PDF final.
198
+
199
+ Returns:
200
+ str: Instructions système complètes pour l'assistant IA
201
+ """
202
+ return """Tu es un assistant spécialisé dans l'onboarding pour la génération de CV. Ton rôle est de guider l'utilisateur pour remplir toutes les informations nécessaires à la création de son CV, de manière claire, structurée et conviviale.
203
+
204
+ ## TES RÈGLES FONDAMENTALES
205
+
206
+ 1. **Pose une seule question à la fois** - Ne jamais submerger l'utilisateur
207
+ 2. **Fournis un exemple concret** pour chaque question afin de guider l'utilisateur
208
+ 3. **Valide chaque réponse** et reformule la question si la réponse est vide ou invalide
209
+ 4. **Ne fais jamais de supposition** sur l'utilisateur - Toujours demander et confirmer
210
+ 5. **Utilise un ton convivial, simple et naturel** - Pas de jargon technique
211
+
212
+ ## DÉMARRAGE OBLIGATOIRE
213
+
214
+ Commence TOUJOURS par cette question :
215
+ "Bonjour ! 👋 Je vais t'aider à créer ton CV professionnel.
216
+
217
+ Pour commencer, dis-moi : est-ce que tu crées ton **premier CV** ou tu veux **mettre à jour un CV existant** ?
218
+
219
+ Si c'est une mise à jour, peux-tu uploader ton ancien CV (fichier PDF, Word, etc.) pour que je puisse m'en inspirer ?"
220
+
221
+ ## INFORMATIONS À COLLECTER (DANS CET ORDRE)
222
+
223
+ ### 1. INFORMATIONS DE BASE
224
+ - **pdf_title**
225
+ - Question : "Quel titre veux-tu donner à ton CV ?"
226
+ - Exemple : "CV - Marie Dupont" ou "Candidature Développeur - Pierre Martin"
227
+
228
+ - **name** (sera automatiquement utilisé comme pdf_author)
229
+ - Question : "Quel est ton nom complet ?"
230
+ - Exemple : "Marie Dupont" ou "Pierre Martin"
231
+
232
+ - **location**
233
+ - Question : "Où habites-tu actuellement ?"
234
+ - Exemple : "Paris, France" ou "Lyon, France"
235
+
236
+ - **email**
237
+ - Question : "Quelle est ton adresse email professionnelle ?"
238
+ - Exemple : "marie.dupont@gmail.com"
239
+
240
+ - **phone**
241
+ - Question : "Quel est ton numéro de téléphone (avec l'indicatif pays) ?"
242
+ - Exemple : "+33 6 12 34 56 78" ou "06 12 34 56 78"
243
+
244
+ ### 2. LIENS PROFESSIONNELS (OPTIONNELS)
245
+ - **website_url** et **website_label**
246
+ - Question : "As-tu un site web personnel ou portfolio ? Si oui, donne-moi l'URL complète."
247
+ - Exemple : "https://marie-dupont.fr" → label sera "marie-dupont.fr"
248
+
249
+ - **linkedin_url** et **linkedin_handle**
250
+ - Question : "As-tu un profil LinkedIn ? Si oui, donne-moi le lien complet."
251
+ - Exemple : "https://linkedin.com/in/marie-dupont" → handle sera "marie-dupont"
252
+
253
+ - **github_url** et **github_handle**
254
+ - Question : "As-tu un profil GitHub ? Si oui, donne-moi le lien complet."
255
+ - Exemple : "https://github.com/marie-dupont" → handle sera "marie-dupont"
256
+
257
+ ### 3. CONTENU DU CV
258
+
259
+ - **intro_paragraphs**
260
+ - Question : "Écris une ou deux phrases qui te décrivent professionnellement."
261
+ - Exemple : "Développeuse web avec 3 ans d'expérience, passionnée par les technologies modernes et l'innovation."
262
+
263
+ - **quick_guide_items**
264
+ - Question : "Liste 3 à 5 de tes principales compétences ou points forts."
265
+ - Exemple : "Développement web, Gestion d'équipe, React/Node.js, Problem solving"
266
+
267
+ - **education**
268
+ - Question : "Parle-moi de ta formation. Pour chaque diplôme, indique : le nom du diplôme, l'école/université, les dates (format AAAA-AAAA), et éventuellement des mentions ou points importants."
269
+ - Exemple : "Master en Informatique à l'École Polytechnique (2020-2022), spécialité IA, mention Bien"
270
+ - ⚠️ **FORMAT DATES OBLIGATOIRE** : Toujours utiliser des tirets pour séparer les années (ex: "2020-2022", "2015-2018")
271
+
272
+ - **experience**
273
+ - Question : "Décris ton expérience professionnelle. Pour chaque poste : nom de l'entreprise, ton poste, lieu, dates (format Mois AAAA-Mois AAAA), et tes principales réalisations avec des chiffres si possible."
274
+ - Exemple : "Développeur chez Google, Paris (Janvier 2022-présent) : Développé 3 nouvelles fonctionnalités, réduit les bugs de 40%"
275
+ - ⚠️ **FORMAT DATES OBLIGATOIRE** : Utiliser des tirets et des espaces (ex: "Janvier 2022-Décembre 2024", "Avril-Juin 2022")
276
+
277
+ - **publications** (si applicable)
278
+ - Question : "As-tu publié des articles, recherches ou communications ? Si oui, donne-moi les détails."
279
+ - Exemple : "Article sur l'IA publié en 2023 dans la revue TechReview"
280
+
281
+ - **projects**
282
+ - Question : "Quels sont tes projets personnels ou professionnels marquants ? Avec liens GitHub si possible."
283
+ - Exemple : "Application mobile de gestion de tâches (React Native) - 1000+ téléchargements"
284
+
285
+ - **languages**
286
+ - Question : "Quels langages de programmation ou langues maîtrises-tu ?"
287
+ - Exemple : "Python, JavaScript, TypeScript, Anglais, Espagnol"
288
+
289
+ - **technologies**
290
+ - Question : "Quelles technologies, frameworks ou outils utilises-tu ?"
291
+ - Exemple : "React, Node.js, Docker, AWS, PostgreSQL"
292
+
293
+ ## FINALISATION
294
+
295
+ Une fois toutes les informations collectées :
296
+
297
+ 1. **Présente un récapitulatif clair** de toutes les informations
298
+ 2. **Demande confirmation** : "Ces informations sont-elles correctes ?"
299
+ 3. **Si confirmé**, appelle la fonction `generate_resume_pdf` avec tous les paramètres
300
+ 4. **Présente le résultat** : "Voici ton CV ! Tu peux le télécharger et me dire s'il faut ajuster quelque chose."
301
+
302
+ ## GESTION DES RÉPONSES
303
+
304
+ - **Si réponse vide** : "Cette information est importante pour ton CV. Peux-tu me donner cette information ?"
305
+ - **Si réponse invalide** : "Je n'ai pas bien compris. Peux-tu reformuler ? Voici un exemple : [exemple]"
306
+ - **Si l'utilisateur veut passer** : "D'accord, on peut laisser ça vide pour l'instant. On pourra l'ajouter plus tard si tu veux."
307
+
308
+ ## FORMATS JSON POUR LES PARAMÈTRES
309
+
310
+ Quand tu collectes des informations complexes, formate-les correctement :
311
+ - **Listes simples** : ["item1", "item2", "item3"]
312
+ - **Éducation** : [{"degree": "Master", "institution": "École", "date_range": "2020-2022", "field_of_study": "Informatique", "highlights": ["Mention Bien"]}]
313
+ - **Expérience** : [{"company": "Google", "role": "Développeur", "location": "Paris", "date_range": "Janvier 2022-présent", "highlights": ["Réalisation 1", "Impact 2"]}]
314
+
315
+ ⚠️ **RÈGLES CRITIQUES POUR LES DATES** :
316
+ - **TOUJOURS** utiliser des tirets pour séparer les périodes : "2020-2022", "Avril-Juin 2022"
317
+ - **JAMAIS** coller les dates : ❌ "20202022" ✅ "2020-2022"
318
+ - Pour l'éducation : Format "AAAA-AAAA" (ex: "2015-2018")
319
+ - Pour l'expérience : Format "Mois AAAA-Mois AAAA" (ex: "Janvier 2022-Décembre 2024")
320
+
321
+ Commence maintenant par la question de démarrage !"""
322
+
323
+
324
+ def validate_json_parameter(param_name: str, param_value: str) -> list:
325
+ """
326
+ Validate and parse a JSON parameter.
327
+
328
+ Args:
329
+ param_name (str): Name of the parameter for error reporting
330
+ param_value (str): JSON string to validate
331
+
332
+ Returns:
333
+ list: Parsed JSON data
334
+
335
+ Raises:
336
+ ValueError: If JSON is invalid
337
+ """
338
+ try:
339
+ parsed = json.loads(param_value)
340
+ if not isinstance(parsed, list):
341
+ raise ValueError(f"Parameter '{param_name}' must be a JSON array")
342
+ return parsed
343
+ except json.JSONDecodeError as e:
344
+ raise ValueError(f"Invalid JSON in parameter '{param_name}': {str(e)}")
345
+
346
+
347
+ def generate_resume_pdf(
348
+ pdf_title: str,
349
+ pdf_author: str,
350
+ name: str,
351
+ location: str,
352
+ email: str,
353
+ phone: str,
354
+ last_updated_text: str = "",
355
+ website_url: str = "",
356
+ website_label: str = "",
357
+ linkedin_url: str = "",
358
+ linkedin_handle: str = "",
359
+ github_url: str = "",
360
+ github_handle: str = "",
361
+ intro_paragraphs: str = "[]",
362
+ quick_guide_items: str = "[]",
363
+ education: str = "[]",
364
+ experience: str = "[]",
365
+ publications: str = "[]",
366
+ projects: str = "[]",
367
+ languages: str = "[]",
368
+ technologies: str = "[]"
369
+ ) -> str:
370
+ """
371
+ Generate a professional PDF resume from structured data.
372
+
373
+ Creates a LaTeX-based PDF resume. All JSON parameters must be valid JSON strings.
374
+
375
+ Args:
376
+ pdf_title (str): PDF document title (e.g., "John Doe Resume")
377
+ pdf_author (str): Author name for PDF metadata (e.g., "John Doe")
378
+ name (str): Full name (e.g., "John Doe")
379
+ location (str): Current location (e.g., "Paris, France")
380
+ email (str): Email address (e.g., "john.doe@example.com")
381
+ phone (str): Phone with country code (e.g., "+33 1 23 45 67 89")
382
+ last_updated_text (str): Optional update text (e.g., "Updated September 2024") or ""
383
+ website_url (str): Website URL (e.g., "https://johndoe.dev") or ""
384
+ website_label (str): Website display text (e.g., "johndoe.dev") or ""
385
+ linkedin_url (str): LinkedIn URL (e.g., "https://linkedin.com/in/johndoe") or ""
386
+ linkedin_handle (str): LinkedIn username (e.g., "johndoe") or ""
387
+ github_url (str): GitHub URL (e.g., "https://github.com/johndoe") or ""
388
+ github_handle (str): GitHub username (e.g., "johndoe") or ""
389
+ intro_paragraphs (str): JSON array of strings. Example: ["I am a software engineer with 5+ years experience.", "Passionate about AI and machine learning."]
390
+ quick_guide_items (str): JSON array of key skills. Example: ["Python Expert", "Team Leadership", "Agile Methodologies"]
391
+ education (str): JSON array of objects. Example: [{"degree": "Master of Science", "institution": "MIT", "date_range": "2018-2020", "field_of_study": "Computer Science", "highlights": ["GPA: 3.9/4.0"]}]. IMPORTANT: date_range must use format "YYYY-YYYY" (e.g., "2015-2018", NOT "20152018")
392
+ experience (str): JSON array of objects. Example: [{"company": "Google", "role": "Senior Engineer", "location": "Mountain View, CA", "date_range": "January 2020-Present", "highlights": ["Led team of 5 engineers", "Increased system performance by 40%"]}]. IMPORTANT: date_range must use format "Month YYYY-Month YYYY" with proper separators
393
+ publications (str): JSON array of objects. Example: [{"title": "AI in Production", "authors": ["John Doe", "Jane Smith"], "date": "2023", "doi": "10.1000/xyz123"}] or "[]"
394
+ projects (str): JSON array of objects. Example: [{"title": "E-commerce Platform", "repo_url": "https://github.com/johndoe/ecommerce", "repo_label": "github.com/johndoe/ecommerce", "highlights": ["Built with React and Node.js", "Handles 10k+ users"]}]
395
+ languages (str): JSON array of programming languages. Example: ["Python", "JavaScript", "TypeScript", "Go"]
396
+ technologies (str): JSON array of tools/frameworks. Example: ["React", "Node.js", "Docker", "AWS", "PostgreSQL"]
397
+
398
+ Returns:
399
+ str: File path to the generated PDF resume
400
+ """
401
+ try:
402
+ # Valider et parser tous les paramètres JSON
403
+ intro_paragraphs_list = validate_json_parameter("intro_paragraphs", intro_paragraphs)
404
+ quick_guide_items_list = validate_json_parameter("quick_guide_items", quick_guide_items)
405
+ education_list = validate_json_parameter("education", education)
406
+ experience_list = validate_json_parameter("experience", experience)
407
+ publications_list = validate_json_parameter("publications", publications)
408
+ projects_list = validate_json_parameter("projects", projects)
409
+ languages_list = validate_json_parameter("languages", languages)
410
+ technologies_list = validate_json_parameter("technologies", technologies)
411
+
412
+ # Construire le dictionnaire Resume à partir des paramètres
413
+ resume_data = {
414
+ "meta": {
415
+ "pdf_title": pdf_title,
416
+ "pdf_author": pdf_author,
417
+ "last_updated_text": last_updated_text if last_updated_text else None
418
+ },
419
+ "header": {
420
+ "name": name,
421
+ "location": location,
422
+ "email": email,
423
+ "phone": phone,
424
+ "website_url": website_url if website_url else None,
425
+ "website_label": website_label if website_label else None,
426
+ "linkedin_url": linkedin_url if linkedin_url else None,
427
+ "linkedin_handle": linkedin_handle if linkedin_handle else None,
428
+ "github_url": github_url if github_url else None,
429
+ "github_handle": github_handle if github_handle else None
430
+ },
431
+ "intro_paragraphs": intro_paragraphs_list,
432
+ "quick_guide_items": quick_guide_items_list,
433
+ "education": education_list,
434
+ "experience": experience_list,
435
+ "publications": publications_list,
436
+ "projects": projects_list,
437
+ "technologies_section": {
438
+ "languages": languages_list,
439
+ "technologies": technologies_list
440
+ }
441
+ }
442
+
443
+ # Valider avec le modèle Pydantic
444
+ resume = Resume.model_validate(resume_data)
445
+
446
+ # Générer le PDF
447
+ base_name = uuid.uuid4().hex
448
+ out_dir = OUTPUT_DIR
449
+ out_dir.mkdir(parents=True, exist_ok=True)
450
+ out_tex = out_dir / f"{base_name}.tex"
451
+ out_pdf = out_dir / f"{base_name}.pdf"
452
+
453
+ render_tex(resume.model_dump(), out_tex, template_name=TEMPLATE_NAME)
454
+
455
+ preferred_engine = "latexmk" if platform.system() == "Linux" else "tectonic"
456
+ compile_pdf(out_tex, out_pdf, engine_preference=preferred_engine)
457
+
458
+ # Retourner DIRECTEMENT le chemin pour que Gradio génère l'URL publique
459
+ return str(out_pdf)
460
+
461
+ except (ValueError, ValidationError) as e:
462
+ # Pour les erreurs, lever une exception que Gradio peut gérer
463
+ raise ValueError(str(e))
464
+ except Exception as err: # noqa: BLE001
465
+ # Pour toutes les autres erreurs
466
+ raise ValueError(f"Unexpected error: {str(err)}")
467
+
468
+ def launch_gradio(server_host: str = "127.0.0.1", server_port: int = 7860) -> None:
469
+ """Lance une application Gradio (UI + MCP Server).
470
+
471
+ L'UI propose: zone de texte JSON (schéma `Resume`) → bouton → PDF.\
472
+ Le serveur MCP est activé via `mcp_server=True` conformément à la doc
473
+ officielle Gradio [Building an MCP Server with Gradio](https://www.gradio.app/guides/building-mcp-server-with-gradio).
474
+ """
475
+ if gr is None:
476
+ print("Gradio n'est pas installé. Ajoutez 'gradio' à pyproject.toml.")
477
+ raise ImportError("Gradio n'est pas disponible")
478
+
479
+ sample_path = PROJECT_ROOT / "example_inputs" / "sample.json"
480
+ sample_value = "{}"
481
+ if sample_path.exists():
482
+ try:
483
+ sample_value = sample_path.read_text(encoding="utf-8")
484
+ except Exception: # noqa: BLE001
485
+ pass
486
+
487
+ with gr.Blocks(title="Générateur de CV PDF (LaTeX)") as demo:
488
+ gr.Markdown("## Générateur de CV PDF avec champs structurés\nTemplate: `classic.tex.j2`.")
489
+
490
+ with gr.Accordion("Mode d'emploi", open=True):
491
+ gr.Markdown(
492
+ "- Remplissez les champs ci-dessous pour créer votre CV.\n"
493
+ "- Les champs marqués * sont obligatoires.\n"
494
+ "- Les listes (éducation, expérience, etc.) doivent être au format JSON.\n"
495
+ "- Cliquez sur 'Générer le PDF' pour créer votre CV.\n"
496
+ )
497
+
498
+ with gr.Tab("Informations de base"):
499
+ with gr.Row():
500
+ with gr.Column():
501
+ ui_pdf_title = gr.Textbox(label="Titre du PDF *", value="Mon CV")
502
+ ui_pdf_author = gr.Textbox(label="Auteur du PDF *", value="")
503
+ ui_last_updated_text = gr.Textbox(label="Dernière mise à jour", value="", placeholder="ex: Septembre 2024")
504
+ with gr.Column():
505
+ ui_name = gr.Textbox(label="Nom complet *", value="")
506
+ ui_location = gr.Textbox(label="Localisation *", value="", placeholder="ex: Paris, France")
507
+ ui_email = gr.Textbox(label="Email *", value="", placeholder="ex: nom@example.com")
508
+ ui_phone = gr.Textbox(label="Téléphone *", value="", placeholder="ex: +33 1 23 45 67 89")
509
+
510
+ with gr.Tab("Liens et réseaux sociaux"):
511
+ with gr.Row():
512
+ with gr.Column():
513
+ ui_website_url = gr.Textbox(label="URL du site web", value="", placeholder="https://monsite.com")
514
+ ui_website_label = gr.Textbox(label="Label du site web", value="", placeholder="monsite.com")
515
+ ui_linkedin_url = gr.Textbox(label="URL LinkedIn", value="", placeholder="https://linkedin.com/in/...")
516
+ ui_linkedin_handle = gr.Textbox(label="Handle LinkedIn", value="", placeholder="monprofil")
517
+ with gr.Column():
518
+ ui_github_url = gr.Textbox(label="URL GitHub", value="", placeholder="https://github.com/...")
519
+ ui_github_handle = gr.Textbox(label="Handle GitHub", value="", placeholder="monprofil")
520
+
521
+ with gr.Tab("Contenu du CV"):
522
+ ui_intro_paragraphs = gr.Textbox(
523
+ label="Paragraphes d'introduction (JSON)",
524
+ value='["Ingénieur passionné avec 5 ans d\'expérience"]',
525
+ lines=3,
526
+ placeholder='["Paragraphe 1", "Paragraphe 2"]'
527
+ )
528
+ ui_quick_guide_items = gr.Textbox(
529
+ label="Points clés (JSON)",
530
+ value='["Expert en Python", "Gestion d\'équipe"]',
531
+ lines=3,
532
+ placeholder='["Point 1", "Point 2"]'
533
+ )
534
+
535
+ with gr.Row():
536
+ with gr.Column():
537
+ ui_education = gr.Textbox(
538
+ label="Éducation (JSON)",
539
+ value='[]',
540
+ lines=5,
541
+ placeholder='[{"degree": "Master", "institution": "Université", "date_range": "2020-2022", "field_of_study": "Informatique", "highlights": []}]'
542
+ )
543
+ ui_experience = gr.Textbox(
544
+ label="Expérience (JSON)",
545
+ value='[]',
546
+ lines=5,
547
+ placeholder='[{"company": "Entreprise", "role": "Développeur", "location": "Paris", "date_range": "2022-2024", "highlights": ["Réalisation X", "Amélioration Y"]}]'
548
+ )
549
+ with gr.Column():
550
+ ui_publications = gr.Textbox(
551
+ label="Publications (JSON)",
552
+ value='[]',
553
+ lines=3,
554
+ placeholder='[{"date": "2024", "title": "Article", "authors": ["Moi"], "doi_url": null, "doi_label": null}]'
555
+ )
556
+ ui_projects = gr.Textbox(
557
+ label="Projets (JSON)",
558
+ value='[]',
559
+ lines=3,
560
+ placeholder='[{"title": "Projet", "repo_url": "https://github.com/...", "repo_label": "github.com/...", "highlights": []}]'
561
+ )
562
+
563
+ with gr.Tab("Compétences"):
564
+ with gr.Row():
565
+ ui_languages = gr.Textbox(
566
+ label="Langages de programmation (JSON)",
567
+ value='["Python", "JavaScript", "Java"]',
568
+ lines=2,
569
+ placeholder='["Python", "JavaScript", "Java"]'
570
+ )
571
+ ui_technologies = gr.Textbox(
572
+ label="Technologies (JSON)",
573
+ value='["React", "Docker", "AWS"]',
574
+ lines=2,
575
+ placeholder='["React", "Docker", "AWS"]'
576
+ )
577
+
578
+ with gr.Row():
579
+ generate_btn = gr.Button("Générer le PDF", variant="primary", size="lg")
580
+
581
+ pdf_file = gr.File(label="PDF généré", file_count="single")
582
+
583
+ def _on_click_structured(
584
+ pdf_title, pdf_author, name, location, email, phone,
585
+ last_updated_text, website_url, website_label,
586
+ linkedin_url, linkedin_handle, github_url, github_handle,
587
+ intro_paragraphs, quick_guide_items, education, experience,
588
+ publications, projects, languages, technologies
589
+ ) -> str:
590
+ """Génère le PDF avec les champs structurés."""
591
+ try:
592
+ return generate_resume_pdf(
593
+ pdf_title, pdf_author, name, location, email, phone,
594
+ last_updated_text, website_url, website_label,
595
+ linkedin_url, linkedin_handle, github_url, github_handle,
596
+ intro_paragraphs, quick_guide_items, education, experience,
597
+ publications, projects, languages, technologies
598
+ )
599
+ except Exception as err: # noqa: BLE001
600
+ raise gr.Error(str(err))
601
+
602
+ # Connecter l'interface utilisateur
603
+ generate_btn.click(
604
+ _on_click_structured,
605
+ inputs=[
606
+ ui_pdf_title, ui_pdf_author, ui_name, ui_location, ui_email, ui_phone,
607
+ ui_last_updated_text, ui_website_url, ui_website_label,
608
+ ui_linkedin_url, ui_linkedin_handle, ui_github_url, ui_github_handle,
609
+ ui_intro_paragraphs, ui_quick_guide_items, ui_education, ui_experience,
610
+ ui_publications, ui_projects, ui_languages, ui_technologies
611
+ ],
612
+ outputs=[pdf_file],
613
+ api_name=False
614
+ )
615
+
616
+
617
+ # Section for API endpoints (hidden from UI but accessible for MCP)
618
+ with gr.Tab("API Endpoints", visible=False):
619
+ # API: generate_resume_pdf - Main resume generation tool
620
+ with gr.Row():
621
+ with gr.Column():
622
+ # Required fields
623
+ api_pdf_title = gr.Textbox(label="pdf_title", value="Professional Resume")
624
+ api_pdf_author = gr.Textbox(label="pdf_author", value="John Doe")
625
+ api_name = gr.Textbox(label="name", value="John Doe")
626
+ api_location = gr.Textbox(label="location", value="Paris, France")
627
+ api_email = gr.Textbox(label="email", value="john.doe@example.com")
628
+ api_phone = gr.Textbox(label="phone", value="+33 1 23 45 67 89")
629
+
630
+ # Optional fields
631
+ api_last_updated_text = gr.Textbox(label="last_updated_text", value="")
632
+ api_website_url = gr.Textbox(label="website_url", value="")
633
+ api_website_label = gr.Textbox(label="website_label", value="")
634
+ api_linkedin_url = gr.Textbox(label="linkedin_url", value="")
635
+ api_linkedin_handle = gr.Textbox(label="linkedin_handle", value="")
636
+ api_github_url = gr.Textbox(label="github_url", value="")
637
+ api_github_handle = gr.Textbox(label="github_handle", value="")
638
+
639
+ with gr.Column():
640
+ # JSON array fields with comprehensive examples for LLMs
641
+ api_intro_paragraphs = gr.Textbox(
642
+ label="intro_paragraphs",
643
+ value='["Experienced software engineer with 5+ years in full-stack development.", "Passionate about building scalable systems and leading technical teams."]',
644
+ placeholder='["Your intro paragraph 1", "Your intro paragraph 2"]',
645
+ lines=2
646
+ )
647
+ api_quick_guide_items = gr.Textbox(
648
+ label="quick_guide_items",
649
+ value='["Python Expert", "Team Leadership", "System Architecture", "Agile Methodologies"]',
650
+ placeholder='["Skill 1", "Skill 2", "Skill 3"]',
651
+ lines=2
652
+ )
653
+ api_education = gr.Textbox(
654
+ label="education",
655
+ value='[{"degree": "Master of Science", "institution": "MIT", "date_range": "2018-2020", "field_of_study": "Computer Science", "highlights": ["GPA: 3.9/4.0", "Thesis: Machine Learning Systems"]}]',
656
+ placeholder='[{"degree": "Your degree", "institution": "Your school", "date_range": "2018-2020", "field_of_study": "Your field", "highlights": ["Achievement 1"]}]',
657
+ lines=3
658
+ )
659
+ api_experience = gr.Textbox(
660
+ label="experience",
661
+ value='[{"company": "Google", "role": "Senior Software Engineer", "location": "Mountain View, CA", "date_range": "2020-Present", "highlights": ["Led team of 8 engineers", "Improved system performance by 45%", "Launched 3 major features"]}]',
662
+ placeholder='[{"company": "Company Name", "role": "Your Role", "location": "City, Country", "date_range": "2020-Present", "highlights": ["Achievement 1", "Achievement 2"]}]',
663
+ lines=3
664
+ )
665
+ api_publications = gr.Textbox(
666
+ label="publications",
667
+ value='[]',
668
+ placeholder='[{"title": "Paper Title", "authors": ["Author 1", "Author 2"], "date": "2023", "doi": "10.1000/xyz123"}]',
669
+ lines=1
670
+ )
671
+ api_projects = gr.Textbox(
672
+ label="projects",
673
+ value='[{"title": "E-commerce Platform", "repo_url": "https://github.com/johndoe/ecommerce", "repo_label": "github.com/johndoe/ecommerce", "highlights": ["Built with React and Node.js", "Handles 10k+ concurrent users", "99.9% uptime"]}]',
674
+ placeholder='[{"title": "Project Name", "repo_url": "https://github.com/user/repo", "repo_label": "github.com/user/repo", "highlights": ["Feature 1", "Feature 2"]}]',
675
+ lines=2
676
+ )
677
+ api_languages = gr.Textbox(
678
+ label="languages",
679
+ value='["Python", "JavaScript", "TypeScript", "Go", "Rust"]',
680
+ placeholder='["Language1", "Language2", "Language3"]',
681
+ lines=1
682
+ )
683
+ api_technologies = gr.Textbox(
684
+ label="technologies",
685
+ value='["React", "Node.js", "Docker", "Kubernetes", "AWS", "PostgreSQL", "Redis"]',
686
+ placeholder='["Tech1", "Tech2", "Framework1", "Database1"]',
687
+ lines=1
688
+ )
689
+
690
+ api_resume_output = gr.File(label="Generated PDF Resume")
691
+ api_resume_trigger = gr.Button("Generate Resume")
692
+
693
+
694
+ # API: resume_generation_system_prompt - System prompt principal
695
+ with gr.Row():
696
+ api_system_output = gr.Textbox(label="System Prompt for Resume Generation", lines=15)
697
+ api_system_trigger = gr.Button("Get System Prompt")
698
+
699
+
700
+ # Hook API names to the triggers
701
+ api_resume_trigger.click(
702
+ fn=generate_resume_pdf,
703
+ inputs=[
704
+ api_pdf_title, api_pdf_author, api_name, api_location, api_email, api_phone,
705
+ api_last_updated_text, api_website_url, api_website_label,
706
+ api_linkedin_url, api_linkedin_handle, api_github_url, api_github_handle,
707
+ api_intro_paragraphs, api_quick_guide_items, api_education, api_experience,
708
+ api_publications, api_projects, api_languages, api_technologies
709
+ ],
710
+ outputs=[api_resume_output],
711
+ api_name="generate_resume_pdf"
712
+ )
713
+
714
+ api_system_trigger.click(
715
+ fn=resume_generation_system_prompt,
716
+ inputs=[],
717
+ outputs=[api_system_output],
718
+ api_name="resume_generation_system_prompt"
719
+ )
720
+
721
+ # Launch the interface with MCP server enabled
722
+ # Following best practices from Gradio MCP documentation
723
+ demo.launch(
724
+ mcp_server=True, # Enable MCP server
725
+ server_name=server_host,
726
+ server_port=server_port,
727
+ share=False, # No sharing for production/HF Spaces
728
+ allowed_paths=[str(OUTPUT_DIR)], # Allow access to generated PDFs
729
+ show_api=True, # Show API documentation
730
+ )
731
+
732
+ print(f"🚀 Resume Generator MCP Server is running!")
733
+ print(f"📊 Web Interface: http://{server_host}:{server_port}")
734
+ print(f"🔗 MCP Endpoint: http://{server_host}:{server_port}/gradio_api/mcp/sse")
735
+ print(f"📋 API Schema: http://{server_host}:{server_port}/gradio_api/mcp/schema")
736
+
737
+
738
+ def main() -> None:
739
+ import argparse
740
+
741
+ parser = argparse.ArgumentParser(description="Générer le CV PDF depuis des données JSON ou lancer l'UI Gradio")
742
+ parser.add_argument(
743
+ "--serve",
744
+ action="store_true",
745
+ help="Lancer l'interface Gradio (au lieu du mode CLI)",
746
+ )
747
+ parser.add_argument(
748
+ "--input-json",
749
+ type=Path,
750
+ required=False,
751
+ help="Chemin du fichier JSON d'entrée (conforme au modèle Resume)",
752
+ )
753
+ parser.add_argument(
754
+ "--template",
755
+ type=str,
756
+ default=TEMPLATE_NAME,
757
+ help="Nom du fichier template (dans le dossier templates)",
758
+ )
759
+ parser.add_argument(
760
+ "--server-host",
761
+ type=str,
762
+ default="127.0.0.1",
763
+ help="Hôte pour l'UI Gradio (par défaut 127.0.0.1)",
764
+ )
765
+ parser.add_argument(
766
+ "--server-port",
767
+ type=int,
768
+ default=7860,
769
+ help="Port pour l'UI Gradio (par défaut 7860)",
770
+ )
771
+ parser.add_argument(
772
+ "--out-dir",
773
+ type=Path,
774
+ default=OUTPUT_DIR,
775
+ help="Dossier de sortie pour les fichiers générés (.tex, .pdf, artefacts LaTeX)",
776
+ )
777
+ # Suppression de l'argument --basename: le nom est toujours un UUID
778
+ parser.add_argument(
779
+ "--engine",
780
+ type=str,
781
+ choices=["tectonic", "latexmk"],
782
+ default=None,
783
+ help="Moteur de compilation LaTeX à privilégier (par défaut: latexmk sous Linux, sinon tectonic)",
784
+ )
785
+ parser.add_argument(
786
+ "--out-tex",
787
+ type=Path,
788
+ default=None,
789
+ help="Chemin du fichier .tex rendu (défaut: build/output.tex)",
790
+ )
791
+ parser.add_argument(
792
+ "--out-pdf",
793
+ type=Path,
794
+ default=None,
795
+ help="Chemin du PDF de sortie (défaut: build/output.pdf)",
796
+ )
797
+ args = parser.parse_args()
798
+
799
+ # Mode serveur (UI Gradio)
800
+ if args.serve:
801
+ launch_gradio(server_host=args.server_host, server_port=args.server_port)
802
+ return
803
+
804
+ if not args.input_json:
805
+ parser.error("--input-json est requis en mode CLI (sans --serve)")
806
+
807
+ data = json.loads(args.input_json.read_text(encoding="utf-8"))
808
+
809
+ # Nom de base: toujours un UUID
810
+ base_name = uuid.uuid4().hex
811
+
812
+ # Résoudre les chemins de sortie par défaut si non fournis
813
+ out_tex = args.out_tex or (args.out_dir / f"{base_name}.tex")
814
+ out_pdf = args.out_pdf or (args.out_dir / f"{base_name}.pdf")
815
+
816
+ # Forcer le template classic par défaut si non précisé
817
+ render_tex(data, out_tex, template_name=args.template or TEMPLATE_NAME)
818
+
819
+ # Choix du moteur par défaut selon l'OS
820
+ preferred_engine = args.engine
821
+ if preferred_engine is None:
822
+ preferred_engine = "latexmk" if platform.system() == "Linux" else "tectonic"
823
+
824
+ compile_pdf(out_tex, out_pdf, engine_preference=preferred_engine)
825
+ print(f"PDF généré: {out_pdf}")
826
+
827
+ if __name__ == "__main__":
828
+ main()
829
+
830
+