使用Python和Gradio製作互動式儀表盤的9個步驟

使用Python和Gradio製作互動式儀表盤

您是否曾經遇到過這樣的情況:您擁有一個龐大的資料集,卻想從中獲得洞察?聽起來很可怕,對吧?獲取有用的洞察,尤其是從龐大的資料集中獲取洞察,是一項艱鉅的任務。想象一下,在沒有任何資料視覺化前端專業知識的情況下,將您的資料集轉換為互動式 Web 應用程式。Gradio 與 Python 結合使用,只需極少的程式碼即可實現此功能。資料視覺化是有效呈現資料洞察的強大工具。在本指南中,我們將探討如何構建現代化的互動式資料儀表板,重點介紹 Gradio 資料視覺化,並演示如何使用 Python 構建 GUI。

瞭解Gradio

Gradio 是一個用於構建基於 Web 介面的開源 Python 庫。它專為簡化用於部署機器學習模型和資料應用程式的使用者介面開發而構建。您無需具備 HTML、JavaScript 和 CSS 等 Web 技術方面的豐富背景。Gradio 會在內部處理所有複雜問題和其他事務。這使您只需專注於 Python 程式碼即可。

Gradio

Gradio與Streamlit

Streamlit 和 Gradio 都支援以最少的程式碼行開發 Web 應用程式。它們彼此完全不同。因此,瞭解它們的差異可以幫助您選擇合適的 Web 應用程式構建框架。

方面 Gradio Streamlit
易用性 Gradio 上手難度低,介面及 API 簡潔直觀,新手也能快速入門。 Streamlit 功能豐富、可定製性高,但學習曲線相對更陡峭。
主要定位 側重於為機器學習 / 人工智慧模型快速構建互動式介面。 更偏向通用型的應用框架,可用於更廣泛的資料應用場景。
響應模型 元件通常在特定動作(如點選按鈕)後更新,也可配置即時重新整理。 採用整體式響應模型,任何輸入變動都會觸發指令碼整體重跑。
優勢 適合快速演示模型、構建輕量級視覺化工具。 擅長資料驅動型應用和複雜的互動式資料儀表盤。

Gradio與Streamlit

兩種工具均可用於製作互動式儀表板。具體選擇哪種工具取決於專案的具體需求。

構建互動式儀表板的步驟

讓我們來看看構建此互動式儀表板所需的關鍵步驟。

1. 獲取資料

建立儀表板之前的關鍵步驟之一是獲取用於視覺化的基礎資料。我們將為 Python Gradio 儀表板準備一個合成的 CSV 檔案。它包含 100,000 條模擬網站使用者互動的記錄。每條記錄代表一次使用者會話或一次重要的互動。

以下是我們的 CSV 檔案示例:

timestamp user_id page_visited session_duration_seconds country device_type browser
2023-01-15 10:30:00 U1001 /home 120 USA Desktop Chrome
2023-01-15 10:32:00 U1002 /products 180 Canada Mobile Safari
2023-01-15 10:35:00 U1001 /contact 90 USA Desktop Chrome

