Files
parcoursup-motivation/generate_letters.py
2023-02-26 11:44:24 +01:00

76 lines
3.0 KiB
Python

"""Generate all 'lettres de motivation' for Parcourssup platform"""
import os
import sys
import re
TEMPLATE_PATH = os.path.join(os.path.dirname(__file__), "templates")
OUT_PATH = os.path.join(os.path.dirname(__file__), "output")
SIGNATURE = "Moi-même"
CONF = {
"prepa": [
{"name": "Lycée Thiers", "name_de": "du #", "name_le": "le #", "name_à": "au #", "name_à_superlatif": "au prestigieux #",},
{"name": "Lycée Henri IV", "name_de": "du #", "name_le": "le #", "name_à": "au #", "name_à_superlatif": "au prestigieux #",},
],
"insa": [
{"name": "INSA de Lyon", "name_de": "de l'#", "name_le": "l'#", "name_à": "à l'#",},
{"name": "INSA de Toulouse", "name_de": "de l'#", "name_le": "l'#", "name_à": "à l'#",},
],
"fac": [
{"name": "Licence Mathématiques", "name_de": "de la #", "name_le": "la #", "name_à": "dans la #",},
{"name": "Licence Physique", "name_de": "de la #", "name_le": "la #", "name_à": "dans la #",},
],
"mpci": [
{"name": "Licence MPCI", "ville_de": "de Marseille", "name_de": "de la #", "name_le": "la #", "name_à": "dans la #",},
],
}
sys.stdout.reconfigure(encoding='utf-8')
#For each type of 'voeux'
for voeu_type in CONF:
#Filename for the template
template_filename = os.path.join(TEMPLATE_PATH, voeu_type + ".txt")
#Chech whether the template exists
if os.path.exists(template_filename):
#Read the template
with open(template_filename, "r", encoding="utf-8") as fileobj:
template_content = fileobj.read()
#Find all tags in the template
tags = set(re.findall("\[(\w+)\]", template_content))
#Get list of 'voeux' in the type of 'voeux'
voeux_list = CONF[voeu_type]
for voeu in voeux_list:
#Replace '#' by the 'name'
for item in voeu.copy():
voeu[item] = voeu[item].replace("#", voeu["name"])
#Add the 'signature' in the dictionary
voeu["signature"] = SIGNATURE
#Add the capitalized version in the dictionary
for item in voeu.copy():
voeu[item.capitalize()] = voeu[item][0].upper() + voeu[item][1:]
#Build the final 'lettre de motivation'
motivation_content = template_content
for tag in tags:
if tag not in voeu:
raise KeyError(f"Missing '{tag}' in CONF for template {voeu_type}")
motivation_content = motivation_content.replace(f"[{tag}]", voeu[tag])
#Filename for the output file
motivation_filename = os.path.join(OUT_PATH, voeu_type, voeu["name"].replace(" ", "_") + ".txt")
#Create missing folders if needed
os.makedirs(os.path.dirname(motivation_filename), exist_ok=True)
#Wrtie the final 'lettre de motivation'
with open(motivation_filename, "w", encoding="utf-8") as fileobj:
fileobj.write(motivation_content)