Create scripts/prepare_rag_jsonl.py
Browse files- scripts/prepare_rag_jsonl.py +118 -0
scripts/prepare_rag_jsonl.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
|
| 5 |
+
# On définit les chemins par rapport à la racine du projet
|
| 6 |
+
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 7 |
+
INPUT_DIR = os.path.join(ROOT_DIR, "data", "input")
|
| 8 |
+
OUTPUT_JSONL = os.path.join(ROOT_DIR, "data", "metiers_rag.jsonl")
|
| 9 |
+
OUTPUT_PARQUET = os.path.join(ROOT_DIR, "data", "metiers_rag.parquet")
|
| 10 |
+
|
| 11 |
+
def prepare_expert_rag_jsonl(max_words=300):
|
| 12 |
+
print(f"🚀 Démarrage de la préparation (Racine: {ROOT_DIR})")
|
| 13 |
+
|
| 14 |
+
try:
|
| 15 |
+
df_metiers = pd.read_csv(os.path.join(INPUT_DIR, "gem_metiers.csv"))
|
| 16 |
+
df_liens = pd.read_csv(os.path.join(INPUT_DIR, "gem_metiers_competences.csv"))
|
| 17 |
+
df_dict_comp = pd.read_csv(os.path.join(INPUT_DIR, "gem_competences.csv"))
|
| 18 |
+
|
| 19 |
+
df_verbatims = pd.DataFrame(columns=["id_metier", "verbatim"])
|
| 20 |
+
v_path = os.path.join(INPUT_DIR, "metiers_verbatims.csv")
|
| 21 |
+
if os.path.exists(v_path):
|
| 22 |
+
df_verbatims = pd.read_csv(v_path)
|
| 23 |
+
print(f"✅ {len(df_verbatims)} verbatims trouvés.")
|
| 24 |
+
|
| 25 |
+
except Exception as e:
|
| 26 |
+
print(f"❌ Erreur : {e}")
|
| 27 |
+
return
|
| 28 |
+
|
| 29 |
+
comp_defs = {}
|
| 30 |
+
for _, row in df_dict_comp.iterrows():
|
| 31 |
+
c_id = row['Id interne Neobrain Compétence']
|
| 32 |
+
comp_defs[c_id] = {i: row.get(f'Description Niveau {i} Compétence', '') for i in range(1, 5)}
|
| 33 |
+
|
| 34 |
+
rag_items = []
|
| 35 |
+
|
| 36 |
+
for _, metier in df_metiers.iterrows():
|
| 37 |
+
code_m = metier['Code Métier']
|
| 38 |
+
nom_m = metier['Métier collaborateur']
|
| 39 |
+
famille = metier['Famille métier']
|
| 40 |
+
|
| 41 |
+
comp_du_metier = df_liens[df_liens['Code Métier'] == code_m].sort_values(by='Poids de la compétence', ascending=False)
|
| 42 |
+
|
| 43 |
+
header = f"# Fiche Métier : {nom_m}\n\n"
|
| 44 |
+
header += f"- **Code Métier** : {code_m}\n"
|
| 45 |
+
header += f"- **Famille** : {famille}\n\n"
|
| 46 |
+
|
| 47 |
+
v_list = df_verbatims[df_verbatims['id_metier'] == code_m]['verbatim'].tolist()
|
| 48 |
+
if v_list:
|
| 49 |
+
header += "## Missions quotidiennes (Verbatims)\n"
|
| 50 |
+
for v in v_list:
|
| 51 |
+
header += f"- \"{v}\"\n"
|
| 52 |
+
header += "\n"
|
| 53 |
+
|
| 54 |
+
header += "## Profil de compétences (Attentes)\n\n"
|
| 55 |
+
|
| 56 |
+
comp_lines = []
|
| 57 |
+
for groupe, df_g in comp_du_metier.groupby('Groupe de compétences', sort=False):
|
| 58 |
+
comp_lines.append(f"### {groupe}")
|
| 59 |
+
for _, row_c in df_g.iterrows():
|
| 60 |
+
nom_c = row_c['Nom de la compétence']
|
| 61 |
+
val = row_c['Niveau requis pour le métier']
|
| 62 |
+
niv_req = int(float(val)) if pd.notna(val) else 0
|
| 63 |
+
c_id = row_c['Id interne Neobrain Compétence']
|
| 64 |
+
desc_niveau = comp_defs.get(c_id, {}).get(niv_req, "")
|
| 65 |
+
|
| 66 |
+
line = f"- **{nom_c}** (Niveau {niv_req})"
|
| 67 |
+
if pd.notna(desc_niveau) and desc_niveau != "":
|
| 68 |
+
line += f" : {desc_niveau}"
|
| 69 |
+
comp_lines.append(line)
|
| 70 |
+
comp_lines.append("")
|
| 71 |
+
|
| 72 |
+
current_chunk_comps = []
|
| 73 |
+
current_word_count = len(header.split())
|
| 74 |
+
chunk_id = 1
|
| 75 |
+
|
| 76 |
+
def add_item(cid, text, midx):
|
| 77 |
+
rag_items.append({
|
| 78 |
+
"id": f"{cid}_{midx}" if midx > 1 else cid,
|
| 79 |
+
"title": nom_m,
|
| 80 |
+
"text": text,
|
| 81 |
+
"metadata": {"famille": famille, "chunk": midx, "source": "OPT-NC Expert Ref 2025"}
|
| 82 |
+
})
|
| 83 |
+
|
| 84 |
+
for line in comp_lines:
|
| 85 |
+
line_words = len(line.split())
|
| 86 |
+
if current_word_count + line_words > max_words and current_chunk_comps:
|
| 87 |
+
add_item(code_m, header + "\n".join(current_chunk_comps), chunk_id)
|
| 88 |
+
chunk_id += 1
|
| 89 |
+
current_chunk_comps = [line]
|
| 90 |
+
current_word_count = len(header.split()) + line_words
|
| 91 |
+
else:
|
| 92 |
+
current_chunk_comps.append(line)
|
| 93 |
+
current_word_count += line_words
|
| 94 |
+
|
| 95 |
+
if current_chunk_comps:
|
| 96 |
+
add_item(code_m, header + "\n".join(current_chunk_comps), chunk_id)
|
| 97 |
+
|
| 98 |
+
# EXPORT DOUBLE FORMAT
|
| 99 |
+
os.makedirs(os.path.dirname(OUTPUT_JSONL), exist_ok=True)
|
| 100 |
+
|
| 101 |
+
# 1. JSONL
|
| 102 |
+
with open(OUTPUT_JSONL, "w", encoding="utf-8") as f:
|
| 103 |
+
for item in rag_items:
|
| 104 |
+
f.write(json.dumps(item, ensure_ascii=False) + "\n")
|
| 105 |
+
|
| 106 |
+
# 2. PARQUET (On aplatit un peu pour le format colonnaire)
|
| 107 |
+
df_final = pd.DataFrame(rag_items)
|
| 108 |
+
df_final['famille'] = df_final['metadata'].apply(lambda x: x['famille'])
|
| 109 |
+
df_final['source'] = df_final['metadata'].apply(lambda x: x['source'])
|
| 110 |
+
df_final['chunk_index'] = df_final['metadata'].apply(lambda x: x['chunk'])
|
| 111 |
+
df_final.drop(columns=['metadata']).to_parquet(OUTPUT_PARQUET, index=False)
|
| 112 |
+
|
| 113 |
+
print(f"✨ Terminé !")
|
| 114 |
+
print(f"📄 JSONL : {OUTPUT_JSONL}")
|
| 115 |
+
print(f"📦 PARQUET : {OUTPUT_PARQUET}")
|
| 116 |
+
|
| 117 |
+
if __name__ == "__main__":
|
| 118 |
+
prepare_expert_rag_jsonl()
|