Spaces:
Runtime error
Runtime error
Download app.py from Ikeitany/CIB-In-Kenya: direct link, hf CLI and curl.
- Browser
- Download file 7.18 kB
-
https://huggingface.co/spaces/Ikeitany/CIB-In-Kenya/resolve/main/app.py
- Command line
-
hf download hf://spaces/Ikeitany/CIB-In-Kenya/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Ikeitany/CIB-In-Kenya/resolve/main/app.py
7.18 kB
| 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.") |