-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1507 lines (1284 loc) · 47.1 KB
/
Copy pathapp.py
File metadata and controls
1507 lines (1284 loc) · 47.1 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
"""
SafeGuard AI - Women's Legal Rights Assistant (Pakistan)
"""
import os
import hashlib
import sqlite3
from io import BytesIO
from datetime import datetime
from pathlib import Path
import streamlit as st
import streamlit.components.v1 as components
from dotenv import load_dotenv
load_dotenv()
try:
from google import genai
from google.genai import types
from PIL import Image
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import inch
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
from reportlab.lib import colors
from reportlab.lib.enums import TA_CENTER
except ImportError:
st.error("Install: pip install google-genai streamlit pillow python-dotenv reportlab")
st.stop()
# -----------------------------------------------------------------------------
# DATABASE SETUP
# -----------------------------------------------------------------------------
DB_PATH = Path("safeguard_evidence.db")
def init_database():
"""Initialize SQLite database and create tables if they don't exist"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS evidence_timeline (
id INTEGER PRIMARY KEY AUTOINCREMENT,
logged_at TEXT NOT NULL,
incident_date TEXT NOT NULL,
incident_time TEXT NOT NULL,
incident_type TEXT NOT NULL,
description TEXT NOT NULL,
witnesses TEXT,
location TEXT,
evidence_files TEXT
)
""")
conn.commit()
conn.close()
def save_evidence_to_db(entry):
"""Save evidence entry to database"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Serialize evidence_files to JSON string
import json
evidence_files_json = json.dumps(entry.get("evidence_files", []))
cursor.execute("""
INSERT INTO evidence_timeline
(logged_at, incident_date, incident_time, incident_type, description, witnesses, location, evidence_files)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", (
entry["logged_at"],
entry["incident_date"],
entry["incident_time"],
entry["incident_type"],
entry["description"],
entry.get("witnesses", ""),
entry.get("location", ""),
evidence_files_json
))
entry_id = cursor.lastrowid
conn.commit()
conn.close()
return entry_id
def load_evidence_from_db():
"""Load all evidence entries from database"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("""
SELECT id, logged_at, incident_date, incident_time, incident_type,
description, witnesses, location, evidence_files
FROM evidence_timeline
ORDER BY incident_date DESC, incident_time DESC
""")
rows = cursor.fetchall()
conn.close()
# Convert to list of dictionaries
import json
evidence_list = []
for row in rows:
evidence_list.append({
"id": row[0],
"logged_at": row[1],
"incident_date": row[2],
"incident_time": row[3],
"incident_type": row[4],
"description": row[5],
"witnesses": row[6] or "",
"location": row[7] or "",
"evidence_files": json.loads(row[8]) if row[8] else []
})
return evidence_list
def delete_evidence_from_db(entry_id):
"""Delete an evidence entry from database"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute("DELETE FROM evidence_timeline WHERE id = ?", (entry_id,))
conn.commit()
conn.close()
# -----------------------------------------------------------------------------
# OPTIONALS
# -----------------------------------------------------------------------------
SHOW_EVIDENCE_UPLOAD_CARD = True
# -----------------------------------------------------------------------------
# MODELS
# -----------------------------------------------------------------------------
MODEL_CANDIDATES = ["gemini-3-flash-preview", "gemini-3-pro-preview"]
def _model_variants(name: str):
return [name, f"models/{name}"]
# -----------------------------------------------------------------------------
# CONFIG
# -----------------------------------------------------------------------------
st.set_page_config(
page_title="SafeGuard AI - Women's Legal Rights Assistant",
page_icon="🛡️",
layout="wide",
initial_sidebar_state="expanded",
)
# -----------------------------------------------------------------------------
# IMPROVED CSS with better contrast and browser compatibility
# -----------------------------------------------------------------------------
st.markdown(
"""
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&family=Poppins:wght@500;600;700;800&display=swap');
* { font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
#MainMenu {visibility: hidden;}
footer {visibility: hidden;}
header {visibility: hidden;}
.stDeployButton {display: none;}
div[data-testid="stNotification"] {display: none !important;}
.stAlert {display:none !important;}
/* Force color scheme to light */
:root {
color-scheme: light !important;
}
/* Page - Force white background */
[data-testid="stAppViewContainer"] {
background: #f7f7fb !important;
color-scheme: light !important;
}
[data-testid="stAppViewContainer"] > div {
background: #f7f7fb !important;
}
.main {
background: #f7f7fb !important;
}
.block-container{
max-width: 1500px;
padding-top: 1.0rem;
padding-bottom: 1.0rem;
background: #f7f7fb !important;
}
/* Sidebar */
[data-testid="stSidebar"] {
min-width: 310px !important;
max-width: 310px !important;
}
[data-testid="stSidebar"]{
background: linear-gradient(180deg, #2b0f55 0%, #35126a 35%, #4c1d95 75%, #5b21b6 100%) !important;
color-scheme: dark !important;
}
[data-testid="stSidebar"] > div:first-child {
padding: 1.35rem 1.05rem 1.0rem 1.05rem;
}
/* Sidebar header */
.sg-sidebar-header{
display:flex; gap: 12px; align-items:flex-start;
padding-bottom: 1.05rem;
border-bottom: 1px solid rgba(255,255,255,0.12);
margin-bottom: 1rem;
}
.sg-sidebar-logo{
width: 46px; height: 46px; border-radius: 14px;
background: rgba(255,255,255,0.12);
display:flex; align-items:center; justify-content:center;
font-size: 20px; color: #fff !important;
}
.sg-sidebar-title{
font-family: Poppins, Inter, sans-serif;
color: #fff !important;
font-size: 18px;
font-weight: 800;
line-height: 1.15;
margin:0;
}
.sg-sidebar-subtitle{
color: rgba(255,255,255,0.70) !important;
font-size: 12px;
margin: 2px 0 0 0;
line-height: 1.25;
}
/* Sidebar - Force all text to white */
[data-testid="stSidebar"] * {
color: #ffffff !important;
}
[data-testid="stSidebar"] p,
[data-testid="stSidebar"] span,
[data-testid="stSidebar"] div,
[data-testid="stSidebar"] label,
[data-testid="stSidebar"] h1,
[data-testid="stSidebar"] h2,
[data-testid="stSidebar"] h3 {
color: #ffffff !important;
}
/* Sidebar navigation (radio -> cards) */
[data-testid="stSidebar"] .stRadio > label { display:none !important; }
[data-testid="stSidebar"] div[role="radiogroup"]{
display:flex !important;
flex-direction:column !important;
gap: 12px !important;
}
[data-testid="stSidebar"] div[role="radiogroup"] label{
background: rgba(255,255,255,0.10) !important;
border: 1px solid rgba(255,255,255,0.12) !important;
border-radius: 14px !important;
padding: 14px 14px !important;
cursor: pointer !important;
transition: all .18s ease !important;
}
[data-testid="stSidebar"] div[role="radiogroup"] label:hover{
background: rgba(255,255,255,0.14) !important;
transform: translateY(-1px);
}
[data-testid="stSidebar"] div[role="radiogroup"] label[aria-checked="true"]{
background: rgba(255,255,255,0.20) !important;
border-color: rgba(255,255,255,0.22) !important;
}
/* Hide the radio circle */
[data-testid="stSidebar"] div[role="radiogroup"] label > div:first-child{
display:none !important;
}
/* Make label text white and allow newline */
[data-testid="stSidebar"] div[role="radiogroup"] label span{
white-space: pre-line !important;
color: rgba(255,255,255,0.94) !important;
font-size: 14px !important;
font-weight: 700 !important;
line-height: 1.25 !important;
}
/* Sidebar chat uploader hidden offscreen (keep functional) */
[data-testid="stSidebar"] div[data-testid="stFileUploader"]{
position: fixed !important;
left: -9999px !important;
top: -9999px !important;
width: 1px !important;
height: 1px !important;
opacity: 0 !important;
overflow: hidden !important;
}
/* Privacy notice */
.sg-privacy{
margin-top: 18px;
background: rgba(255,255,255,0.10);
border: 1px solid rgba(255,255,255,0.12);
border-radius: 14px;
padding: 14px;
}
.sg-privacy strong{
display:block;
color:#fff !important;
font-size: 12px;
font-weight: 800;
margin-bottom: 4px;
}
.sg-privacy p{
margin:0;
color: rgba(255,255,255,0.82) !important;
font-size: 11px;
line-height: 1.45;
}
/* Top header */
.sg-topline {
height: 1px;
background: rgba(91,33,182,0.12);
margin: .55rem 0 .95rem 0;
}
.secure-badge{
display:inline-flex;
align-items:center;
gap: 12px;
background: #ffffff !important;
border: 1px solid rgba(47,21,94,0.12);
padding: 8px 14px;
border-radius: 999px;
font-size: 13px;
color: #2f155e !important;
font-weight: 700;
}
.secure-badge .muted{
opacity:.65;
font-weight: 600;
color: #2f155e !important;
}
/* Quick Exit */
.stButton button[kind="primary"]{
background: #ef4444 !important;
border: 1px solid #ef4444 !important;
color: #fff !important;
border-radius: 999px !important;
padding: 10px 18px !important;
font-weight: 800 !important;
font-size: 13px !important;
}
/* Export PDF button */
.stDownloadButton button{
background: #2f155e !important;
color: #fff !important;
border: 1px solid #2f155e !important;
border-radius: 999px !important;
padding: 10px 18px !important;
font-weight: 800 !important;
font-size: 13px !important;
}
.stDownloadButton button:hover{
background: #3a1a73 !important;
border-color: #3a1a73 !important;
}
/* Welcome */
.sg-welcome{
text-align:center;
padding: 3.3rem 1.5rem 1.6rem 1.5rem;
max-width: 980px;
margin: 0 auto;
background: #f7f7fb !important;
}
.sg-welcome-icon{
width: 66px;
height: 66px;
border-radius: 18px;
background: #2f155e !important;
display:flex;
align-items:center;
justify-content:center;
color:#fff !important;
font-size: 28px;
margin: 0 auto 1.2rem auto;
}
.sg-welcome-title{
font-family: Poppins, Inter, sans-serif;
font-size: 30px;
font-weight: 800;
color:#1f1147 !important;
margin: 0 0 10px 0;
}
.sg-welcome-sub{
color: rgba(47,21,94,.62) !important;
font-size: 15px;
line-height: 1.6;
margin: 0 auto 18px auto;
max-width: 720px;
}
/* Quick action pills */
div[data-testid="column"] .stButton button{
background: #ffffff !important;
color: #2f155e !important;
border: 1px solid rgba(47,21,94,0.12) !important;
border-radius: 999px !important;
padding: 10px 16px !important;
font-size: 13px !important;
font-weight: 700 !important;
}
div[data-testid="column"] .stButton button:hover{
background: #f9f9fb !important;
border-color: rgba(47,21,94,0.20) !important;
}
/* Chat messages */
div[data-testid="stChatMessage"]{
border-radius: 16px !important;
padding: 1rem 1.1rem !important;
margin: .7rem 0 !important;
border: none !important;
box-shadow: 0 8px 18px rgba(17,24,39,.06);
}
/* AI Assistant messages - Purple box with white text */
div[data-testid="stChatMessage"]:has(div[data-testid="chatAvatarIcon-assistant"]){
background: linear-gradient(135deg, #5b21b6 0%, #7c3aed 100%) !important;
}
div[data-testid="stChatMessage"]:has(div[data-testid="chatAvatarIcon-assistant"]) [data-testid="stChatMessageContent"]{
color: #ffffff !important;
font-size: 14px !important;
line-height: 1.65 !important;
}
div[data-testid="stChatMessage"]:has(div[data-testid="chatAvatarIcon-assistant"]) [data-testid="stChatMessageContent"] *{
color: #ffffff !important;
}
/* User messages - Light purple-pink gradient with black text */
div[data-testid="stChatMessage"]:has(div[data-testid="chatAvatarIcon-user"]){
background: linear-gradient(135deg, #fae8ff 0%, #fce7f3 50%, #ffe4e6 100%) !important;
border: 1px solid rgba(147,51,234,0.15) !important;
}
div[data-testid="stChatMessage"]:has(div[data-testid="chatAvatarIcon-user"]) [data-testid="stChatMessageContent"]{
color: #1f1147 !important;
font-size: 14px !important;
line-height: 1.65 !important;
}
div[data-testid="stChatMessage"]:has(div[data-testid="chatAvatarIcon-user"]) [data-testid="stChatMessageContent"] *{
color: #1f1147 !important;
}
/* Avatars */
[data-testid="chatAvatarIcon-assistant"]{
background: #2b0f55 !important;
color: #fff !important;
border-radius: 12px !important;
width: 34px !important;
height: 34px !important;
font-weight: 800 !important;
}
[data-testid="chatAvatarIcon-user"]{
background: #ef4444 !important;
color: #fff !important;
border-radius: 999px !important;
width: 34px !important;
height: 34px !important;
font-weight: 800 !important;
}
.message-time{
font-size: 11px;
opacity: .65;
margin-top: 8px;
}
/* Chat input */
div[data-testid="stChatInput"]{
background: #ffffff !important;
border: 1px solid rgba(47,21,94,0.18) !important;
border-radius: 16px !important;
box-shadow: 0 10px 20px rgba(17,24,39,.06) !important;
position: relative;
}
div[data-testid="stChatInput"] textarea{
padding-left: 52px !important;
font-size: 14px !important;
color: #1f1147 !important;
background: #ffffff !important;
}
div[data-testid="stChatInput"] textarea::placeholder{
color: rgba(47,21,94,0.45) !important;
}
/* Paperclip label injected into chat input */
.sg-clip-label{
position: absolute;
left: 14px;
bottom: 12px;
width: 34px;
height: 34px;
border-radius: 10px;
border: 1px solid rgba(47,21,94,0.14);
background: rgba(255,255,255,0.96) !important;
color: rgba(47,21,94,.75) !important;
display:flex;
align-items:center;
justify-content:center;
cursor:pointer;
user-select:none;
z-index: 6000;
}
.sg-clip-label:hover{
border-color: rgba(47,21,94,0.22);
background: #ffffff !important;
}
/* Evidence upload card */
.sg-evidence-card{
width: min(820px, 100%);
margin: 18px auto 18px auto;
border-radius: 18px;
border: 2px dashed rgba(47,21,94,0.20);
background: #fbfbfe !important;
padding: 34px 26px;
position: relative;
text-align:center;
}
.sg-evidence-icon{
width: 52px;
height: 52px;
border-radius: 16px;
margin: 0 auto 14px auto;
background: rgba(91,33,182,0.14) !important;
display:flex;
align-items:center;
justify-content:center;
color: #2f155e !important;
font-size: 22px;
}
.sg-evidence-title{
font-family: Poppins, Inter, sans-serif;
color:#1f1147 !important;
font-size:18px;
font-weight:800;
}
.sg-evidence-sub{
color: rgba(47,21,94,.62) !important;
font-size:13px;
margin-top:6px;
}
.sg-evidence-tags{
display:flex;
gap:16px;
justify-content:center;
flex-wrap:wrap;
margin-top:10px;
color: rgba(47,21,94,.70) !important;
font-weight:600;
}
/* Evidence overlay uploader */
.sg-evidence-uploader{
position:absolute !important;
inset: 0 !important;
opacity: 0 !important;
z-index: 5 !important;
}
.sg-evidence-uploader section{ height:100% !important; }
.sg-evidence-uploader [data-testid="stFileUploaderDropzone"]{ height: 100% !important; }
/* Resource cards */
.resource-card{
background: #ffffff !important;
border: 1px solid rgba(47,21,94,0.10);
border-radius: 16px;
padding: 16px 18px;
margin: 10px 0;
position: relative;
}
.resource-card::after{
content: '↗';
position:absolute;
right: 16px;
top: 16px;
color: rgba(47,21,94,0.35) !important;
font-size: 16px;
}
.resource-title{
font-weight: 800;
color:#1f1147 !important;
font-size: 15px;
margin-bottom: 4px;
}
.resource-desc{
color: rgba(47,21,94,.62) !important;
font-size: 13px;
line-height: 1.55;
padding-right: 24px;
}
.section-h{
margin: 22px 0 10px 0;
font-weight: 900;
color: #1f1147 !important;
display:flex;
align-items:center;
gap: 8px;
}
/* Disclaimer */
.disclaimer{
margin-top: 14px;
background: rgba(255, 243, 199, 0.85) !important;
border: 1px solid rgba(245,158,11,.25);
border-left: 4px solid #f59e0b;
padding: 12px 14px;
border-radius: 14px;
color: #92400e !important;
font-size: 12px;
line-height: 1.5;
}
/* Forms and inputs */
.stTextInput input,
.stTextArea textarea,
.stSelectbox select,
.stDateInput input,
.stTimeInput input {
background: #ffffff !important;
color: #1f1147 !important;
border-color: rgba(47,21,94,0.18) !important;
}
.stTextInput label,
.stTextArea label,
.stSelectbox label,
.stDateInput label,
.stTimeInput label {
color: #1f1147 !important;
}
/* Success/Info messages */
.stSuccess {
background: #d1fae5 !important;
color: #065f46 !important;
}
.stInfo {
background: #dbeafe !important;
color: #1e40af !important;
}
.stError {
background: #fee2e2 !important;
color: #991b1b !important;
}
/* Expander */
.streamlit-expanderHeader {
background: #ffffff !important;
color: #1f1147 !important;
border-color: rgba(47,21,94,0.12) !important;
}
.streamlit-expanderContent {
background: #ffffff !important;
}
/* Delete button */
.stButton button[kind="secondary"]{
background: transparent !important;
border: 1px solid #ef4444 !important;
color: #ef4444 !important;
border-radius: 8px !important;
padding: 6px 12px !important;
font-weight: 600 !important;
font-size: 12px !important;
}
.stButton button[kind="secondary"]:hover{
background: #fee2e2 !important;
}
</style>
""",
unsafe_allow_html=True,
)
# -----------------------------------------------------------------------------
# SYSTEM PROMPT
# -----------------------------------------------------------------------------
SYSTEM_INSTRUCTION = """You are SafeGuard AI, a legal assistant for women's rights in Pakistan.
RULES:
1. Start with: "⚠️ SafeGuard AI is not a lawyer. It is a first step toward safety, awareness, and documentation."
2. If danger: "🚨 IMMEDIATE DANGER: Call 1099 or Police 15"
3. Be supportive and trauma-informed.
PAKISTANI LAWS:
- Protection Against Harassment of Women at Workplace Act 2010
- Domestic Violence Acts (Sindh 2012, Punjab 2016)
- Prevention of Electronic Crimes Act (PECA) 2016
"""
# -----------------------------------------------------------------------------
# STATE
# -----------------------------------------------------------------------------
def init_state():
if "nav_page" not in st.session_state:
st.session_state.nav_page = "chat"
if "messages" not in st.session_state:
st.session_state.messages = []
if "message_translations" not in st.session_state:
st.session_state.message_translations = {}
if "uploaded_image" not in st.session_state:
st.session_state.uploaded_image = None
if "show_full_image" not in st.session_state:
st.session_state.show_full_image = {}
if "evidence_timeline" not in st.session_state:
# Load from database on startup
st.session_state.evidence_timeline = load_evidence_from_db()
if "_quick_exit" not in st.session_state:
st.session_state._quick_exit = False
if "_pdf_cache" not in st.session_state:
st.session_state._pdf_cache = None
if "_pdf_cache_hash" not in st.session_state:
st.session_state._pdf_cache_hash = None
if "_toast_incident_saved" not in st.session_state:
st.session_state._toast_incident_saved = None
if "_clear_chat_attach" not in st.session_state:
st.session_state._clear_chat_attach = False
# -----------------------------------------------------------------------------
# GEMINI
# -----------------------------------------------------------------------------
def initialize_gemini():
# Try Streamlit secrets first (for cloud deployment)
try:
api_key = st.secrets["GOOGLE_API_KEY"]
except (KeyError, FileNotFoundError, AttributeError):
# Fallback to .env (for local development)
api_key = os.getenv("GOOGLE_API_KEY")
if not api_key:
st.error("🔑 Add GOOGLE_API_KEY to Streamlit secrets or .env file")
st.stop()
return genai.Client(api_key=api_key)
def get_gemini_response(client, user_message, image_bytes=None):
"""
Uses only:
- gemini-3-flash-preview
- gemini-3-pro-preview
Tries both bare and 'models/<name>' variants for compatibility.
"""
try:
parts = []
if user_message:
parts.append(types.Part(text=user_message))
if image_bytes:
parts.append(types.Part(inline_data=types.Blob(mime_type="image/jpeg", data=image_bytes)))
contents = [types.Content(role="user", parts=parts)]
config = types.GenerateContentConfig(
system_instruction=SYSTEM_INSTRUCTION,
temperature=0.7,
max_output_tokens=2000,
)
last_error = None
for name in MODEL_CANDIDATES:
for model_name in _model_variants(name):
try:
resp = client.models.generate_content(
model=model_name,
contents=contents,
config=config,
)
return resp.text, None
except Exception as e:
last_error = e
continue
return None, f"Model error: {last_error}"
except Exception as e:
return None, str(e)
def translate_to_urdu(client, text):
try:
prompt = (
"Translate the following text to Urdu. "
"Keep legal terms accurate and understandable:\n\n"
f"{text}"
)
contents = [types.Content(role="user", parts=[types.Part(text=prompt)])]
config = types.GenerateContentConfig(temperature=0.3, max_output_tokens=2048)
last_error = None
for name in MODEL_CANDIDATES:
for model_name in _model_variants(name):
try:
resp = client.models.generate_content(
model=model_name,
contents=contents,
config=config,
)
return resp.text
except Exception as e:
last_error = e
continue
return f"Translation unavailable. Model error: {last_error}"
except Exception:
return "Translation unavailable at the moment."
def process_image(uploaded_file):
"""Returns (jpeg_bytes, PIL_image_for_display)"""
try:
img = Image.open(uploaded_file)
if img.mode != "RGB":
img = img.convert("RGB")
img.thumbnail((1920, 1920), Image.Resampling.LANCZOS)
buf = BytesIO()
img.save(buf, format="JPEG", quality=85)
return buf.getvalue(), img
except Exception as e:
st.error(f"Image error: {e}")
return None, None
# -----------------------------------------------------------------------------
# EVIDENCE / PDF
# -----------------------------------------------------------------------------
def serialize_uploaded_files(uploaded_files):
if not uploaded_files:
return []
return [
{"name": getattr(f, "name", "file"), "type": getattr(f, "type", ""), "size": getattr(f, "size", 0)}
for f in uploaded_files
]
def add_evidence_entry(incident_date, incident_time, incident_type, description,
evidence_files=None, witnesses="", location=""):
entry = {
"logged_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"incident_date": incident_date.strftime("%Y-%m-%d"),
"incident_time": incident_time.strftime("%H:%M"),
"incident_type": incident_type,
"description": description,
"witnesses": witnesses,
"location": location,
"evidence_files": serialize_uploaded_files(evidence_files),
}
# Save to database and get the ID
entry_id = save_evidence_to_db(entry)
entry["id"] = entry_id
# Add to session state (for current session)
st.session_state.evidence_timeline.append(entry)
return entry
def evidence_hash():
parts = []
for e in st.session_state.evidence_timeline:
files = ",".join([f.get("name", "") for f in (e.get("evidence_files") or [])])
parts.append(
f"{e.get('incident_date')}|{e.get('incident_time')}|{e.get('incident_type')}|"
f"{e.get('location')}|{e.get('witnesses')}|{e.get('description')}|{files}"
)
return hashlib.md5("\n".join(parts).encode("utf-8", errors="ignore")).hexdigest()
def generate_pdf_bytes():
if not st.session_state.evidence_timeline:
return None
buf = BytesIO()
doc = SimpleDocTemplate(buf, pagesize=A4)
elements = []
styles = getSampleStyleSheet()
title_style = ParagraphStyle("Title", parent=styles["Heading1"], fontSize=22, alignment=TA_CENTER, spaceAfter=24)
elements.append(Paragraph("EVIDENCE TIMELINE REPORT", title_style))
elements.append(Spacer(1, 0.2 * inch))
metadata = [
["Generated:", datetime.now().strftime("%Y-%m-%d %H:%M:%S")],
["Incidents:", str(len(st.session_state.evidence_timeline))],
]
metadata_table = Table(metadata, colWidths=[2 * inch, 4 * inch])
metadata_table.setStyle(TableStyle([("GRID", (0, 0), (-1, -1), 0.8, colors.grey)]))
elements.append(metadata_table)
elements.append(Spacer(1, 0.35 * inch))
for idx, entry in enumerate(
sorted(st.session_state.evidence_timeline, key=lambda x: (x["incident_date"], x["incident_time"])), 1
):
file_names = ", ".join([f.get("name", "") for f in (entry.get("evidence_files") or [])]) or "N/A"
entry_data = [
["#:", str(entry.get("id", idx))],
["Date:", f"{entry['incident_date']} at {entry['incident_time']}"],
["Type:", entry["incident_type"]],
["Location:", entry["location"] or "N/A"],
["Witnesses:", entry["witnesses"] or "N/A"],
["Evidence files:", file_names],
["Description:", entry["description"]],
]
entry_table = Table(entry_data, colWidths=[1.5 * inch, 4.5 * inch])
entry_table.setStyle(TableStyle([("GRID", (0, 0), (-1, -1), 0.5, colors.grey)]))
elements.append(entry_table)
elements.append(Spacer(1, 0.18 * inch))
doc.build(elements)
buf.seek(0)
return buf.getvalue()
def get_cached_pdf():
h = evidence_hash()
if st.session_state._pdf_cache is None or st.session_state._pdf_cache_hash != h:
st.session_state._pdf_cache = generate_pdf_bytes()
st.session_state._pdf_cache_hash = h
return st.session_state._pdf_cache
# -----------------------------------------------------------------------------
# JS helpers
# -----------------------------------------------------------------------------
def inject_chat_paperclip_label_js():
"""Inject a <label> into chat input linked to sidebar file input."""
components.html(
"""