您可以使用以下 Python 程式碼生成此類資料。此處我們生成一個用於演示。請確保您已安裝 numpy 和 pandas。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
def generate_website_data(nrows: int, filename: str):
# Possible values for categorical fields
pages = ["/home", "/products", "/services", "/about", "/contact", "/blog"]
countries = ["USA", "Canada", "UK", "Germany", "France", "India", "Australia"]
device_types = ["Desktop", "Mobile", "Tablet"]
browsers = ["Chrome", "Firefox", "Safari", "Edge", "Opera"]
# Generate random data
user_ids = [f"User_{i}" for i in np.random.randint(1000, 2000, size=nrows)]
page_visited_data = np.random.choice(pages, size=nrows)
session_durations = np.random.randint(30, 1800, size=nrows) # Session duration between 30s and 30min
country_data = np.random.choice(countries, size=nrows)
device_type_data = np.random.choice(device_types, size=nrows)
browser_data = np.random.choice(browsers, size=nrows)
# Generate random timestamps over the last two years
end_t = datetime.now()
start_t = end_t - timedelta(days=730)
time_range_seconds = int((end_t - start_t).total_seconds())
timestamps_data = []
for _ in range(nrows):
random_seconds = np.random.randint(0, time_range_seconds)
timestamp = start_t + timedelta(seconds=random_seconds)
timestamps_data.append(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
# Define columns for the DataFrame
columns = {
"timestamp": timestamps_data,
"user_id": user_ids,
"page_visited": page_visited_data,
"session_duration_seconds": session_durations,
"country": country_data,
"device_type": device_type_data,
"browser": browser_data,
}
# Create Pandas DataFrame
df = pd.DataFrame(columns)
# Sort by timestamp
df['timestamp'] = pd.to_datetime(df['timestamp'])
df = df.sort_values(by="timestamp").reset_index(drop=True)
# Write to CSV
df.to_csv(filename, index=False)
print(f"{nrows} rows of data generated and saved to {filename}")
# Generate 100,000 rows of data
generate_website_data(100_000, "website_engagement_data.csv")
# print("Please uncomment the above line to generate the data.")
import numpy as np import pandas as pd from datetime import datetime, timedelta def generate_website_data(nrows: int, filename: str): # Possible values for categorical fields pages = ["/home", "/products", "/services", "/about", "/contact", "/blog"] countries = ["USA", "Canada", "UK", "Germany", "France", "India", "Australia"] device_types = ["Desktop", "Mobile", "Tablet"] browsers = ["Chrome", "Firefox", "Safari", "Edge", "Opera"] # Generate random data user_ids = [f"User_{i}" for i in np.random.randint(1000, 2000, size=nrows)] page_visited_data = np.random.choice(pages, size=nrows) session_durations = np.random.randint(30, 1800, size=nrows) # Session duration between 30s and 30min country_data = np.random.choice(countries, size=nrows) device_type_data = np.random.choice(device_types, size=nrows) browser_data = np.random.choice(browsers, size=nrows) # Generate random timestamps over the last two years end_t = datetime.now() start_t = end_t - timedelta(days=730) time_range_seconds = int((end_t - start_t).total_seconds()) timestamps_data = [] for _ in range(nrows): random_seconds = np.random.randint(0, time_range_seconds) timestamp = start_t + timedelta(seconds=random_seconds) timestamps_data.append(timestamp.strftime('%Y-%m-%d %H:%M:%S')) # Define columns for the DataFrame columns = { "timestamp": timestamps_data, "user_id": user_ids, "page_visited": page_visited_data, "session_duration_seconds": session_durations, "country": country_data, "device_type": device_type_data, "browser": browser_data, } # Create Pandas DataFrame df = pd.DataFrame(columns) # Sort by timestamp df['timestamp'] = pd.to_datetime(df['timestamp']) df = df.sort_values(by="timestamp").reset_index(drop=True) # Write to CSV df.to_csv(filename, index=False) print(f"{nrows} rows of data generated and saved to {filename}") # Generate 100,000 rows of data generate_website_data(100_000, "website_engagement_data.csv") # print("Please uncomment the above line to generate the data.")
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
def generate_website_data(nrows: int, filename: str):
   # Possible values for categorical fields
   pages = ["/home", "/products", "/services", "/about", "/contact", "/blog"]
   countries = ["USA", "Canada", "UK", "Germany", "France", "India", "Australia"]
   device_types = ["Desktop", "Mobile", "Tablet"]
   browsers = ["Chrome", "Firefox", "Safari", "Edge", "Opera"]
   # Generate random data
   user_ids = [f"User_{i}" for i in np.random.randint(1000, 2000, size=nrows)]
   page_visited_data = np.random.choice(pages, size=nrows)
   session_durations = np.random.randint(30, 1800, size=nrows) # Session duration between 30s and 30min
   country_data = np.random.choice(countries, size=nrows)
   device_type_data = np.random.choice(device_types, size=nrows)
   browser_data = np.random.choice(browsers, size=nrows)
   # Generate random timestamps over the last two years
   end_t = datetime.now()
   start_t = end_t - timedelta(days=730)
   time_range_seconds = int((end_t - start_t).total_seconds())
   timestamps_data = []
   for _ in range(nrows):
       random_seconds = np.random.randint(0, time_range_seconds)
       timestamp = start_t + timedelta(seconds=random_seconds)
       timestamps_data.append(timestamp.strftime('%Y-%m-%d %H:%M:%S'))
   # Define columns for the DataFrame
   columns = {
       "timestamp": timestamps_data,
       "user_id": user_ids,
       "page_visited": page_visited_data,
       "session_duration_seconds": session_durations,
       "country": country_data,
       "device_type": device_type_data,
       "browser": browser_data,
   }
   # Create Pandas DataFrame
   df = pd.DataFrame(columns)
   # Sort by timestamp
   df['timestamp'] = pd.to_datetime(df['timestamp'])
   df = df.sort_values(by="timestamp").reset_index(drop=True)
   # Write to CSV
   df.to_csv(filename, index=False)
   print(f"{nrows} rows of data generated and saved to {filename}")
# Generate 100,000 rows of data
generate_website_data(100_000, "website_engagement_data.csv")
# print("Please uncomment the above line to generate the data.")

輸出:

100000 rows of data generated and saved to website_engagement_data.csv

執行此程式碼後,您將看到輸出,並生成一個包含資料的 CSV 檔案。

2. 安裝Gradio

使用 pip 安裝 Gradio 非常簡單。建議使用專用的 Python 環境。可以使用 venv 和 conda 等工具建立獨立的環境。Gradio 需要 Python 3.8 或更高版本。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
python -m venv gradio_env
source gradio_env/bin/activate # On Linux/macOS
.\gradio_env\Scripts\activate # On Windows
python -m venv gradio_env source gradio_env/bin/activate # On Linux/macOS .\gradio_env\Scripts\activate # On Windows
python -m venv gradio_env
source gradio_env/bin/activate  # On Linux/macOS
.\gradio_env\Scripts\activate  # On Windows

安裝必要的庫

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
pip install gradio pandas plotly cachetools
pip install gradio pandas plotly cachetools
pip install gradio pandas plotly cachetools

現在我們已經安裝了所有依賴項,讓我們逐步建立儀表板。

3. 匯入必要的庫

首先,建立一個 app.py 檔案,然後匯入構建互動式儀表板所需的庫。我們將使用 Plotly 進行 Gradio 資料視覺化。並使用 Cachetools 為昂貴的函式呼叫建立快取,以提高效能。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import gradio as gr
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, date
from cachetools import cached, TTLCache
import warnings
warnings.filterwarnings("ignore", category=FutureWarning, module="plotly")
warnings.filterwarnings("ignore", category=UserWarning, module="plotly")
import gradio as gr import pandas as pd import plotly.express as px import plotly.graph_objects as go from datetime import datetime, date from cachetools import cached, TTLCache import warnings warnings.filterwarnings("ignore", category=FutureWarning, module="plotly") warnings.filterwarnings("ignore", category=UserWarning, module="plotly")
import gradio as gr
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, date
from cachetools import cached, TTLCache
import warnings
warnings.filterwarnings("ignore", category=FutureWarning, module="plotly")
warnings.filterwarnings("ignore", category=UserWarning, module="plotly")

4. 載入CSV資料

讓我們載入生成的 CSV 檔案。確保該 CSV 檔案與你的 app.py 檔案位於同一目錄中。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# --- Load CSV data ---
DATA_FILE = "website_engagement_data.csv" # Make sure this file is generated and in the same directory or provide full path
raw_data = None
def load_engagement_data():
global raw_data
try:
# Generate data if it doesn't exist (for first-time run)
import os
if not os.path.exists(DATA_FILE):
print(f"{DATA_FILE} not found. Generating synthetic data...")
print(f"Please generate '{DATA_FILE}' using the provided script first if it's missing.")
return pd.DataFrame()
dtype_spec = {
'user_id': 'string',
'page_visited': 'category',
'session_duration_seconds': 'int32',
'country': 'category',
'device_type': 'category',
'browser': 'category'
}
raw_data = pd.read_csv(
DATA_FILE,
parse_dates=["timestamp"],
dtype=dtype_spec,
low_memory=False
)
# Ensure timestamp is datetime
raw_data['timestamp'] = pd.to_datetime(raw_data['timestamp'])
print(f"Data loaded successfully: {len(raw_data)} rows.")
except FileNotFoundError:
print(f"Error: The file {DATA_FILE} was not found.")
raw_data = pd.DataFrame() # Return empty dataframe if file not found
except Exception as e:
print(f"An error occurred while loading data: {e}")
raw_data = pd.DataFrame()
return raw_data
# Load data at script startup
load_engagement_data()
# --- Load CSV data --- DATA_FILE = "website_engagement_data.csv" # Make sure this file is generated and in the same directory or provide full path raw_data = None def load_engagement_data(): global raw_data try: # Generate data if it doesn't exist (for first-time run) import os if not os.path.exists(DATA_FILE): print(f"{DATA_FILE} not found. Generating synthetic data...") print(f"Please generate '{DATA_FILE}' using the provided script first if it's missing.") return pd.DataFrame() dtype_spec = { 'user_id': 'string', 'page_visited': 'category', 'session_duration_seconds': 'int32', 'country': 'category', 'device_type': 'category', 'browser': 'category' } raw_data = pd.read_csv( DATA_FILE, parse_dates=["timestamp"], dtype=dtype_spec, low_memory=False ) # Ensure timestamp is datetime raw_data['timestamp'] = pd.to_datetime(raw_data['timestamp']) print(f"Data loaded successfully: {len(raw_data)} rows.") except FileNotFoundError: print(f"Error: The file {DATA_FILE} was not found.") raw_data = pd.DataFrame() # Return empty dataframe if file not found except Exception as e: print(f"An error occurred while loading data: {e}") raw_data = pd.DataFrame() return raw_data # Load data at script startup load_engagement_data()
# --- Load CSV data ---
DATA_FILE = "website_engagement_data.csv" # Make sure this file is generated and in the same directory or provide full path
raw_data = None
def load_engagement_data():
   global raw_data
   try:
       # Generate data if it doesn't exist (for first-time run)
       import os
       if not os.path.exists(DATA_FILE):
           print(f"{DATA_FILE} not found. Generating synthetic data...")
           print(f"Please generate '{DATA_FILE}' using the provided script first if it's missing.")
           return pd.DataFrame()
       dtype_spec = {
           'user_id': 'string',
           'page_visited': 'category',
           'session_duration_seconds': 'int32',
           'country': 'category',
           'device_type': 'category',
           'browser': 'category'
       }
       raw_data = pd.read_csv(
           DATA_FILE,
           parse_dates=["timestamp"],
           dtype=dtype_spec,
           low_memory=False
       )
       # Ensure timestamp is datetime
       raw_data['timestamp'] = pd.to_datetime(raw_data['timestamp'])
       print(f"Data loaded successfully: {len(raw_data)} rows.")
   except FileNotFoundError:
       print(f"Error: The file {DATA_FILE} was not found.")
       raw_data = pd.DataFrame() # Return empty dataframe if file not found
   except Exception as e:
       print(f"An error occurred while loading data: {e}")
       raw_data = pd.DataFrame()
   return raw_data
# Load data at script startup
load_engagement_data()

5. 快取和實用函式

這些函式用於建立快取,以便快速載入資料,從而減少計算時間。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Caching and Utility Functions ---
# Cache for expensive function calls to improve performance
ttl_cache = TTLCache(maxsize=100, ttl=300) # Cache up to 100 items, expire after 5 minutes
@cached(ttl_cache)
def get_unique_filter_values():
if raw_data is None or raw_data.empty:
return [], [], []
pages = sorted(raw_data['page_visited'].dropna().unique().tolist())
devices = sorted(raw_data['device_type'].dropna().unique().tolist())
countries = sorted(raw_data['country'].dropna().unique().tolist())
return pages, devices, countries
def get_date_range_from_data():
if raw_data is None or raw_data.empty:
return date.today(), date.today()
min_dt = raw_data['timestamp'].min().date()
max_dt = raw_data['timestamp'].max().date()
return min_dt, max_dt
# Caching and Utility Functions --- # Cache for expensive function calls to improve performance ttl_cache = TTLCache(maxsize=100, ttl=300) # Cache up to 100 items, expire after 5 minutes @cached(ttl_cache) def get_unique_filter_values(): if raw_data is None or raw_data.empty: return [], [], [] pages = sorted(raw_data['page_visited'].dropna().unique().tolist()) devices = sorted(raw_data['device_type'].dropna().unique().tolist()) countries = sorted(raw_data['country'].dropna().unique().tolist()) return pages, devices, countries def get_date_range_from_data(): if raw_data is None or raw_data.empty: return date.today(), date.today() min_dt = raw_data['timestamp'].min().date() max_dt = raw_data['timestamp'].max().date() return min_dt, max_dt
# Caching and Utility Functions ---
# Cache for expensive function calls to improve performance
ttl_cache = TTLCache(maxsize=100, ttl=300) # Cache up to 100 items, expire after 5 minutes
@cached(ttl_cache)
def get_unique_filter_values():
   if raw_data is None or raw_data.empty:
       return [], [], []
   pages = sorted(raw_data['page_visited'].dropna().unique().tolist())
   devices = sorted(raw_data['device_type'].dropna().unique().tolist())
   countries = sorted(raw_data['country'].dropna().unique().tolist())
   return pages, devices, countries
def get_date_range_from_data():
   if raw_data is None or raw_data.empty:
       return date.today(), date.today()
   min_dt = raw_data['timestamp'].min().date()
   max_dt = raw_data['timestamp'].max().date()
   return min_dt, max_dt

6. 資料過濾和關鍵指標函式

以下函式將用於根據使用者在儀表板上的輸入或操作來過濾資料。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Data Filtering Function ---
def filter_engagement_data(start_date_dt, end_date_dt, selected_page, selected_device, selected_country):
global raw_data
if raw_data is None or raw_data.empty:
return pd.DataFrame()
# Ensure dates are datetime.date objects if they are strings
if isinstance(start_date_dt, str):
start_date_dt = datetime.strptime(start_date_dt, '%Y-%m-%d').date()
if isinstance(end_date_dt, str):
end_date_dt = datetime.strptime(end_date_dt, '%Y-%m-%d').date()
# Convert dates to datetime for comparison with timestamp column
start_datetime = datetime.combine(start_date_dt, datetime.min.time())
end_datetime = datetime.combine(end_date_dt, datetime.max.time())
filtered_df = raw_data[
(raw_data['timestamp'] >= start_datetime) &
(raw_data['timestamp'] <= end_datetime)
].copy()
if selected_page != "All Pages" and selected_page is not None:
filtered_df = filtered_df[filtered_df['page_visited'] == selected_page]
if selected_device != "All Devices" and selected_device is not None:
filtered_df = filtered_df[filtered_df['device_type'] == selected_device]
if selected_country != "All Countries" and selected_country is not None:
filtered_df = filtered_df[filtered_df['country'] == selected_country]
return filtered_df
# Data Filtering Function --- def filter_engagement_data(start_date_dt, end_date_dt, selected_page, selected_device, selected_country): global raw_data if raw_data is None or raw_data.empty: return pd.DataFrame() # Ensure dates are datetime.date objects if they are strings if isinstance(start_date_dt, str): start_date_dt = datetime.strptime(start_date_dt, '%Y-%m-%d').date() if isinstance(end_date_dt, str): end_date_dt = datetime.strptime(end_date_dt, '%Y-%m-%d').date() # Convert dates to datetime for comparison with timestamp column start_datetime = datetime.combine(start_date_dt, datetime.min.time()) end_datetime = datetime.combine(end_date_dt, datetime.max.time()) filtered_df = raw_data[ (raw_data['timestamp'] >= start_datetime) & (raw_data['timestamp'] <= end_datetime) ].copy() if selected_page != "All Pages" and selected_page is not None: filtered_df = filtered_df[filtered_df['page_visited'] == selected_page] if selected_device != "All Devices" and selected_device is not None: filtered_df = filtered_df[filtered_df['device_type'] == selected_device] if selected_country != "All Countries" and selected_country is not None: filtered_df = filtered_df[filtered_df['country'] == selected_country] return filtered_df
# Data Filtering Function ---
def filter_engagement_data(start_date_dt, end_date_dt, selected_page, selected_device, selected_country):
   global raw_data
   if raw_data is None or raw_data.empty:
       return pd.DataFrame()
   # Ensure dates are datetime.date objects if they are strings
   if isinstance(start_date_dt, str):
       start_date_dt = datetime.strptime(start_date_dt, '%Y-%m-%d').date()
   if isinstance(end_date_dt, str):
       end_date_dt = datetime.strptime(end_date_dt, '%Y-%m-%d').date()
   # Convert dates to datetime for comparison with timestamp column
   start_datetime = datetime.combine(start_date_dt, datetime.min.time())
   end_datetime = datetime.combine(end_date_dt, datetime.max.time())
   filtered_df = raw_data[
       (raw_data['timestamp'] >= start_datetime) &
       (raw_data['timestamp'] <= end_datetime)
   ].copy()
   if selected_page != "All Pages" and selected_page is not None:
       filtered_df = filtered_df[filtered_df['page_visited'] == selected_page]
   if selected_device != "All Devices" and selected_device is not None:
       filtered_df = filtered_df[filtered_df['device_type'] == selected_device]
   if selected_country != "All Countries" and selected_country is not None:
       filtered_df = filtered_df[filtered_df['country'] == selected_country]
   return filtered_df

下一個函式將用於計算關鍵指標,如總會話數、獨立使用者數和按訪問者數量排名的首頁。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#Function to Calculate Key Metrics ---
@cached(ttl_cache)
def calculate_key_metrics(start_date_dt, end_date_dt, page, device, country):
df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country)
if df.empty:
return 0, 0, 0, "N/A"
total_sessions = df['user_id'].count() # Assuming each row is a session/interaction
unique_users = df['user_id'].nunique()
avg_session_duration = df['session_duration_seconds'].mean()
if pd.isna(avg_session_duration): # Handle case where mean is NaN (e.g., no sessions)
avg_session_duration = 0
# Top page by number of visits
if not df['page_visited'].mode().empty:
top_page_visited = df['page_visited'].mode()[0]
else:
top_page_visited = "N/A"
return total_sessions, unique_users, round(avg_session_duration, 2), top_page_visited
#Function to Calculate Key Metrics --- @cached(ttl_cache) def calculate_key_metrics(start_date_dt, end_date_dt, page, device, country): df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country) if df.empty: return 0, 0, 0, "N/A" total_sessions = df['user_id'].count() # Assuming each row is a session/interaction unique_users = df['user_id'].nunique() avg_session_duration = df['session_duration_seconds'].mean() if pd.isna(avg_session_duration): # Handle case where mean is NaN (e.g., no sessions) avg_session_duration = 0 # Top page by number of visits if not df['page_visited'].mode().empty: top_page_visited = df['page_visited'].mode()[0] else: top_page_visited = "N/A" return total_sessions, unique_users, round(avg_session_duration, 2), top_page_visited
#Function to Calculate Key Metrics ---
@cached(ttl_cache)
def calculate_key_metrics(start_date_dt, end_date_dt, page, device, country):
   df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country)
   if df.empty:
       return 0, 0, 0, "N/A"
   total_sessions = df['user_id'].count() # Assuming each row is a session/interaction
   unique_users = df['user_id'].nunique()
   avg_session_duration = df['session_duration_seconds'].mean()
   if pd.isna(avg_session_duration): # Handle case where mean is NaN (e.g., no sessions)
       avg_session_duration = 0
   # Top page by number of visits
   if not df['page_visited'].mode().empty:
       top_page_visited = df['page_visited'].mode()[0]
   else:
       top_page_visited = "N/A"
   return total_sessions, unique_users, round(avg_session_duration, 2), top_page_visited

