-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
907 lines (757 loc) · 40.9 KB
/
app.py
File metadata and controls
907 lines (757 loc) · 40.9 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
# ==========================================================
# CONFLICT OBSERVATORY – MAIN APPLICATION
# ==========================================================
# Streamlit application core
#
# Responsibilities:
# - Data loading
# - Temporal preparation
# - Analytical filters
# - Strategic dashboard
# - Module navigation
# ==========================================================
import streamlit as st
import pandas as pd
import plotly.express as px
import os
import hashlib
import uuid
import base64
from streamlit_folium import st_folium
from modules.statistical_module import render_statistical_module
from modules.methodology_module import render_methodology
from modules.TOO_module import render_overview_map
from modules.Geospatial_analysis_module import (
render_analytical_map,
render_sector_pressure_map,
render_regional_activity_map,
render_control_zone_map,
render_operational_corridor_map
)
from modules.table_module import render_table_module
from modules.report_builder import (
generate_csv,
generate_citation_txt,
generate_bibtex,
generate_ris,
generate_mla,
generate_chicago,
generate_numbered,
generate_html_report
)
from modules.mobile_module import inject_mobile_responsiveness
# ==========================================================
# PAGE CONFIGURATION
# ==========================================================
st.set_page_config(
page_title="Western Sahara War Archive (2020–2024)",
layout="wide",
initial_sidebar_state="expanded",
menu_items={
'About': "### Western Sahara War Archive\nA Digital Humanities research project by Jorge Teixeira (CEAUP)."
}
)
# ==========================================================
# PREMIUM CSS INJECTION
# ==========================================================
st.markdown("""
<style>
/* Styling for the Sidebar */
[data-testid="stSidebar"] {
border-right: 1px solid rgba(128, 128, 128, 0.2);
width: 442px !important;
min-width: 442px !important;
max-width: 442px !important;
}
/* Elegant Sidebar Headers */
[data-testid="stSidebarNav"] h1, [data-testid="stSidebar"] h1, [data-testid="stSidebar"] h2 {
font-family: 'Inter', sans-serif;
font-weight: 700;
letter-spacing: -0.02em;
}
/* Enhancing Multiselect appearance */
.stMultiSelect, .stSelectbox, .stRadio {
border-radius: 8px !important;
}
/* Style for the Select All Checkboxes */
.stCheckbox {
padding-bottom: 0px !important;
margin-bottom: -5px !important;
}
.stCheckbox label div p {
font-size: 11px !important;
font-style: italic;
opacity: 0.7;
}
/* Expander styling */
.st-emotion-cache-p5msec {
border-radius: 10px !important;
border: 1px solid rgba(128, 128, 128, 0.2) !important;
}
/* Small text for methodological sidebar section */
.framework-text {
font-size: 0.8rem !important;
line-height: 1.3 !important;
opacity: 0.9;
}
.framework-text h3 {
font-size: 0.9rem !important;
margin-top: 10px !important;
margin-bottom: 5px !important;
}
</style>
""", unsafe_allow_html=True)
# Injetar regras específicas para tablets/telemóveis
inject_mobile_responsiveness()
# ==========================================================
# GLOBAL UNIQUE KEY SYSTEM
# ==========================================================
_visual_counter = 0
def get_unique_key(prefix: str = "viz") -> str:
"""
Generate a globally unique, stable widget key.
Uses a monotonically incrementing counter to produce deterministic
keys that remain stable across reruns as long as render order is unchanged.
Parameters
----------
prefix : str
Human-readable prefix to identify the widget type (e.g. 'selectbox').
Returns
-------
str
A unique key string in the format '<prefix>_<counter>'.
"""
global _visual_counter
_visual_counter += 1
return f"{prefix}_{_visual_counter}"
def st_selectbox_unique(label: str, options: list, **kwargs) -> object:
"""Wrapper for st.selectbox that auto-assigns a unique key if none is provided."""
if "key" not in kwargs:
kwargs["key"] = get_unique_key("selectbox")
return st.selectbox(label, options, **kwargs)
def st_multiselect_unique(label: str, options: list, default: list = None, **kwargs) -> list:
"""Wrapper for st.multiselect that auto-assigns a unique key if none is provided."""
if "key" not in kwargs:
kwargs["key"] = get_unique_key("multiselect")
return st.multiselect(label, options, default=default, **kwargs)
def st_radio_unique(label: str, options: list, **kwargs) -> object:
"""Wrapper for st.radio that auto-assigns a unique key if none is provided."""
if "key" not in kwargs:
kwargs["key"] = get_unique_key("radio")
return st.radio(label, options, **kwargs)
_original_st_folium = st_folium
def st_folium_unique(map_object, **kwargs) -> dict:
"""Wrapper for st_folium that auto-assigns a unique key if none is provided."""
if "key" not in kwargs:
kwargs["key"] = get_unique_key("folium")
return _original_st_folium(map_object, **kwargs)
st_folium = st_folium_unique
# ==========================================================
# UI COMPONENTS (BREADCRUMBS & HELPERS)
# ==========================================================
def render_breadcrumbs(current_menu: str, sub_path: str = None):
"""Render a clean, responsive breadcrumb navigation bar."""
items = ["Archive", current_menu]
if sub_path:
items.append(sub_path)
# Modern breadcrumb style
bc_links = []
for i, item in enumerate(items):
if i == len(items) - 1:
bc_links.append(f'<span style="color: #64B5F6; font-weight: 700;">{item}</span>')
else:
bc_links.append(f'<span style="opacity: 0.6;">{item}</span>')
bc_html = f"""
<div style="margin-top: -15px; margin-bottom: 25px; font-size: 0.85rem; letter-spacing: 0.02em; display: flex; align-items: center; gap: 10px;">
{" <span style='opacity: 0.3;'>/</span> ".join(bc_links)}
</div>
"""
st.markdown(bc_html, unsafe_allow_html=True)
def metric_card(label: str, value: str, delta: str = None, help_text: str = None):
"""Custom metric card with more professional styling."""
with st.container():
st.markdown(f"""
<div style="background: rgba(255,255,255,0.03); padding: 20px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.05); height: 100%;">
<div style="font-size: 0.8rem; color: #AAA; text-transform: uppercase; font-weight: 600; margin-bottom: 8px;">{label}</div>
<div style="font-size: 1.8rem; font-weight: 700; color: #FFF;">{value}</div>
{f'<div style="font-size: 0.8rem; color: #64B5F6; margin-top: 5px;">{delta}</div>' if delta else ''}
</div>
""", unsafe_allow_html=True)
# ==========================================================
# ARCHIVAL INFRASTRUCTURE (DATA & HELPERS)
# ==========================================================
@st.cache_data
def load_events() -> pd.DataFrame:
"""
Load and pre-process the conflict event dataset from CSV.
Reads the archival CSV, parses dates, cleans coordinate strings,
and converts all temporal columns to integer types.
Results are cached by Streamlit to avoid redundant I/O on reruns.
Returns
-------
pd.DataFrame
Fully cleaned and typed event dataframe ready for analysis.
"""
df = pd.read_csv("data/Matrix_Database_2020_2024.csv", sep=";", low_memory=False)
df["Event_Date"] = pd.to_datetime(df["Event_Date"], dayfirst=True, errors="coerce")
df["N_of_Event"] = pd.to_numeric(df["N_of_Event"], errors="coerce").fillna(0)
def clean_coord(val: object, pos_suffix: str, neg_suffix: str) -> float:
"""Parse a coordinate string with cardinal direction suffix to float."""
if pd.isna(val) or not isinstance(val, str): return 0.0
val = val.replace("°", "")
if pos_suffix in val: return float(val.replace(pos_suffix, ""))
if neg_suffix in val: return -float(val.replace(neg_suffix, ""))
try: return float(val)
except: return 0.0
df["Meso_Level_Latitude"] = df["Meso_Level_Latitude"].apply(lambda x: clean_coord(x, "N", "S"))
df["Meso_Level_Longitude"] = df["Meso_Level_Longitude"].apply(lambda x: clean_coord(x, "E", "W"))
# Convert temporal columns to numeric/int safely
temp_cols = [
"Calender_Year", "Calender_Month", "Calender_Quarter", "Calender_Semester", "Calender_Week",
"Conflict_Year", "Conflict_Month", "Conflict_Quarter", "Conflict_Semester", "Conflict_Week"
]
for c in temp_cols:
if c in df.columns:
df[c] = pd.to_numeric(df[c], errors="coerce").fillna(0).astype(int)
return df
def sort_sectors(sectors: list) -> list:
"""
Sort sector IDs numerically (e.g. S1, S2, ..., S13).
Extracts the numeric suffix from each sector label and sorts
accordingly, avoiding the alphabetical mismatch of 'S10' < 'S2'.
Parameters
----------
sectors : list
List of sector ID strings (e.g. ['S3', 'S10', 'S1']).
Returns
-------
list
Sorted list of sector IDs in natural numeric order.
"""
def get_num(s: str) -> int:
"""Extract the numeric suffix from a sector ID string."""
if not isinstance(s, str): return 0
num_part = ''.join(filter(str.isdigit, s))
return int(num_part) if num_part else 0
return sorted(sectors, key=get_num)
df = load_events()
# ==========================================================
# INSTITUTIONAL HEADER
# ==========================================================
# --- Institutional Header (Centered with Logo) ---
logo_path_header = os.path.join("assets", "logos", "logo_wswa.png")
if os.path.exists(logo_path_header):
with open(logo_path_header, "rb") as f:
encoded_logo = base64.b64encode(f.read()).decode()
st.markdown(f"""
<div style="text-align: center; margin-bottom: 30px;">
<div style="display: flex; align-items: center; justify-content: center; gap: 25px; margin-bottom: 15px; flex-wrap: wrap;">
<img src="data:image/png;base64,{encoded_logo}" width="120">
<h1 style="margin: 0; font-family: 'Inter', sans-serif; font-weight: 800; letter-spacing: -0.03em;">
Western Sahara War Archive (2020–2024)
</h1>
</div>
<h3 style="margin: 0; font-weight: 400; opacity: 0.9;">Interactive Geospatial Conflict Observatory</h3>
<p style="margin: 10px 0; font-size: 0.9rem; font-style: italic; opacity: 0.7;">
Note: This information is subject to continuous update and institutional review.
</p>
<a href="https://westernsaharawararchive.com/" target="_blank" style="text-decoration: none; color: #64B5F6; font-weight: 600; font-size: 1.1rem;">
Visit Project Page
</a>
</div>
""", unsafe_allow_html=True)
else:
st.title("Western Sahara War Archive (2020–2024)")
st.markdown("### Interactive Geospatial Conflict Observatory")
st.markdown("*Note: This information is subject to continuous update and institutional review.*")
st.markdown("[Visit Project Page](https://westernsaharawararchive.com/)")
# ==========================================================
# CENTRALIZED NAVIGATION
# ==========================================================
st.markdown("""
<style>
/* Sleek container rounding */
.block-container {
padding-top: 2rem !important;
padding-bottom: 2rem !important;
}
/* Blocky Navbar Styling (Refined for Streamlit Radio) */
div[role="radiogroup"] {
background-color: #000000; /* Solid Black Background */
padding: 0 !important;
border-radius: 0 !important;
display: flex !important;
flex-direction: row !important;
flex-wrap: nowrap !important;
gap: 0 !important;
width: 100% !important;
max-width: 100% !important;
border: none !important;
margin-top: 15px;
margin-bottom: 25px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.6);
}
/* Force all Streamlit wrappers for the radio to be full width */
div[role="radiogroup"] > div {
width: 100% !important;
display: flex !important;
flex-direction: row !important;
gap: 0 !important;
}
/* Hide the radio button markers (dots) */
div[role="radiogroup"] [data-testid="stMarker"] {
display: none !important;
}
/* Style the labels as full-width blocks */
div[role="radiogroup"] label {
flex: 1 1 0% !important; /* Ensure they grow equally and start from 0 */
background-color: #000000 !important;
color: #FFFFFF !important;
padding: 22px 10px !important;
border-radius: 0 !important;
transition: all 0.2s ease;
cursor: pointer;
border: none !important;
border-right: 1px solid rgba(255, 255, 255, 0.15) !important;
text-align: center;
display: flex;
align-items: center;
justify-content: center;
font-weight: 600 !important;
font-size: 0.85rem;
text-transform: uppercase;
letter-spacing: 0.08em;
margin: 0 !important;
}
div[role="radiogroup"] label:hover {
background-color: #1a1a1a !important;
color: #ef7d00 !important;
}
/* Active State (Orange highlight) */
div[role="radiogroup"] label[data-checked="true"],
div[role="radiogroup"] label:has(input:checked) {
background-color: #ef7d00 !important;
color: #000000 !important;
font-weight: 800 !important;
box-shadow: inset 0 0 10px rgba(0,0,0,0.2);
}
/* Remove border from last child labels */
div[role="radiogroup"] label:last-child {
border-right: none !important;
}
/* Ensure the text inside labels is centered and has no extra space */
div[role="radiogroup"] label div[data-testid="stMarkdownContainer"] p {
margin: 0 !important;
line-height: 1 !important;
white-space: nowrap; /* Prevent text wrapping within the blocks */
}
/* Metrics beautification (Dark Theme) */
div[data-testid="stMetricValue"] {
font-size: 2.2rem !important;
font-weight: 700 !important;
color: #e0e0e0 !important;
}
</style>
""", unsafe_allow_html=True)
menu = st.radio(
"Explore the Observatory",
[
"Theatre of Operations Overview",
"Data",
"Conflict Analysis Suite",
"Methodology",
"Documents",
"About Us"
],
horizontal=True,
label_visibility="collapsed"
)
# Render Breadcrumbs based on active menu
render_breadcrumbs(menu)
# ==========================================================
# GLOBAL STATE & DATA FILTERING (NO UI HERE)
# ==========================================================
# Initialize defaults in session_state if missing to prevent crashes
if "global_time_framework" not in st.session_state: st.session_state.global_time_framework = "Conflict Time"
if "global_years_filter" not in st.session_state: st.session_state.global_years_filter = sorted(df["Conflict_Year"].dropna().unique())
if "global_quarter_filter" not in st.session_state: st.session_state.global_quarter_filter = sorted(df["Conflict_Quarter"].dropna().unique())
if "global_semester_filter" not in st.session_state: st.session_state.global_semester_filter = sorted(df["Conflict_Semester"].dropna().unique())
if "global_season_filter" not in st.session_state: st.session_state.global_season_filter = sorted(df["Conflict_Season"].dropna().unique())
if "global_mr_filter" not in st.session_state: st.session_state.global_mr_filter = []
if "global_sector_filter" not in st.session_state: st.session_state.global_sector_filter = []
if "global_actor_filter" not in st.session_state: st.session_state.global_actor_filter = []
# Fetch active global filters from session_state
time_mode = st.session_state.global_time_framework
year_col = "Conflict_Year" if time_mode == "Conflict Time" else "Calender_Year"
q_col = "Conflict_Quarter" if time_mode == "Conflict Time" else "Calender_Quarter"
sem_col = "Conflict_Semester" if time_mode == "Conflict Time" else "Calender_Semester"
sea_col = "Conflict_Season" if time_mode == "Conflict Time" else "Calender_Season"
selected_years = st.session_state.global_years_filter
selected_quarters = st.session_state.global_quarter_filter
selected_semesters = st.session_state.global_semester_filter
selected_seasons = st.session_state.global_season_filter
mr_filter = st.session_state.global_mr_filter
sector_filter = st.session_state.global_sector_filter
actor_filter = st.session_state.global_actor_filter
# Global data filtering logic
df_f = df[
(df[year_col].isin(selected_years)) &
(df[q_col].isin(selected_quarters)) &
(df[sem_col].isin(selected_semesters)) &
(df[sea_col].isin(selected_seasons))
]
if mr_filter:
df_f = df_f[df_f["Macro_Level_ID"].isin(mr_filter)]
if sector_filter:
df_f = df_f[df_f["Meso_Level_ID"].isin(sector_filter)]
if actor_filter:
df_f = df_f[
(df_f["Attacker"].isin(actor_filter)) |
(df_f["N_of_Event"] == 0)
]
def get_timeframe_str() -> str:
years = sorted(selected_years)
if not years: return "No Period Selected"
if len(years) == 1: return str(years[0])
return f"{min(years)}-{max(years)}"
timeframe_str = get_timeframe_str()
# Performance Optimization: "Apply" state for heavy analytics
if "analysis_applied" not in st.session_state: st.session_state.analysis_applied = False
st.markdown("---")
# ==========================================================
# COLOR SYSTEM
# ==========================================================
region_colors = {
"MR1": "#E2EFD9",
"MR2": "#FEF2CB",
"MR3": "#FBE4D5"
}
sector_colors = {
"S1": "#BED5B4", "S2": "#90BB7A", "S3": "#68A242", "S4": "#568736",
"S5": "#FFDDAD", "S6": "#FFCA69", "S7": "#EFB300", "S8": "#C89600",
"S9": "#FF6161", "S10": "#FF3737", "S11": "#FF1D1D", "S12": "#D20000",
"S13": "#A80000"
}
# ==========================================================
# CONFLICT TIMELINE (FUNCTION)
# ==========================================================
def render_timeline():
st.subheader("Conflict Chronology Since 13 November 2020")
timeline_data = pd.DataFrame({
"Phase":[
"Ceasefire Breakdown (Guerguerat)",
"Initial Low Intensity Exchange Phase",
"Sustained Attritional Phase",
"Current Operational Phase"
],
"Start":[pd.to_datetime(d) for d in [
"2020-11-13",
"2021-01-01",
"2022-01-01",
"2023-01-01"
]],
"End":[
pd.to_datetime("2020-12-31"),
pd.to_datetime("2021-12-31"),
pd.to_datetime("2022-12-31"),
pd.Timestamp.today()
]
})
fig_timeline = px.timeline(
timeline_data,
x_start="Start",
x_end="End",
y="Phase"
)
fig_timeline.update_yaxes(autorange="reversed")
st.plotly_chart(fig_timeline, width="stretch")
# ==========================================================
# ABOUT US (TEAM & PROJECT)
# ==========================================================
def render_about_us():
st.header("About the Project")
tab1, tab2, tab3 = st.tabs(["About Project", "Cookies Policy", "Legal Framework (EU)"])
with tab1:
col1, col2 = st.columns([2, 1])
with col1:
st.markdown("""
### Western Sahara War Archive (WSWA)
The **Western Sahara War Archive** is a Digital Humanities research project dedicated to the documentation and geospatial analysis of the conflict in Western Sahara since the breakdown of the ceasefire on November 13, 2020.
Our mission is to provide an open-access, academically rigorous platform for researchers, analysts, and the public to understand the operational dynamics and human impact of this protracted war.
""")
st.subheader("Project Team")
team_col1, team_col2 = st.columns(2)
with team_col1:
st.image("https://www.cienciavitae.pt/portal/FB17-55DF-0E11/foto", width=150) # Fallback image if possible or just text
st.markdown("""
**Jorge Teixeira**
*Lead Investigator & PI*
[CiênciaVitae Profile](https://www.cienciavitae.pt/portal/FB17-55DF-0E11)
""")
with team_col2:
st.markdown("""
<br><br>
""", unsafe_allow_html=True) # Spacer
st.markdown("""
**Isabel Lourenço**
*Researcher & Contributor*
[CiênciaVitae Profile](https://www.cienciavitae.pt/portal/6E15-6D4A-6324)
""")
with col2:
st.info("**Support the Research**")
st.markdown("""
This archive is hosted at the **Centro de Estudos Africanos da Universidade do Porto (CEAUP)**.
For inquiries or data contributions, please visit our [official website](https://westernsaharawararchive.com/).
""")
st.subheader("Multimedia")
st.markdown("[](https://www.youtube.com/channel/UCDtLsJ05L5EblXSzfcKbRkA)")
with tab2:
st.subheader("Privacy & Cookie Policy (GDPR / ePrivacy)")
st.markdown("""
**1. Personal Data Protection (GDPR & PT Law 58/2019)**
In strict compliance with the European General Data Protection Regulation (Regulation (EU) 2016/679) and the Portuguese Data Protection Law (Law no. 58/2019), the *Western Sahara War Archive* **does not collect, store, or process** any Personally Identifiable Information (PII) from its visitors. Access to the platform is fully anonymous and requires no registration. We do not engage in data brokerage or third-party data sharing.
**2. Cookie Compliance (ePrivacy Directive & PT Law 41/2004)**
This academic infrastructure utilizes only **strictly necessary technical cookies** natively generated by the *Streamlit* framework. These cookies are exclusively deployed to maintain the active state of your session (e.g., filter memory, interactive map states) during navigation.
We do not deploy targeting cookies, corporate marketing trackers (pixels), or third-party analytics engines. In accordance with Portuguese Law no. 46/2012 (transposing the EU ePrivacy Directive), explicit prior consent is not required for purely functional and technical session cookies. By continuing to interact with the dashboard, you acknowledge the temporary use of these technical session identifiers, which are automatically erased upon closing your browser.
""")
with tab3:
st.subheader("Legal Framework (EU & Portugal)")
st.markdown("""
**1. Academic Exemption & EU Digital Services Act (DSA)**
The *Western Sahara War Archive* operates strictly as a **Digital Humanities and Scientific Research Archive**. The platform operates under the explicit exemptions granted for academic research, journalistic purposes, and open scientific inquiry under European legislation, including the Digital Services Act (Regulation (EU) 2022/2065). The overarching objective is to promote open-access transparency and empirical conflict analysis.
**2. Institutional Identity (E-Commerce DL no. 7/2004)**
In accordance with the Portuguese legal requirements for digital platforms, this project is managed by independent researchers hosted at the **Centro de Estudos Africanos da Universidade do Porto (CEAUP)**.
**Scientific Lead:** Jorge Teixeira. This analytical observatory is strictly non-profit and engages in zero commercial activity.
**3. Intellectual Property & Copyright (CDADC)**
Under the Portuguese Code of Copyright and Related Rights (CDADC) and the EU Copyright Directive (Directive (EU) 2019/790), the custom analytical visualizations (Modules [B] and [G]), underlying algorithmic methodology, and comprehensive statistical reports are protected intellectual property.
The primary cartographic and chronological datasets are aggregated from public domain official military communiqués under the scientific "Fair Use" doctrine. Appropriate academic citation leveraging the provided Zenodo/DOI identifiers is mandatory for the replication or reuse of this infrastructure's data.
""")
# ==========================================================
# DOCUMENTS (FILE MANAGER)
# ==========================================================
def render_documents():
st.header("Institutional & Research Documents")
st.markdown("""
This repository contains official documents and authorizations granted by the **Sahrawi Press Service (SPS)** and the **Sahrawi Arab Democratic Republic (SADR)**.
These documents formally authorize the research team to utilize, archive, analyse, and publish conflict data, official communiqués, and news released through their institutional platforms for academic and historical documentation.
""")
docs_dir = "docs"
if not os.path.exists(docs_dir):
st.error(f"Directory '{docs_dir}' not found.")
return
files = [f for f in os.listdir(docs_dir) if os.path.isfile(os.path.join(docs_dir, f))]
if not files:
st.info("No documents currently available in this section.")
return
for file in files:
col1, col2 = st.columns([3, 1])
file_path = os.path.join(docs_dir, file)
with col1:
st.write(f"**{file}**")
with col2:
with open(file_path, "rb") as f:
st.download_button(
label="Download PDF",
data=f,
file_name=file,
mime="application/pdf",
key=f"dl_{file}"
)
st.markdown("---")
# Logic replaced and moved to the infrastructure section above
# Rendering Logic - Replaced by global sidebar and direct module calls in selection blocks
# ==========================================================
# RENDERING LOGIC
# ==========================================================
if menu == "Theatre of Operations Overview":
st.header("Theatre of Operations Overview")
# --- Strategic Metrics ---
with st.container():
m1, m2, m3, m4 = st.columns(4)
total_ev = int(df_f["N_of_Event"].sum())
active_sectors = df_f[df_f["N_of_Event"] > 0]["Meso_Level_ID"].nunique()
total_sectors = df_f["Meso_Level_ID"].nunique()
territorial_spread = (active_sectors / total_sectors) * 100 if total_sectors > 0 else 0
# Combat Pressure (Avg events per day in selection)
days_in_selection = df_f["Event_Date"].nunique()
strategic_tempo = total_ev / days_in_selection if days_in_selection > 0 else 0
with m1: metric_card("Total Conflict Events", f"{total_ev:,}")
with m2: metric_card("Sectors with Combat", str(active_sectors))
with m3: metric_card("Territorial Spread", f"{territorial_spread:.1f}%")
with m4: metric_card("Strategic Tempo", f"{strategic_tempo:.2f} Ev/Day")
st.markdown("---")
st.subheader("B1: Full Operational Theater Overview")
render_overview_map(timeframe_str, mode="B1")
st.caption("**How to read (B1):** Displays the comprehensive geographic layout of the operational theater. © Jorge Teixeira")
st.markdown("---")
render_timeline()
st.caption("**How to read (Timeline):** Displays key milestones and chronological progression.")
elif menu == "Conflict Analysis Suite":
st.header("Conflict Analysis Suite")
# 1. THE CONTROL PANEL (FILTERS UI)
st.markdown("### 1. Global Analytical Control Panel")
with st.container():
# Compact style for the filter section
st.markdown('<div style="background: rgba(100, 181, 246, 0.05); padding: 20px; border-radius: 12px; border: 1px solid rgba(100, 181, 246, 0.2); margin-bottom: 25px;">', unsafe_allow_html=True)
fcol1, fcol2, fcol3 = st.columns([1.5, 1.2, 1.2])
with fcol1:
st.markdown("**Temporal Parameters**")
new_time_mode = st_radio_unique("Framework", ["Conflict Time", "Civil Time"], key="global_time_framework", horizontal=True)
new_year_col = "Conflict_Year" if new_time_mode == "Conflict Time" else "Calender_Year"
fy1, fy2 = st.columns(2)
avail_y = sorted(df[new_year_col].dropna().unique())
def_y = [y for y in st.session_state.get("global_years_filter", []) if y in avail_y]
with fy1: st_multiselect_unique("Year(s)", avail_y, default=def_y if def_y else avail_y, key="global_years_filter")
avail_q = sorted(df[q_col].dropna().unique())
def_q = [q for q in st.session_state.get("global_quarter_filter", []) if q in avail_q]
with fy2: st_multiselect_unique("Quarter(s)", avail_q, default=def_q if def_q else avail_q, key="global_quarter_filter")
with fcol2:
st.markdown("**Territorial Parameters**")
avail_mrs = sorted(df["Macro_Level_ID"].unique())
def_mr = [m for m in st.session_state.get("global_mr_filter", []) if m in avail_mrs]
st_multiselect_unique("Military Region (Macro)", avail_mrs, default=def_mr, key="global_mr_filter")
sector_opts = sort_sectors(df["Meso_Level_ID"].unique())
def_sec = [s for s in st.session_state.get("global_sector_filter", []) if s in sector_opts]
st_multiselect_unique("Sector (Meso)", sector_opts, default=def_sec, key="global_sector_filter")
with fcol3:
st.markdown("**Actor Initiative**")
if "Attacker" in df.columns:
avail_actors = sorted([str(x) for x in df["Attacker"].dropna().unique() if str(x).strip() != ""])
def_act = [a for a in st.session_state.get("global_actor_filter", []) if a in avail_actors]
st_multiselect_unique("Attacker", avail_actors, default=def_act if def_act else avail_actors, key="global_actor_filter")
st.markdown(f"**Status:** {int(df_f['N_of_Event'].sum())} events filtered for {timeframe_str}.")
# Performance "Apply" Button
apply_col1, apply_col2 = st.columns([1, 1])
with apply_col1:
if st.button("Execute Analytical Deep-Dive", type="primary", use_container_width=True):
st.session_state.analysis_applied = True
st.rerun()
with apply_col2:
if st.button("Reset Parameters", use_container_width=True):
st.session_state.analysis_applied = False
# Reset logic could be more thorough if needed
st.rerun()
st.markdown('</div>', unsafe_allow_html=True)
st.markdown("---")
# 2. THE PERSPECTIVES (SUB-MENU)
st.markdown("### 2. Analytical Perspectives")
suite_view = st.radio("Select Perspective", [
"Strategic Macro Maps",
"Geospatial Analytics",
"Statistical Models",
"Report Exporter"
], horizontal=True, label_visibility="collapsed")
# Update breadcrumbs with sub-path
render_breadcrumbs(menu, suite_view)
st.markdown("---")
if not st.session_state.analysis_applied and suite_view != "Report Exporter":
st.info("💡 Adjust your filters above and click **Execute Analytical Deep-Dive** to generate the maps and models.")
st.stop()
if suite_view == "Strategic Macro Maps":
with st.popover("ℹ️ About Strategic Macro Maps (B2–B6)"):
st.markdown("""
**Strategic Macro Maps [B2–B6]** focus on the static and structural elements of the operational theater.
They provide the baseline geospatial context (territorial control, command boundaries, and defensive infrastructure)
necessary to interpret dynamic tactical events.
""")
b_tabs = st.tabs(["B2: Territorial Control", "B3: Military Regions", "B4: Operational Sectors", "B5: Military Wall", "B6: Logistics & Hydro"])
with b_tabs[0]: st.subheader("B2: Territorial Control Map"); render_overview_map(timeframe_str, mode="B2")
with b_tabs[1]: st.subheader("B3: Military Regions Map"); render_overview_map(timeframe_str, mode="B3")
with b_tabs[2]: st.subheader("B4: Operational Sectors Map"); render_overview_map(timeframe_str, mode="B4")
with b_tabs[3]: st.subheader("B5: Moroccan Military Wall Map"); render_overview_map(timeframe_str, mode="B5")
with b_tabs[4]: st.subheader("B6: Logistics & Strategic Geography"); render_overview_map(timeframe_str, mode="B6")
elif suite_view == "Geospatial Analytics":
if df_f.empty:
st.warning("No events for the selected filters.")
else:
with st.popover("ℹ️ About Geospatial Analytics (G1–G8)"):
st.markdown("""
**Geospatial Analytics [G1–G8]** apply advanced spatial modeling (KDE, Cluster Analysis) to conflict events.
These dynamic maps identify tactical density, conflict hotspots, and operational corridors,
allowing for the visualization of shifting combat pressure over time.
""")
selection_hash = hashlib.md5(str(selected_years + mr_filter + sector_filter + actor_filter).encode()).hexdigest()[:8]
g_tabs = st.tabs(["G1: Control Zones", "G2: Sector Pressure", "G3: Regional Activity", "G4: Tactical Density", "G5: Hotspots", "G6: Wall Pressure", "G7: Corridors", "G8: Actor Activity"])
with g_tabs[0]: st.markdown(f"### G1: Control Zone Map"); render_control_zone_map(df_f, map_key=f"control_{selection_hash}", timeframe=timeframe_str)
with g_tabs[1]: st.markdown(f"### G2: Sector Pressure Map"); render_sector_pressure_map(df_f, map_key=f"sector_{selection_hash}", timeframe=timeframe_str)
with g_tabs[2]: st.markdown(f"### G3: Regional Activity Map"); render_regional_activity_map(df_f, map_key=f"region_{selection_hash}", timeframe=timeframe_str)
with g_tabs[3]: st.markdown(f"### G4: Tactical Density Map"); render_analytical_map(df_f, mode="density", map_key=f"heat_{selection_hash}", timeframe=timeframe_str)
with g_tabs[4]: st.markdown(f"### G5: Conflict Hotspots Map"); render_analytical_map(df_f, mode="hotspot", map_key=f"hotspot_{selection_hash}", timeframe=timeframe_str)
with g_tabs[5]: st.markdown(f"### G6: Tactical Wall Pressure Map"); render_analytical_map(df_f, mode="wall_pressure", map_key=f"wall_p_{selection_hash}", timeframe=timeframe_str)
with g_tabs[6]: st.markdown(f"### G7: Operational Corridors Map"); render_operational_corridor_map(df_f, map_key=f"corridor_{selection_hash}", timeframe=timeframe_str)
with g_tabs[7]: st.markdown(f"### G8: Actor Activity Distribution Map"); render_analytical_map(df_f, mode="actor", map_key=f"actor_{selection_hash}", timeframe=timeframe_str)
elif suite_view == "Statistical Models":
with st.popover("ℹ️ About Statistical Analysis Suite (A1–A25)"):
st.markdown("""
**Statistical Models [A1–A25]** provide quantitative insights into the conflict's behavior.
From high-resolution descriptive statistics to predictive Markov chains, these models analyze
operational tempo, seasonal dynamics, and tactical initiative distribution.
""")
if df_f.empty:
st.warning("No events correspond to the selected analytical configuration.")
else:
df_stat = df_f.copy()
for col, default in [("Micro_Level_Name", "Unknown"), ("Meso_Level_Name", "Unknown"), ("Macro_Level_Name", "Unknown"), ("Country", "Unknown")]:
if col not in df_stat.columns: df_stat[col] = default
render_statistical_module(df_stat, timeframe=timeframe_str)
elif suite_view == "Report Exporter":
st.subheader("Data Export & Reporting")
rcol1, rcol2 = st.columns(2)
with rcol1:
st.markdown("#### Raw Database Export")
st.download_button("Download Active Dataset (CSV)", data=generate_csv(df_f), file_name=f"WSWA_Data_{timeframe_str.replace('-','_')}.csv", mime="text/csv", width="stretch")
with rcol2:
st.markdown("#### Comprehensive HTML Report")
if "report_html" not in st.session_state: st.session_state.report_html = None
if st.button("Compile Full Diagnostic Report", width="stretch"):
with st.spinner("Compiling full analytical report..."):
st.session_state.report_html = generate_html_report(df_f, timeframe_str, time_mode)
st.rerun()
if st.session_state.report_html:
st.download_button("Download Generated Report (HTML)", data=st.session_state.report_html, file_name=f"WSWA_Report_{timeframe_str.replace('-','_')}.html", mime="text/html", width="stretch")
elif menu == "Data":
render_table_module(df_f)
elif menu == "Methodology":
render_methodology(df_f, timeframe_str)
elif menu == "Documents":
render_documents()
elif menu == "About Us":
render_about_us()
# ==========================================================
# FOOTER (LOGOS)
# ==========================================================
st.markdown("---")
footer_col1, footer_col2, footer_col3, footer_col4 = st.columns([1,1,1,3])
logo_path = os.path.join("assets", "logos")
with footer_col1:
if os.path.exists(os.path.join(logo_path, "logo_wswa.png")):
with open(os.path.join(logo_path, "logo_wswa.png"), "rb") as f:
encoded = base64.b64encode(f.read()).decode()
st.markdown(f'<div style="background: white; padding: 12px; border-radius: 10px; display: inline-block; box-shadow: 0 4px 8px rgba(0,0,0,0.3);"><img src="data:image/png;base64,{encoded}" width="180"></div>', unsafe_allow_html=True)
st.markdown("<br>", unsafe_allow_html=True)
st.markdown("[](https://www.youtube.com/channel/UCDtLsJ05L5EblXSzfcKbRkA)")
with footer_col2:
if os.path.exists(os.path.join(logo_path, "logo_ceaup.jpg")):
with open(os.path.join(logo_path, "logo_ceaup.jpg"), "rb") as f:
encoded = base64.b64encode(f.read()).decode()
st.markdown(f'<div style="background: white; padding: 12px; border-radius: 10px; display: inline-block; box-shadow: 0 4px 8px rgba(0,0,0,0.3);"><img src="data:image/jpeg;base64,{encoded}" width="180"></div>', unsafe_allow_html=True)
st.markdown("<p style='font-size:20px; margin-top:8px;'><b>Host Institution</b></p>", unsafe_allow_html=True)
with footer_col3:
if os.path.exists(os.path.join(logo_path, "logo_fct.jpg")):
with open(os.path.join(logo_path, "logo_fct.jpg"), "rb") as f:
encoded = base64.b64encode(f.read()).decode()
st.markdown(f'<div style="background: white; padding: 12px; border-radius: 10px; display: inline-block; box-shadow: 0 4px 8px rgba(0,0,0,0.3);"><img src="data:image/jpeg;base64,{encoded}" width="180"></div>', unsafe_allow_html=True)
st.markdown("<p style='font-size:20px; margin-top:8px;'><b>Funding Agency</b></p>", unsafe_allow_html=True)
with footer_col4:
st.markdown("""
<div style="font-size: 18px; line-height: 1.8; color: #EEE; background: rgba(0,0,0,0.2); padding: 20px; border-radius: 10px;">
<b style="color: #FFF;">© 2024–2026 Jorge Teixeira / Western Sahara War Archive.</b> All rights reserved.<br>
<i style="color: #CCC;">Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0)</i><br><br>
This work is funded by Portuguese national funds through <b>FCT – Fundação para a Ciência e a Tecnologia, I.P.</b>,
under the Project <b>UIDB/00495/2020</b> (DOI: <a href="https://doi.org/10.54499/UIDB/00495/2020" target="_blank" style="color: #64B5F6; text-decoration: none; font-weight: bold;">10.54499/UIDB/00495/2020</a>).
<div style="margin-top: 15px; padding-top: 15px; border-top: 1px solid rgba(255,255,255,0.1); font-size: 12px; line-height: 1.4; color: #AAA;">
<b>Legal Compliance:</b> This platform strictly complies with the <b>EU GDPR</b> (Regulation 2016/679), the <b>ePrivacy Directive</b>, and Portuguese Legislative Frameworks (Lei 58/2019, Lei 41/2004, DL 7/2004, CDADC). Operating under the <b>EU Digital Services Act (DSA)</b> exemptions for non-profit Open Scientific Inquiry and Academic Research.<br>
<i>For detailed information regarding Data Protection, Copyrights, and essential Technical Cookies, please consult the "About Us" section.</i>
</div>
</div>
""", unsafe_allow_html=True)