File size: 11,186 Bytes
d8de34b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
# Generated by Copilot
"""
Advanced Webhook Integration for Text2Speech Project
Provides automated workflows, monitoring, and integrations
"""

import os
import json
import asyncio
from datetime import datetime
from typing import Optional, Dict, Any
from pathlib import Path
from huggingface_hub import WebhooksServer, WebhookPayload, webhook_endpoint
import gradio as gr
import tempfile
import requests
from dataclasses import dataclass

# Configuration
WEBHOOK_SECRET = os.getenv("WEBHOOK_SECRET", "tts_webhook_secret_2024")
TTS_REPO_ID = "Toowired/text2speech-gradio-app"

@dataclass
class WebhookEvent:
    timestamp: str
    event_type: str
    repo_name: str
    action: str
    details: Dict[str, Any]

class TTSWebhookManager:
    """Manages webhook events for TTS project"""
    
    def __init__(self):
        self.events_log = []
        self.auto_features = {
            "auto_redeploy": True,
            "model_sync": True,
            "usage_tracking": True,
            "error_monitoring": True
        }
    
    def log_event(self, event: WebhookEvent):
        """Log webhook event"""
        self.events_log.append(event)
        # Keep only last 100 events
        if len(self.events_log) > 100:
            self.events_log = self.events_log[-100:]
    
    def get_events_summary(self) -> str:
        """Get formatted events summary"""
        if not self.events_log:
            return "No webhook events recorded yet."
        
        summary = ["πŸ“Š Recent Webhook Events:\n"]
        for event in self.events_log[-10:]:  # Last 10 events
            summary.append(f"β€’ {event.timestamp} | {event.event_type} | {event.repo_name} | {event.action}")
        
        return "\n".join(summary)

# Initialize webhook manager
webhook_manager = TTSWebhookManager()

# Create custom Gradio UI for webhook dashboard
def create_webhook_ui():
    """Create webhook management dashboard"""
    
    with gr.Blocks(title="πŸ”— TTS Webhook Dashboard", theme=gr.themes.Soft()) as webhook_ui:
        gr.Markdown("""
        # πŸ”— Text2Speech Webhook Dashboard
        
        **Automated workflows and monitoring for your TTS project**
        
        ## 🎯 Available Webhook Features:
        - **Auto-Redeploy**: Automatically redeploy when code changes
        - **Model Sync**: Sync with new TTS models and datasets  
        - **Usage Tracking**: Monitor Space usage and performance
        - **Error Monitoring**: Get notified of deployment issues
        """)
        
        with gr.Tabs():
            
            # Events Tab
            with gr.Tab("πŸ“‹ Event Log"):
                gr.Markdown("### Recent Webhook Events")
                events_display = gr.Textbox(
                    label="Event History",
                    lines=15,
                    value=webhook_manager.get_events_summary()
                )
                refresh_btn = gr.Button("πŸ”„ Refresh Events")
                
                def refresh_events():
                    return webhook_manager.get_events_summary()
                
                refresh_btn.click(refresh_events, outputs=[events_display])
            
            # Configuration Tab
            with gr.Tab("βš™οΈ Configuration"):
                gr.Markdown("### Webhook Settings")
                
                with gr.Row():
                    auto_redeploy = gr.Checkbox(
                        label="Auto-Redeploy on Code Changes",
                        value=webhook_manager.auto_features["auto_redeploy"]
                    )
                    model_sync = gr.Checkbox(
                        label="Auto-Sync New Models",
                        value=webhook_manager.auto_features["model_sync"]
                    )
                
                with gr.Row():
                    usage_tracking = gr.Checkbox(
                        label="Usage Tracking",
                        value=webhook_manager.auto_features["usage_tracking"]
                    )
                    error_monitoring = gr.Checkbox(
                        label="Error Monitoring",
                        value=webhook_manager.auto_features["error_monitoring"]
                    )
                
                save_config_btn = gr.Button("πŸ’Ύ Save Configuration", variant="primary")
                config_status = gr.Textbox(label="Status", interactive=False)
                
                def save_configuration(redeploy, sync, tracking, monitoring):
                    webhook_manager.auto_features.update({
                        "auto_redeploy": redeploy,
                        "model_sync": sync,
                        "usage_tracking": tracking,
                        "error_monitoring": monitoring
                    })
                    return "βœ… Configuration saved successfully!"
                
                save_config_btn.click(
                    save_configuration,
                    inputs=[auto_redeploy, model_sync, usage_tracking, error_monitoring],
                    outputs=[config_status]
                )
            
            # Setup Tab
            with gr.Tab("πŸ› οΈ Setup Guide"):
                gr.Markdown("""
                ### πŸ”§ How to Set Up Webhooks
                
                1. **Go to Webhook Settings**: Visit [HuggingFace Webhooks](https://huggingface.co/settings/webhooks)
                
                2. **Create New Webhook**: Click "New webhook"
                
                3. **Configure Webhook**:
                   - **URL**: `{your-space-url}/webhooks/tts_automation`
                   - **Secret**: `tts_webhook_secret_2024`
                   - **Events**: Select relevant events (repo updates, discussions, etc.)
                
                4. **Target Repositories**: Add your TTS project repos:
                   - `Toowired/text2speech-gradio-app`
                   - Any model repos you want to monitor
                
                5. **Test**: Use the "Test webhook" button to verify connectivity
                
                ### πŸ“‘ Webhook Endpoints Available:
                - `/webhooks/tts_automation` - Main automation endpoint
                - `/webhooks/model_sync` - Model synchronization
                - `/webhooks/usage_tracker` - Usage analytics
                - `/webhooks/error_monitor` - Error notifications
                
                ### πŸ” Security:
                - All webhooks are secured with HMAC signature verification
                - Secret key: `tts_webhook_secret_2024`
                - Only authorized events are processed
                """)
                
                test_webhook_btn = gr.Button("πŸ§ͺ Test Webhook Connection")
                test_result = gr.Textbox(label="Test Result", interactive=False)
                
                def test_webhook_connection():
                    try:
                        # Simulate a test webhook payload
                        test_event = WebhookEvent(
                            timestamp=datetime.now().isoformat(),
                            event_type="test",
                            repo_name="test-repo",
                            action="connection_test",
                            details={"status": "success"}
                        )
                        webhook_manager.log_event(test_event)
                        return "βœ… Webhook system is working correctly!"
                    except Exception as e:
                        return f"❌ Error testing webhook: {str(e)}"
                
                test_webhook_btn.click(test_webhook_connection, outputs=[test_result])
    
    return webhook_ui

