The error AttributeError: module 'plotly.express' has no attribute 'Figure' occurs because px.Figure is not a valid attribute in Plotly Express. Instead, Plotly Express functions like px.bar() return a plotly.graph_objects.Figure object, which is defined in the plotly.graph_objects module, not in plotly.express.
To fix this, you need to update the type hint in the create_chart method to use plotly.graph_objects.Figure instead of px.Figure. Here's the corrected version of the relevant part of your code, along with the necessary import:
Corrected Code
import sys
import os
from typing import Optional
import sqlite3
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go # Import graph_objects for Figure type
from datetime import datetime
class ScreenTimeAnalyzer:
"""Class to analyze and visualize screen time data."""
def __init__(self, db_path: str):
"""Initialize with database path."""
self.db_path = db_path
self._validate_database_path()
def _validate_database_path(self) -> None:
"""Validate if the database file exists."""
if not os.path.exists(self.db_path):
raise FileNotFoundError(f"Database file '{self.db_path}' does not exist.")
@staticmethod
def _get_db_connection(db_path: str) -> sqlite3.Connection:
"""Create and return a database connection."""
return sqlite3.connect(db_path)
def get_screen_time_data(self) -> pd.DataFrame:
"""Retrieve screen time data from the database."""
query = """
SELECT _id, _from, _duration
FROM screen_events
WHERE _duration > 0 -- Filter out invalid durations
"""
try:
with self._get_db_connection(self.db_path) as conn:
# Use chunksize for memory efficiency with large datasets
return pd.read_sql_query(query, conn, chunksize=10000).read()
except sqlite3.Error as e:
raise RuntimeError(f"Database error: {str(e)}")
@staticmethod
def process_daily_usage(df: pd.DataFrame) -> pd.DataFrame:
"""Process raw data to get daily usage statistics."""
# Create a copy to avoid modifying original dataframe
df_processed = df.copy()
# Convert timestamp and extract date in one step
df_processed['date'] = pd.to_datetime(
df_processed['_from'],
unit='ms'
).dt.date
# Convert duration to hours using vectorized operation
df_processed['duration_hours'] = df_processed['_duration'] / 3.6e6 # More efficient than multiple multiplications
# Group and aggregate
return (df_processed
.groupby('date', as_index=False)
.agg({'duration_hours': 'sum'})
.sort_values('date'))
@staticmethod
def create_chart(daily_usage: pd.DataFrame) -> go.Figure: # Use go.Figure instead of px.Figure
"""Create a bar chart of daily screen time usage."""
fig = px.bar(
daily_usage,
x='date',
y='duration_hours',
title='Daily Screen Time Usage',
labels={
'date': 'Date',
'duration_hours': 'Screen Time (Hours)'
},
template='plotly_white' # Use built-in template instead of custom styling
)
# Update layout with minimal necessary customizations
fig.update_layout(
bargap=0.2,
showlegend=False,
xaxis_title="Date",
yaxis_title="Screen Time (Hours)",
yaxis={'gridcolor': 'lightgrey', 'gridwidth': 0.5}
)
return fig
def analyze_and_visualize(self) -> None:
"""Main method to run the analysis and visualization pipeline."""
try:
# Get and process data
raw_data = self.get_screen_time_data()
if raw_data.empty:
raise ValueError("No data found in the database.")
daily_usage = self.process_daily_usage(raw_data)
# Create and show visualization
fig = self.create_chart(daily_usage)
fig.show()
print("Visualization completed successfully.")
except Exception as e:
print(f"Error during analysis: {str(e)}")
sys.exit(1)
def validate_arguments() -> str:
"""Validate command line arguments and return database path."""
if len(sys.argv) != 2:
print("Usage: python script_name.py database_file")
sys.exit(1)
return sys.argv[1]
def main() -> None:
"""Main entry point of the application."""
db_path = validate_arguments()
analyzer = ScreenTimeAnalyzer(db_path)
analyzer.analyze_and_visualize()
if __name__ == "__main__":
main()