import streamlit as st import pandas as pd import plotly.express as px import plotly.graph_objects as go from collections import Counter import re import gc # --- PAGE CONFIG --- st.set_page_config(page_title="Kenya Propaganda Tracker", layout="wide", page_icon="πŸ•΅οΈ") # --- CUSTOM CSS FOR UI/UX --- st.markdown(""" """, unsafe_allow_html=True) st.title("πŸ•΅οΈ Kenya Propaganda Tracker") st.markdown("#### *Forensic Analysis of Coordinated Social Media Campaigns*") st.markdown("---") # --- SIDEBAR --- with st.sidebar: st.header("πŸ“ Data Ingestion") uploaded_file = st.file_uploader("Upload Tracker CSV/Excel", type=['csv', 'xlsx']) if uploaded_file: try: df = pd.read_csv(uploaded_file) if uploaded_file.name.endswith('.csv') else pd.read_excel(uploaded_file) # Auto-fill missing dates for manual trackers date_col_guess = [c for c in df.columns if 'date' in c.lower() or '/' in c.lower()] if date_col_guess: df[date_col_guess[0]] = df[date_col_guess[0]].ffill() st.success("βœ… Data Loaded") except Exception as e: st.error(f"Load Error: {e}") st.stop() st.divider() st.header("πŸ”§ Mapping") cols = df.columns.tolist() time_col = st.selectbox("Timestamp", cols, index=0) user_col = st.selectbox("Actor/Hashtag", cols, index=1 if len(cols)>1 else 0) text_col = st.selectbox("Content/Text", cols, index=3 if len(cols)>3 else 0) run = st.button("πŸš€ Run Forensic Analysis", type="primary", use_container_width=True) # --- MAIN ANALYSIS --- if uploaded_file and run: # DATA CLEANING df['dt_clean'] = pd.to_datetime(df[time_col].astype(str).str.replace('.', ':'), errors='coerce', dayfirst=True) df = df.dropna(subset=['dt_clean']) df['dt_clean'] = df['dt_clean'].dt.tz_localize(None) df = df.sort_values('dt_clean') # METRICS CALCULATION total_entries = len(df) unique_actors = df[user_col].nunique() duplicates = df[text_col].duplicated().sum() coord_score = (duplicates / total_entries) * 100 if total_entries > 0 else 0 # --- TOP METRICS ROW --- m1, m2, m3, m4 = st.columns(4) m1.metric("Total Records", f"{total_entries:,}") m2.metric("Unique Sources", f"{unique_actors:,}") # Color-coded Coordination Score if coord_score > 15: m3.markdown(f"

Coordination Score

{coord_score:.1f}%

🚨 High Risk

", unsafe_allow_html=True) else: m3.metric("Coordination Score", f"{coord_score:.1f}%", delta="Low Risk", delta_color="normal") m4.metric("Avg Posts/Source", f"{total_entries/unique_actors:.1f}") # --- TABS FOR UX --- tab1, tab2, tab3 = st.tabs(["πŸ“ˆ Activity Timeline", "πŸ” Pattern Detection", "πŸ” Evidence Deep-Dive"]) with tab1: st.subheader("Campaign Pulse") # Robust grouping instead of resample df['date_only'] = df['dt_clean'].dt.date timeline = df.groupby('date_only').size().reset_index(name='count') fig = px.area(timeline, x='date_only', y='count', title="Daily Activity Volume") fig.update_traces(line_color='#1d3557', fillcolor='rgba(29, 53, 87, 0.2)') fig.update_layout(hovermode="x unified", plot_bgcolor="white") st.plotly_chart(fig, use_container_width=True) st.info("πŸ’‘ **Insight:** Look for 'Inorganic Bursts'β€”sudden vertical climbs in activity that don't match natural news cycles.") with tab2: c_left, c_right = st.columns(2) with c_left: st.subheader("Top Recurring Scripts") scripts = df[text_col].value_counts().head(10).reset_index() scripts.columns = ['Message', 'Frequency'] st.dataframe(scripts, use_container_width=True, hide_index=True) st.caption("Identical text shared by multiple sources is the 'Smoking Gun' of coordination.") with c_right: st.subheader("Main Narrative Drivers") actors = df[user_col].value_counts().head(10).reset_index() actors.columns = ['Source', 'Volume'] fig_bar = px.bar(actors, x='Volume', y='Source', orientation='h', color='Volume', color_continuous_scale='Blues') st.plotly_chart(fig_bar, use_container_width=True) with tab3: st.subheader("Raw Evidence Log") st.write("Filter and search through the suspicious entries below.") # Clean display table display_df = df[[time_col, user_col, text_col]].copy() display_df.columns = ['Time', 'Source', 'Content'] st.dataframe(display_df, use_container_width=True, hide_index=True) st.download_button( "πŸ“₯ Export Evidence for Reporting", df.to_csv(index=False).encode('utf-8'), "propaganda_report.csv", "text/csv", use_container_width=True ) # --- AUTOMATED SUMMARY BOX --- st.markdown("---") with st.expander("πŸ“ **Generate Automated Editorial Summary**", expanded=True): peak_date = timeline.loc[timeline['count'].idxmax(), 'date_only'] top_script = scripts.iloc[0]['Message'][:100] if not scripts.empty else "N/A" summary_text = f""" **Investigation Findings:** - This dataset contains **{total_entries}** records with a **{coord_score:.1f}%** coordination rate. - Activity peaked on **{peak_date}**, suggesting a concentrated push. - The most repeated narrative involves: *"{top_script}..."* - **Conclusion:** {"The high volume of identical content suggests a coordinated influence operation." if coord_score > 10 else "The activity appears largely organic with low levels of repetition."} """ st.markdown(summary_text) else: # Landing Page UX st.empty() c1, c2, c3 = st.columns([1,2,1]) with c2: st.markdown("""

πŸ•΅οΈ Ready for Investigation

Upload your tracker file in the sidebar to begin forensic analysis.

""", unsafe_allow_html=True) st.info("Welcome, Journalist. Please upload your X/Twitter tracker file in the sidebar to begin the forensic analysis.")