7. 圖形繪製函式

現在我們將使用 Plotly 建立一些圖形繪製函式。這將使我們的儀表盤看起來更加詳細和引人入勝。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Functions for Plotting with Plotly ---
def create_sessions_over_time_plot(start_date_dt, end_date_dt, page, device, country):
df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country)
if df.empty:
fig = go.Figure().update_layout(title_text="No data for selected filters", xaxis_showgrid=False, yaxis_showgrid=False)
return fig
sessions_by_date = df.groupby(df['timestamp'].dt.date)['user_id'].count().reset_index()
sessions_by_date.rename(columns={'timestamp': 'date', 'user_id': 'sessions'}, inplace=True)
fig = px.line(sessions_by_date, x='date', y='sessions', title='User Sessions Over Time')
fig.update_layout(margin=dict(l=20, r=20, t=40, b=20))
return fig
def create_engagement_by_device_plot(start_date_dt, end_date_dt, page, device, country):
df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country)
if df.empty:
fig = go.Figure().update_layout(title_text="No data for selected filters", xaxis_showgrid=False, yaxis_showgrid=False)
return fig
device_engagement = df.groupby('device_type')['session_duration_seconds'].sum().reset_index()
device_engagement.rename(columns={'session_duration_seconds': 'total_duration'}, inplace=True)
fig = px.bar(device_engagement, x='device_type', y='total_duration',
title='Total Session Duration by Device Type', color='device_type')
fig.update_layout(margin=dict(l=20, r=20, t=40, b=20))
return fig
def create_page_visits_distribution_plot(start_date_dt, end_date_dt, page, device, country):
df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country)
if df.empty:
fig = go.Figure().update_layout(title_text="No data for selected filters", xaxis_showgrid=False, yaxis_showgrid=False)
return fig
page_visits = df['page_visited'].value_counts().reset_index()
page_visits.columns = ['page_visited', 'visits']
fig = px.pie(page_visits, names='page_visited', values='visits',
title='Distribution of Page Visits', hole=0.3)
fig.update_layout(margin=dict(l=20, r=20, t=40, b=20))
return fig
# Functions for Plotting with Plotly --- def create_sessions_over_time_plot(start_date_dt, end_date_dt, page, device, country): df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country) if df.empty: fig = go.Figure().update_layout(title_text="No data for selected filters", xaxis_showgrid=False, yaxis_showgrid=False) return fig sessions_by_date = df.groupby(df['timestamp'].dt.date)['user_id'].count().reset_index() sessions_by_date.rename(columns={'timestamp': 'date', 'user_id': 'sessions'}, inplace=True) fig = px.line(sessions_by_date, x='date', y='sessions', title='User Sessions Over Time') fig.update_layout(margin=dict(l=20, r=20, t=40, b=20)) return fig def create_engagement_by_device_plot(start_date_dt, end_date_dt, page, device, country): df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country) if df.empty: fig = go.Figure().update_layout(title_text="No data for selected filters", xaxis_showgrid=False, yaxis_showgrid=False) return fig device_engagement = df.groupby('device_type')['session_duration_seconds'].sum().reset_index() device_engagement.rename(columns={'session_duration_seconds': 'total_duration'}, inplace=True) fig = px.bar(device_engagement, x='device_type', y='total_duration', title='Total Session Duration by Device Type', color='device_type') fig.update_layout(margin=dict(l=20, r=20, t=40, b=20)) return fig def create_page_visits_distribution_plot(start_date_dt, end_date_dt, page, device, country): df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country) if df.empty: fig = go.Figure().update_layout(title_text="No data for selected filters", xaxis_showgrid=False, yaxis_showgrid=False) return fig page_visits = df['page_visited'].value_counts().reset_index() page_visits.columns = ['page_visited', 'visits'] fig = px.pie(page_visits, names='page_visited', values='visits', title='Distribution of Page Visits', hole=0.3) fig.update_layout(margin=dict(l=20, r=20, t=40, b=20)) return fig
# Functions for Plotting with Plotly ---
def create_sessions_over_time_plot(start_date_dt, end_date_dt, page, device, country):
   df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country)
   if df.empty:
       fig = go.Figure().update_layout(title_text="No data for selected filters", xaxis_showgrid=False, yaxis_showgrid=False)
       return fig
   sessions_by_date = df.groupby(df['timestamp'].dt.date)['user_id'].count().reset_index()
   sessions_by_date.rename(columns={'timestamp': 'date', 'user_id': 'sessions'}, inplace=True)
   fig = px.line(sessions_by_date, x='date', y='sessions', title='User Sessions Over Time')
   fig.update_layout(margin=dict(l=20, r=20, t=40, b=20))
   return fig
