Spaces:
Runtime error
Runtime error
File size: 7,181 Bytes
5e56620 f6fdc57 5e56620 e67e704 0910bd7 5e56620 e67e704 3a92543 5e56620 7c7f08f e67e704 5e56620 e67e704 7c7f08f 8c6321b e67e704 b498c2e 7c7f08f b498c2e 7c7f08f b498c2e 8c6321b 7c7f08f b498c2e 7c7f08f 8c6321b 7c7f08f 5e56620 aeec4a6 e67e704 7c7f08f 3a92543 7c7f08f 0910bd7 7c7f08f 0910bd7 7c7f08f 3a92543 7c7f08f 0910bd7 7c7f08f 9c6610c 7c7f08f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | 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("""
<style>
.main { background-color: #f8f9fa; }
.stMetric { background-color: #ffffff; padding: 15px; border-radius: 10px; border: 1px solid #e9ecef; box-shadow: 0 2px 4px rgba(0,0,0,0.05); }
.stTabs [data-baseweb="tab-list"] { gap: 24px; }
.stTabs [data-baseweb="tab"] { height: 50px; white-space: pre-wrap; background-color: #f1f3f5; border-radius: 5px 5px 0 0; padding: 10px 20px; }
.stTabs [aria-selected="true"] { background-color: #1d3557 !important; color: white !important; }
h1, h2, h3 { color: #1d3557; font-family: 'Helvetica Neue', sans-serif; }
</style>
""", 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"<div class='stMetric'><p style='color:red; font-size:14px; margin:0;'>Coordination Score</p><h2 style='color:red; margin:0;'>{coord_score:.1f}%</h2><p style='color:red; font-size:12px;'>π¨ High Risk</p></div>", 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("""
<div style="background-color:#1d3557; padding:40px; border-radius:10px; text-align:center;">
<h2 style="color:white; margin:0;">π΅οΈ Ready for Investigation</h2>
<p style="color:#a8dadc; font-size:18px;">Upload your tracker file in the sidebar to begin forensic analysis.</p>
</div>
""", unsafe_allow_html=True)
st.info("Welcome, Journalist. Please upload your X/Twitter tracker file in the sidebar to begin the forensic analysis.") |