File size: 7,563 Bytes
af248b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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())