def create_engagement_by_device_plot(start_date_dt, end_date_dt, page, device, country):
   df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country)
   if df.empty:
       fig = go.Figure().update_layout(title_text="No data for selected filters", xaxis_showgrid=False, yaxis_showgrid=False)
       return fig
   device_engagement = df.groupby('device_type')['session_duration_seconds'].sum().reset_index()
   device_engagement.rename(columns={'session_duration_seconds': 'total_duration'}, inplace=True)
   fig = px.bar(device_engagement, x='device_type', y='total_duration',
                title='Total Session Duration by Device Type', color='device_type')
   fig.update_layout(margin=dict(l=20, r=20, t=40, b=20))
   return fig
def create_page_visits_distribution_plot(start_date_dt, end_date_dt, page, device, country):
   df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country)
   if df.empty:
       fig = go.Figure().update_layout(title_text="No data for selected filters", xaxis_showgrid=False, yaxis_showgrid=False)
       return fig
   page_visits = df['page_visited'].value_counts().reset_index()
   page_visits.columns = ['page_visited', 'visits']
   fig = px.pie(page_visits, names='page_visited', values='visits',
                title='Distribution of Page Visits', hole=0.3)
   fig.update_layout(margin=dict(l=20, r=20, t=40, b=20))
   return fig

8. 表格顯示和資料更新函式

