om4r932 commited on
Commit
c9903ae
·
verified ·
1 Parent(s): 23bfe85

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -23
app.py CHANGED
@@ -1,9 +1,6 @@
1
- from fastapi import FastAPI, Request, HTTPException
2
- from huggingface_hub import HfApi
3
  import os
4
-
5
- app = FastAPI()
6
- api = HfApi()
7
 
8
  # Configuration
9
  HF_TOKEN = os.getenv("HF_TOKEN")
@@ -13,33 +10,102 @@ SPACES_TO_RESTART = [
13
  "OrganizedProgrammers/SpecSplitter"
14
  ]
15
 
16
- @app.post("/webhook")
17
- async def handle_webhook(request: Request):
18
- # Vérification du secret
19
- received_secret = request.headers.get("X-Webhook-Secret")
20
- if received_secret != WEBHOOK_SECRET:
21
- raise HTTPException(status_code=400, detail="Invalid secret")
 
22
 
23
- payload = await request.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
  # Vérifier si c'est une mise à jour de dataset
26
- if (payload.get("repo", {}).get("type") == "dataset" and
27
- payload.get("event", {}).get("action") == "update"):
28
 
29
- print(f"Dataset {payload['repo']['name']} mis à jour!")
30
 
31
  # Redémarrer tous les Spaces liés
32
  for space_id in SPACES_TO_RESTART:
33
  try:
34
  api.restart_space(space_id, token=HF_TOKEN)
35
- print(f"✅ Space redémarré: {space_id}")
 
 
36
  except Exception as e:
37
- print(f"❌ Erreur redémarrage {space_id}: {e}")
 
 
38
 
39
- return {"message": "Spaces mis à jour avec succès"}
40
-
41
- return {"message": "Aucune action nécessaire"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
- @app.get("/")
44
- async def root():
45
- return {"message": "Webhook server is running"}
 
 
 
 
 
 
 
 
 
1
  import os
2
+ import gradio as gr
3
+ from huggingface_hub import WebhooksServer, WebhookPayload, HfApi
 
4
 
5
  # Configuration
6
  HF_TOKEN = os.getenv("HF_TOKEN")
 
10
  "OrganizedProgrammers/SpecSplitter"
11
  ]
12
 
13
+ # Initialiser l'API Hugging Face
14
+ api = HfApi()
15
+
16
+ # Interface utilisateur personnalisée (optionnelle)
17
+ with gr.Blocks(title="Dataset Update Webhook Server") as ui:
18
+ gr.Markdown("""
19
+ # 🔄 Dataset Update Webhook Server
20
 
21
+ Ce serveur redémarre automatiquement les Spaces configurés lorsqu'un dataset est mis à jour.
22
+
23
+ ## Spaces surveillés :
24
+ - OrganizedProgrammers/DpcFinder
25
+ - OrganizedProgrammers/SpecSplitter
26
+
27
+ ## Configuration
28
+ Assurez-vous que votre webhook Hugging Face pointe vers `/webhooks/dataset_update`
29
+ """)
30
+
31
+ with gr.Row():
32
+ with gr.Column():
33
+ gr.Markdown("### Status")
34
+ status_text = gr.Textbox(
35
+ value="🟢 Serveur en attente de webhooks...",
36
+ label="État du serveur",
37
+ interactive=False
38
+ )
39
+
40
+ with gr.Column():
41
+ gr.Markdown("### Dernière activité")
42
+ activity_log = gr.Textbox(
43
+ value="Aucune activité récente",
44
+ label="Log d'activité",
45
+ lines=5,
46
+ interactive=False
47
+ )
48
+
49
+ # Créer le serveur de webhooks avec l'interface personnalisée
50
+ app = WebhooksServer(ui=ui, webhook_secret=WEBHOOK_SECRET)
51
+
52
+ @app.add_webhook
53
+ async def dataset_update(payload: WebhookPayload):
54
+ """
55
+ Webhook déclenché lors de la mise à jour d'un dataset.
56
+ """
57
+ print(f"🔔 Webhook reçu - Type: {payload.repo.type}, Action: {payload.event.action}")
58
+ print(f"📦 Repo: {payload.repo.name}")
59
 
60
  # Vérifier si c'est une mise à jour de dataset
61
+ if payload.repo.type == "dataset" and payload.event.action == "update":
62
+ print(f" Dataset {payload.repo.name} mis à jour!")
63
 
64
+ results = []
65
 
66
  # Redémarrer tous les Spaces liés
67
  for space_id in SPACES_TO_RESTART:
68
  try:
69
  api.restart_space(space_id, token=HF_TOKEN)
70
+ success_msg = f"✅ Space redémarré: {space_id}"
71
+ print(success_msg)
72
+ results.append(success_msg)
73
  except Exception as e:
74
+ error_msg = f"❌ Erreur redémarrage {space_id}: {str(e)}"
75
+ print(error_msg)
76
+ results.append(error_msg)
77
 
78
+ return {
79
+ "message": "Spaces mis à jour avec succès",
80
+ "dataset": payload.repo.name,
81
+ "spaces_restarted": SPACES_TO_RESTART,
82
+ "results": results
83
+ }
84
+ else:
85
+ print(f"ℹ️ Événement ignoré - Type: {payload.repo.type}, Action: {payload.event.action}")
86
+ return {
87
+ "message": "Aucune action nécessaire",
88
+ "reason": f"Type: {payload.repo.type}, Action: {payload.event.action}"
89
+ }
90
+
91
+ # Webhook de test pour vérifier que le serveur fonctionne
92
+ @app.add_webhook("/health")
93
+ async def health_check(payload: WebhookPayload):
94
+ """
95
+ Endpoint de santé pour vérifier que le serveur fonctionne.
96
+ """
97
+ return {
98
+ "status": "healthy",
99
+ "message": "Webhook server is running",
100
+ "configured_spaces": SPACES_TO_RESTART
101
+ }
102
 
103
+ # Démarrer le serveur
104
+ if __name__ == "__main__":
105
+ print("🚀 Démarrage du serveur de webhooks...")
106
+ print(f"📋 Spaces configurés: {SPACES_TO_RESTART}")
107
+ print(f"🔐 Secret configuré: {'✅' if WEBHOOK_SECRET else '❌'}")
108
+ print(f"🔑 Token HF configuré: {'✅' if HF_TOKEN else '❌'}")
109
+
110
+ # Le serveur se lance automatiquement
111
+ app.launch()