qhuang0805123 commited on
Commit
35fb087
·
verified ·
1 Parent(s): 7d366d0

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +404 -0
app.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from datetime import datetime
4
+ import gradio as gr
5
+ from twilio.rest import Client
6
+ from twilio.twiml.voice_response import VoiceResponse, Gather, Dial
7
+
8
+ # Initialize Twilio client - you'll need to set these environment variables
9
+ account_sid = os.environ.get('TWILIO_ACCOUNT_SID')
10
+ auth_token = os.environ.get('TWILIO_AUTH_TOKEN')
11
+ twilio_client = Client(account_sid, auth_token)
12
+
13
+ # Database simulation (in a real app, use a proper database)
14
+ call_routes = {}
15
+ call_logs = []
16
+ tracking_numbers = {}
17
+
18
+ # Call routing configuration
19
+ def save_call_route(name, description, tracking_number, destinations, routing_type, schedules=None):
20
+ """Save a call routing configuration"""
21
+ if tracking_number in tracking_numbers:
22
+ route_id = tracking_numbers[tracking_number]
23
+ else:
24
+ route_id = f"route_{len(call_routes) + 1}"
25
+ tracking_numbers[tracking_number] = route_id
26
+
27
+ call_routes[route_id] = {
28
+ "name": name,
29
+ "description": description,
30
+ "tracking_number": tracking_number,
31
+ "destinations": destinations,
32
+ "routing_type": routing_type, # "sequential", "simultaneous", "percentage", "time_based"
33
+ "schedules": schedules if schedules else [],
34
+ "created_at": datetime.now().isoformat()
35
+ }
36
+ return route_id
37
+
38
+ # Twilio TwiML generation for call routing
39
+ def generate_call_routing_twiml(tracking_number, caller_id, call_sid):
40
+ """Generate TwiML for routing calls based on the configuration"""
41
+ resp = VoiceResponse()
42
+
43
+ # Log the call
44
+ log_call(call_sid, caller_id, tracking_number, "inbound", "initiated")
45
+
46
+ # Find the appropriate route
47
+ if tracking_number not in tracking_numbers:
48
+ resp.say("We're sorry, but this number is not configured for routing.")
49
+ return str(resp)
50
+
51
+ route_id = tracking_numbers[tracking_number]
52
+ route = call_routes[route_id]
53
+
54
+ # Check if there's a greeting message
55
+ if "greeting" in route:
56
+ resp.say(route["greeting"])
57
+
58
+ # Check routing type and implement accordingly
59
+ if route["routing_type"] == "simultaneous":
60
+ # Ring all destinations at once
61
+ dial = Dial(
62
+ caller_id=caller_id,
63
+ action=f"/call-status?call_sid={call_sid}&tracking_number={tracking_number}",
64
+ timeout=30
65
+ )
66
+ for dest in route["destinations"]:
67
+ dial.number(dest["number"])
68
+ resp.append(dial)
69
+
70
+ elif route["routing_type"] == "sequential":
71
+ # Use Twilio's redirect to chain through destinations
72
+ resp.redirect(f"/sequential-route?call_sid={call_sid}&tracking_number={tracking_number}&index=0")
73
+
74
+ elif route["routing_type"] == "percentage":
75
+ # Implement percentage-based routing (simplified version)
76
+ import random
77
+ total = sum(dest.get("percentage", 0) for dest in route["destinations"])
78
+ r = random.randint(1, total)
79
+ cumulative = 0
80
+
81
+ for dest in route["destinations"]:
82
+ cumulative += dest.get("percentage", 0)
83
+ if r <= cumulative:
84
+ dial = Dial(
85
+ caller_id=caller_id,
86
+ action=f"/call-status?call_sid={call_sid}&tracking_number={tracking_number}",
87
+ timeout=30
88
+ )
89
+ dial.number(dest["number"])
90
+ resp.append(dial)
91
+ break
92
+
93
+ elif route["routing_type"] == "time_based":
94
+ # Time-based routing implementation
95
+ now = datetime.now()
96
+ current_day = now.strftime("%A").lower()
97
+ current_hour = now.hour
98
+
99
+ # Find the appropriate schedule
100
+ for schedule in route.get("schedules", []):
101
+ if current_day in schedule["days"]:
102
+ start_hour = int(schedule["start_time"].split(":")[0])
103
+ end_hour = int(schedule["end_time"].split(":")[0])
104
+
105
+ if start_hour <= current_hour < end_hour:
106
+ # Route to the destination for this schedule
107
+ dial = Dial(
108
+ caller_id=caller_id,
109
+ action=f"/call-status?call_sid={call_sid}&tracking_number={tracking_number}",
110
+ timeout=30
111
+ )
112
+ dial.number(schedule["destination"])
113
+ resp.append(dial)
114
+ return str(resp)
115
+
116
+ # If no schedule matches, use the default destination or voicemail
117
+ if "default_destination" in route:
118
+ dial = Dial(
119
+ caller_id=caller_id,
120
+ action=f"/call-status?call_sid={call_sid}&tracking_number={tracking_number}",
121
+ timeout=30
122
+ )
123
+ dial.number(route["default_destination"])
124
+ resp.append(dial)
125
+ else:
126
+ resp.say("I'm sorry, we're currently closed. Please leave a message after the tone.")
127
+ resp.record(
128
+ action=f"/voicemail?call_sid={call_sid}&tracking_number={tracking_number}",
129
+ max_length=120
130
+ )
131
+
132
+ return str(resp)
133
+
134
+ # Call logging
135
+ def log_call(call_sid, caller_id, tracking_number, call_type, status, duration=0, recording_url=None):
136
+ """Log a call in the system"""
137
+ call_logs.append({
138
+ "call_sid": call_sid,
139
+ "caller_id": caller_id,
140
+ "tracking_number": tracking_number,
141
+ "timestamp": datetime.now().isoformat(),
142
+ "type": call_type,
143
+ "status": status,
144
+ "duration": duration,
145
+ "recording_url": recording_url
146
+ })
147
+ return len(call_logs) - 1
148
+
149
+ # Purchase a new Twilio number
150
+ def purchase_tracking_number(area_code, friendly_name):
151
+ """Purchase a new Twilio phone number"""
152
+ try:
153
+ available_numbers = twilio_client.available_phone_numbers('US').local.list(area_code=area_code, limit=1)
154
+
155
+ if not available_numbers:
156
+ return {"success": False, "message": f"No available numbers found with area code {area_code}"}
157
+
158
+ number = available_numbers[0]
159
+ purchased_number = twilio_client.incoming_phone_numbers.create(
160
+ phone_number=number.phone_number,
161
+ friendly_name=friendly_name,
162
+ voice_url="https://your-gradio-app-url.com/voice" # You'll need to update this with your actual URL
163
+ )
164
+
165
+ return {
166
+ "success": True,
167
+ "number": purchased_number.phone_number,
168
+ "sid": purchased_number.sid
169
+ }
170
+ except Exception as e:
171
+ return {"success": False, "message": str(e)}
172
+
173
+ # Gradio Interface
174
+
175
+ # Function to display the call logs
176
+ def view_call_logs():
177
+ if not call_logs:
178
+ return "No calls logged yet."
179
+
180
+ output = "Call Logs:\n\n"
181
+ for i, log in enumerate(call_logs):
182
+ output += f"Call {i+1}:\n"
183
+ output += f" SID: {log['call_sid']}\n"
184
+ output += f" From: {log['caller_id']}\n"
185
+ output += f" To: {log['tracking_number']}\n"
186
+ output += f" Time: {log['timestamp']}\n"
187
+ output += f" Status: {log['status']}\n"
188
+ output += f" Duration: {log['duration']} seconds\n"
189
+ if log.get('recording_url'):
190
+ output += f" Recording: {log['recording_url']}\n"
191
+ output += "\n"
192
+
193
+ return output
194
+
195
+ # Function to create a new call route
196
+ def create_call_route(name, description, tracking_number, destinations_json, routing_type, schedules_json=None):
197
+ try:
198
+ destinations = json.loads(destinations_json)
199
+ schedules = json.loads(schedules_json) if schedules_json else None
200
+
201
+ route_id = save_call_route(name, description, tracking_number, destinations, routing_type, schedules)
202
+
203
+ return f"Call route created successfully with ID: {route_id}"
204
+ except Exception as e:
205
+ return f"Error creating call route: {str(e)}"
206
+
207
+ # Function to list all call routes
208
+ def list_call_routes():
209
+ if not call_routes:
210
+ return "No call routes configured yet."
211
+
212
+ output = "Call Routes:\n\n"
213
+ for route_id, route in call_routes.items():
214
+ output += f"Route ID: {route_id}\n"
215
+ output += f" Name: {route['name']}\n"
216
+ output += f" Tracking Number: {route['tracking_number']}\n"
217
+ output += f" Routing Type: {route['routing_type']}\n"
218
+ output += f" Destinations: {len(route['destinations'])}\n"
219
+ output += "\n"
220
+
221
+ return output
222
+
223
+ # Function to purchase a new tracking number
224
+ def buy_tracking_number(area_code, name):
225
+ result = purchase_tracking_number(area_code, name)
226
+
227
+ if result["success"]:
228
+ return f"Successfully purchased number: {result['number']}"
229
+ else:
230
+ return f"Failed to purchase number: {result['message']}"
231
+
232
+ # Create the Gradio interface
233
+ with gr.Blocks(title="Twilio Call Router (CallRail Alternative)") as app:
234
+ gr.Markdown("# Twilio Call Router\nA CallRail alternative built with Twilio and Gradio")
235
+
236
+ with gr.Tab("Dashboard"):
237
+ gr.Markdown("## Dashboard")
238
+ dashboard_btn = gr.Button("Refresh Dashboard")
239
+ dashboard_output = gr.Textbox(label="Call Statistics", lines=10)
240
+ dashboard_btn.click(view_call_logs, inputs=[], outputs=dashboard_output)
241
+
242
+ with gr.Tab("Call Routes"):
243
+ gr.Markdown("## Call Routes")
244
+
245
+ with gr.Accordion("Create New Route"):
246
+ route_name = gr.Textbox(label="Route Name")
247
+ route_desc = gr.Textbox(label="Description")
248
+ tracking_num = gr.Textbox(label="Tracking Number (E.164 format)")
249
+ destinations = gr.Textbox(
250
+ label="Destinations (JSON format)",
251
+ value="""[
252
+ {"number": "+15551234567", "name": "Main Office"},
253
+ {"number": "+15557654321", "name": "Sales Team"}
254
+ ]"""
255
+ )
256
+ routing_type = gr.Dropdown(
257
+ label="Routing Type",
258
+ choices=["sequential", "simultaneous", "percentage", "time_based"],
259
+ value="simultaneous"
260
+ )
261
+ schedules = gr.Textbox(
262
+ label="Schedules (JSON format, for time_based routing)",
263
+ value="""[
264
+ {"days": ["monday", "tuesday", "wednesday", "thursday", "friday"],
265
+ "start_time": "09:00",
266
+ "end_time": "17:00",
267
+ "destination": "+15551234567"}
268
+ ]"""
269
+ )
270
+ create_route_btn = gr.Button("Create Route")
271
+ create_route_output = gr.Textbox(label="Result")
272
+
273
+ create_route_btn.click(
274
+ create_call_route,
275
+ inputs=[route_name, route_desc, tracking_num, destinations, routing_type, schedules],
276
+ outputs=create_route_output
277
+ )
278
+
279
+ list_routes_btn = gr.Button("List Routes")
280
+ routes_output = gr.Textbox(label="Routes", lines=10)
281
+ list_routes_btn.click(list_call_routes, inputs=[], outputs=routes_output)
282
+
283
+ with gr.Tab("Numbers"):
284
+ gr.Markdown("## Phone Numbers")
285
+
286
+ with gr.Row():
287
+ area_code = gr.Textbox(label="Area Code (e.g., 415)")
288
+ number_name = gr.Textbox(label="Friendly Name")
289
+
290
+ buy_number_btn = gr.Button("Purchase Number")
291
+ number_output = gr.Textbox(label="Result")
292
+
293
+ buy_number_btn.click(buy_tracking_number, inputs=[area_code, number_name], outputs=number_output)
294
+
295
+ with gr.Tab("Call Logs"):
296
+ gr.Markdown("## Call Logs")
297
+ view_logs_btn = gr.Button("View Call Logs")
298
+ logs_output = gr.Textbox(label="Logs", lines=15)
299
+ view_logs_btn.click(view_call_logs, inputs=[], outputs=logs_output)
300
+
301
+ # Add Flask routes for Twilio webhooks
302
+ # Note: In a production environment, you'll need to expose these routes to the internet
303
+ # For local development, you can use ngrok
304
+ # These routes would be registered with your Flask app
305
+ """
306
+ @app.route('/voice', methods=['POST'])
307
+ def voice():
308
+ # Extract call details from the request
309
+ caller_id = request.values.get('From')
310
+ tracking_number = request.values.get('To')
311
+ call_sid = request.values.get('CallSid')
312
+
313
+ # Generate and return TwiML
314
+ return generate_call_routing_twiml(tracking_number, caller_id, call_sid)
315
+
316
+ @app.route('/sequential-route', methods=['POST'])
317
+ def sequential_route():
318
+ # Handle sequential routing logic
319
+ call_sid = request.values.get('call_sid')
320
+ tracking_number = request.values.get('tracking_number')
321
+ index = int(request.values.get('index', 0))
322
+
323
+ route_id = tracking_numbers[tracking_number]
324
+ route = call_routes[route_id]
325
+
326
+ resp = VoiceResponse()
327
+
328
+ if index >= len(route["destinations"]):
329
+ resp.say("We're sorry, but we were unable to connect your call. Please try again later.")
330
+ return str(resp)
331
+
332
+ destination = route["destinations"][index]
333
+ dial = Dial(
334
+ caller_id=request.values.get('From'),
335
+ action=f"/sequential-next?call_sid={call_sid}&tracking_number={tracking_number}&index={index}",
336
+ timeout=20
337
+ )
338
+ dial.number(destination["number"])
339
+ resp.append(dial)
340
+
341
+ return str(resp)
342
+
343
+ @app.route('/sequential-next', methods=['POST'])
344
+ def sequential_next():
345
+ # Handle the next step in sequential routing
346
+ call_sid = request.values.get('call_sid')
347
+ tracking_number = request.values.get('tracking_number')
348
+ index = int(request.values.get('index', 0))
349
+ dial_status = request.values.get('DialCallStatus')
350
+
351
+ resp = VoiceResponse()
352
+
353
+ if dial_status == 'completed':
354
+ # Call was answered and completed
355
+ return str(resp)
356
+ else:
357
+ # Call failed or wasn't answered, try the next destination
358
+ resp.redirect(f"/sequential-route?call_sid={call_sid}&tracking_number={tracking_number}&index={index + 1}")
359
+ return str(resp)
360
+
361
+ @app.route('/call-status', methods=['POST'])
362
+ def call_status():
363
+ # Update call status
364
+ call_sid = request.values.get('call_sid')
365
+ tracking_number = request.values.get('tracking_number')
366
+ dial_status = request.values.get('DialCallStatus')
367
+ duration = int(request.values.get('DialCallDuration', 0))
368
+
369
+ # Find the call in logs and update its status
370
+ for log in call_logs:
371
+ if log['call_sid'] == call_sid:
372
+ log['status'] = dial_status
373
+ log['duration'] = duration
374
+ break
375
+
376
+ resp = VoiceResponse()
377
+ if dial_status != 'completed':
378
+ resp.say("We're sorry, but we were unable to connect your call. Please try again later.")
379
+
380
+ return str(resp)
381
+
382
+ @app.route('/voicemail', methods=['POST'])
383
+ def voicemail():
384
+ # Handle voicemail recording
385
+ call_sid = request.values.get('call_sid')
386
+ tracking_number = request.values.get('tracking_number')
387
+ recording_url = request.values.get('RecordingUrl')
388
+
389
+ # Update the call log with the recording URL
390
+ for log in call_logs:
391
+ if log['call_sid'] == call_sid:
392
+ log['recording_url'] = recording_url
393
+ break
394
+
395
+ resp = VoiceResponse()
396
+ resp.say("Thank you for your message. We'll get back to you as soon as possible.")
397
+
398
+ return str(resp)
399
+ """
400
+
401
+ # Launch the Gradio app
402
+ if __name__ == "__main__":
403
+ app.launch()
404
+