以下函式用於準備表格顯示的資料,並在使用者執行任何函式或輸入後更新儀表板值。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Function to Prepare Data for Table Display ---
def get_data_for_table_display(start_date_dt, end_date_dt, page, device, country):
df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country)
if df.empty:
return pd.DataFrame(columns=['timestamp', 'user_id', 'page_visited', 'session_duration_seconds', 'country', 'device_type', 'browser'])
# Select and order columns for display
display_columns = ['timestamp', 'user_id', 'page_visited', 'session_duration_seconds', 'country', 'device_type', 'browser']
df_display = df[display_columns].copy()
df_display['timestamp'] = df_display['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S') # Format date for display
return df_display.head(100) # Display top 100 rows for performance
#Main Update Function for the Dashboard ---
def update_full_dashboard(start_date_str, end_date_str, selected_page, selected_device, selected_country):
if raw_data is None or raw_data.empty: # Handle case where data loading failed
empty_fig = go.Figure().update_layout(title_text="Data not loaded", xaxis_showgrid=False, yaxis_showgrid=False)
empty_df = pd.DataFrame()
return empty_fig, empty_fig, empty_fig, empty_df, 0, 0, 0.0, "N/A"
# Convert date strings from Gradio input to datetime.date objects
start_date_obj = datetime.strptime(start_date_str, '%Y-%m-%d').date() if isinstance(start_date_str, str) else start_date_str
end_date_obj = datetime.strptime(end_date_str, '%Y-%m-%d').date() if isinstance(end_date_str, str) else end_date_str
# Get key metrics
sessions, users, avg_duration, top_page = calculate_key_metrics(
start_date_obj, end_date_obj, selected_page, selected_device, selected_country
)
# Generate plots
plot_sessions_time = create_sessions_over_time_plot(
start_date_obj, end_date_obj, selected_page, selected_device, selected_country
)
plot_engagement_device = create_engagement_by_device_plot(
start_date_obj, end_date_obj, selected_page, selected_device, selected_country
)
plot_page_visits = create_page_visits_distribution_plot(
start_date_obj, end_date_obj, selected_page, selected_device, selected_country
)
# Get data for table
table_df = get_data_for_table_display(
start_date_obj, end_date_obj, selected_page, selected_device, selected_country
)
return (
plot_sessions_time,
plot_engagement_device,
plot_page_visits,
table_df,
sessions,
users,
avg_duration,
top_page
)
# Function to Prepare Data for Table Display --- def get_data_for_table_display(start_date_dt, end_date_dt, page, device, country): df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country) if df.empty: return pd.DataFrame(columns=['timestamp', 'user_id', 'page_visited', 'session_duration_seconds', 'country', 'device_type', 'browser']) # Select and order columns for display display_columns = ['timestamp', 'user_id', 'page_visited', 'session_duration_seconds', 'country', 'device_type', 'browser'] df_display = df[display_columns].copy() df_display['timestamp'] = df_display['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S') # Format date for display return df_display.head(100) # Display top 100 rows for performance #Main Update Function for the Dashboard --- def update_full_dashboard(start_date_str, end_date_str, selected_page, selected_device, selected_country): if raw_data is None or raw_data.empty: # Handle case where data loading failed empty_fig = go.Figure().update_layout(title_text="Data not loaded", xaxis_showgrid=False, yaxis_showgrid=False) empty_df = pd.DataFrame() return empty_fig, empty_fig, empty_fig, empty_df, 0, 0, 0.0, "N/A" # Convert date strings from Gradio input to datetime.date objects start_date_obj = datetime.strptime(start_date_str, '%Y-%m-%d').date() if isinstance(start_date_str, str) else start_date_str end_date_obj = datetime.strptime(end_date_str, '%Y-%m-%d').date() if isinstance(end_date_str, str) else end_date_str # Get key metrics sessions, users, avg_duration, top_page = calculate_key_metrics( start_date_obj, end_date_obj, selected_page, selected_device, selected_country ) # Generate plots plot_sessions_time = create_sessions_over_time_plot( start_date_obj, end_date_obj, selected_page, selected_device, selected_country ) plot_engagement_device = create_engagement_by_device_plot( start_date_obj, end_date_obj, selected_page, selected_device, selected_country ) plot_page_visits = create_page_visits_distribution_plot( start_date_obj, end_date_obj, selected_page, selected_device, selected_country ) # Get data for table table_df = get_data_for_table_display( start_date_obj, end_date_obj, selected_page, selected_device, selected_country ) return ( plot_sessions_time, plot_engagement_device, plot_page_visits, table_df, sessions, users, avg_duration, top_page )
# Function to Prepare Data for Table Display ---
def get_data_for_table_display(start_date_dt, end_date_dt, page, device, country):
   df = filter_engagement_data(start_date_dt, end_date_dt, page, device, country)
   if df.empty:
       return pd.DataFrame(columns=['timestamp', 'user_id', 'page_visited', 'session_duration_seconds', 'country', 'device_type', 'browser'])
   # Select and order columns for display
   display_columns = ['timestamp', 'user_id', 'page_visited', 'session_duration_seconds', 'country', 'device_type', 'browser']
   df_display = df[display_columns].copy()
   df_display['timestamp'] = df_display['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S') # Format date for display
   return df_display.head(100) # Display top 100 rows for performance
