195 lines
7.5 KiB
Python
195 lines
7.5 KiB
Python
# ihh.py
|
|
|
|
import re
|
|
import yaml
|
|
from jinja2 import Template
|
|
from ..utils.pastille import pastille
|
|
|
|
IHH_RE = re.compile(r"```yaml\s+opération:(.*?)```", re.S | re.I)
|
|
|
|
def _extraire_donnees_operations(operations: list[dict]) -> dict:
|
|
"""Extrait et organise les données des opérations par item."""
|
|
data_by_item = {}
|
|
|
|
for op in operations:
|
|
item_id = op.get('minerai', op.get('produit', op.get('composant', '')))
|
|
if not item_id:
|
|
continue
|
|
|
|
if item_id not in data_by_item:
|
|
data_by_item[item_id] = {
|
|
'type': 'minerai' if 'extraction' in op or 'reserves' in op or 'traitement' in op else
|
|
'produit' if 'assemblage' in op else 'composant',
|
|
'extraction_ihh_pays': '-',
|
|
'extraction_ihh_acteurs': '-',
|
|
'reserves_ihh_pays': '-',
|
|
'traitement_ihh_pays': '-',
|
|
'traitement_ihh_acteurs': '-',
|
|
'assemblage_ihh_pays': '-',
|
|
'assemblage_ihh_acteurs': '-',
|
|
'fabrication_ihh_pays': '-',
|
|
'fabrication_ihh_acteurs': '-'
|
|
}
|
|
|
|
if 'extraction' in op:
|
|
data_by_item[item_id]['extraction_ihh_pays'] = op['extraction'].get('ihh_pays', '-')
|
|
data_by_item[item_id]['extraction_ihh_acteurs'] = op['extraction'].get('ihh_acteurs', '-')
|
|
data_by_item[item_id]['reserves_ihh_pays'] = op['reserves'].get('ihh_pays', '-')
|
|
data_by_item[item_id]['traitement_ihh_pays'] = op['traitement'].get('ihh_pays', '-')
|
|
data_by_item[item_id]['traitement_ihh_acteurs'] = op['traitement'].get('ihh_acteurs', '-')
|
|
elif 'assemblage' in op:
|
|
data_by_item[item_id]['assemblage_ihh_pays'] = op['assemblage'].get('ihh_pays', '-')
|
|
data_by_item[item_id]['assemblage_ihh_acteurs'] = op['assemblage'].get('ihh_acteurs', '-')
|
|
elif 'fabrication' in op:
|
|
data_by_item[item_id]['fabrication_ihh_pays'] = op['fabrication'].get('ihh_pays', '-')
|
|
data_by_item[item_id]['fabrication_ihh_acteurs'] = op['fabrication'].get('ihh_acteurs', '-')
|
|
|
|
return data_by_item
|
|
|
|
|
|
def _generer_tableau_produits(produits: dict) -> str:
|
|
"""Génère un tableau markdown pour les produits."""
|
|
if not produits:
|
|
return ""
|
|
|
|
resultat = ["\n\n## Assemblage des produits\n"]
|
|
lignes = [
|
|
"| Produit | Assemblage IHH Pays | Assemblage IHH Acteurs |",
|
|
"| :-- | :--: | :--: |"
|
|
]
|
|
|
|
for produit, data in sorted(produits.items()):
|
|
pastille_1 = pastille("IHH", data['assemblage_ihh_pays'])
|
|
pastille_2 = pastille("IHH", data['assemblage_ihh_acteurs'])
|
|
lignes.append(
|
|
f"| {produit} | {pastille_1} {data['assemblage_ihh_pays']} | {pastille_2} {data['assemblage_ihh_acteurs']} |"
|
|
)
|
|
|
|
resultat.append("\n".join(lignes))
|
|
return "\n".join(resultat)
|
|
|
|
|
|
def _generer_tableau_composants(composants: dict) -> str:
|
|
"""Génère un tableau markdown pour les composants."""
|
|
if not composants:
|
|
return ""
|
|
|
|
resultat = ["\n\n## Fabrication des composants\n"]
|
|
lignes = [
|
|
"| Composant | Fabrication IHH Pays | Fabrication IHH Acteurs |",
|
|
"| :-- | :--: | :--: |"
|
|
]
|
|
|
|
for composant, data in sorted(composants.items()):
|
|
pastille_1 = pastille("IHH", data['fabrication_ihh_pays'])
|
|
pastille_2 = pastille("IHH", data['fabrication_ihh_acteurs'])
|
|
lignes.append(
|
|
f"| {composant} | {pastille_1} {data['fabrication_ihh_pays']} | {pastille_2} {data['fabrication_ihh_acteurs']} |"
|
|
)
|
|
|
|
resultat.append("\n".join(lignes))
|
|
return "\n".join(resultat)
|
|
|
|
|
|
def _generer_tableau_minerais(minerais: dict) -> str:
|
|
"""Génère un tableau markdown pour les minerais."""
|
|
if not minerais:
|
|
return ""
|
|
|
|
resultat = ["\n\n## Opérations sur les minerais\n"]
|
|
lignes = [
|
|
"| Minerai | Extraction IHH Pays | Extraction IHH Acteurs | Réserves IHH Pays | Traitement IHH Pays | Traitement IHH Acteurs |",
|
|
"| :-- | :--: | :--: | :--: | :--: | :--: |"
|
|
]
|
|
|
|
for minerai, data in sorted(minerais.items()):
|
|
pastille_1 = pastille("IHH", data['extraction_ihh_pays'])
|
|
pastille_2 = pastille("IHH", data['extraction_ihh_acteurs'])
|
|
pastille_3 = pastille("IHH", data['reserves_ihh_pays'])
|
|
pastille_4 = pastille("IHH", data['traitement_ihh_pays'])
|
|
pastille_5 = pastille("IHH", data['traitement_ihh_acteurs'])
|
|
lignes.append(
|
|
f"| {minerai} | {pastille_1} {data['extraction_ihh_pays']} | {pastille_2} {data['extraction_ihh_acteurs']} | "
|
|
f"{pastille_3} {data['reserves_ihh_pays']} | {pastille_4} {data['traitement_ihh_pays']} | {pastille_5} {data['traitement_ihh_acteurs']} |"
|
|
)
|
|
|
|
resultat.append("\n".join(lignes))
|
|
return "\n".join(resultat)
|
|
|
|
|
|
def _synth_ihh(operations: list[dict]) -> str:
|
|
"""Génère des tableaux de synthèse pour les indices HHI à partir des opérations."""
|
|
# Extraction et organisation des données
|
|
data_by_item = _extraire_donnees_operations(operations)
|
|
|
|
# Catégorisation des items
|
|
produits = {k: v for k, v in data_by_item.items() if v['type'] == 'produit'}
|
|
composants = {k: v for k, v in data_by_item.items() if v['type'] == 'composant'}
|
|
minerais = {k: v for k, v in data_by_item.items() if v['type'] == 'minerai'}
|
|
|
|
# Génération des tableaux pour chaque catégorie
|
|
tableaux = [
|
|
_generer_tableau_produits(produits),
|
|
_generer_tableau_composants(composants),
|
|
_generer_tableau_minerais(minerais)
|
|
]
|
|
|
|
# Assemblage du résultat final
|
|
return "\n".join([t for t in tableaux if t])
|
|
|
|
def build_ihh_sections(md: str) -> str:
|
|
"""
|
|
Fonction principale pour générer les sections dynamiques dans le markdown, spécifiquement dédiée à l'analyse des indices IHH.
|
|
|
|
La fonction gère les différents types de données présents dans les fiches, notamment :
|
|
- Les opérations d'extraction et de traitement du minerai
|
|
- L'assemblage des produits finaux
|
|
- La fabrication des composants intermédiaires
|
|
|
|
Args:
|
|
md (str): Contenu brut du fichier Markdown contenant les structures YAML à analyser.
|
|
|
|
Returns:
|
|
str: Le markdown enrichi avec les tableaux de donnée analysés, ou le contenu original inchangé si aucun bloc structuré n'est trouvé.
|
|
"""
|
|
segments = []
|
|
operations = []
|
|
intro = None
|
|
|
|
matches = list(IHH_RE.finditer(md))
|
|
if matches:
|
|
first = matches[0]
|
|
intro = md[:first.start()].strip()
|
|
else:
|
|
return md
|
|
|
|
for m in matches:
|
|
bloc_text = m.group(1)
|
|
bloc = yaml.safe_load("opération:" + bloc_text)
|
|
operations.append(bloc["opération"])
|
|
|
|
start = m.end()
|
|
next_match = IHH_RE.search(md, start)
|
|
end = next_match.start() if next_match else len(md)
|
|
|
|
section_template = md[start:end].strip()
|
|
rendered = Template(section_template).render(**bloc["opération"])
|
|
segments.append(rendered)
|
|
|
|
if intro:
|
|
segments.insert(0, intro)
|
|
|
|
if "# Tableaux de synthèse" in md:
|
|
synth_table = _synth_ihh(operations)
|
|
md_final = "\n\n".join(segments)
|
|
md_final = re.sub(
|
|
r"(?:##?|#) Tableaux de synthèse\s*\n<!---- AUTO-BEGIN:TABLEAU-FINAL -->.*?<!---- AUTO-END:TABLEAU-FINAL -->",
|
|
f"# Tableaux de synthèse\n<!---- AUTO-BEGIN:TABLEAU-FINAL -->\n{synth_table}\n<!---- AUTO-END:TABLEAU-FINAL -->",
|
|
md_final,
|
|
flags=re.S
|
|
)
|
|
else:
|
|
md_final = "\n\n".join(segments)
|
|
|
|
return md_final
|