text2speech-gradio-app / webhook_server.py
Your Name
Add comprehensive webhook integration: automation, monitoring, and analytics
d8de34b
Raw
History Blame Contribute Delete
11.2 kB
# 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
)