#Main Update Function for the Dashboard ---
def update_full_dashboard(start_date_str, end_date_str, selected_page, selected_device, selected_country):
   if raw_data is None or raw_data.empty: # Handle case where data loading failed
       empty_fig = go.Figure().update_layout(title_text="Data not loaded", xaxis_showgrid=False, yaxis_showgrid=False)
       empty_df = pd.DataFrame()
       return empty_fig, empty_fig, empty_fig, empty_df, 0, 0, 0.0, "N/A"
   # Convert date strings from Gradio input to datetime.date objects
   start_date_obj = datetime.strptime(start_date_str, '%Y-%m-%d').date() if isinstance(start_date_str, str) else start_date_str
   end_date_obj = datetime.strptime(end_date_str, '%Y-%m-%d').date() if isinstance(end_date_str, str) else end_date_str
   # Get key metrics
   sessions, users, avg_duration, top_page = calculate_key_metrics(
       start_date_obj, end_date_obj, selected_page, selected_device, selected_country
   )
   # Generate plots
   plot_sessions_time = create_sessions_over_time_plot(
       start_date_obj, end_date_obj, selected_page, selected_device, selected_country
   )
   plot_engagement_device = create_engagement_by_device_plot(
       start_date_obj, end_date_obj, selected_page, selected_device, selected_country
   )
   plot_page_visits = create_page_visits_distribution_plot(
       start_date_obj, end_date_obj, selected_page, selected_device, selected_country
   )
   # Get data for table
   table_df = get_data_for_table_display(
       start_date_obj, end_date_obj, selected_page, selected_device, selected_country
   )
   return (
       plot_sessions_time,
       plot_engagement_device,
       plot_page_visits,
       table_df,
       sessions,
       users,
       avg_duration,
       top_page
   )

9. 建立Gradio介面

