File size: 6,800 Bytes
25f8116
 
e6211d5
25f8116
 
e6211d5
25f8116
 
 
e6211d5
25f8116
 
e6211d5
 
 
 
 
 
 
 
 
 
 
25f8116
e6211d5
 
 
 
 
 
 
 
25f8116
 
e6211d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f8116
e6211d5
 
 
 
 
 
 
 
 
25f8116
 
e6211d5
 
 
 
 
 
 
 
 
 
25f8116
e6211d5
 
 
 
25f8116
e6211d5
25f8116
e6211d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#!/usr/bin/env python3
"""
πŸ“¦ PrΓ©diction BATCH - API Hugging Face (Gradio)

Usage: python demo_batch_hf.py
PrΓ©requis: pip install gradio_client pandas
"""

import os
import sys
from datetime import datetime

try:
    import pandas as pd
    from gradio_client import Client, handle_file
except ImportError:
    print("❌ Dépendances manquantes. Installez avec:")
    print("   pip install gradio_client pandas")
    sys.exit(1)

# ═══════════════════════════════════════════════════════════════
# CONFIGURATION
# ═══════════════════════════════════════════════════════════════
API_URL = os.getenv("HF_API_URL", "https://asi-engineer-oc-p5.hf.space")
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))

# Fichiers par dΓ©faut
DEFAULT_FILES = {
    "eval": os.path.join(SCRIPT_DIR, "02_predict_batch_eval.csv"),
    "sirh": os.path.join(SCRIPT_DIR, "02_predict_batch_sirh.csv"),
    "sondage": os.path.join(SCRIPT_DIR, "02_predict_batch_sondage.csv"),
}

print("╔══════════════════════════════════════════════════════════╗")
print("β•‘  πŸ“¦ PRΓ‰DICTION BATCH - API Hugging Face                  β•‘")
print("β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•")
print(f"\n🌐 API: {API_URL}\n")

# ═══════════════════════════════════════════════════════════════
# SÉLECTION DES FICHIERS
# ═══════════════════════════════════════════════════════════════
print("═" * 60)
print("πŸ“ SΓ‰LECTION DES FICHIERS CSV")
print("═" * 60)

use_default = (
    input("\nUtiliser les fichiers exemples par dΓ©faut? [O/n]: ").strip().lower()
)

if use_default in ("", "o", "oui", "y", "yes"):
    fichier_eval = DEFAULT_FILES["eval"]
    fichier_sirh = DEFAULT_FILES["sirh"]
    fichier_sondage = DEFAULT_FILES["sondage"]
    print(f"\nπŸ“„ Γ‰valuation: {os.path.basename(fichier_eval)}")
    print(f"πŸ“„ SIRH:       {os.path.basename(fichier_sirh)}")
    print(f"πŸ“„ Sondage:    {os.path.basename(fichier_sondage)}")
else:
    print("\nEntrez les chemins des fichiers CSV:")
    fichier_eval = input("πŸ“„ Fichier Γ©valuation: ").strip()
    fichier_sirh = input("πŸ“„ Fichier SIRH: ").strip()
    fichier_sondage = input("πŸ“„ Fichier sondage: ").strip()

# VΓ©rification des fichiers
for name, path in [
    ("Γ‰valuation", fichier_eval),
    ("SIRH", fichier_sirh),
    ("Sondage", fichier_sondage),
]:
    if not os.path.exists(path):
        print(f"\n❌ Fichier {name} introuvable: {path}")
        sys.exit(1)

# ═══════════════════════════════════════════════════════════════
# PRÉDICTION BATCH
# ═══════════════════════════════════════════════════════════════
print("\n" + "═" * 60)
print("⏳ TRAITEMENT EN COURS...")
print("═" * 60)

try:
    print("\n⏳ Connexion à l'API...")
    client = Client(API_URL)
    print("βœ… ConnectΓ©")

    print("⏳ Envoi des fichiers...")
    result = client.predict(
        fichier_eval=handle_file(fichier_eval),
        fichier_sirh=handle_file(fichier_sirh),
        fichier_sondage=handle_file(fichier_sondage),
        api_name="/predict_batch",
    )

    # ═══════════════════════════════════════════════════════════════
    # AFFICHAGE DU RÉSULTAT
    # ═══════════════════════════════════════════════════════════════
    print("\n" + "═" * 60)
    print("πŸ“Š RΓ‰SULTAT DE LA PRΓ‰DICTION BATCH")
    print("═" * 60)

    if isinstance(result, dict):
        # Lecture du fichier rΓ©sultat
        result_path = result.get("value") or result.get("path")
        if result_path and os.path.exists(result_path):
            df = pd.read_csv(result_path)
            total = len(df)

            # Statistiques
            if "prediction" in df.columns:
                restent = (df["prediction"] == "Reste").sum()
                partent = (df["prediction"] == "Part").sum()
            else:
                restent = partent = 0

            if "risk_level" in df.columns:
                risque_eleve = (df["risk_level"] == "Γ‰levΓ©").sum()
                risque_moyen = (df["risk_level"] == "Moyen").sum()
                risque_faible = (df["risk_level"] == "Faible").sum()
            else:
                risque_eleve = risque_moyen = risque_faible = 0

            # Affichage des stats
            print(f"\nπŸ‘₯ Total employΓ©s analysΓ©s: {total}")
            print(f"\nπŸ“ˆ Vont RESTER:  {restent} ({100 * restent / total:.1f}%)")
            print(f"πŸ“‰ Vont PARTIR:  {partent} ({100 * partent / total:.1f}%)")

            print(f"\n🟒 Risque faible: {risque_faible}")
            print(f"🟠 Risque moyen:  {risque_moyen}")
            print(f"πŸ”΄ Risque Γ©levΓ©:  {risque_eleve}")

            # Sauvegarde
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            output_file = os.path.join(SCRIPT_DIR, f"predictions_batch_{timestamp}.csv")
            df.to_csv(output_file, index=False)

            print("\n" + "─" * 60)
            print(f"πŸ’Ύ Fichier sauvegardΓ©: {os.path.basename(output_file)}")
            print("─" * 60)

            # AperΓ§u
            print("\nπŸ“‹ AperΓ§u des rΓ©sultats:")
            cols = ["employee_id", "prediction", "prob_depart", "risk_level"]
            cols_exist = [c for c in cols if c in df.columns]
            if cols_exist:
                print(df[cols_exist].head(10).to_string(index=False))
        else:
            print(f"\n⚠️ Fichier résultat non trouvé: {result_path}")
    else:
        print(f"\nπŸ“‹ RΓ©sultat: {result}")

    print("\nβœ… PrΓ©diction batch terminΓ©e avec succΓ¨s!")

except Exception as e:
    print(f"\n❌ Erreur: {e}")
    sys.exit(1)