overgrowth / examples /huggingface_integration.py
Graham Paasch
feat: Add GNS3 lab viewer integration for HuggingFace Space
af248b9
Raw
History Blame
7.56 kB
"""
HuggingFace Space Integration Example
Shows how to integrate GNS3 lab viewer with the Overgrowth HuggingFace Space UI
"""
import sys
import os
# Add parent directory to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
from web.gns3_viewer import GNS3Viewer, get_deployment_markdown, get_web_ui_link
def create_deployment_result_card(deployment_success: bool, devices_configured: list) -> dict:
"""
Create a result card to display in HuggingFace Space after deployment
Args:
deployment_success: Whether the deployment was successful
devices_configured: List of device names that were configured
Returns:
Dictionary with UI components
"""
viewer = GNS3Viewer()
if not deployment_success:
return {
'status': 'error',
'title': '❌ Deployment Failed',
'message': 'There was an error deploying your configuration.',
'actions': []
}
# Get live status
summary = viewer.get_deployment_summary()
return {
'status': 'success',
'title': '✅ Deployment Successful!',
'message': f'Successfully deployed configuration to {len(devices_configured)} device(s).',
'devices': devices_configured,
'lab_info': {
'web_ui_url': summary['web_ui_url'],
'total_devices': summary['total_devices'],
'deployed_switches': summary['switches']['deployed'],
'deployed_routers': summary['routers']['deployed']
},
'actions': [
{
'label': '🌐 View Live Topology',
'url': summary['web_ui_url'],
'type': 'primary'
},
{
'label': '📊 View API Status',
'url': summary['project']['api_url'],
'type': 'secondary'
}
],
'console_access': [
{'device': d['name'], 'url': d['console']}
for d in summary['switches']['devices']
]
}
def get_lab_status_widget() -> str:
"""
Get HTML widget showing current lab status for embedding in HuggingFace Space
Returns:
HTML string
"""
viewer = GNS3Viewer()
summary = viewer.get_deployment_summary()
if not summary['accessible']:
return """
<div style="padding: 20px; background: #fff3cd; border-left: 4px solid #ffc107; border-radius: 4px;">
<h3>⚠️ Lab Currently Unavailable</h3>
<p>The GNS3 lab is not currently accessible. Please try again later.</p>
</div>
"""
switches_html = ""
for switch in summary['switches']['devices']:
switches_html += f"""
<div style="padding: 10px; margin: 5px 0; background: #e8f5e9; border-radius: 4px;">
<strong>✅ {switch['name']}</strong> - <code>{switch['status']}</code>
<br><small>Console: <code>{switch['console']}</code></small>
</div>
"""
return f"""
<div style="padding: 20px; background: #f8f9fa; border-radius: 8px; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
<h2 style="margin-top: 0; color: #2c3e50;">🌐 Live Network Lab</h2>
<div style="margin: 15px 0;">
<a href="{summary['web_ui_url']}"
target="_blank"
style="display: inline-block; padding: 12px 24px; background: #007bff; color: white; text-decoration: none; border-radius: 6px; font-weight: bold;">
📡 Open GNS3 Web UI
</a>
</div>
<div style="margin: 20px 0;">
<h3 style="color: #2c3e50;">Deployment Status</h3>
<p><strong>Total Devices:</strong> {summary['total_devices']}</p>
<p><strong>Deployed Switches:</strong> {summary['switches']['deployed']}/{summary['switches']['total']}</p>
</div>
<div style="margin: 20px 0;">
<h3 style="color: #2c3e50;">Active Devices</h3>
{switches_html}
</div>
<div style="margin: 20px 0; padding: 15px; background: #e3f2fd; border-radius: 4px;">
<h4 style="margin-top: 0;">How to Access</h4>
<ol style="margin: 0; padding-left: 20px;">
<li>Click "Open GNS3 Web UI" above to view the live topology</li>
<li>Use telnet to console URLs for device access</li>
<li>API available at: <code>{summary['project']['api_url']}</code></li>
</ol>
</div>
<div style="margin-top: 15px; padding: 10px; background: #fff; border-left: 4px solid #28a745; border-radius: 4px;">
<strong>Project:</strong> {summary['project']['name']}<br>
<small>ID: <code>{summary['project']['id']}</code></small>
</div>
</div>
"""
def example_gradio_integration():
"""
Example of how to integrate with Gradio UI in HuggingFace Space
This would be added to your app.py in the HuggingFace Space
"""
try:
import gradio as gr
except ImportError:
print("This example requires gradio: pip install gradio")
return
def deploy_and_show_results(config_text):
"""Simulated deployment function"""
# Your deployment logic here
# ...
# After deployment, show results
viewer = GNS3Viewer()
markdown_output = viewer.format_for_ui()
html_widget = get_lab_status_widget()
return markdown_output, html_widget
# Create Gradio interface
with gr.Blocks() as demo:
gr.Markdown("# 🌐 Overgrowth Network Automation")
with gr.Tab("Deploy Configuration"):
config_input = gr.Textbox(
label="Network Configuration",
placeholder="Enter your network configuration...",
lines=10
)
deploy_btn = gr.Button("🚀 Deploy to Lab", variant="primary")
with gr.Tab("View Lab Status"):
refresh_btn = gr.Button("🔄 Refresh Status")
status_markdown = gr.Markdown(get_deployment_markdown())
status_html = gr.HTML(get_lab_status_widget())
refresh_btn.click(
fn=lambda: (get_deployment_markdown(), get_lab_status_widget()),
outputs=[status_markdown, status_html]
)
# Show results after deployment
deploy_btn.click(
fn=deploy_and_show_results,
inputs=[config_input],
outputs=[status_markdown, status_html]
)
return demo
if __name__ == "__main__":
print("=" * 70)
print("HuggingFace Space Integration - Deployment Result Example")
print("=" * 70)
print()
# Example 1: Create deployment result card
result_card = create_deployment_result_card(
deployment_success=True,
devices_configured=['SW-HQ-Core', 'SW-West', 'SW-East']
)
print("Deployment Result Card (JSON):")
import json
print(json.dumps(result_card, indent=2))
print()
# Example 2: Get lab status widget
print("=" * 70)
print("Lab Status Widget (HTML):")
print("=" * 70)
print()
print(get_lab_status_widget())
print()
# Example 3: Get markdown for display
print("=" * 70)
print("Markdown Output:")
print("=" * 70)
print()
print(get_deployment_markdown())