最後,我們將利用上面建立的所有實用函式來建立 Gradio 介面。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Create Gradio Dashboard Interface ---
def build_engagement_dashboard():
unique_pages, unique_devices, unique_countries = get_unique_filter_values()
min_data_date, max_data_date = get_date_range_from_data()
# Set initial dates as strings for Gradio components
initial_start_date_str = min_data_date.strftime('%Y-%m-%d')
initial_end_date_str = max_data_date.strftime('%Y-%m-%d')
with gr.Blocks(theme=gr.themes.Soft(), title="Website Engagement Dashboard") as dashboard_interface:
gr.Markdown("# Website User Engagement Dashboard")
gr.Markdown("Explore user activity trends and engagement metrics for your website. This **Python Gradio dashboard** helps with **Gradio data visualization**.")
# --- Filters Row ---
with gr.Row():
start_date_picker = gr.Textbox(label="Start Date (YYYY-MM-DD)", value=initial_start_date_str, type="text")
end_date_picker = gr.Textbox(label="End Date (YYYY-MM-DD)", value=initial_end_date_str, type="text")
with gr.Row():
page_dropdown = gr.Dropdown(choices=["All Pages"] + unique_pages, label="Page Visited", value="All Pages")
device_dropdown = gr.Dropdown(choices=["All Devices"] + unique_devices, label="Device Type", value="All Devices")
country_dropdown = gr.Dropdown(choices=["All Countries"] + unique_countries, label="Country", value="All Countries")
# --- Key Metrics Display ---
gr.Markdown("## Key Metrics")
with gr.Row():
total_sessions_num = gr.Number(label="Total Sessions", value=0, precision=0)
unique_users_num = gr.Number(label="Unique Users", value=0, precision=0)
avg_duration_num = gr.Number(label="Avg. Session Duration (s)", value=0, precision=2)
top_page_text = gr.Textbox(label="Most Visited Page", value="N/A", interactive=False)
# --- Visualizations Tabs ---
gr.Markdown("## Visualizations")
with gr.Tabs():
with gr.TabItem("Sessions Over Time"):
sessions_plot_output = gr.Plot()
with gr.TabItem("Engagement by Device"):
device_plot_output = gr.Plot()
with gr.TabItem("Page Visit Distribution"):
page_visits_plot_output = gr.Plot()
# --- Raw Data Table ---
gr.Markdown("## Raw Engagement Data (Sample)")
# Corrected: Removed max_rows. The number of rows displayed will be controlled
# by the DataFrame returned by get_data_for_table_display (which returns head(100)).
# Gradio will then paginate or scroll this.
data_table_output = gr.DataFrame(
label="User Sessions Data",
interactive=False,
headers=['Timestamp', 'User ID', 'Page Visited', 'Duration (s)', 'Country', 'Device', 'Browser']
# For display height, you can use the `height` parameter, e.g., height=400
)
# --- Define Inputs & Outputs for Update Function ---
inputs_list = [start_date_picker, end_date_picker, page_dropdown, device_dropdown, country_dropdown]
outputs_list = [
sessions_plot_output, device_plot_output, page_visits_plot_output,
data_table_output,
total_sessions_num, unique_users_num, avg_duration_num, top_page_text
]
# --- Event Handling: Update dashboard when filters change ---
for filter_component in inputs_list:
if isinstance(filter_component, gr.Textbox):
filter_component.submit(fn=update_full_dashboard, inputs=inputs_list, outputs=outputs_list)
else:
filter_component.change(fn=update_full_dashboard, inputs=inputs_list, outputs=outputs_list)
# --- Initial load of the dashboard ---
dashboard_interface.load(
fn=update_full_dashboard,
inputs=inputs_list,
outputs=outputs_list
)
return dashboard_interface
# Create Gradio Dashboard Interface --- def build_engagement_dashboard(): unique_pages, unique_devices, unique_countries = get_unique_filter_values() min_data_date, max_data_date = get_date_range_from_data() # Set initial dates as strings for Gradio components initial_start_date_str = min_data_date.strftime('%Y-%m-%d') initial_end_date_str = max_data_date.strftime('%Y-%m-%d') with gr.Blocks(theme=gr.themes.Soft(), title="Website Engagement Dashboard") as dashboard_interface: gr.Markdown("# Website User Engagement Dashboard") gr.Markdown("Explore user activity trends and engagement metrics for your website. This **Python Gradio dashboard** helps with **Gradio data visualization**.") # --- Filters Row --- with gr.Row(): start_date_picker = gr.Textbox(label="Start Date (YYYY-MM-DD)", value=initial_start_date_str, type="text") end_date_picker = gr.Textbox(label="End Date (YYYY-MM-DD)", value=initial_end_date_str, type="text") with gr.Row(): page_dropdown = gr.Dropdown(choices=["All Pages"] + unique_pages, label="Page Visited", value="All Pages") device_dropdown = gr.Dropdown(choices=["All Devices"] + unique_devices, label="Device Type", value="All Devices") country_dropdown = gr.Dropdown(choices=["All Countries"] + unique_countries, label="Country", value="All Countries") # --- Key Metrics Display --- gr.Markdown("## Key Metrics") with gr.Row(): total_sessions_num = gr.Number(label="Total Sessions", value=0, precision=0) unique_users_num = gr.Number(label="Unique Users", value=0, precision=0) avg_duration_num = gr.Number(label="Avg. Session Duration (s)", value=0, precision=2) top_page_text = gr.Textbox(label="Most Visited Page", value="N/A", interactive=False) # --- Visualizations Tabs --- gr.Markdown("## Visualizations") with gr.Tabs(): with gr.TabItem("Sessions Over Time"): sessions_plot_output = gr.Plot() with gr.TabItem("Engagement by Device"): device_plot_output = gr.Plot() with gr.TabItem("Page Visit Distribution"): page_visits_plot_output = gr.Plot() # --- Raw Data Table --- gr.Markdown("## Raw Engagement Data (Sample)") # Corrected: Removed max_rows. The number of rows displayed will be controlled # by the DataFrame returned by get_data_for_table_display (which returns head(100)). # Gradio will then paginate or scroll this. data_table_output = gr.DataFrame( label="User Sessions Data", interactive=False, headers=['Timestamp', 'User ID', 'Page Visited', 'Duration (s)', 'Country', 'Device', 'Browser'] # For display height, you can use the `height` parameter, e.g., height=400 ) # --- Define Inputs & Outputs for Update Function --- inputs_list = [start_date_picker, end_date_picker, page_dropdown, device_dropdown, country_dropdown] outputs_list = [ sessions_plot_output, device_plot_output, page_visits_plot_output, data_table_output, total_sessions_num, unique_users_num, avg_duration_num, top_page_text ] # --- Event Handling: Update dashboard when filters change --- for filter_component in inputs_list: if isinstance(filter_component, gr.Textbox): filter_component.submit(fn=update_full_dashboard, inputs=inputs_list, outputs=outputs_list) else: filter_component.change(fn=update_full_dashboard, inputs=inputs_list, outputs=outputs_list) # --- Initial load of the dashboard --- dashboard_interface.load( fn=update_full_dashboard, inputs=inputs_list, outputs=outputs_list ) return dashboard_interface
# Create Gradio Dashboard Interface ---
def build_engagement_dashboard():
   unique_pages, unique_devices, unique_countries = get_unique_filter_values()
   min_data_date, max_data_date = get_date_range_from_data()
   # Set initial dates as strings for Gradio components
   initial_start_date_str = min_data_date.strftime('%Y-%m-%d')
   initial_end_date_str = max_data_date.strftime('%Y-%m-%d')
   with gr.Blocks(theme=gr.themes.Soft(), title="Website Engagement Dashboard") as dashboard_interface:
       gr.Markdown("# Website User Engagement Dashboard")
       gr.Markdown("Explore user activity trends and engagement metrics for your website. This **Python Gradio dashboard** helps with **Gradio data visualization**.")
       # --- Filters Row ---
       with gr.Row():
           start_date_picker = gr.Textbox(label="Start Date (YYYY-MM-DD)", value=initial_start_date_str, type="text")
           end_date_picker = gr.Textbox(label="End Date (YYYY-MM-DD)", value=initial_end_date_str, type="text")
       with gr.Row():
           page_dropdown = gr.Dropdown(choices=["All Pages"] + unique_pages, label="Page Visited", value="All Pages")
           device_dropdown = gr.Dropdown(choices=["All Devices"] + unique_devices, label="Device Type", value="All Devices")
           country_dropdown = gr.Dropdown(choices=["All Countries"] + unique_countries, label="Country", value="All Countries")
       # --- Key Metrics Display ---
       gr.Markdown("## Key Metrics")
       with gr.Row():
           total_sessions_num = gr.Number(label="Total Sessions", value=0, precision=0)
           unique_users_num = gr.Number(label="Unique Users", value=0, precision=0)
           avg_duration_num = gr.Number(label="Avg. Session Duration (s)", value=0, precision=2)
           top_page_text = gr.Textbox(label="Most Visited Page", value="N/A", interactive=False)
       # --- Visualizations Tabs ---
       gr.Markdown("## Visualizations")
       with gr.Tabs():
           with gr.TabItem("Sessions Over Time"):
               sessions_plot_output = gr.Plot()
           with gr.TabItem("Engagement by Device"):
               device_plot_output = gr.Plot()
           with gr.TabItem("Page Visit Distribution"):
               page_visits_plot_output = gr.Plot()
       # --- Raw Data Table ---
       gr.Markdown("## Raw Engagement Data (Sample)")
       # Corrected: Removed max_rows. The number of rows displayed will be controlled
       # by the DataFrame returned by get_data_for_table_display (which returns head(100)).
       # Gradio will then paginate or scroll this.
       data_table_output = gr.DataFrame(
           label="User Sessions Data",
           interactive=False,
           headers=['Timestamp', 'User ID', 'Page Visited', 'Duration (s)', 'Country', 'Device', 'Browser']
           # For display height, you can use the `height` parameter, e.g., height=400
       )
       # --- Define Inputs & Outputs for Update Function ---
       inputs_list = [start_date_picker, end_date_picker, page_dropdown, device_dropdown, country_dropdown]
       outputs_list = [
           sessions_plot_output, device_plot_output, page_visits_plot_output,
           data_table_output,
           total_sessions_num, unique_users_num, avg_duration_num, top_page_text
       ]
       # --- Event Handling: Update dashboard when filters change ---
       for filter_component in inputs_list:
           if isinstance(filter_component, gr.Textbox):
                filter_component.submit(fn=update_full_dashboard, inputs=inputs_list, outputs=outputs_list)
           else:
                filter_component.change(fn=update_full_dashboard, inputs=inputs_list, outputs=outputs_list)
       # --- Initial load of the dashboard ---
       dashboard_interface.load(
           fn=update_full_dashboard,
           inputs=inputs_list,
           outputs=outputs_list
       )
   return dashboard_interface

