-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3260 lines (2866 loc) · 143 KB
/
Copy pathapp.py
File metadata and controls
3260 lines (2866 loc) · 143 KB
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import streamlit as st
import sqlite3
import pandas as pd
import datetime
import folium
from streamlit_folium import st_folium
import requests as _req_geo
import math as _math_geo
import base64 as _b64
st.set_page_config(page_title="Pollygraph", layout="wide", page_icon="assets/parrot_icon.png")
# ── Theme-aware logo helper ───────────────────────────────────────────────────
@st.cache_data
def _logo_b64(path: str) -> str:
with open(path, "rb") as f:
return _b64.b64encode(f.read()).decode()
def _theme_logo(width: int = 280):
dark = _logo_b64("assets/logo_dark_bg.png")
light = _logo_b64("assets/logo_light_bg.png")
st.markdown(
f'<picture>'
f'<source srcset="data:image/png;base64,{dark}" media="(prefers-color-scheme: dark)">'
f'<img src="data:image/png;base64,{light}" width="{width}" style="max-width:100%">'
f'</picture>',
unsafe_allow_html=True,
)
# ── Password gate ─────────────────────────────────────────────────────────────
def _check_password():
correct = st.secrets.get("password", "")
if not correct:
return True
if st.session_state.get("authenticated"):
return True
st.markdown(
'<style>'
'#_pw-container { max-width: 320px; margin: 0 auto; }'
'[data-testid="stVerticalBlock"] { align-items: center; }'
'</style>',
unsafe_allow_html=True,
)
_theme_logo(260)
col_l, col_c, col_r = st.columns([1, 2, 1])
with col_c:
pwd = st.text_input("Enter password to continue", type="password", key="_pw")
if pwd and pwd == correct:
st.session_state.authenticated = True
st.rerun()
elif pwd:
st.error("Incorrect password.")
st.stop()
_check_password()
st.markdown("""
<style>
/* Faint border on all Streamlit text inputs, selects, and textareas for light-mode contrast */
div[data-baseweb="input"] > div,
div[data-baseweb="select"] > div,
div[data-baseweb="textarea"] > div {
border: 1px solid rgba(0, 0, 0, 0.15) !important;
border-radius: 6px;
}
</style>
""", unsafe_allow_html=True)
DB = "grit_cache.db"
# Ensure all tables exist (idempotent — safe to run every time)
from build_schema import init_db as _init_db
_init_db()
# ── Comparison state ───────────────────────────────────────────────────────────
if "compare_ids" not in st.session_state:
st.session_state.compare_ids = []
def _compare_has(pid):
return pid in st.session_state.get("compare_ids", [])
def _compare_add(pid):
ids = st.session_state.get("compare_ids", [])
if pid not in ids:
ids.append(pid)
st.session_state.compare_ids = ids
def _compare_remove(pid):
ids = st.session_state.get("compare_ids", [])
if pid in ids:
ids.remove(pid)
st.session_state.compare_ids = ids
ELECTION_DATE_APPROX = True
NEXT_ELECTION = datetime.date(2028, 5, 6)
LAST_ELECTION = datetime.date(2025, 5, 3)
RISK_COLOURS = {
"High": "#e94560",
"Moderate": "#f5a623",
"Low": "#27ae60",
}
def query(sql, params=()):
try:
with sqlite3.connect(DB, check_same_thread=False) as _conn:
return pd.read_sql_query(sql, _conn, params=params)
except Exception:
return pd.DataFrame()
def days_until(target):
return (target - datetime.date.today()).days
def postcode_to_state(postcode: str) -> str | None:
try:
pc = int(postcode.strip())
except ValueError:
return None
if 200 <= pc <= 299 or 2600 <= pc <= 2618 or 2900 <= pc <= 2920:
return "Australian Capital Territory"
if 1000 <= pc <= 1999 or 2000 <= pc <= 2599 or 2619 <= pc <= 2899 or 2921 <= pc <= 2999:
return "New South Wales"
if 3000 <= pc <= 3999 or 8000 <= pc <= 8999:
return "Victoria"
if 4000 <= pc <= 4999 or 9000 <= pc <= 9999:
return "Queensland"
if 5000 <= pc <= 5999:
return "South Australia"
if 6000 <= pc <= 6999:
return "Western Australia"
if 7000 <= pc <= 7999:
return "Tasmania"
if 800 <= pc <= 999:
return "Northern Territory"
return None
def _haversine(lat1, lon1, lat2, lon2):
R = 6371
dlat = _math_geo.radians(lat2 - lat1)
dlon = _math_geo.radians(lon2 - lon1)
a = (_math_geo.sin(dlat / 2) ** 2 +
_math_geo.cos(_math_geo.radians(lat1)) *
_math_geo.cos(_math_geo.radians(lat2)) *
_math_geo.sin(dlon / 2) ** 2)
return R * 2 * _math_geo.atan2(_math_geo.sqrt(a), _math_geo.sqrt(1 - a))
def risk_badge(risk_text: str) -> str:
for level, colour in RISK_COLOURS.items():
if level.lower() in risk_text.lower():
return f'<span style="background:{colour};color:#fff;padding:2px 8px;border-radius:4px;font-size:11px;font-weight:600">{level} Risk</span>'
return ""
MARGIN_COLOURS = {
"Highly Marginal": "#e94560",
"Marginal": "#f5a623",
"Fairly Safe": "#3498db",
"Safe": "#27ae60",
}
PARTY_COLOURS = {
"ALP": "#e53935",
"LNP": "#1565c0", "LP": "#1565c0", "NP": "#1565c0",
"GRN": "#2e7d32",
"IND": "#8e24aa",
}
def electorate_card(electorate: str):
"""Show margin classification + interactive map for an electorate."""
margin_df = query(
"SELECT * FROM electorate_margins WHERE division = ?", (electorate,)
)
places_df = query(
"SELECT lat, lng, name, suburb FROM polling_places WHERE division = ? AND lat IS NOT NULL",
(electorate,)
)
if margin_df.empty and places_df.empty:
return
st.markdown(f"#### Electorate: {electorate}")
col_margin, col_map = st.columns([1, 2])
with col_margin:
if not margin_df.empty:
m = margin_df.iloc[0]
mtype = m["margin_type"]
colour = MARGIN_COLOURS.get(mtype, "#aaa")
party = m["winning_party"]
p_col = PARTY_COLOURS.get(party, "#555")
margin_tip = (
"The margin is the gap between the winning candidate and 50%. "
"A larger margin means the seat is safer for the incumbent party."
)
mtype_tip = {
"Highly Marginal": "Under 2% margin — could change hands easily at the next election",
"Marginal": "2–6% margin — competitive seat that requires active campaigning to hold",
"Fairly Safe": "6–10% margin — the incumbent party has a solid but not unassailable lead",
"Safe": "Over 10% margin — very unlikely to change hands without a major swing",
}.get(mtype, "")
party_tip = f"The party that won this electorate on a two-party-preferred basis in 2025"
alp_tip = "ALP's share of the two-party-preferred vote — the final count after preferences are distributed"
coal_tip = "Coalition's share of the two-party-preferred vote — the final count after preferences are distributed"
swing_tip = (
"The change in two-party-preferred vote share compared to the previous election. "
"Positive means a swing toward the winning party; negative means a swing away."
)
votes_tip = "Total formal votes counted in this electorate at the 2025 federal election"
st.markdown(
f"""
<div style="background:#1a1a2e;border-radius:10px;padding:16px;margin-bottom:8px">
<div style="color:#aaa;font-size:12px;text-transform:uppercase;letter-spacing:1px">
2025 Result
</div>
<div style="display:flex;align-items:center;gap:10px;margin:8px 0">
<span title="{party_tip}" style="background:{p_col};color:#fff;padding:3px 10px;
border-radius:4px;font-weight:700;font-size:14px;cursor:help">{party}</span>
<span title="{mtype_tip}" style="background:{colour};color:#fff;padding:3px 10px;
border-radius:4px;font-weight:600;font-size:13px;cursor:help">{mtype}</span>
</div>
<div title="{margin_tip}" style="color:#fff;font-size:28px;font-weight:700;line-height:1;cursor:help">
{m['margin_pct']:.1f}%
</div>
<div style="color:#aaa;font-size:12px">margin</div>
<hr style="border-color:#333;margin:10px 0">
<div style="color:#ddd;font-size:13px">
<span title="{alp_tip}" style="cursor:help">ALP: {m['alp_pct']:.1f}%</span>
|
<span title="{coal_tip}" style="cursor:help">Coalition: {m['coalition_pct']:.1f}%</span>
</div>
<div style="color:#aaa;font-size:12px">
<span title="{swing_tip}" style="cursor:help">Swing: {m['swing']:+.1f}%</span>
|
<span title="{votes_tip}" style="cursor:help">{int(m['total_votes']):,} votes</span>
</div>
</div>
""",
unsafe_allow_html=True,
)
with col_map:
if not places_df.empty:
centre_lat = places_df["lat"].mean()
centre_lng = places_df["lng"].mean()
party = margin_df.iloc[0]["winning_party"] if not margin_df.empty else "IND"
tile_colour = PARTY_COLOURS.get(party, "#555")
m_map = folium.Map(
location=[centre_lat, centre_lng],
zoom_start=10,
tiles="CartoDB positron",
)
for _, p in places_df.iterrows():
folium.CircleMarker(
location=[p["lat"], p["lng"]],
radius=5,
color=tile_colour,
fill=True,
fill_color=tile_colour,
fill_opacity=0.7,
tooltip=f"{p['name']} — {p['suburb']}",
).add_to(m_map)
st_folium(m_map, height=280, width=500, returned_objects=[])
st.caption(
f"{len(places_df)} polling places shown. "
f"[View AEC boundary map →](https://electorate.aec.gov.au/)"
)
def bipolar_bar(controversy: int, positive: int, compact: bool = False) -> str:
"""
Bipolar bar centred on a midpoint.
Red extends LEFT (controversy/heat), green extends RIGHT (positive).
Both are independent 1-10 scales.
Empty bar shown when both are zero (no AI data yet).
"""
height = "7px" if compact else "9px"
font = "10px" if compact else "11px"
c_pct = max(0, min(100, (controversy or 0) * 10))
p_pct = max(0, min(100, (positive or 0) * 10))
no_data = controversy == 0 and positive == 0
# Labels row — only shown when there's data
if no_data:
labels = (
f'<div style="font-size:{font};color:#444;margin-top:2px;font-style:italic">'
f'no AI data</div>'
)
else:
left_label = f'<span style="color:#e74c3c">− {controversy}/10</span>' if controversy else '<span></span>'
right_label = f'<span style="color:#27ae60">+ {positive}/10</span>' if positive else '<span></span>'
labels = (
f'<div style="display:flex;justify-content:space-between;'
f'font-size:{font};margin-top:2px">'
f'{left_label}{right_label}</div>'
)
return f"""
<div style="margin:4px 0 1px 0">
<div style="display:flex;height:{height};border-radius:4px;overflow:hidden;background:#222">
<!-- left half: red grows rightward from left edge toward centre -->
<div style="flex:1;display:flex;justify-content:flex-end;background:#222">
<div style="width:{c_pct}%;height:100%;background:linear-gradient(to left,#e74c3c,#7b1a1a)"></div>
</div>
<!-- centre line -->
<div style="width:2px;background:#444;flex-shrink:0"></div>
<!-- right half: green grows leftward from right edge toward centre -->
<div style="flex:1;background:#222">
<div style="width:{p_pct}%;height:100%;background:linear-gradient(to right,#27ae60,#1a5c36)"></div>
</div>
</div>
{labels}
</div>"""
def heat_badge(score: int) -> str:
"""Legacy single-score badge used in the AI analysis section."""
HEAT_COLOURS = ["#27ae60","#2ecc71","#f1c40f","#f39c12","#e67e22","#e74c3c","#c0392b","#922b21","#7b241c","#641e16"]
score = max(1, min(10, score))
colour = HEAT_COLOURS[score - 1]
label = ["Very Low","Low","Low-Mod","Moderate","Mod-High","High","High","Very High","Very High","Extreme"][score - 1]
return f'<span style="background:{colour};color:#fff;padding:2px 10px;border-radius:4px;font-size:12px;font-weight:700">{score}/10 — {label}</span>'
def ai_analysis_section(politician_id: int):
ai = query("SELECT * FROM ai_analysis WHERE politician_id = ?", (politician_id,))
if ai.empty:
return
a = ai.iloc[0]
flags_raw = a.get("rhetoric_flags") or "{}"
try:
import json
flags_data = json.loads(flags_raw)
rhetoric_flags = flags_data.get("rhetoric_flags", [])
positive_notes = flags_data.get("positive_notes", [])
except Exception:
rhetoric_flags, positive_notes = [], []
pos_score = flags_data.get("positive_score", 0)
source_quality = flags_data.get("source_quality", "")
st.markdown("**AI Analysis** *(updated every few days)*")
st.markdown(
bipolar_bar(int(a["heat_score"] or 0), pos_score),
unsafe_allow_html=True,
)
cols = st.columns([2, 1])
with cols[0]:
st.markdown(a["summary"] or "")
with cols[1]:
sq_colours = {"high": "#27ae60", "mixed": "#f39c12", "low": "#e74c3c"}
sq_label = source_quality.capitalize() if source_quality else ""
sq_html = (
f' · Source quality: <span style="color:{sq_colours.get(source_quality, "#888")}'
f'">{sq_label}</span>'
) if sq_label else ""
st.markdown(
f'<span style="font-size:12px;color:#888">Sentiment: {a["sentiment"] or "neutral"}'
f'{sq_html}</span>',
unsafe_allow_html=True,
)
if rhetoric_flags:
st.markdown("**Flagged concerns:**")
for flag in rhetoric_flags:
st.markdown(f"- {flag}")
if positive_notes:
st.markdown("**Positive notes:**")
for note in positive_notes:
st.markdown(f"- {note}")
st.caption(f"Last analysed: {a['last_analyzed'] or '—'}")
def news_section(politician_id: int, limit: int = 8):
news = query('''
SELECT headline, url, source, published_date
FROM politician_news
WHERE politician_id = ?
ORDER BY published_date DESC, id DESC
LIMIT ?
''', (politician_id, limit))
if news.empty:
return
st.markdown("**Recent news:**")
for _, row in news.iterrows():
date = row["published_date"] or ""
source = row["source"] or ""
st.markdown(
f'<div style="margin:4px 0;font-size:13px">'
f'<a href="{row["url"]}" target="_blank">{row["headline"]}</a>'
f'<span style="color:#888;font-size:11px"> — {source} {date}</span>'
f'</div>',
unsafe_allow_html=True,
)
def voting_record_section(politician_id: int, party: str, chamber: str):
"""Rebellions + recent attendance breakdown inside the profile expander."""
# Career rebellion count from TVFY API (covers all divisions, not just synced ones)
career_row = query("SELECT rebellions FROM politicians WHERE id = ?", (politician_id,))
career_total = int(career_row.iloc[0]["rebellions"]) if not career_row.empty else 0
# ── Rebellions: votes where politician differed from party majority ──────
rebellions_df = query("""
SELECT d.date, d.name AS division, v.vote AS my_vote,
d.house, d.number,
(SELECT CASE
WHEN SUM(CASE WHEN v2.vote='aye' THEN 1 ELSE 0 END) >
SUM(CASE WHEN v2.vote='no' THEN 1 ELSE 0 END)
THEN 'aye' ELSE 'no' END
FROM votes v2
JOIN politicians p2 ON p2.id = v2.politician_id
WHERE v2.division_id = v.division_id
AND p2.party = ?) AS party_majority
FROM votes v
JOIN divisions d ON d.id = v.division_id
WHERE v.politician_id = ?
ORDER BY d.date DESC
""", (party, politician_id))
if not rebellions_df.empty:
reb = rebellions_df[rebellions_df["my_vote"] != rebellions_df["party_majority"]]
recent = rebellions_df.head(30)
attended_ids = set(
query("SELECT division_id FROM votes WHERE politician_id = ?", (politician_id,))
["division_id"].tolist()
)
all_divs = query(
"SELECT id, date, name AS division FROM divisions WHERE house = ? ORDER BY date DESC LIMIT 50",
(chamber,)
)
missed_df = all_divs[~all_divs["id"].isin(attended_ids)].head(20)
r_tab, a_tab = st.tabs([
f"Rebellions ({len(reb)} found locally)",
f"Attendance log",
])
with r_tab:
if career_total > 0:
tvfy_profile = (
f"https://theyvoteforyou.org.au/people/"
f"{chamber}/{politician_id}"
)
st.caption(
f"They Vote For You records **{career_total} career rebellion{'s' if career_total != 1 else ''}** total. "
f"Only divisions synced to this app ({len(rebellions_df)}) can be shown below — "
f"earlier rebellions may not be in our local database. "
f"[View full record on TVFY ↗](https://theyvoteforyou.org.au)"
)
if reb.empty:
st.caption("No rebellions found in locally synced divisions.")
else:
for _, row in reb.iterrows():
try:
tvfy_url = (
f"https://theyvoteforyou.org.au/divisions"
f"/{row['house']}/{row['date']}/{int(row['number'])}"
)
except (ValueError, TypeError):
tvfy_url = "https://theyvoteforyou.org.au/divisions"
st.markdown(
f'<div style="margin:4px 0;font-size:13px;padding:6px 10px;'
f'background:#1a1a2e;border-left:3px solid #e94560;border-radius:4px">'
f'<a href="{tvfy_url}" target="_blank" style="color:#e94560;font-weight:600">'
f'{row["division"]}</a>'
f'<span style="color:#aaa;font-size:11px"> — {row["date"]}</span><br>'
f'<span style="color:#ddd;font-size:11px">Voted <b>{row["my_vote"].upper()}</b> '
f'(party voted <b>{row["party_majority"].upper()}</b>)</span>'
f'</div>',
unsafe_allow_html=True,
)
with a_tab:
att_col, miss_col = st.columns(2)
with att_col:
st.markdown("**Recently attended**")
for _, row in recent.iterrows():
div_name = (row["division"] or "Division")[:55]
try:
tvfy_url = (
f"https://theyvoteforyou.org.au/divisions"
f"/{row['house']}/{row['date']}/{int(row['number'])}"
)
link = f'<a href="{tvfy_url}" target="_blank">{div_name}</a>'
except (ValueError, TypeError):
link = div_name
st.markdown(
f'<div style="font-size:12px;margin:2px 0">'
f'{link}<span style="color:#aaa"> {row["date"]}</span>'
f'</div>',
unsafe_allow_html=True,
)
with miss_col:
st.markdown("**Recently missed**")
if missed_df.empty:
st.caption("No recent absences found.")
else:
for _, row in missed_df.iterrows():
div_name = (row["division"] or "Division")[:55]
st.markdown(
f'<div style="font-size:12px;margin:2px 0;color:#aaa">'
f'{div_name}'
f'<span style="color:#666"> {row["date"]}</span>'
f'</div>',
unsafe_allow_html=True,
)
def _clean_bio(wiki_text: str, name: str, party: str, chamber: str,
electorate: str, state: str) -> str:
"""
Build a concise, readable bio. Use Wikipedia text if substantive,
otherwise generate a short intro from structured data.
"""
role = "Senator" if chamber == "senate" else "MP"
location = electorate or state or ""
# Build a structured intro line
first_name = name.split()[0]
if role == "Senator":
intro = f"{name} is a {party} {role} for {state}."
else:
intro = f"{name} is a {party} {role} for the Division of {location}."
if not wiki_text:
return intro
# Strip unhelpful generic openers and replace with our cleaner one
skip_phrases = [
f"{name} is an Australian politician",
f"{first_name} is an Australian politician",
"is an Australian politician.",
"is a member of the Australian Parliament",
]
cleaned = wiki_text
for phrase in skip_phrases:
if phrase.lower() in cleaned[:150].lower():
# Find the end of the first sentence and keep everything after
first_dot = cleaned.find(". ", 1)
if first_dot > 0 and first_dot < 200:
remaining = cleaned[first_dot + 2:].strip()
if remaining:
cleaned = intro + " " + remaining
else:
cleaned = intro
else:
cleaned = intro
break
else:
# Wikipedia text looks substantive — prepend our intro
if not cleaned.startswith(name):
cleaned = intro + " " + cleaned
# Trim to reasonable length
if len(cleaned) > 600:
cut = cleaned[:600].rfind(". ")
if cut > 200:
cleaned = cleaned[:cut + 1]
else:
cleaned = cleaned[:600] + "…"
return cleaned
def profile_expander(name: str, politician_id: int = None, photo_url: str = None):
prof = query("SELECT * FROM profiles WHERE name = ?", (name,))
bio = query("SELECT * FROM politician_bio WHERE politician_id = ?", (politician_id,)) if politician_id else None
pol = query(
"SELECT party, chamber, electorate, state FROM politicians WHERE id = ?",
(politician_id,)
) if politician_id else None
has_profile = not prof.empty
has_bio = bio is not None and not bio.empty
has_ai = politician_id is not None
has_votes = pol is not None and not pol.empty
if not has_profile and not has_bio and not has_ai:
return
with st.expander("▶ Profile, News & AI Analysis"):
if photo_url:
st.markdown(
f'<div class="mobile-photo">'
f'<img src="{photo_url}" width="100" '
f'style="border-radius:8px;margin-bottom:8px;object-fit:cover">'
f'</div>',
unsafe_allow_html=True,
)
# ── Bio ────────────────────────────────────────────────────────────────
p_party = pol.iloc[0]["party"] if has_votes else ""
p_chamber = pol.iloc[0]["chamber"] if has_votes else ""
p_elect = pol.iloc[0]["electorate"] if has_votes else ""
p_state = pol.iloc[0]["state"] if has_votes else ""
wiki_text = bio.iloc[0]["wikipedia_summary"] if has_bio else ""
wiki_url = (bio.iloc[0]["wikipedia_url"] if has_bio else "") or ""
bio_text = _clean_bio(wiki_text, name, p_party, p_chamber, p_elect, p_state)
if bio_text:
st.markdown(bio_text)
if wiki_url:
st.caption(f"[Read more on Wikipedia →]({wiki_url})")
# ── Manual profile (from CSV) ────────────────────────────────────────
if has_profile:
p = prof.iloc[0]
if p["employment_history"]:
st.markdown(f"**Employment background** \n{p['employment_history']}")
if p["notes"]:
st.markdown(f"**Overview** \n{p['notes']}")
cols = st.columns(2)
with cols[0]:
if p["media_positive"]:
st.markdown(f"**Media (+)** \n{p['media_positive']}")
if p["integrity_notes"]:
st.markdown(f"**Integrity record** \n{p['integrity_notes']}")
if p["funding_info"]:
st.markdown(f"**Funding** \n{p['funding_info']}")
with cols[1]:
if p["media_negative"]:
st.markdown(f"**Media (−)** \n{p['media_negative']}")
if p["risk_assessment"]:
st.markdown(
f"**Risk assessment** \n"
f"{risk_badge(p['risk_assessment'])} \n"
f"{p['risk_assessment']}",
unsafe_allow_html=True,
)
if p["funding_risk"]:
st.markdown(f"**Funding risk** \n{p['funding_risk']}")
if p["media_veracity"]:
st.markdown(f"**Media veracity** \n{p['media_veracity']}")
if p["term_end"]:
st.markdown(f"**Term / re-election:** {p['term_end']}")
if p["postal_address"]:
st.markdown(f"**Electorate office:** {p['postal_address']}")
# ── Voting record & rebellions ───────────────────────────────────────
if has_votes:
st.divider()
party = pol.iloc[0]["party"]
chamber = pol.iloc[0]["chamber"]
voting_record_section(politician_id, party, chamber)
# ── AI analysis ──────────────────────────────────────────────────────
if politician_id:
st.divider()
ai_analysis_section(politician_id)
st.divider()
news_section(politician_id)
def politician_grid(df, chamber="representatives", tab_key=""):
days_left = days_until(NEXT_ELECTION)
cols_per_row = 4
for i in range(0, len(df), cols_per_row):
cols = st.columns(cols_per_row, gap="small")
for j, col in enumerate(cols):
idx = i + j
if idx >= len(df):
break
row = df.iloc[idx]
pid = int(row["id"])
with col:
if row.get("photo_url"):
st.markdown(
f'<div class="desktop-photo" style="text-align:center">'
f'<img src="{row["photo_url"]}" width="90" '
f'style="border-radius:6px;object-fit:cover">'
f'</div>',
unsafe_allow_html=True,
)
location = row.get("state") or row.get("electorate", "")
att = row.get("attendance_%", "—")
reb = int(row["rebellions"])
reb_label = f"Reb: {reb}*" if reb > 0 else "Reb: 0"
st.markdown(
f'<div style="text-align:center;margin-bottom:4px">'
f'<div style="font-size:14px;font-weight:700">{row["name"]}</div>'
f'<div style="font-size:11px;color:#888;line-height:1.4;margin-top:2px">'
f'{row["party"]}<br>'
f'{location}<br>'
f'Att: {att} · {reb_label}<br>'
f'{days_left:,}d'
f'</div></div>',
unsafe_allow_html=True,
)
heat = int(row.get("heat_score") or 0)
pos = int(row.get("positive_score") or 0)
st.markdown(bipolar_bar(heat, pos, compact=True), unsafe_allow_html=True)
# Compare checkbox
in_compare = _compare_has(pid)
if st.checkbox(
"Compare" if not in_compare else "In compare",
key=f"cmp_{tab_key}_{pid}",
value=in_compare,
):
_compare_add(pid)
else:
_compare_remove(pid)
profile_expander(row["name"], pid, photo_url=row.get("photo_url"))
# ── CSS ───────────────────────────────────────────────────────────────────────
st.markdown("""
<style>
/* ── Desktop defaults ──────────────────────────────── */
.desktop-photo { display: block; }
.mobile-photo { display: none; }
/* ── Mobile overrides (<640px) ─────────────────────── */
@media screen and (max-width: 640px) {
/* Photos: hide in grid, show inside expander */
.desktop-photo { display: none !important; }
.mobile-photo { display: block !important; }
/* 2-column grid */
[data-testid="stHorizontalBlock"] > [data-testid="stColumn"] {
min-width: 45% !important;
max-width: 50% !important;
flex: 1 1 45% !important;
}
/* Smaller name text in cards */
[data-testid="stColumn"] p strong {
font-size: 13px !important;
line-height: 1.2 !important;
}
/* Smaller caption text */
[data-testid="stColumn"] small,
[data-testid="stColumn"] [data-testid="stCaptionContainer"] {
font-size: 11px !important;
line-height: 1.3 !important;
}
/* Compact expander button */
[data-testid="stColumn"] [data-testid="stExpander"] summary {
font-size: 11px !important;
padding: 5px 8px !important;
min-height: 0 !important;
}
[data-testid="stColumn"] [data-testid="stExpander"] summary p {
font-size: 11px !important;
line-height: 1.2 !important;
}
/* "no AI data" label — smaller on mobile */
.no-info-mobile { font-size: 10px !important; }
/* Tighter column padding */
[data-testid="stColumn"] > div {
padding-left: 4px !important;
padding-right: 4px !important;
}
}
/* Tighten card padding */
[data-testid="stColumn"] { padding: 4px !important; }
</style>
""", unsafe_allow_html=True)
# ── Header (logo + tagline only) ──────────────────────────────────────────────
_theme_logo(280)
st.markdown("#### Cut through the ~~bull~~parrotshit.")
# state_from_pc used by build_mp_tab for Senate filtering
state_from_pc = None
# ── Promise tracker summary ────────────────────────────────────────────────────
_promise_summary = query("""
SELECT party, status, COUNT(*) AS n
FROM promises
GROUP BY party, status
""")
STATUS_COLOURS = {
"Delivered": "#27ae60",
"In Progress": "#3498db",
"Not Started": "#555",
"Broken": "#e94560",
}
STATUS_ORDER = ["Delivered", "In Progress", "Not Started", "Broken"]
GOVERNMENT_PARTY = "ALP" # update if government changes
STATUS_ICON = {"Delivered": "Done", "In Progress": "WIP", "Not Started": "Pending", "Broken": "Broken"}
def _promise_list_html(promises_df, is_government: bool = True) -> str:
"""Render promises as native <details> accordion items."""
html = ""
for _, p in promises_df.iterrows():
colour = STATUS_COLOURS.get(p["status"], "#555")
icon = STATUS_ICON.get(p["status"], "")
if is_government:
badge = (
f'<span style="background:{colour};color:#fff;'
f'padding:1px 8px;border-radius:8px;font-size:11px;font-weight:600;'
f'white-space:nowrap;margin-right:6px">{icon} {p["status"]}</span>'
)
else:
badge = ""
colour = "#555"
# Detail body — richer for government, simple for opposition
body_parts = []
if is_government:
if p.get("evidence"):
body_parts.append(
f'<div style="font-size:12px;color:#ccc;margin:6px 0 4px;'
f'border-left:2px solid {colour};padding-left:8px">'
f'<strong>Progress:</strong> {p["evidence"]}</div>'
)
if p.get("scrutiny"):
body_parts.append(
f'<div style="font-size:12px;color:#bbb;margin:4px 0;'
f'border-left:2px solid #f5a623;padding-left:8px">'
f'<strong>Scrutiny:</strong> {p["scrutiny"]}</div>'
)
if p.get("scrutiny_source"):
body_parts.append(
f'<div style="font-size:11px;color:#888;margin:2px 0">'
f'Scrutiny source: <em>{p["scrutiny_source"]}</em></div>'
)
else:
if p.get("evidence"):
body_parts.append(
f'<div style="font-size:12px;color:#aaa;margin:4px 0">{p["evidence"]}</div>'
)
if p.get("source_url"):
body_parts.append(
f'<a href="{p["source_url"]}" target="_blank" '
f'style="color:#3498db;font-size:11px">Source ↗</a>'
)
body = "".join(body_parts)
html += (
f'<details style="border-left:3px solid {colour};'
f'padding:6px 10px;margin:5px 0;'
f'background:rgba(255,255,255,0.03);border-radius:0 4px 4px 0;cursor:pointer">'
f'<summary style="list-style:none;font-size:13px;display:flex;'
f'align-items:flex-start;gap:6px;flex-wrap:wrap">'
f'{badge}<span>{p["promise"]}</span></summary>'
f'{body}'
f'</details>'
)
return html
# ── Compare banner (shows when 1+ politicians selected) ───────────────────────
n_compare = len(st.session_state.get("compare_ids", []))
if n_compare > 0:
banner_col, clear_col = st.columns([5, 1])
with banner_col:
if n_compare == 1:
cid = st.session_state.compare_ids[0]
cname = query("SELECT name FROM politicians WHERE id=?", (cid,))
cname_str = cname.iloc[0]["name"] if not cname.empty else str(cid)
st.info(f"**1 selected:** {cname_str} — select at least one more to compare.")
else:
cnames = query(
f"SELECT name FROM politicians WHERE id IN ({','.join('?'*n_compare)})",
tuple(st.session_state.get("compare_ids", [])),
)["name"].tolist()
st.success(f"**{n_compare} selected for comparison:** {', '.join(cnames)} — see the **Compare** tab.")
with clear_col:
if st.button("Clear", key="clear_compare_btn"):
st.session_state.compare_ids = []
st.rerun()
# ── Tabs ──────────────────────────────────────────────────────────────────────
(tab_currentgov, tab_yourreps, tab_reps, tab_senate, tab_indep, tab_divs, tab_bills, tab_votes,
tab_compare, tab_promises, tab_revolving, tab_media, tab_ai_explainer) = st.tabs([
"Current Gov", "Your Reps", "House of Reps", "Senate", "Independents", "Votes",
"Dodgy Deals", "Look Up", "Compare", "Promises", "Revolving Door", "Media",
"How AI Works",
])
days_left = days_until(NEXT_ELECTION)
mandate_pct = round(100 * (1 - days_left / (NEXT_ELECTION - LAST_ELECTION).days), 1)
def build_mp_tab(chamber: str):
parties = query(
"SELECT DISTINCT party FROM politicians WHERE chamber=? ORDER BY party",
(chamber,)
)["party"].tolist()
filter_col, sort_col = st.columns([2, 2])
with filter_col:
selected_party = st.selectbox("Filter by party", ["All"] + parties, key=f"party_{chamber}")
with sort_col:
sort_by = st.selectbox(
"Sort by",
["Heat Score ↓", "Name (A–Z)", "Rebellions ↓", "Rebellions ↑", "Attendance ↓", "Attendance ↑"],
key=f"sort_{chamber}",
)
upd_col1, upd_col2, upd_col3 = st.columns(3)
with upd_col1:
only_news = st.checkbox("Has recent news", key=f"news_{chamber}")
with upd_col2:
only_ai = st.checkbox("Has AI analysis", key=f"ai_{chamber}")
with upd_col3:
only_controversial = st.checkbox(
"Controversial",
key=f"controversial_{chamber}",
help="Both positive and controversy scores exceed 15% — bar extends meaningfully in both directions.",
)
mps = query("""
SELECT p.id, p.name, p.party, p.electorate, p.state, p.photo_url,
p.votes_attended, p.votes_possible, p.rebellions,
CASE WHEN n.politician_id IS NOT NULL THEN 1 ELSE 0 END AS has_news,
CASE WHEN a.politician_id IS NOT NULL THEN 1 ELSE 0 END AS has_ai,
COALESCE(a.heat_score, 0) AS heat_score,
COALESCE(a.rhetoric_flags, '{}') AS flags_json
FROM politicians p
LEFT JOIN (
SELECT DISTINCT politician_id FROM politician_news
WHERE published_date >= date('now', '-14 days')
) n ON n.politician_id = p.id
LEFT JOIN ai_analysis a ON a.politician_id = p.id
WHERE p.chamber = ?
AND (? = 'All' OR p.party = ?)
""", (chamber, selected_party, selected_party))
import json as _json
mps["positive_score"] = mps["flags_json"].apply(
lambda x: _json.loads(x).get("positive_score", 0) if x and x != "{}" else 0
)
if mps.empty:
st.info("No data yet. Run: python sync_data.py")
return
if only_news:
mps = mps[mps["has_news"] == 1]
if only_ai:
mps = mps[mps["has_ai"] == 1]
if only_controversial:
# Both sides of the bar must exceed 15% (score > 1.5 → integer threshold ≥ 2)
mps = mps[(mps["heat_score"] >= 2) & (mps["positive_score"] >= 2)]
if mps.empty:
st.info("No politicians match the current filters.")
return
mps["attendance_num"] = mps.apply(
lambda r: 100 * r["votes_attended"] / r["votes_possible"]
if r["votes_possible"] > 0 else 0,
axis=1,
)
mps["attendance_%"] = mps["attendance_num"].apply(
lambda v: f"{v:.0f}%" if v > 0 else "—"
)
sort_map = {
"Name (A–Z)": ("name", True),
"Rebellions ↓": ("rebellions", False),
"Rebellions ↑": ("rebellions", True),
"Attendance ↓": ("attendance_num", False),
"Attendance ↑": ("attendance_num", True),
"Heat Score ↓": ("heat_score", False),
}
sort_col_name, sort_asc = sort_map[sort_by]
mps = mps.sort_values(sort_col_name, ascending=sort_asc)
if state_from_pc and chamber == "senate":
mps = mps[mps["state"] == state_from_pc]
politician_grid(mps, chamber, tab_key=chamber)
st.caption(
f"{len(mps)} shown. "
"\\* Rebellion count is a career total from They Vote For You and may exceed "
"what's visible in locally synced divisions."
)
# ── House of Reps ─────────────────────────────────────────────────────────────
# ── Your Reps ──────────────────────────────────────────────────────────────────
with tab_yourreps: