File size: 3,798 Bytes
f70fcdd
c9903ae
 
f70fcdd
 
23bfe85
 
 
 
 
 
f70fcdd
c9903ae
 
 
 
 
 
 
bb10a6d
c9903ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f70fcdd
 
c9903ae
 
f70fcdd
c9903ae
23bfe85
 
 
 
 
c9903ae
 
 
23bfe85
c9903ae
 
 
f70fcdd
c9903ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23bfe85
c9903ae
 
 
 
 
 
 
 
 
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
import os
import gradio as gr
from huggingface_hub import WebhooksServer, WebhookPayload, HfApi

# Configuration
HF_TOKEN = os.getenv("HF_TOKEN")
WEBHOOK_SECRET = os.getenv("WEBHOOK_SECRET")
SPACES_TO_RESTART = [
    "OrganizedProgrammers/DpcFinder",
    "OrganizedProgrammers/SpecSplitter"
]

# Initialiser l'API Hugging Face
api = HfApi()

# Interface utilisateur personnalisée (optionnelle)
with gr.Blocks(title="Dataset Update Webhook Server") as ui:
    gr.Markdown("""
    # 🔄 Dataset Update Webhook Server
    
    Ce serveur redémarre automatiquement les Spaces configurés lorsqu'un dataset est mis à jour.
    
    ## Spaces surveillés :
    - OrganizedProgrammers/DpcFinder
    - OrganizedProgrammers/SpecSplitter
    
    ## Configuration
    Assurez-vous que votre webhook Hugging Face pointe vers `/webhooks/dataset_update`
    """)
    
    with gr.Row():
        with gr.Column():
            gr.Markdown("### Status")
            status_text = gr.Textbox(
                value="🟢 Serveur en attente de webhooks...", 
                label="État du serveur",
                interactive=False
            )
        
        with gr.Column():
            gr.Markdown("### Dernière activité")
            activity_log = gr.Textbox(
                value="Aucune activité récente", 
                label="Log d'activité",
                lines=5,
                interactive=False
            )

# Créer le serveur de webhooks avec l'interface personnalisée
app = WebhooksServer(ui=ui, webhook_secret=WEBHOOK_SECRET)

@app.add_webhook
async def dataset_update(payload: WebhookPayload):
    """
    Webhook déclenché lors de la mise à jour d'un dataset.
    """
    print(f"🔔 Webhook reçu - Type: {payload.repo.type}, Action: {payload.event.action}")
    print(f"📦 Repo: {payload.repo.name}")
    
    # Vérifier si c'est une mise à jour de dataset
    if payload.repo.type == "dataset" and payload.event.action == "update":
        print(f"✅ Dataset {payload.repo.name} mis à jour!")
        
        results = []
        
        # Redémarrer tous les Spaces liés
        for space_id in SPACES_TO_RESTART:
            try:
                api.restart_space(space_id, token=HF_TOKEN)
                success_msg = f"✅ Space redémarré: {space_id}"
                print(success_msg)
                results.append(success_msg)
            except Exception as e:
                error_msg = f"❌ Erreur redémarrage {space_id}: {str(e)}"
                print(error_msg)
                results.append(error_msg)
        
        return {
            "message": "Spaces mis à jour avec succès",
            "dataset": payload.repo.name,
            "spaces_restarted": SPACES_TO_RESTART,
            "results": results
        }
    else:
        print(f"ℹ️ Événement ignoré - Type: {payload.repo.type}, Action: {payload.event.action}")
        return {
            "message": "Aucune action nécessaire",
            "reason": f"Type: {payload.repo.type}, Action: {payload.event.action}"
        }

# Webhook de test pour vérifier que le serveur fonctionne
@app.add_webhook("/health")
async def health_check(payload: WebhookPayload):
    """
    Endpoint de santé pour vérifier que le serveur fonctionne.
    """
    return {
        "status": "healthy",
        "message": "Webhook server is running",
        "configured_spaces": SPACES_TO_RESTART
    }

# Démarrer le serveur
if __name__ == "__main__":
    print("🚀 Démarrage du serveur de webhooks...")
    print(f"📋 Spaces configurés: {SPACES_TO_RESTART}")
    print(f"🔐 Secret configuré: {'✅' if WEBHOOK_SECRET else '❌'}")
    print(f"🔑 Token HF configuré: {'✅' if HF_TOKEN else '❌'}")
    
    # Le serveur se lance automatiquement
    app.launch()