Follower_Predictions / src /streamlit_app.py
besimabdulai's picture
Update src/streamlit_app.py
c2f3a3f verified
Raw History Blame Contribute Delete
12.6 kB
import streamlit as st
import pandas as pd
import plotly.express as px
import io
import re
# =========================
# 1. Global Constants
# =========================
PRIMARY_KEY = 'DateTime'
REQUIRED_COLUMNS = [
'DateTime',
'Interactions_Insta',
'Follower_Insta',
'Organic_Follower_Lin',
'Paid_Follower_Lin',
'Engagement_Rate_Lin'
]
# Mapping for common column name variations to the REQUIRED_COLUMNS format
COLUMN_RENAMES = {
'Follower Insta': 'Follower_Insta',
'Followers_Insta': 'Follower_Insta',
'Instagram Followers': 'Follower_Insta',
'Follower (Instagram)': 'Follower_Insta',
'Insta_Followers': 'Follower_Insta',
'Organic Follower Lin': 'Organic_Follower_Lin',
'Paid Follower Lin': 'Paid_Follower_Lin',
'Engagement Rate Lin': 'Engagement_Rate_Lin',
'Interactions Insta': 'Interactions_Insta',
# Add more renames as needed
}
# =========================
# 2. Helper functions (copied from notebook)
# =========================
def standardize_dataframe(file_name: str, file_bytes: bytes) -> pd.DataFrame:
# Attempt to read CSV with semicolon separator first, then comma
try:
df = pd.read_csv(io.BytesIO(file_bytes), sep=';')
except Exception:
df = pd.read_csv(io.BytesIO(file_bytes), sep=',')
df.columns = [str(c).strip() for c in df.columns]
# Apply column renames based on COLUMN_RENAMES dictionary
new_columns = []
for col in df.columns:
if col in COLUMN_RENAMES:
new_columns.append(COLUMN_RENAMES[col])
else:
new_columns.append(col)
df.columns = new_columns
# Try to intelligently find the primary key column if 'DateTime' isn't explicitly found
# This part can be more robust, but for now, we'll rely on explicit PRIMARY_KEY matching
if PRIMARY_KEY not in df.columns:
date_cols = [col for col in df.columns if 'date' in col.lower() or 'time' in col.lower()]
if date_cols:
df.rename(columns={date_cols[0]: PRIMARY_KEY}, inplace=True)
st.warning(f"Renamed '{date_cols[0]}' to '{PRIMARY_KEY}' in '{file_name}'.")
else:
raise ValueError(f"The file '{file_name}' does not contain the required primary key column: {PRIMARY_KEY} or any recognizable date/time column.")
available_columns = [col for col in REQUIRED_COLUMNS if col in df.columns]
if len(available_columns) <= 1: # Only DateTime is available
metric_cols_in_file = [col for col in df.columns if col != PRIMARY_KEY]
if metric_cols_in_file:
raise ValueError(f"The file '{file_name}' contains metrics ({', '.join(metric_cols_in_file)}) but none match the required metrics: {', '.join([c for c in REQUIRED_COLUMNS if c != PRIMARY_KEY])} after mapping. Please ensure column names are compatible or adjust COLUMN_RENAMES.")
else:
raise ValueError(f"The file '{file_name}' does not contain any of the required metric columns.")
df = df[available_columns].copy()
df[PRIMARY_KEY] = pd.to_datetime(df[PRIMARY_KEY], errors='coerce')
df = df[df[PRIMARY_KEY].notna()].copy()
df[PRIMARY_KEY] = df[PRIMARY_KEY].dt.normalize()
metric_columns = [c for c in df.columns if c != PRIMARY_KEY]
for col in metric_columns:
if df[col].dtype == object:
df[col] = (
df[col]
.astype(str)
.str.replace('%', '', regex=False)
.str.replace(',', '.', regex=False)
.str.strip()
)
df[col] = pd.to_numeric(df[col], errors='coerce')
df = df.groupby(PRIMARY_KEY, as_index=False).sum(numeric_only=True)
return df
def merge_dataframes(dfs):
if not dfs:
raise ValueError('No valid CSV files were loaded.')
merged = dfs[0].copy()
for df_to_merge in dfs[1:]:
merged = pd.merge(merged, df_to_merge, on=PRIMARY_KEY, how='outer')
merged = merged.sort_values(PRIMARY_KEY).reset_index(drop=True)
return merged
def create_long_format_for_chart(df: pd.DataFrame) -> pd.DataFrame:
id_vars = [PRIMARY_KEY]
value_vars = [col for col in df.columns if col not in id_vars]
df_long = df.melt(id_vars=id_vars, value_vars=value_vars, var_name='Metric', value_name='Value')
return df_long
def build_streamlit_interactive_chart(df_merged_data: pd.DataFrame):
st.subheader("Interactive Metrics Chart")
df_long = create_long_format_for_chart(df_merged_data)
# Filter out NaN values from Value, as Plotly can struggle with them
df_long_cleaned = df_long.dropna(subset=['Value'])
if df_long_cleaned.empty:
st.warning("No data available for charting after cleaning. Please check your uploaded files and selections.")
return
metric_options = sorted(df_long_cleaned['Metric'].unique().tolist())
if not metric_options:
st.warning("No metrics found in the data for charting.")
return
# Streamlit widgets for chart controls
col1, col2 = st.columns(2)
with col1:
x_axis_options = [PRIMARY_KEY] + metric_options
x_col = st.selectbox('Select X-axis:', options=x_axis_options, index=0)
with col2:
# Initial value for y-axis: try to select a meaningful metric if possible
default_y_index = 0
if 'Follower_Insta' in metric_options:
default_y_index = metric_options.index('Follower_Insta')
elif 'Interactions_Insta' in metric_options:
default_y_index = metric_options.index('Interactions_Insta')
elif 'Organic_Follower_Lin' in metric_options:
default_y_index = metric_options.index('Organic_Follower_Lin')
y_col = st.selectbox('Select Y-axis:', options=metric_options, index=default_y_index)
col3, col4 = st.columns(2)
with col3:
color_options = ['None'] + metric_options
color_col = st.selectbox('Color by:', options=color_options, index=0)
with col4:
chart_type = st.selectbox('Chart Type:', options=['line', 'bar', 'scatter'])
# --- Chart Generation Logic ---
if not y_col:
st.info("Please select a Y-axis metric to generate the chart.")
return
# Determine the DataFrame to use for plotting
df_plot = df_long_cleaned[df_long_cleaned['Metric'] == y_col].copy()
# If x_col is a metric, we need to bring its values into df_plot.
# This involves merging the original wide df back in, or doing a more complex melt/pivot
# For simplicity, if x_col is a metric, we use the original merged_df to get its values.
# This logic assumes we want to plot `y_col`'s value against `x_col`'s value on the same dates.
x_source_data = None
if x_col == PRIMARY_KEY:
x_source_data = df_plot[PRIMARY_KEY]
x_label = PRIMARY_KEY
elif x_col != 'None' and x_col in df_merged_data.columns:
# Merge the x_col metric values back into df_plot by PRIMARY_KEY
df_x_metric = df_merged_data[[PRIMARY_KEY, x_col]].copy()
df_plot = pd.merge(df_plot, df_x_metric, on=PRIMARY_KEY, how='left')
x_source_data = df_plot[x_col]
x_label = x_col
else:
# Fallback if x_col is 'None' or unrecognized metric, though selectbox prevents this
x_source_data = df_plot[PRIMARY_KEY]
x_label = PRIMARY_KEY
# Handle coloring
color_param = None
if color_col != 'None':
if color_col == y_col: # If coloring by the y-axis metric, Plotly can handle 'Value' directly
color_param = 'Metric' # or could be a categorical binning of 'Value'
elif color_col == x_col and x_col != PRIMARY_KEY:
color_param = x_col # if x_col is a metric, use its column name
else:
# If coloring by another metric, we need to ensure it's available and merged if necessary
# For simplicity for now, let's allow coloring by the selected Y-axis metric or no coloring
# Advanced coloring by a *third* metric would require further merging/reshaping.
st.warning(f"Coloring by '{color_col}' is not directly supported with current logic for a single y_col selection. Choose 'None' or a categorical variable from the original data if available.")
color_param = None # Revert to no coloring for complex cases
title = f'{y_col} vs {x_label}'
labels = {PRIMARY_KEY: 'Date', 'Value': y_col, x_label: x_label} # Labels for the plot
# Plotly Charting
fig = None
if chart_type == 'line':
fig = px.line(
df_plot,
x=PRIMARY_KEY if x_col == PRIMARY_KEY else x_col,
y='Value',
color=color_param, # This will color by metric name if y_col is selected
title=title,
labels=labels
)
elif chart_type == 'bar':
fig = px.bar(
df_plot,
x=PRIMARY_KEY if x_col == PRIMARY_KEY else x_col,
y='Value',
color=color_param,
title=title,
labels=labels
)
elif chart_type == 'scatter':
fig = px.scatter(
df_plot,
x=PRIMARY_KEY if x_col == PRIMARY_KEY else x_col,
y='Value',
color=color_param,
title=title,
labels=labels
)
if fig:
fig.update_layout(hovermode="x unified")
st.plotly_chart(fig, use_container_width=True)
else:
st.warning("Could not generate chart. Please check selections.")
def main():
st.set_page_config(layout="wide")
st.title('Social Media Analytics Dashboard')
st.markdown("""
Welcome to the **Social Media Analytics Dashboard**!
This application allows you to:
1. **Upload multiple CSV files** containing social media metrics (e.g., Instagram, LinkedIn).
2. **View** the processed and merged data.
3. **Explore** an interactive chart to visualize trends across different metrics.
""")
# --- File Uploader ---
st.sidebar.header('Upload your data')
uploaded_files = st.sidebar.file_uploader("Upload your input CSV files", type=["csv"], accept_multiple_files=True)
merged_df = None
processing_log = []
if uploaded_files:
standardized_dfs = []
for uploaded_file in uploaded_files:
file_name = uploaded_file.name
file_bytes = uploaded_file.getvalue()
try:
std_df = standardize_dataframe(file_name, file_bytes)
standardized_dfs.append(std_df)
processing_log.append({
'file_name': file_name,
'status': 'loaded',
'rows_loaded': len(std_df),
'columns_loaded': ', '.join(std_df.columns)
})
except Exception as e:
processing_log.append({
'file_name': file_name,
'status': f'error: {str(e)}',
'rows_loaded': 0,
'columns_loaded': ''
})
log_df = pd.DataFrame(processing_log)
st.subheader('File Processing Log')
st.dataframe(log_df, use_container_width=True)
if standardized_dfs:
try:
merged_df = merge_dataframes(standardized_dfs)
# Fill any NaN values that result from outer merge (for metrics not present in all files)
metric_cols = [col for col in merged_df.columns if col != PRIMARY_KEY]
merged_df[metric_cols] = merged_df[metric_cols].fillna(0)
st.subheader('Merged Data Preview')
st.dataframe(merged_df.head(), use_container_width=True)
st.success("Data successfully merged and processed.")
# --- Interactive Metrics Chart ---
build_streamlit_interactive_chart(merged_df)
# --- Download Merged Data Option ---
csv_export = merged_df.to_csv(index=False).encode('utf-8')
st.download_button(
label="Download Merged Data as CSV",
data=csv_export,
file_name='merged_social_media_data.csv',
mime='text/csv',
help="Click here to download the combined and processed social media data."
)
except Exception as e:
st.error(f"Error merging data: {e}")
else:
st.warning("No valid files were processed for merging.")
else:
st.info("Upload CSV files in the sidebar to get started.")
if __name__ == '__main__':
main()