File size: 4,853 Bytes
c4e6d00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
import pandas as pd
import json
import os

# On définit les chemins par rapport à la racine du projet
ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INPUT_DIR = os.path.join(ROOT_DIR, "data", "input")
OUTPUT_JSONL = os.path.join(ROOT_DIR, "data", "metiers_rag.jsonl")
OUTPUT_PARQUET = os.path.join(ROOT_DIR, "data", "metiers_rag.parquet")

def prepare_expert_rag_jsonl(max_words=300):
    print(f"🚀 Démarrage de la préparation (Racine: {ROOT_DIR})")
    
    try:
        df_metiers = pd.read_csv(os.path.join(INPUT_DIR, "gem_metiers.csv"))
        df_liens = pd.read_csv(os.path.join(INPUT_DIR, "gem_metiers_competences.csv"))
        df_dict_comp = pd.read_csv(os.path.join(INPUT_DIR, "gem_competences.csv"))
        
        df_verbatims = pd.DataFrame(columns=["id_metier", "verbatim"])
        v_path = os.path.join(INPUT_DIR, "metiers_verbatims.csv")
        if os.path.exists(v_path):
            df_verbatims = pd.read_csv(v_path)
            print(f"✅ {len(df_verbatims)} verbatims trouvés.")
        
    except Exception as e:
        print(f"❌ Erreur : {e}")
        return

    comp_defs = {}
    for _, row in df_dict_comp.iterrows():
        c_id = row['Id interne Neobrain Compétence']
        comp_defs[c_id] = {i: row.get(f'Description Niveau {i} Compétence', '') for i in range(1, 5)}

    rag_items = []
    
    for _, metier in df_metiers.iterrows():
        code_m = metier['Code Métier']
        nom_m = metier['Métier collaborateur']
        famille = metier['Famille métier']
        
        comp_du_metier = df_liens[df_liens['Code Métier'] == code_m].sort_values(by='Poids de la compétence', ascending=False)
        
        header = f"# Fiche Métier : {nom_m}\n\n"
        header += f"- **Code Métier** : {code_m}\n"
        header += f"- **Famille** : {famille}\n\n"

        v_list = df_verbatims[df_verbatims['id_metier'] == code_m]['verbatim'].tolist()
        if v_list:
            header += "## Missions quotidiennes (Verbatims)\n"
            for v in v_list:
                header += f"- \"{v}\"\n"
            header += "\n"

        header += "## Profil de compétences (Attentes)\n\n"

        comp_lines = []
        for groupe, df_g in comp_du_metier.groupby('Groupe de compétences', sort=False):
            comp_lines.append(f"### {groupe}")
            for _, row_c in df_g.iterrows():
                nom_c = row_c['Nom de la compétence']
                val = row_c['Niveau requis pour le métier']
                niv_req = int(float(val)) if pd.notna(val) else 0 
                c_id = row_c['Id interne Neobrain Compétence']
                desc_niveau = comp_defs.get(c_id, {}).get(niv_req, "")
                
                line = f"- **{nom_c}** (Niveau {niv_req})"
                if pd.notna(desc_niveau) and desc_niveau != "":
                    line += f" : {desc_niveau}"
                comp_lines.append(line)
            comp_lines.append("")

        current_chunk_comps = []
        current_word_count = len(header.split())
        chunk_id = 1

        def add_item(cid, text, midx):
            rag_items.append({
                "id": f"{cid}_{midx}" if midx > 1 else cid,
                "title": nom_m,
                "text": text,
                "metadata": {"famille": famille, "chunk": midx, "source": "OPT-NC Expert Ref 2025"}
            })

        for line in comp_lines:
            line_words = len(line.split())
            if current_word_count + line_words > max_words and current_chunk_comps:
                add_item(code_m, header + "\n".join(current_chunk_comps), chunk_id)
                chunk_id += 1
                current_chunk_comps = [line]
                current_word_count = len(header.split()) + line_words
            else:
                current_chunk_comps.append(line)
                current_word_count += line_words

        if current_chunk_comps:
            add_item(code_m, header + "\n".join(current_chunk_comps), chunk_id)

    # EXPORT DOUBLE FORMAT
    os.makedirs(os.path.dirname(OUTPUT_JSONL), exist_ok=True)
    
    # 1. JSONL
    with open(OUTPUT_JSONL, "w", encoding="utf-8") as f:
        for item in rag_items:
            f.write(json.dumps(item, ensure_ascii=False) + "\n")
    
    # 2. PARQUET (On aplatit un peu pour le format colonnaire)
    df_final = pd.DataFrame(rag_items)
    df_final['famille'] = df_final['metadata'].apply(lambda x: x['famille'])
    df_final['source'] = df_final['metadata'].apply(lambda x: x['source'])
    df_final['chunk_index'] = df_final['metadata'].apply(lambda x: x['chunk'])
    df_final.drop(columns=['metadata']).to_parquet(OUTPUT_PARQUET, index=False)
    
    print(f"✨ Terminé !")
    print(f"📄 JSONL : {OUTPUT_JSONL}")
    print(f"📦 PARQUET : {OUTPUT_PARQUET}")

if __name__ == "__main__":
    prepare_expert_rag_jsonl()