Make this code more readable, better performance
import sqlite3
import pandas as pd
import plotly.express as px
from datetime import datetime
import sys
import os
if len(sys.argv) != 2:
print("Usage: python script_name.py database_file")
sys.exit(1)
elif not os.path.exists(sys.argv[1]):
print(f"Error: The database file '{sys.argv[1]}' does not exist.")
sys.exit(1)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
def process_daily_usage(df):
# Convert timestamp from milliseconds to datetime
df['date'] = pd.to_datetime(df['_from'], unit='ms')
# Extract just the date part (without time)
df['date'] = df['date'].dt.date
# Convert duration from milliseconds to hours
df['duration_hours'] = df['_duration'] / (1000 * 60 * 60)
# Group by date and sum the durations
daily_usage = df.groupby('date')['duration_hours'].sum().reset_index()
return daily_usage
# Customize the layout
fig.update_layout(
xaxis_title="Date",
yaxis_title="Screen Time (Hours)",
bargap=0.2,
showlegend=False,
plot_bgcolor='white'
)
# Add gridlines
fig.update_yaxes(gridcolor='lightgrey', gridwidth=0.5)
return fig
def main():
# Replace 'your_database.db' with your actual database file path
db_path = database_filename
try:
# Get data from database
df = get_screen_time_data(db_path)
# Process data
daily_usage = process_daily_usage(df)
# Create chart
fig = create_chart(daily_usage)
# Show the chart in browser
fig.show()
print("Opened.")
except Exception as e:
print(f"An error occurred: {str(e)}")
if name == "main":
main()
Assistant
Here's a more readable and optimized version of your code with better organization, error handling, and documentation:
#!/usr/bin/env python3
"""
Screen Time Analysis Script
This script analyzes screen time data from a SQLite database and creates a visualization.
"""
import os
import sys
from typing import Optional
import sqlite3
import pandas as pd
import plotly.express as px
from datetime import datetime
# Constants
MS_TO_HOURS = 1000 * 60 * 60 # Conversion factor from milliseconds to hours
DEFAULT_CHART_CONFIG = {
'bargap': 0.2,
'showlegend': False,
'plot_bgcolor': 'white'
}
class ScreenTimeAnalyzer:
def __init__(self, database_path: str):
"""Initialize the analyzer with database path."""
self.database_path = database_path
self.validate_database()
def validate_database(self) -> None:
"""Validate if the database file exists."""
if not os.path.exists(self.database_path):
raise FileNotFoundError(f"Database file '{self.database_path}' not found.")
def fetch_data(self) -> pd.DataFrame:
"""Fetch screen time data from SQLite database."""
try:
with sqlite3.connect(self.database_path) as conn:
query = "SELECT _id, _from, _duration FROM screen_events"
return pd.read_sql_query(query, conn)
except sqlite3.Error as e:
raise DatabaseError(f"Database error: {str(e)}")
def process_daily_usage(self, df: pd.DataFrame) -> pd.DataFrame:
"""Process raw data to calculate daily usage statistics."""
df['date'] = pd.to_datetime(df['_from'], unit='ms').dt.date
df['duration_hours'] = df['_duration'] / MS_TO_HOURS
return df.groupby('date')['duration_hours'].sum().reset_index()
def create_visualization(self, daily_usage: pd.DataFrame) -> px.Figure:
"""Create an interactive 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)'}
)
fig.update_layout(
xaxis_title="Date",
yaxis_title="Screen Time (Hours)",
**DEFAULT_CHART_CONFIG
)
fig.update_yaxes(gridcolor='lightgrey', gridwidth=0.5)
return fig
def analyze(self) -> Optional[px.Figure]:
"""Perform complete analysis and return visualization."""
try:
raw_data = self.fetch_data()
daily_usage = self.process_daily_usage(raw_data)
return self.create_visualization(daily_usage)
except Exception as e:
print(f"Analysis failed: {str(e)}")
return None
class DatabaseError(Exception):
"""Custom exception for database-related errors."""
pass
def parse_arguments() -> str:
"""Parse and validate command line arguments."""
if len(sys.argv) != 2:
print("Usage: python script_name.py database_file")
sys.exit(1)
return sys.argv[1]
def main():
"""Main execution function."""
try:
database_path = parse_arguments()
analyzer = ScreenTimeAnalyzer(database_path)
figure = analyzer.analyze()
if figure:
figure.show()
print("Visualization opened in browser.")
except Exception as e:
print(f"Error: {str(e)}")
sys.exit(1)
if __name__ == "__main__":
main()
User
AttributeError: module 'plotly.express' has no attribute 'Figure'
Assistant
The error occurs because px.Figure is not the correct type hint. Here's the corrected version using the proper type hint from plotly.graph_objects:
#!/usr/bin/env python3
"""
Screen Time Analysis Script
This script analyzes screen time data from a SQLite database and creates a visualization.
"""
import os
import sys
from typing import Optional
import sqlite3
import pandas as pd
import plotly.express as px
from plotly.graph_objects import Figure
from datetime import datetime
# Constants
MS_TO_HOURS = 1000 * 60 * 60 # Conversion factor from milliseconds to hours
DEFAULT_CHART_CONFIG = {
'bargap': 0.2,
'showlegend': False,
'plot_bgcolor': 'white'
}
class ScreenTimeAnalyzer:
def __init__(self, database_path: str):
"""Initialize the analyzer with database path."""
self.database_path = database_path
self.validate_database()
def validate_database(self) -> None:
"""Validate if the database file exists."""
if not os.path.exists(self.database_path):
raise FileNotFoundError(f"Database file '{self.database_path}' not found.")
def fetch_data(self) -> pd.DataFrame:
"""Fetch screen time data from SQLite database."""
try:
with sqlite3.connect(self.database_path) as conn:
query = "SELECT _id, _from, _duration FROM screen_events"
return pd.read_sql_query(query, conn)
except sqlite3.Error as e:
raise DatabaseError(f"Database error: {str(e)}")
def process_daily_usage(self, df: pd.DataFrame) -> pd.DataFrame:
"""Process raw data to calculate daily usage statistics."""
df['date'] = pd.to_datetime(df['_from'], unit='ms').dt.date
df['duration_hours'] = df['_duration'] / MS_TO_HOURS
return df.groupby('date')['duration_hours'].sum().reset_index()
def create_visualization(self, daily_usage: pd.DataFrame) -> Figure:
"""Create an interactive 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)'}
)
fig.update_layout(
xaxis_title="Date",
yaxis_title="Screen Time (Hours)",
**DEFAULT_CHART_CONFIG
)
fig.update_yaxes(gridcolor='lightgrey', gridwidth=0.5)
return fig
def analyze(self) -> Optional[Figure]:
"""Perform complete analysis and return visualization."""
try:
raw_data = self.fetch_data()
daily_usage = self.process_daily_usage(raw_data)
return self.create_visualization(daily_usage)
except Exception as e:
print(f"Analysis failed: {str(e)}")
return None
class DatabaseError(Exception):
"""Custom exception for database-related errors."""
pass
def parse_arguments() -> str:
"""Parse and validate command line arguments."""
if len(sys.argv) != 2:
print("Usage: python script_name.py database_file")
sys.exit(1)
return sys.argv[1]
def main():
"""Main execution function."""
try:
database_path = parse_arguments()
analyzer = ScreenTimeAnalyzer(database_path)
figure = analyzer.analyze()
if figure:
figure.show()
print("Visualization opened in browser.")
except Exception as e:
print(f"Error: {str(e)}")
sys.exit(1)
if __name__ == "__main__":
main()
Better Organization: Created a ScreenTimeAnalyzer class to encapsulate all related functionality.
Type Hints: Added type hints to improve code readability and IDE support.
Better Error Handling: Implemented more specific error handling with custom exceptions.
Constants: Moved magic numbers and configuration to constants.
Documentation: Added docstrings and comments to explain the code's functionality.
Context Managers: Used with statement for database connections to ensure proper resource cleanup.
Modular Design: Split functionality into smaller, more focused methods.
Input Validation: Added more robust input validation.
Resource Management: Improved resource handling with proper cleanup.
To use this script:
python script_name.py path_to_database.db
This version is more maintainable, easier to test, and follows better Python practices. The code is more organized and each component has a single responsibility, making it easier to modify or extend in the future.
The main change is importing Figure from plotly.graph_objects instead of trying to use px.Figure. This provides the correct type hint for Plotly figures. The rest of the functionality remains the same.