Spaces:
Runtime error
Runtime error
Download app.py from mattfutureflow/Futureflow_Cold_Caller_Dan: direct link, hf CLI and curl.
- Browser
- Download file 8.69 kB
-
https://huggingface.co/spaces/mattfutureflow/Futureflow_Cold_Caller_Dan/resolve/main/app.py
- Command line
-
hf download hf://spaces/mattfutureflow/Futureflow_Cold_Caller_Dan/app.py
-
curl -L -o app.py https://huggingface.co/spaces/mattfutureflow/Futureflow_Cold_Caller_Dan/resolve/main/app.py
8.69 kB
| import streamlit as st | |
| import requests | |
| import json | |
| from datetime import datetime, timedelta | |
| import os | |
| import pandas as pd | |
| import plotly.express as px | |
| from datetime import datetime, date # Import both `datetime` and `date` | |
| from pytz import timezone | |
| import pytz | |
| def convert_to_utc(dt, tz_name='America/Los_Angeles'): | |
| local_tz = timezone(tz_name) | |
| # If dt is a date object, convert it to a datetime object | |
| if isinstance(dt, date) and not isinstance(dt, datetime): | |
| dt = datetime.combine(dt, datetime.min.time()) | |
| local_dt = local_tz.localize(dt, is_dst=None) | |
| return local_dt.astimezone(pytz.utc) | |
| st.set_page_config(page_title="Call Dashboard", layout="wide", initial_sidebar_state="collapsed") | |
| # Custom CSS for a more professional look | |
| st.markdown(""" | |
| <style> | |
| .reportview-container .main .block-container { | |
| max-width: 1200px; | |
| padding-top: 2rem; | |
| padding-bottom: 2rem; | |
| background-color: #f8f9fa; | |
| } | |
| .stMetric { | |
| background-color: white; | |
| border-radius: 10px; | |
| padding: 15px; | |
| box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); | |
| transition: all 0.3s ease; | |
| } | |
| .stMetric:hover { | |
| transform: translateY(-5px); | |
| } | |
| .stPlotlyChart { | |
| background-color: white; | |
| border-radius: 10px; | |
| padding: 15px; | |
| box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); | |
| } | |
| h1, h2, h3 { | |
| color: #2c3e50; | |
| } | |
| .stButton>button { | |
| background-color: #3498db; | |
| color: white; | |
| font-weight: bold; | |
| border-radius: 5px; | |
| border: none; | |
| padding: 0.5rem 1rem; | |
| transition: all 0.3s ease; | |
| } | |
| .stButton>button:hover { | |
| background-color: #2980b9; | |
| transform: translateY(-2px); | |
| } | |
| .dataframe { | |
| font-family: Arial, sans-serif; | |
| border-collapse: collapse; | |
| width: 100%; | |
| } | |
| .dataframe th, .dataframe td { | |
| border: 1px solid #ddd; | |
| padding: 8px; | |
| } | |
| .dataframe tr:nth-child(even) { | |
| background-color: #f2f2f2; | |
| } | |
| .dataframe th { | |
| padding-top: 12px; | |
| padding-bottom: 12px; | |
| text-align: left; | |
| background-color: #3498db; | |
| color: white; | |
| } | |
| </style> | |
| """, unsafe_allow_html=True) | |
| def fetch_vapi_data(start_date, end_date): | |
| if start_date == end_date: | |
| end_date = datetime.combine(end_date, datetime.max.time()) | |
| else: | |
| end_date = datetime.combine(end_date, datetime.max.time()) | |
| if isinstance(start_date, (date, datetime)): | |
| start_date = datetime.combine(start_date, datetime.min.time()) | |
| start_date_utc = convert_to_utc(start_date) | |
| end_date_utc = convert_to_utc(end_date) | |
| api_key = os.environ.get('VAPI_API_KEY', '4227a00b-77cc-4bab-9850-a0de4f76e2c6') | |
| assistant_id = os.environ.get('VAPI_ASSISTANT_ID', 'aade5968-bc38-4e6b-8959-0a87859d9a53') | |
| base_url = 'https://api.vapi.ai/call' | |
| headers = { | |
| 'Authorization': f'Bearer {api_key}' | |
| } | |
| params = { | |
| 'createdAtGt': start_date_utc.strftime('%Y-%m-%dT%H:%M:%SZ'), | |
| 'createdAtLt': end_date_utc.strftime('%Y-%m-%dT%H:%M:%SZ'), | |
| 'limit': 1000, | |
| 'assistantId': assistant_id | |
| } | |
| try: | |
| response = requests.get(base_url, headers=headers, params=params) | |
| response.raise_for_status() | |
| return response.json() | |
| except requests.RequestException as e: | |
| st.error(f"Failed to fetch data from VAPI: {str(e)}") | |
| return None | |
| def format_duration(seconds): | |
| minutes, seconds = divmod(int(seconds), 60) | |
| hours, minutes = divmod(minutes, 60) | |
| if hours > 0: | |
| return f"{hours}h {minutes}m {seconds}s" | |
| elif minutes > 0: | |
| return f"{minutes}m {seconds}s" | |
| else: | |
| return f"{seconds}s" | |
| def process_vapi_data(data): | |
| if not data: | |
| return {'stats': [], 'recentCalls': []} | |
| total_calls = len(data) | |
| inbound_calls = sum(1 for call in data if call.get('type') == 'inboundPhoneCall') | |
| outbound_calls = sum(1 for call in data if call.get('type') == 'outboundPhoneCall') | |
| customer_ended = sum(1 for call in data if call.get('endedReason') == 'customer-ended-call') | |
| total_cost = sum(call.get('cost', 0) for call in data) | |
| stats = [ | |
| {'name': 'Total Calls', 'value': total_calls}, | |
| {'name': 'Inbound Calls', 'value': inbound_calls}, | |
| {'name': 'Outbound Calls', 'value': outbound_calls}, | |
| {'name': 'Customer Ended', 'value': customer_ended}, | |
| {'name': 'Total Cost', 'value': f'${total_cost:.2f}'}, | |
| ] | |
| recent_calls = [ | |
| { | |
| 'First Name': call.get('first_name', 'N/A'), | |
| 'Phone Number': call.get('phone', 'N/A'), | |
| 'Email': call.get('email', 'N/A'), | |
| 'Company Name': call.get('company_name', 'N/A'), | |
| 'Success Evaluation': call.get('analysis', {}).get('successEvaluation', 'N/A'), # Re-added Success Evaluation | |
| 'Direction': 'Inbound' if call.get('type') == 'inboundPhoneCall' else 'Outbound', | |
| 'Outcome': call.get('status', 'N/A'), | |
| 'Started At': call.get('startedAt', 'N/A'), | |
| 'Duration': format_duration( | |
| (datetime.fromisoformat(call.get('endedAt', '')[:-1]) - datetime.fromisoformat(call.get('startedAt', '')[:-1])).total_seconds() | |
| if call.get('endedAt') and call.get('startedAt') else 0), | |
| 'Cost': f"${call.get('cost', 0):.2f}", | |
| 'Recording': call.get('recordingUrl', 'N/A') | |
| } | |
| for call in sorted(data, key=lambda x: x.get('createdAt', ''), reverse=True) | |
| ] | |
| return {'stats': stats, 'recentCalls': recent_calls} | |
| def display_report(processed_data): | |
| st.subheader("π Call Statistics") | |
| cols = st.columns(5) | |
| for i, stat in enumerate(processed_data['stats']): | |
| with cols[i]: | |
| st.metric(stat['name'], stat['value']) | |
| st.subheader("π Recent Calls") | |
| df = pd.DataFrame(processed_data['recentCalls']) | |
| items_per_page = st.selectbox("Calls per page", [10, 50, 100], key="items_per_page") | |
| col_top_left, col_top_right = st.columns([3, 1]) | |
| with col_top_right: | |
| total_pages = (len(df) // items_per_page) + 1 | |
| page_top = st.number_input("Page number", min_value=1, max_value=total_pages, step=1, key="page_number_top") | |
| start_idx = (page_top - 1) * items_per_page | |
| end_idx = start_idx + items_per_page | |
| df_paginated = df.iloc[start_idx:end_idx] | |
| search_term = st.text_input("Search by Phone Number", key="search_term") | |
| if search_term: | |
| df_paginated = df_paginated[df_paginated['Phone Number'].str.contains(search_term, case=False, na=False)] | |
| sort_column = st.selectbox("Sort by", ["Duration", "Cost", "Success Evaluation"], key="sort_column") | |
| sort_order = st.radio("Sort order", ["Ascending", "Descending"], key="sort_order") | |
| if sort_column == "Duration": | |
| df_paginated['Duration'] = pd.to_timedelta(df_paginated['Duration']) | |
| elif sort_column == "Cost": | |
| df_paginated['Cost'] = df_paginated['Cost'].str.replace('$', '').astype(float) | |
| df_paginated = df_paginated.sort_values(by=sort_column, ascending=(sort_order == "Ascending")) | |
| df_paginated['Recording'] = df_paginated['Recording'].apply(lambda x: f'<a href="{x}" target="_blank">Listen</a>' if x != 'N/A' else 'N/A') | |
| st.write(df_paginated.to_html(escape=False, index=False), unsafe_allow_html=True) | |
| col_bottom_left, col_bottom_right = st.columns([3, 1]) | |
| with col_bottom_right: | |
| page_bottom = st.number_input("Page number", min_value=1, max_value=total_pages, step=1, key="page_number_bottom") | |
| def main(): | |
| st.title("π Call Dashboard") | |
| if 'start_date' not in st.session_state: | |
| st.session_state.start_date = datetime.now() - timedelta(days=7) | |
| if 'end_date' not in st.session_state: | |
| st.session_state.end_date = datetime.now() | |
| col1, col2 = st.columns(2) | |
| with col1: | |
| st.session_state.start_date = st.date_input("Start Date", st.session_state.start_date) | |
| with col2: | |
| st.session_state.end_date = st.date_input("End Date", st.session_state.end_date) | |
| if st.button("Generate Report", key="generate_report"): | |
| with st.spinner("Fetching data..."): | |
| vapi_data = fetch_vapi_data(st.session_state.start_date, st.session_state.end_date) | |
| if vapi_data: | |
| st.session_state.vapi_data = process_vapi_data(vapi_data) | |
| display_report(st.session_state.vapi_data) | |
| else: | |
| st.warning("No data available") | |
| if 'vapi_data' in st.session_state: | |
| display_report(st.session_state.vapi_data) | |
| if __name__ == "__main__": | |
| main() | |