10. 執行Gradio的主執行函式

這裡我們執行的是主函式 build_engagement_dashboard,它將為 Web 應用程式的啟動準備介面。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# --- Main execution block ---
if __name__ == "__main__":
if raw_data is None or raw_data.empty:
print("Halting: Data could not be loaded. Please ensure 'website_engagement_data.csv' exists or can be generated.")
else:
print("Building and launching the Gradio dashboard...")
engagement_dashboard = build_engagement_dashboard()
engagement_dashboard.launch(server_name="0.0.0.0") # Makes it accessible on local network
print("Dashboard is running. Open your browser to the provided URL.")
# --- Main execution block --- if __name__ == "__main__": if raw_data is None or raw_data.empty: print("Halting: Data could not be loaded. Please ensure 'website_engagement_data.csv' exists or can be generated.") else: print("Building and launching the Gradio dashboard...") engagement_dashboard = build_engagement_dashboard() engagement_dashboard.launch(server_name="0.0.0.0") # Makes it accessible on local network print("Dashboard is running. Open your browser to the provided URL.")
# --- Main execution block ---
if __name__ == "__main__":
   if raw_data is None or raw_data.empty:
       print("Halting: Data could not be loaded. Please ensure 'website_engagement_data.csv' exists or can be generated.")
   else:
       print("Building and launching the Gradio dashboard...")
       engagement_dashboard = build_engagement_dashboard()
       engagement_dashboard.launch(server_name="0.0.0.0") # Makes it accessible on local network
       print("Dashboard is running. Open your browser to the provided URL.")

現在,在終端中執行 Python app.py 來執行 Web 應用程式。

輸出:

執行Gradio的主執行函式

單擊本地 URL 連結以啟動 Gradio 介面。

輸出:

執行Gradio的主執行函式

一個互動式儀表板已建立。我們可以使用此介面以互動方式分析資料集並輕鬆獲取見解。

互動式儀表板

我們可以看到基於不同過濾器的視覺化效果。

基於不同過濾器的視覺化效果 基於不同過濾器的視覺化效果

小結

Gradio 可以有效地從海量資料集中獲取洞察。透過建立互動式視覺化儀表板,資料分析過程可以更加引人入勝。如果您完成了本詳細指南,那麼您將能夠高效地使用 Gradio 建立互動式儀表板。我們涵蓋了資料生成、載入、快取、定義過濾邏輯、計算指標以及使用 Plotly 建立圖表。無需任何前端程式設計和技術知識即可構建此儀表板。雖然我們在本指南中使用了 CSV,但您可以根據需要使用任何其他資料來源。事實證明,Gradio 是一款建立動態且使用者友好的儀表板的寶貴工具。

評論留言