Spaces:
Runtime error
Runtime error
File size: 12,428 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 301 302 303 304 305 306 307 308 309 310 311 | # Generated by Copilot
"""
Webhook Integration Module for Text2Speech App
Adds webhook capabilities to the existing TTS Gradio app
"""
import json
import os
from datetime import datetime
from typing import Dict, List, Optional
from dataclasses import dataclass, asdict
import gradio as gr
@dataclass
class WebhookConfig:
"""Webhook configuration settings"""
webhook_secret: str = "tts_webhook_secret_2024"
auto_redeploy: bool = True
model_sync: bool = True
usage_tracking: bool = True
error_monitoring: bool = True
notification_email: Optional[str] = None
slack_webhook_url: Optional[str] = None
@dataclass
class WebhookEvent:
"""Webhook event data structure"""
timestamp: str
event_type: str
repo_name: str
action: str
details: Dict
processed: bool = False
class WebhookIntegration:
"""Webhook integration manager for TTS app"""
def __init__(self, config_file: str = "webhook_config.json"):
self.config_file = config_file
self.config = self.load_config()
self.events: List[WebhookEvent] = []
self.webhooks_enabled = True
def load_config(self) -> WebhookConfig:
"""Load webhook configuration from file"""
try:
if os.path.exists(self.config_file):
with open(self.config_file, 'r') as f:
data = json.load(f)
return WebhookConfig(**data)
except Exception as e:
print(f"Warning: Could not load webhook config: {e}")
return WebhookConfig()
def save_config(self):
"""Save webhook configuration to file"""
try:
with open(self.config_file, 'w') as f:
json.dump(asdict(self.config), f, indent=2)
except Exception as e:
print(f"Error saving webhook config: {e}")
def add_event(self, event: WebhookEvent):
"""Add a webhook event to the log"""
self.events.append(event)
# Keep only last 50 events
if len(self.events) > 50:
self.events = self.events[-50:]
def get_recent_events(self, limit: int = 10) -> List[WebhookEvent]:
"""Get recent webhook events"""
return self.events[-limit:] if self.events else []
def get_events_summary(self) -> str:
"""Get formatted summary of recent events"""
if not self.events:
return "No webhook events recorded yet."
lines = ["π Recent Webhook Activity:\n"]
for event in self.get_recent_events():
status = "β
" if event.processed else "β³"
lines.append(f"{status} {event.timestamp[:19]} | {event.event_type} | {event.repo_name}")
return "\n".join(lines)
def create_webhook_tab(self) -> gr.Tab:
"""Create webhook management tab for the TTS app"""
with gr.Tab("π Webhooks") as webhook_tab:
gr.Markdown("""
## π Webhook Integration
Automate your TTS workflow with Hugging Face webhooks!
### π― Available Automations:
- **Auto-redeploy** when you push code changes
- **Model sync** when new TTS models are released
- **Usage tracking** for analytics and optimization
- **Error monitoring** with instant notifications
""")
with gr.Row():
with gr.Column(scale=2):
# Configuration Section
gr.Markdown("### βοΈ Configuration")
with gr.Row():
auto_redeploy_cb = gr.Checkbox(
label="π Auto-redeploy on code changes",
value=self.config.auto_redeploy
)
model_sync_cb = gr.Checkbox(
label="π Auto-sync new TTS models",
value=self.config.model_sync
)
with gr.Row():
usage_tracking_cb = gr.Checkbox(
label="π Usage tracking",
value=self.config.usage_tracking
)
error_monitoring_cb = gr.Checkbox(
label="π¨ Error monitoring",
value=self.config.error_monitoring
)
notification_email = gr.Textbox(
label="π§ Notification Email (optional)",
placeholder="your@email.com",
value=self.config.notification_email or ""
)
save_config_btn = gr.Button("πΎ Save Configuration", variant="primary")
config_status = gr.Textbox(label="Status", interactive=False)
with gr.Column(scale=1):
# Status Section
gr.Markdown("### π‘ Webhook Status")
webhook_status = gr.Textbox(
label="Connection Status",
value="π’ Ready to receive webhooks" if self.webhooks_enabled else "π΄ Webhooks disabled",
interactive=False
)
webhook_secret = gr.Textbox(
label="Webhook Secret",
value=self.config.webhook_secret,
interactive=False,
type="password"
)
test_webhook_btn = gr.Button("π§ͺ Test Webhook", variant="secondary")
test_result = gr.Textbox(label="Test Result", interactive=False)
# Events Section
gr.Markdown("### π Recent Events")
events_display = gr.Textbox(
label="Event Log",
value=self.get_events_summary(),
lines=8,
interactive=False
)
refresh_events_btn = gr.Button("π Refresh Events")
# Setup Instructions
with gr.Accordion("π οΈ Setup Instructions", open=False):
gr.Markdown(f"""
### How to Set Up Webhooks:
1. **Go to [Hugging Face Webhooks Settings](https://huggingface.co/settings/webhooks)**
2. **Click "New webhook"**
3. **Configure the webhook:**
- **URL**: `https://toowired-text2speech-gradio-app.hf.space/webhooks/tts_automation`
- **Secret**: `{self.config.webhook_secret}`
- **Select events**: Repository updates, model uploads, etc.
4. **Target repositories:**
- Your TTS Space: `Toowired/text2speech-gradio-app`
- Any model repos you want to monitor
5. **Save and test** the webhook connection
### π§ Available Endpoints:
- `/webhooks/tts_automation` - Main automation
- `/webhooks/model_sync` - Model synchronization
- `/webhooks/usage_tracker` - Usage analytics
- `/webhooks/error_monitor` - Error notifications
""")
# Event handlers
def save_webhook_config(auto_redeploy, model_sync, usage_tracking, error_monitoring, email):
try:
self.config.auto_redeploy = auto_redeploy
self.config.model_sync = model_sync
self.config.usage_tracking = usage_tracking
self.config.error_monitoring = error_monitoring
self.config.notification_email = email if email.strip() else None
self.save_config()
return "β
Configuration saved successfully!"
except Exception as e:
return f"β Error saving configuration: {str(e)}"
def test_webhook():
try:
# Simulate a test event
test_event = WebhookEvent(
timestamp=datetime.now().isoformat(),
event_type="test",
repo_name="test-webhook",
action="connection_test",
details={"test": True},
processed=True
)
self.add_event(test_event)
return "β
Test webhook event logged successfully!"
except Exception as e:
return f"β Test failed: {str(e)}"
def refresh_events():
return self.get_events_summary()
# Connect event handlers
save_config_btn.click(
save_webhook_config,
inputs=[auto_redeploy_cb, model_sync_cb, usage_tracking_cb, error_monitoring_cb, notification_email],
outputs=[config_status]
)
test_webhook_btn.click(test_webhook, outputs=[test_result])
refresh_events_btn.click(refresh_events, outputs=[events_display])
return webhook_tab
def setup_webhook_endpoints(self, app):
"""Set up webhook endpoints on the Gradio app"""
# This would integrate with the FastAPI backend if available
# For now, we'll document the endpoints that should be created
webhook_endpoints = {
"/webhooks/tts_automation": self.handle_automation_webhook,
"/webhooks/model_sync": self.handle_model_sync_webhook,
"/webhooks/usage_tracker": self.handle_usage_webhook,
"/webhooks/error_monitor": self.handle_error_webhook
}
return webhook_endpoints
def handle_automation_webhook(self, payload):
"""Handle main automation webhook"""
event = WebhookEvent(
timestamp=datetime.now().isoformat(),
event_type="automation",
repo_name=payload.get("repo", {}).get("name", "unknown"),
action=payload.get("event", {}).get("action", "unknown"),
details=payload,
processed=True
)
self.add_event(event)
return {"status": "processed", "event_id": len(self.events)}
def handle_model_sync_webhook(self, payload):
"""Handle model sync webhook"""
event = WebhookEvent(
timestamp=datetime.now().isoformat(),
event_type="model_sync",
repo_name=payload.get("repo", {}).get("name", "unknown"),
action=payload.get("event", {}).get("action", "unknown"),
details=payload,
processed=True
)
self.add_event(event)
return {"status": "processed", "action": "model_sync"}
def handle_usage_webhook(self, payload):
"""Handle usage tracking webhook"""
event = WebhookEvent(
timestamp=datetime.now().isoformat(),
event_type="usage_tracking",
repo_name=payload.get("repo", {}).get("name", "unknown"),
action=payload.get("event", {}).get("action", "unknown"),
details=payload,
processed=True
)
self.add_event(event)
return {"status": "processed", "action": "usage_logged"}
def handle_error_webhook(self, payload):
"""Handle error monitoring webhook"""
event = WebhookEvent(
timestamp=datetime.now().isoformat(),
event_type="error_monitoring",
repo_name=payload.get("repo", {}).get("name", "unknown"),
action=payload.get("event", {}).get("action", "unknown"),
details=payload,
processed=True
)
self.add_event(event)
return {"status": "processed", "action": "error_monitored"}
# Global webhook integration instance
webhook_integration = WebhookIntegration() |