Phildram1 commited on
Commit
5d6f960
·
verified ·
1 Parent(s): 0f9a93a

Upload app (8).py

Browse files
Files changed (1) hide show
  1. app (8).py +597 -0
app (8).py ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import re
3
+ import os
4
+ from datetime import datetime, timedelta
5
+ import json
6
+
7
+ # Usage tracking - persists across sessions via file
8
+ USAGE_FILE = "usage_stats.json"
9
+
10
+ def load_usage_stats():
11
+ """Load usage statistics from file"""
12
+ try:
13
+ if os.path.exists(USAGE_FILE):
14
+ with open(USAGE_FILE, 'r') as f:
15
+ return json.load(f)
16
+ except:
17
+ pass
18
+ return {
19
+ "total_ai_requests": 0,
20
+ "total_config_validations": 0,
21
+ "total_visitors": 0,
22
+ "first_request": None,
23
+ "last_request": None,
24
+ "requests_by_hour": {}
25
+ }
26
+
27
+ def save_usage_stats(stats):
28
+ """Save usage statistics to file"""
29
+ try:
30
+ with open(USAGE_FILE, 'w') as f:
31
+ json.dump(stats, f, indent=2)
32
+ except:
33
+ pass
34
+
35
+ usage_stats = load_usage_stats()
36
+
37
+ # Rate limiting (in-memory, resets on restart)
38
+ request_tracker = {}
39
+ MAX_REQUESTS_PER_HOUR = 20
40
+ MAX_REQUESTS_PER_USER = 5
41
+
42
+ def check_rate_limit(user_ip):
43
+ """Check if request is within rate limits"""
44
+ current_time = datetime.now()
45
+
46
+ # Clean old entries
47
+ cutoff_time = current_time - timedelta(hours=1)
48
+ request_tracker[user_ip] = [t for t in request_tracker.get(user_ip, []) if t > cutoff_time]
49
+
50
+ # Check user limit
51
+ user_requests = len(request_tracker.get(user_ip, []))
52
+ if user_requests >= MAX_REQUESTS_PER_USER:
53
+ return False, f"Rate limit reached. Please try again in an hour. (Limit: {MAX_REQUESTS_PER_USER} requests/hour per user)"
54
+
55
+ # Check total limit
56
+ total_requests = sum(len(times) for times in request_tracker.values())
57
+ if total_requests >= MAX_REQUESTS_PER_HOUR:
58
+ return False, "System rate limit reached. Please try again later. (Demo usage limit)"
59
+
60
+ return True, None
61
+
62
+ def record_request(user_ip, request_type="ai"):
63
+ """Record a successful request"""
64
+ if user_ip not in request_tracker:
65
+ request_tracker[user_ip] = []
66
+ request_tracker[user_ip].append(datetime.now())
67
+
68
+ # Update global stats
69
+ current_time = datetime.now().isoformat()
70
+ hour_key = datetime.now().strftime("%Y-%m-%d-%H")
71
+
72
+ if request_type == "ai":
73
+ usage_stats["total_ai_requests"] += 1
74
+ elif request_type == "config":
75
+ usage_stats["total_config_validations"] += 1
76
+
77
+ usage_stats["total_visitors"] = len(set(request_tracker.keys()))
78
+ usage_stats["last_request"] = current_time
79
+
80
+ if not usage_stats["first_request"]:
81
+ usage_stats["first_request"] = current_time
82
+
83
+ if hour_key not in usage_stats["requests_by_hour"]:
84
+ usage_stats["requests_by_hour"][hour_key] = 0
85
+ usage_stats["requests_by_hour"][hour_key] += 1
86
+
87
+ save_usage_stats(usage_stats)
88
+
89
+ # SBC validation functions
90
+ def check_codec_issues(config):
91
+ config_lower = config.lower()
92
+ issues = []
93
+
94
+ codec_keywords = ['opus', 'pcmu', 'pcma', 'g729', 'g711']
95
+ codec_count = sum(1 for c in codec_keywords if c in config_lower)
96
+
97
+ if codec_count == 1 and 'opus' in config_lower and 'pcmu' not in config_lower:
98
+ issues.append({
99
+ "finding": "Codec Mismatch - Only Opus configured, PCMU/PCMA missing",
100
+ "impact": "Leads to one-way audio or call setup failure for carriers requiring PCMU/PCMA. Media negotiation will fail when remote endpoint doesn't support Opus.",
101
+ "fix": "Add PCMU and PCMA codecs: codecs=pcmu,pcma,opus,g729",
102
+ "confidence": 0.92,
103
+ "root_cause": "Codec list not aligned between SIP trunk and carrier requirements",
104
+ "severity": "high"
105
+ })
106
+
107
+ return issues
108
+
109
+ def check_security_issues(config):
110
+ config_lower = config.lower()
111
+ issues = []
112
+
113
+ if 'srtp=optional' in config_lower or ('srtp' not in config_lower):
114
+ issues.append({
115
+ "finding": "SRTP Not Enforced (Security Risk)",
116
+ "impact": "Media encryption not enforced. Voice traffic exposed to eavesdropping. Fails PCI-DSS and HIPAA compliance requirements.",
117
+ "fix": "Enforce SRTP encryption: srtp=required, crypto_suites=AES_CM_128_HMAC_SHA1_80",
118
+ "confidence": 0.97,
119
+ "root_cause": "Default configuration prioritizes compatibility over security",
120
+ "severity": "critical"
121
+ })
122
+
123
+ if 'tls_version=1.0' in config_lower or 'tls_version=1.1' in config_lower:
124
+ issues.append({
125
+ "finding": "Deprecated TLS Version (1.0 or 1.1)",
126
+ "impact": "Security vulnerability to downgrade attacks. Modern carriers reject TLS 1.0/1.1 connections, causing trunk registration failure.",
127
+ "fix": "Upgrade to TLS 1.2 minimum: tls_version=1.2, tls_min_version=1.2",
128
+ "confidence": 0.94,
129
+ "root_cause": "Legacy TLS version not updated after security advisories (RFC 8996)",
130
+ "severity": "critical"
131
+ })
132
+
133
+ return issues
134
+
135
+ def check_nat_issues(config):
136
+ config_lower = config.lower()
137
+ issues = []
138
+
139
+ if 'nat_traversal=disabled' in config_lower or 'nat' not in config_lower:
140
+ issues.append({
141
+ "finding": "NAT Traversal Disabled",
142
+ "impact": "One-way audio or no audio on calls traversing NAT boundaries. RTP packets cannot find return path. Critical for cloud-based SBC deployments.",
143
+ "fix": "Enable NAT traversal: nat_traversal=enabled, ice_support=enabled, stun_server=stun.l.google.com:19302",
144
+ "confidence": 0.93,
145
+ "root_cause": "NAT handling disabled or STUN/ICE not configured for cloud deployment",
146
+ "severity": "high"
147
+ })
148
+
149
+ return issues
150
+
151
+ def check_port_issues(config):
152
+ config_lower = config.lower()
153
+ issues = []
154
+
155
+ if 'port=' in config_lower:
156
+ port_match = re.search(r'port=(\d+)', config_lower)
157
+ if port_match:
158
+ port = int(port_match.group(1))
159
+ if port != 5060 and port != 5061:
160
+ issues.append({
161
+ "finding": f"Non-Standard SIP Port ({port})",
162
+ "impact": "Most carriers expect SIP on port 5060 (UDP) or 5061 (TLS). Non-standard ports may be blocked by firewalls or rejected by carriers.",
163
+ "fix": "Use standard ports: port=5060 for UDP/TCP, port=5061 for TLS",
164
+ "confidence": 0.88,
165
+ "root_cause": "Custom port configuration during migration or testing",
166
+ "severity": "medium"
167
+ })
168
+
169
+ if 'rtp_port_range' in config_lower:
170
+ range_match = re.search(r'rtp_port_range=(\d+)-(\d+)', config_lower)
171
+ if range_match:
172
+ start, end = int(range_match.group(1)), int(range_match.group(2))
173
+ range_size = end - start
174
+ if range_size < 1000:
175
+ issues.append({
176
+ "finding": f"Insufficient RTP Port Range ({range_size} ports)",
177
+ "impact": "Port exhaustion during high call volume (>50 concurrent calls). New calls fail with 'No RTP resources available'.",
178
+ "fix": f"Expand RTP port range to at least 1000 ports: rtp_port_range=10000-11000",
179
+ "confidence": 0.91,
180
+ "root_cause": "Default narrow port range not scaled for production load",
181
+ "severity": "medium"
182
+ })
183
+
184
+ return issues
185
+
186
+ def check_session_timer(config):
187
+ config_lower = config.lower()
188
+ issues = []
189
+
190
+ if 'session_expires' in config_lower:
191
+ timer_match = re.search(r'session_expires=(\d+)', config_lower)
192
+ if timer_match:
193
+ timer = int(timer_match.group(1))
194
+ if timer < 900:
195
+ issues.append({
196
+ "finding": f"Session Timer Too Short ({timer} seconds)",
197
+ "impact": "Long-duration calls terminated prematurely during brief network issues. Customer complaints about dropped calls after {timer//60} minutes.",
198
+ "fix": "Increase session timer: session_expires=1800, min_se=900",
199
+ "confidence": 0.86,
200
+ "root_cause": "Conservative timer settings from legacy PBX migration",
201
+ "severity": "medium"
202
+ })
203
+
204
+ return issues
205
+
206
+ def check_dtmf_issues(config):
207
+ config_lower = config.lower()
208
+ issues = []
209
+
210
+ if 'dtmf_relay=inband' in config_lower or 'dtmf' not in config_lower:
211
+ issues.append({
212
+ "finding": "DTMF Method Not Optimal",
213
+ "impact": "In-band DTMF unreliable with compressed codecs. IVR systems may not receive digits correctly, causing customer frustration in phone menus.",
214
+ "fix": "Use RFC2833 for DTMF: dtmf_relay=rfc2833 (preferred by most carriers)",
215
+ "confidence": 0.89,
216
+ "root_cause": "Default in-band DTMF not suitable for VoIP environments",
217
+ "severity": "medium"
218
+ })
219
+
220
+ return issues
221
+
222
+ def check_dns_issues(config):
223
+ config_lower = config.lower()
224
+ issues = []
225
+
226
+ if 'dns_srv_lookup=disabled' in config_lower or 'dns_srv=disabled' in config_lower:
227
+ issues.append({
228
+ "finding": "DNS SRV Lookup Disabled",
229
+ "impact": "SBC cannot discover carrier SIP servers via DNS SRV records. Loses automatic failover and load balancing capabilities.",
230
+ "fix": "Enable DNS SRV resolution: dns_srv_lookup=enabled",
231
+ "confidence": 0.85,
232
+ "root_cause": "DNS SRV disabled to work around temporary DNS issues",
233
+ "severity": "low"
234
+ })
235
+
236
+ return issues
237
+
238
+ def analyze_configuration(config_text, request: gr.Request):
239
+ """Comprehensive configuration analysis"""
240
+
241
+ if not config_text.strip():
242
+ return "Please enter a configuration to analyze."
243
+
244
+ # Track usage
245
+ user_ip = request.client.host if request else "unknown"
246
+ record_request(user_ip, "config")
247
+
248
+ # Run all checks
249
+ all_issues = []
250
+ all_issues.extend(check_codec_issues(config_text))
251
+ all_issues.extend(check_security_issues(config_text))
252
+ all_issues.extend(check_nat_issues(config_text))
253
+ all_issues.extend(check_port_issues(config_text))
254
+ all_issues.extend(check_session_timer(config_text))
255
+ all_issues.extend(check_dtmf_issues(config_text))
256
+ all_issues.extend(check_dns_issues(config_text))
257
+
258
+ # Build output
259
+ if not all_issues:
260
+ return """# ✅ Configuration Validation: PASSED
261
+
262
+ **Status:** No critical issues detected
263
+
264
+ **Summary:** Your SBC configuration follows enterprise VoIP best practices. The configuration includes:
265
+ - ✅ Proper codec negotiation (PCMU/PCMA/Opus)
266
+ - ✅ SRTP encryption enforced
267
+ - ✅ TLS 1.2+ for signaling security
268
+ - ✅ NAT traversal enabled with ICE support
269
+ - ✅ Standard SIP ports (5060/5061)
270
+ - ✅ Adequate RTP port range for scaling
271
+ - ✅ Appropriate session timers
272
+ - ✅ RFC2833 DTMF for IVR compatibility
273
+
274
+ **Next Steps:**
275
+ 1. Test with a trial call to verify audio quality
276
+ 2. Monitor call metrics for 24-48 hours
277
+ 3. Review integration with your UC platform
278
+
279
+ **Need Help?** Contact your carrier's technical team or Bandwidth Support for deployment assistance.
280
+ """
281
+
282
+ # Issues found - categorize by severity
283
+ critical = [i for i in all_issues if i['severity'] == 'critical']
284
+ high = [i for i in all_issues if i['severity'] == 'high']
285
+ medium = [i for i in all_issues if i['severity'] == 'medium']
286
+ low = [i for i in all_issues if i['severity'] == 'low']
287
+
288
+ output = []
289
+
290
+ # Customer impact header
291
+ if critical or high:
292
+ output.append("# ⚠️ Configuration Validation: ISSUES DETECTED\n")
293
+ output.append("**Customer Impact:** This configuration will likely cause audio quality issues, call failures, or security vulnerabilities in production deployments.\n")
294
+ else:
295
+ output.append("# ⚠️ Configuration Validation: WARNINGS\n")
296
+ output.append("**Status:** Configuration will work but has optimization opportunities.\n")
297
+
298
+ output.append(f"\n**Issues Found:** {len(all_issues)} ({len(critical)} critical, {len(high)} high, {len(medium)} medium, {len(low)} low)\n")
299
+ output.append("\n" + "="*80 + "\n\n")
300
+
301
+ # Show issues by severity
302
+ issue_num = 1
303
+
304
+ for severity_name, severity_list in [("🔴 CRITICAL", critical), ("🟠 HIGH", high), ("🟡 MEDIUM", medium), ("⚪ LOW", low)]:
305
+ if severity_list:
306
+ output.append(f"## {severity_name} PRIORITY\n\n")
307
+
308
+ for issue in severity_list:
309
+ output.append(f"### Issue #{issue_num}: {issue['finding']}\n\n")
310
+ output.append(f"**📊 Confidence:** {issue['confidence']:.0%} | ")
311
+ output.append(f"**🎯 Root Cause:** {issue['root_cause']}\n\n")
312
+ output.append(f"**💥 Customer Impact:**\n{issue['impact']}\n\n")
313
+ output.append(f"**✅ How to Fix:**\n```\n{issue['fix']}\n```\n\n")
314
+ output.append("-"*80 + "\n\n")
315
+ issue_num += 1
316
+
317
+ # Action items
318
+ output.append("## 📋 Recommended Actions\n\n")
319
+ if critical:
320
+ output.append("1. **URGENT:** Address all critical issues before deploying to production\n")
321
+ if high:
322
+ output.append("2. Fix high-priority issues to prevent customer-impacting audio problems\n")
323
+ if medium:
324
+ output.append("3. Optimize medium-priority items for better call quality and reliability\n")
325
+
326
+ output.append("\n**Testing Checklist:**\n")
327
+ output.append("- [ ] Make test call and verify two-way audio\n")
328
+ output.append("- [ ] Test DTMF input in IVR menu\n")
329
+ output.append("- [ ] Verify TLS handshake with carrier\n")
330
+ output.append("- [ ] Confirm NAT traversal in cloud environment\n")
331
+ output.append("- [ ] Test emergency calling if applicable\n")
332
+
333
+ return "".join(output)
334
+
335
+ def ai_troubleshoot(symptom_description, request: gr.Request):
336
+ """AI-powered troubleshooting with usage tracking"""
337
+
338
+ if not symptom_description.strip():
339
+ return "Please describe the issue you're experiencing with your SBC or calls."
340
+
341
+ # Rate limiting
342
+ user_ip = request.client.host if request else "unknown"
343
+ allowed, error_msg = check_rate_limit(user_ip)
344
+ if not allowed:
345
+ return f"## ⚠️ Rate Limit Reached\n\n{error_msg}\n\nThis is a demo with usage limits to control costs."
346
+
347
+ # Check for API key
348
+ api_key = os.environ.get("ANTHROPIC_API_KEY")
349
+ if not api_key:
350
+ return fallback_troubleshoot(symptom_description)
351
+
352
+ try:
353
+ import anthropic
354
+
355
+ client = anthropic.Anthropic(api_key=api_key)
356
+
357
+ prompt = f"""You are an expert SBC (Session Border Controller) troubleshooting assistant for enterprise VoIP deployments.
358
+
359
+ A customer reports the following issue:
360
+ "{symptom_description}"
361
+
362
+ Provide a diagnostic analysis with:
363
+ 1. **Likely Root Causes** - What SBC misconfigurations could cause this in an enterprise VoIP environment
364
+ 2. **Configuration Parameters to Check** - Specific config settings to verify
365
+ 3. **Recommended Fixes** - Exact configuration commands to try
366
+ 4. **Confidence Level** - How confident you are in this diagnosis (as a percentage)
367
+
368
+ Focus on common enterprise VoIP issues:
369
+ - NAT traversal for audio problems in cloud deployments
370
+ - DTMF configuration for IVR issues
371
+ - TLS/security for connection failures
372
+ - Codec negotiation for audio quality (PCMU/PCMA/Opus compatibility)
373
+ - Session timers for dropped calls
374
+ - Port configuration for firewall issues
375
+ - Emergency calling routing
376
+
377
+ Format your response in clear sections with markdown. Be specific and actionable."""
378
+
379
+ message = client.messages.create(
380
+ model="claude-3-5-haiku-20241022",
381
+ max_tokens=800,
382
+ messages=[{
383
+ "role": "user",
384
+ "content": prompt
385
+ }]
386
+ )
387
+
388
+ # Record successful request
389
+ record_request(user_ip, "ai")
390
+
391
+ # Format response
392
+ analysis = f"# 🤖 AI-Powered Troubleshooting Analysis\n\n"
393
+ analysis += f"**Your Issue:** {symptom_description}\n\n"
394
+ analysis += "**Powered by Claude 3.5 Haiku** | **Optimized for Bandwidth Duet®**\n\n"
395
+ analysis += "---\n\n"
396
+ analysis += message.content[0].text
397
+ analysis += "\n\n---\n\n"
398
+ analysis += "## 📋 Next Steps\n\n"
399
+ analysis += "1. Review the configuration parameters listed above in your SBC\n"
400
+ analysis += "2. Switch to the **Configuration Validator** tab to paste your full config for detailed analysis\n"
401
+ analysis += "3. Apply the recommended fixes\n"
402
+ analysis += "4. Test with a trial call\n"
403
+ analysis += "5. Verify emergency calling if applicable\n"
404
+
405
+ return analysis
406
+
407
+ except Exception as e:
408
+ return fallback_troubleshoot(symptom_description)
409
+
410
+ def fallback_troubleshoot(symptom_description):
411
+ """Fallback pattern-based analysis"""
412
+ return "## 🔍 Troubleshooting Analysis\n\nAI analysis temporarily unavailable. Please use the Configuration Validator tab or contact Bandwidth Support."
413
+
414
+ def get_usage_stats():
415
+ """Return formatted usage statistics"""
416
+ stats = load_usage_stats()
417
+
418
+ output = f"""# 📊 Bandwidth Duet® SBC Validator - Usage Statistics
419
+
420
+ **Total AI Troubleshooting Requests:** {stats['total_ai_requests']}
421
+ **Total Configuration Validations:** {stats['total_config_validations']}
422
+ **Unique Visitors:** {stats['total_visitors']}
423
+
424
+ **First Request:** {stats['first_request'] or 'No requests yet'}
425
+ **Last Request:** {stats['last_request'] or 'No requests yet'}
426
+
427
+ **Requests by Hour (Last 24 hours):**
428
+ """
429
+
430
+ # Show last 24 hours of activity
431
+ if stats['requests_by_hour']:
432
+ sorted_hours = sorted(stats['requests_by_hour'].items(), reverse=True)[:24]
433
+ for hour, count in sorted_hours:
434
+ output += f"\n- {hour}: {count} requests"
435
+ else:
436
+ output += "\nNo activity recorded yet"
437
+
438
+ return output
439
+
440
+ # Example configurations
441
+ BROKEN_CONFIG = """transport=udp
442
+ port=5060
443
+ codecs=opus
444
+ srtp=optional
445
+ nat_traversal=disabled
446
+ tls_version=1.0
447
+ session_expires=90
448
+ dtmf_relay=inband
449
+ rtp_port_range=10000-10100
450
+ dns_srv_lookup=disabled"""
451
+
452
+ VALID_CONFIG = """transport=tcp
453
+ port=5061
454
+ codecs=pcmu,pcma,opus,g729
455
+ srtp=required
456
+ crypto_suites=AES_CM_128_HMAC_SHA1_80
457
+ nat_traversal=enabled
458
+ ice_support=enabled
459
+ stun_server=stun.l.google.com:19302
460
+ tls_version=1.2
461
+ tls_min_version=1.2
462
+ cipher_suites=ECDHE-RSA-AES256-GCM-SHA384
463
+ session_expires=1800
464
+ min_se=900
465
+ dtmf_relay=rfc2833
466
+ rtp_port_range=10000-20000
467
+ dns_srv_lookup=enabled
468
+ media_anchoring=enabled"""
469
+
470
+ def load_broken_config():
471
+ return BROKEN_CONFIG
472
+
473
+ def load_valid_config():
474
+ return VALID_CONFIG
475
+
476
+ # Create Gradio interface
477
+ demo = gr.Blocks(theme=gr.themes.Soft(), title="Bandwidth Duet® - SBC Configuration Validator")
478
+
479
+ with demo:
480
+
481
+ gr.Markdown("""
482
+ # 🔊 Bandwidth Duet® - AI-Powered SBC Configuration Validator
483
+ ### Intelligent Analysis & Troubleshooting for Enterprise VoIP Deployments
484
+
485
+ **Powered by Bandwidth® - The Global Enterprise Cloud Communications Company**
486
+
487
+ Validate your SBC configuration and get AI-powered troubleshooting recommendations for enterprise voice deployments.
488
+ """)
489
+
490
+ with gr.Tabs():
491
+ with gr.Tab("🤖 AI Troubleshoot"):
492
+ gr.Markdown("""
493
+ ### Describe Your Issue in Plain English
494
+ Tell me what's wrong with your calls and I'll diagnose the likely SBC configuration issues.
495
+ """)
496
+
497
+ with gr.Row():
498
+ with gr.Column(scale=1):
499
+ symptom_input = gr.Textbox(
500
+ label="What issue are you experiencing?",
501
+ lines=5,
502
+ placeholder="Examples:\n- 'My calls have one-way audio'\n- 'IVR menu not responding to key presses'\n- 'Calls dropping after 2 minutes'\n- 'TLS handshake failing with carrier'\n- 'Emergency calls not routing correctly'",
503
+ )
504
+
505
+ with gr.Row():
506
+ example_btn1 = gr.Button("Example: One-way audio", variant="secondary", size="sm")
507
+ example_btn2 = gr.Button("Example: IVR not working", variant="secondary", size="sm")
508
+
509
+ troubleshoot_btn = gr.Button("🔍 Diagnose Issue", variant="primary", size="lg")
510
+
511
+ with gr.Column(scale=1):
512
+ gr.Markdown("### AI Diagnosis")
513
+ troubleshoot_output = gr.Markdown()
514
+
515
+ # Example button actions
516
+ example_btn1.click(fn=lambda: "I can hear the other person but they can't hear me", outputs=symptom_input)
517
+ example_btn2.click(fn=lambda: "Customers can't navigate our IVR menu by pressing numbers", outputs=symptom_input)
518
+ troubleshoot_btn.click(fn=ai_troubleshoot, inputs=symptom_input, outputs=troubleshoot_output)
519
+
520
+ with gr.Tab("⚙️ Configuration Validator"):
521
+ gr.Markdown("""
522
+ ### Paste Your SBC Configuration
523
+ Get detailed analysis of specific configuration parameters for enterprise VoIP deployments.
524
+ """)
525
+
526
+ with gr.Row():
527
+ with gr.Column(scale=1):
528
+ config_input = gr.Textbox(
529
+ label="Paste your configuration here",
530
+ lines=20,
531
+ placeholder="Example:\ntransport=tcp\nport=5061\ncodecs=pcmu,pcma,opus\nsrtp=required\nnat_traversal=enabled\n...",
532
+ )
533
+
534
+ with gr.Row():
535
+ broken_btn = gr.Button("📛 Load Example: Common Mistakes", variant="secondary", size="sm")
536
+ valid_btn = gr.Button("✅ Load Example: Best Practice Config", variant="secondary", size="sm")
537
+
538
+ analyze_btn = gr.Button("🔍 Validate Configuration", variant="primary", size="lg")
539
+
540
+ with gr.Column(scale=1):
541
+ gr.Markdown("### Validation Results")
542
+ output = gr.Markdown()
543
+
544
+ # Button actions
545
+ broken_btn.click(fn=load_broken_config, outputs=config_input)
546
+ valid_btn.click(fn=load_valid_config, outputs=config_input)
547
+ analyze_btn.click(fn=analyze_configuration, inputs=config_input, outputs=output)
548
+
549
+ with gr.Tab("📊 Usage Stats"):
550
+ gr.Markdown("""
551
+ ### Validator Usage Statistics
552
+ Track how many people are using this tool.
553
+ """)
554
+
555
+ stats_output = gr.Markdown()
556
+ refresh_btn = gr.Button("🔄 Refresh Stats", variant="primary")
557
+
558
+ refresh_btn.click(fn=get_usage_stats, outputs=stats_output)
559
+ demo.load(fn=get_usage_stats, outputs=stats_output) # Auto-load on page load
560
+
561
+ gr.Markdown("""
562
+ ---
563
+ ## About Bandwidth Duet®
564
+
565
+ **Bandwidth Duet®** is a comprehensive solution for enterprise voice connectivity, available directly from a carrier who owns and operates its underlying infrastructure.
566
+
567
+ **Key Features:**
568
+ - **Direct Routing:** Seamless enterprise calling with existing SIP trunking
569
+ - **Dynamic E911:** Certified emergency calling with accurate location routing
570
+ - **Software-Driven SIP:** Built on Bandwidth's nationwide IP voice network
571
+ - **Simplified Migration:** Accelerate telecom migration with less complexity
572
+
573
+ **This Validator Checks For:**
574
+ - Security vulnerabilities (SRTP, TLS, authentication)
575
+ - Codec negotiation issues for enterprise UC platforms
576
+ - NAT traversal problems in cloud environments
577
+ - DTMF signaling for IVR systems
578
+ - Port configuration and firewall compatibility
579
+ - Session timer optimizations
580
+ - Emergency calling routing readiness
581
+
582
+ **Powered By:**
583
+ - AI Model: Claude 3.5 Haiku for natural language troubleshooting
584
+ - Detection Engine: Rule-based validation across 7 configuration categories
585
+ - Rate Limiting: 5 requests/user/hour (demo environment)
586
+
587
+ ---
588
+
589
+ 💡 **Pro Tip:** Run this validator before deploying your SBC to production. Most VoIP issues can be prevented with proper configuration.
590
+
591
+ Built by Philip Drammeh | Independent Researcher | [LinkedIn](https://www.linkedin.com/in/philipdrammeh)
592
+
593
+ *Bandwidth Duet® is a registered trademark of Bandwidth Inc. This tool is an independent project and not officially affiliated with or endorsed by Bandwidth Inc.*
594
+ """)
595
+
596
+ if __name__ == "__main__":
597
+ demo.launch()