# Create webhook server with custom UI
webhook_ui = create_webhook_ui()
server = WebhooksServer(ui=webhook_ui, webhook_secret=WEBHOOK_SECRET)

# Main TTS Automation Webhook
@server.add_webhook("/tts_automation")
async def tts_automation_webhook(payload: WebhookPayload):
    """Main automation webhook for TTS project"""
    
    event = WebhookEvent(
        timestamp=datetime.now().isoformat(),
        event_type="automation",
        repo_name=payload.repo.name,
        action=payload.event.action,
        details={
            "scope": payload.event.scope,
            "repo_type": payload.repo.type,
            "private": payload.repo.private
        }
    )
    webhook_manager.log_event(event)
    
    response = {"processed": True, "actions": []}
    
    # Auto-redeploy on code changes
    if (webhook_manager.auto_features["auto_redeploy"] and 
        payload.event.action == "update" and 
        payload.event.scope.startswith("repo.content") and
        payload.repo.name == TTS_REPO_ID):
        
        response["actions"].append("triggered_redeploy")
        # Add redeploy logic here if needed
    
    # Model sync on new models
    if (webhook_manager.auto_features["model_sync"] and
        payload.repo.type == "model" and
        payload.event.action == "create"):
        
        response["actions"].append("model_sync_initiated")
        # Add model sync logic here
    
    return response

# Model Synchronization Webhook
@server.add_webhook("/model_sync")
async def model_sync_webhook(payload: WebhookPayload):
    """Sync new TTS models automatically"""
    
    if payload.repo.type != "model":
        return {"processed": False, "reason": "not_a_model"}
    
    event = WebhookEvent(
        timestamp=datetime.now().isoformat(),
        event_type="model_sync",
        repo_name=payload.repo.name,
        action=payload.event.action,
        details={"model_id": payload.repo.name}
    )
    webhook_manager.log_event(event)
    
    # Logic to evaluate and potentially add new models to your TTS system
    return {"processed": True, "model_evaluated": payload.repo.name}

# Usage Tracking Webhook
@server.add_webhook("/usage_tracker")
async def usage_tracking_webhook(payload: WebhookPayload):
    """Track usage and performance metrics"""
    
    event = WebhookEvent(
        timestamp=datetime.now().isoformat(),
        event_type="usage_tracking",
        repo_name=payload.repo.name,
        action=payload.event.action,
        details={"tracking_enabled": True}
    )
    webhook_manager.log_event(event)
    
    return {"processed": True, "usage_logged": True}

# Error Monitoring Webhook
@server.add_webhook("/error_monitor")
async def error_monitoring_webhook(payload: WebhookPayload):
    """Monitor for errors and deployment issues"""
    
    event = WebhookEvent(
        timestamp=datetime.now().isoformat(),
        event_type="error_monitoring",
        repo_name=payload.repo.name,
        action=payload.event.action,
        details={"monitoring_active": True}
    )
    webhook_manager.log_event(event)
    
    # Add error detection and notification logic
    return {"processed": True, "monitoring_active": True}

if __name__ == "__main__":
    print("πŸ”— Starting TTS Webhook Server...")
    print(f"πŸ“‘ Webhook Secret: {WEBHOOK_SECRET}")
    print(f"🎯 Target TTS Repo: {TTS_REPO_ID}")
    print("πŸš€ Server starting...")
    
    server.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=False
    )