Spaces:
Running
Running
Upload folder using huggingface_hub
Browse files- exemples/demo_batch_hf.py +70 -80
exemples/demo_batch_hf.py
CHANGED
|
@@ -1,24 +1,31 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
📦 Prédiction BATCH via API Hugging Face
|
| 4 |
|
| 5 |
Usage: python demo_batch_hf.py
|
| 6 |
- Utilise par défaut les CSV d'exemple du dossier
|
| 7 |
-
- Envoie les 3 fichiers à la Space HF
|
| 8 |
- Sauvegarde un CSV de résultats
|
| 9 |
|
| 10 |
-
|
| 11 |
"""
|
| 12 |
|
| 13 |
import os
|
|
|
|
| 14 |
import pandas as pd
|
| 15 |
-
import requests
|
| 16 |
from datetime import datetime
|
| 17 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
API_URL = os.getenv("HF_API_URL", "https://asi-engineer-oc-p5.hf.space")
|
| 19 |
|
| 20 |
print("╔══════════════════════════════════════════════════════════╗")
|
| 21 |
-
print("║ 📦 Prédiction BATCH - API Hugging Face
|
| 22 |
print("╚══════════════════════════════════════════════════════════╝\n")
|
| 23 |
print(f"🌐 API: {API_URL}\n")
|
| 24 |
|
|
@@ -32,88 +39,71 @@ sirh_path = os.path.join(script_dir, "02_predict_batch_sirh.csv")
|
|
| 32 |
for path in [sondage_path, eval_path, sirh_path]:
|
| 33 |
if not os.path.exists(path):
|
| 34 |
print(f"❌ Fichier introuvable: {path}")
|
| 35 |
-
|
| 36 |
|
| 37 |
print("✅ Fichiers d'exemple détectés:")
|
| 38 |
print(f" - {os.path.basename(sondage_path)}")
|
| 39 |
print(f" - {os.path.basename(eval_path)}")
|
| 40 |
print(f" - {os.path.basename(sirh_path)}\n")
|
| 41 |
|
| 42 |
-
print("⏳
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
"
|
| 46 |
-
|
| 47 |
-
}
|
| 48 |
-
|
| 49 |
-
api_key = os.getenv("HF_API_KEY")
|
| 50 |
-
if api_key:
|
| 51 |
-
headers["X-API-Key"] = api_key
|
| 52 |
|
|
|
|
| 53 |
try:
|
| 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 |
-
for pred in result.get("predictions", []):
|
| 81 |
-
predictions_data.append(
|
| 82 |
-
{
|
| 83 |
-
"employee_id": pred.get("employee_id"),
|
| 84 |
-
"prediction": (
|
| 85 |
-
"VA PARTIR" if pred.get("prediction") == 1 else "VA RESTER"
|
| 86 |
-
),
|
| 87 |
-
"prediction_code": pred.get("prediction"),
|
| 88 |
-
"risk_level": pred.get("risk_level"),
|
| 89 |
-
"probability_stay": f"{pred.get('probability_stay', 0):.2%}",
|
| 90 |
-
"probability_leave": f"{pred.get('probability_leave', 0):.2%}",
|
| 91 |
-
}
|
| 92 |
-
)
|
| 93 |
-
|
| 94 |
-
df = pd.DataFrame(predictions_data)
|
| 95 |
-
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 96 |
-
output_path = os.path.join(script_dir, f"predictions_batch_hf_{timestamp}.csv")
|
| 97 |
-
df.to_csv(output_path, index=False, encoding="utf-8-sig")
|
| 98 |
-
|
| 99 |
-
# Affichage
|
| 100 |
-
summary = result.get("summary", {})
|
| 101 |
-
print("\n" + "═" * 60)
|
| 102 |
-
print(" 📊 RÉSULTAT (HF)")
|
| 103 |
-
print("═" * 60)
|
| 104 |
-
print(
|
| 105 |
-
f"\n✅ Traités: {result.get('total_employees')} | RESTER: {summary.get('total_stay')} | PARTIR: {summary.get('total_leave')}"
|
| 106 |
-
)
|
| 107 |
-
print(
|
| 108 |
-
f"🔴 High: {summary.get('high_risk_count')} 🟡 Medium: {summary.get('medium_risk_count')} 🟢 Low: {summary.get('low_risk_count')}\n"
|
| 109 |
)
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
📦 Prédiction BATCH via API Hugging Face (Gradio Client)
|
| 4 |
|
| 5 |
Usage: python demo_batch_hf.py
|
| 6 |
- Utilise par défaut les CSV d'exemple du dossier
|
| 7 |
+
- Envoie les 3 fichiers à la Space HF via Gradio Client
|
| 8 |
- Sauvegarde un CSV de résultats
|
| 9 |
|
| 10 |
+
Prérequis: pip install gradio_client
|
| 11 |
"""
|
| 12 |
|
| 13 |
import os
|
| 14 |
+
import sys
|
| 15 |
import pandas as pd
|
|
|
|
| 16 |
from datetime import datetime
|
| 17 |
|
| 18 |
+
try:
|
| 19 |
+
from gradio_client import Client, handle_file
|
| 20 |
+
except ImportError:
|
| 21 |
+
print("❌ gradio_client non installé. Installez-le avec:")
|
| 22 |
+
print(" pip install gradio_client")
|
| 23 |
+
sys.exit(1)
|
| 24 |
+
|
| 25 |
API_URL = os.getenv("HF_API_URL", "https://asi-engineer-oc-p5.hf.space")
|
| 26 |
|
| 27 |
print("╔══════════════════════════════════════════════════════════╗")
|
| 28 |
+
print("║ 📦 Prédiction BATCH - API Hugging Face (Gradio) ║")
|
| 29 |
print("╚══════════════════════════════════════════════════════════╝\n")
|
| 30 |
print(f"🌐 API: {API_URL}\n")
|
| 31 |
|
|
|
|
| 39 |
for path in [sondage_path, eval_path, sirh_path]:
|
| 40 |
if not os.path.exists(path):
|
| 41 |
print(f"❌ Fichier introuvable: {path}")
|
| 42 |
+
sys.exit(1)
|
| 43 |
|
| 44 |
print("✅ Fichiers d'exemple détectés:")
|
| 45 |
print(f" - {os.path.basename(sondage_path)}")
|
| 46 |
print(f" - {os.path.basename(eval_path)}")
|
| 47 |
print(f" - {os.path.basename(sirh_path)}\n")
|
| 48 |
|
| 49 |
+
print("⏳ Connexion à l'API Gradio...")
|
| 50 |
+
try:
|
| 51 |
+
client = Client(API_URL)
|
| 52 |
+
print("✅ Connecté à l'API Gradio\n")
|
| 53 |
+
except Exception as e:
|
| 54 |
+
print(f"❌ Impossible de se connecter: {e}")
|
| 55 |
+
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
+
print("⏳ Envoi des fichiers pour prédiction batch...")
|
| 58 |
try:
|
| 59 |
+
result = client.predict(
|
| 60 |
+
sondage_path=handle_file(sondage_path),
|
| 61 |
+
eval_path=handle_file(eval_path),
|
| 62 |
+
sirh_path=handle_file(sirh_path),
|
| 63 |
+
api_name="/predict_batch",
|
| 64 |
)
|
| 65 |
+
except Exception as e:
|
| 66 |
+
print(f"❌ Erreur lors de la prédiction: {e}")
|
| 67 |
+
sys.exit(1)
|
| 68 |
+
|
| 69 |
+
# Vérifier si erreur dans le résultat
|
| 70 |
+
if isinstance(result, dict) and "error" in result:
|
| 71 |
+
print(f"\n❌ Erreur API: {result.get('error')}")
|
| 72 |
+
print(f" Message: {result.get('message')}")
|
| 73 |
+
sys.exit(1)
|
| 74 |
+
|
| 75 |
+
# Construire le CSV de sortie
|
| 76 |
+
predictions_data = []
|
| 77 |
+
for pred in result.get("predictions", []):
|
| 78 |
+
predictions_data.append(
|
| 79 |
+
{
|
| 80 |
+
"employee_id": pred.get("employee_id"),
|
| 81 |
+
"prediction": "VA PARTIR" if pred.get("prediction") == 1 else "VA RESTER",
|
| 82 |
+
"prediction_code": pred.get("prediction"),
|
| 83 |
+
"risk_level": pred.get("risk_level"),
|
| 84 |
+
"probability_stay": f"{pred.get('probability_stay', 0):.2%}",
|
| 85 |
+
"probability_leave": f"{pred.get('probability_leave', 0):.2%}",
|
| 86 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
)
|
| 88 |
+
|
| 89 |
+
df = pd.DataFrame(predictions_data)
|
| 90 |
+
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 91 |
+
output_path = os.path.join(script_dir, f"predictions_batch_hf_{timestamp}.csv")
|
| 92 |
+
df.to_csv(output_path, index=False, encoding="utf-8-sig")
|
| 93 |
+
|
| 94 |
+
# Affichage résumé
|
| 95 |
+
summary = result.get("summary", {})
|
| 96 |
+
total = result.get("total_employees", len(predictions_data))
|
| 97 |
+
|
| 98 |
+
print("\n" + "=" * 50)
|
| 99 |
+
print("📊 RÉSULTATS DE LA PRÉDICTION BATCH")
|
| 100 |
+
print("=" * 50)
|
| 101 |
+
print(f"\n👥 Total employés analysés: {total}")
|
| 102 |
+
print(f"✅ Vont rester: {summary.get('total_stay', 'N/A')}")
|
| 103 |
+
print(f"❌ Vont partir: {summary.get('total_leave', 'N/A')}")
|
| 104 |
+
print(f"\n🔴 Risque élevé: {summary.get('high_risk_count', 'N/A')}")
|
| 105 |
+
print(f"🟠 Risque moyen: {summary.get('medium_risk_count', 'N/A')}")
|
| 106 |
+
print(f"🟢 Risque faible: {summary.get('low_risk_count', 'N/A')}")
|
| 107 |
+
|
| 108 |
+
print(f"\n💾 Résultats sauvegardés: {os.path.basename(output_path)}")
|
| 109 |
+
print("\n✅ Prédiction batch terminée avec succès!")
|