-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
999 lines (808 loc) · 36.9 KB
/
Copy pathapp.py
File metadata and controls
999 lines (808 loc) · 36.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
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
import streamlit as st
import pandas as pd
import numpy as np
import joblib
import random
import html
if "lang" not in st.session_state:
st.session_state.lang = "en"
def t(en, es):
return es if st.session_state.lang == "es" else en
# =========================
# Configuración general
# =========================
st.set_page_config(
page_title="DPRK UPR Response Prediction Tool",
page_icon="🇰🇵",
layout="wide"
)
# =========================
# CSS
# =========================
st.markdown("""
<style>
.block-container {
max-width: 1100px;
padding-top: 2rem;
padding-bottom: 4rem;
}
h1 { margin-bottom: 0.3rem; }
h2, h3 { margin-top: 1.4rem; }
div[data-testid="stDataFrame"] { border-radius: 12px; }
.stRadio > div { gap: 1rem; }
.result-card-accept {
padding: 2rem;
border-radius: 18px;
background-color: #ecfdf3;
border: 1px solid #bbf7d0;
margin-bottom: 1rem;
}
.result-card-reject {
padding: 2rem;
border-radius: 18px;
background-color: #fef2f2;
border: 1px solid #fecaca;
margin-bottom: 1rem;
}
.warning-card {
padding: 1rem 1.2rem;
border-radius: 14px;
background-color: #fffbeb;
border: 1px solid #fde68a;
margin-bottom: 1rem;
}
.intro-highlight {
display: inline-block;
margin-top: 0.85rem;
margin-bottom: 1.2rem;
padding: 0.35rem 0.6rem;
background-color: #fef3a6;
border-radius: 6px;
font-weight: 600;
}
.opening-copy {
font-size: 1.06rem;
margin-bottom: 0.9rem;
line-height: 1.6;
}
.body-copy,
.stMarkdown p {
text-align: justify;
}
[data-testid="stImage"] img {
border-radius: 6px;
}
</style>
""", unsafe_allow_html=True)
def section_header(text):
st.markdown(f'<h2 style="color:#FF4B4B;">{text}</h2>', unsafe_allow_html=True)
st.image("UN.jpg", use_container_width=True)
st.title("🇰🇵 DPRK UPR Response Prediction Tool")
with st.container(border=True):
read_in_spanish = st.toggle(
"App en Español",
value=st.session_state.lang == "es",
)
st.session_state.lang = "es" if read_in_spanish else "en"
opening_intro = t(
"This tool simulates how the Democratic People's Republic of Korea (DPRK) might respond to a recommendation during the next Universal Periodic Review (UPR) process.",
"La presente herramienta permite estimar posibles respuestas de la República Popular Democrática de Corea (RPDC) frente a recomendaciones formuladas durante el próximo ciclo del Examen Periódico Universal (EPU).",
)
opening_body = t(
"Using historical UPR data and machine learning models, the tool estimates the <strong>probability that a recommendation will be accepted or rejected</strong> based on political, thematic, and discursive variables.<br><br><strong>❗ Predictions are probabilistic and should be interpreted as analytical scenarios rather than deterministic forecasts</strong>.",
"Utilizando datos históricos del EPU y modelos de aprendizaje automático, la aplicación estima la <strong>probabilidad de aceptación o rechazo de una recomendación</strong> a partir de variables políticas, temáticas y discursivas.<br><br><strong>❗ Las predicciones son probabilísticas y deben interpretarse como escenarios analíticos, no como pronósticos deterministas</strong>.",
)
st.markdown(
f'<div class="opening-copy body-copy">{opening_intro}</div>',
unsafe_allow_html=True,
)
st.markdown(
f'<div class="opening-copy body-copy">{opening_body}</div>',
unsafe_allow_html=True,
)
st.markdown(
f'<div class="intro-highlight">{t("Complete the fields below to generate a prediction.", "Complete los campos a continuación para generar una predicción.")}</div>',
unsafe_allow_html=True,
)
# =========================
# Cargar modelo y archivos
# =========================
@st.cache_resource
def load_artifacts():
model = joblib.load("modelo_xgb.pkl")
alignment_lookup = pd.read_csv("alignment_lookup.csv")
areas_lookup = pd.read_csv("areas_lookup.csv")
historical_recommendations = pd.read_csv("historical_recommendations.csv")
return (
model,
alignment_lookup,
areas_lookup,
historical_recommendations
)
try:
(
model,
alignment_lookup,
areas_lookup,
historical_recommendations
) = load_artifacts()
except FileNotFoundError:
st.error(
t(
"Missing artifact. Make sure these files are in the same folder as app.py: "
"modelo_xgb.pkl, alignment_lookup.csv, areas_lookup.csv, "
"historical_recommendations.csv.",
"Falta un archivo necesario. Asegúrese de que estos archivos estén en la misma carpeta que app.py: "
"modelo_xgb.pkl, alignment_lookup.csv, areas_lookup.csv e "
"historical_recommendations.csv.",
)
)
st.stop()
except Exception as e:
st.error(t(f"Error loading artifacts: {e}", f"Error al cargar archivos: {e}"))
st.stop()
# Obtener directamente del modelo las columnas exactas de entrenamiento
model_columns = model.get_booster().feature_names
if not model_columns:
st.error(
t(
"The model does not contain feature names. Retrain and save it using a pandas DataFrame with named columns.",
"El modelo no contiene nombres de variables. Vuelva a entrenarlo y guardarlo usando un DataFrame de pandas con columnas nombradas.",
)
)
st.stop()
model_columns = list(model_columns)
# =========================
# Normalizar lookups
# =========================
alignment_lookup.columns = alignment_lookup.columns.str.strip()
areas_lookup.columns = areas_lookup.columns.str.strip()
required_alignment_cols = {"Recommending_State", "Aligment_Score"}
if not required_alignment_cols.issubset(set(alignment_lookup.columns)):
st.error(
t(
"alignment_lookup.csv must contain the columns: "
"Recommending_State and Aligment_Score.",
"alignment_lookup.csv debe contener las columnas: "
"Recommending_State y Aligment_Score.",
)
)
st.stop()
area_lookup_col = areas_lookup.columns[0]
alignment_lookup["Recommending_State"] = (
alignment_lookup["Recommending_State"].astype(str).str.strip()
)
areas_lookup[area_lookup_col] = (
areas_lookup[area_lookup_col].astype(str).str.strip()
)
available_areas = sorted(
[x for x in areas_lookup[area_lookup_col].dropna().unique() if x != ""]
)
model_area_columns = [
col for col in model_columns
if col.startswith("Macro_Area_")
]
model_areas = sorted([
col.replace("Macro_Area_", "", 1)
for col in model_area_columns
])
areas_for_app = sorted(set(available_areas).intersection(set(model_areas)))
SENSITIVITY_BY_AREA = {
"Civil Liberties & Political Rights": 2,
"Disability Rights": 0,
"Economic & Social Rights": 0,
"Environment, Climate & Emergencies": 0,
"Equality & Non-Discrimination": 1,
"Gender Rights & Violence": 1,
"Governance, Institutions & Rule of Law": 1,
"Human Rights Education & Awareness": 0,
"International Mechanisms & Cooperation": 1,
}
if len(areas_for_app) == 0:
st.error(
t(
"No thematic areas in areas_lookup.csv match the Macro_Area dummy columns used by the model. "
"Regenerate areas_lookup.csv from the same dataset used to train the model.",
"Ninguna área temática de areas_lookup.csv coincide con las columnas dummy Macro_Area utilizadas por el modelo. "
"Regenere areas_lookup.csv a partir del mismo dataset usado para entrenar el modelo.",
)
)
st.stop()
missing_from_model = sorted(set(available_areas) - set(model_areas))
if len(missing_from_model) > 0:
st.markdown(f"""
<div class="warning-card">
{t(
"Some thematic areas in <code>areas_lookup.csv</code> are not present in the trained model columns "
"and were excluded from the selector. This usually means the lookup file and the model were not "
"generated from exactly the same training dataset.",
"Algunas áreas temáticas de <code>areas_lookup.csv</code> no están presentes en las columnas con las que se entrenó el modelo "
"y fueron excluidas del selector. Esto normalmente significa que el archivo lookup y el modelo no fueron "
"generados a partir exactamente del mismo dataset de entrenamiento.",
)}
</div>
""", unsafe_allow_html=True)
# =========================
# 1. País recomendante
# =========================
section_header(t("1. Recommending State", "1. Estado recomendante"))
st.markdown(t(
"""
Select the State issuing the recommendation.
""",
"""
Seleccione el Estado que emite la recomendación.
""",
), unsafe_allow_html=True)
recommending_country = st.selectbox(
t(
"Recommending State",
"Estado recomendante",
),
options=sorted(alignment_lookup["Recommending_State"].dropna().unique())
)
alignment_score = alignment_lookup.loc[
alignment_lookup["Recommending_State"] == recommending_country,
"Aligment_Score"
].iloc[0]
st.caption(
t(
f"**Alignment Score: {alignment_score:.3f}**. This score captures ideological proximity using UN General Assembly voting patterns, following the literature that treats voting behavior as a proxy for state preferences (Voeten, 2013). In this project, it is operationalized as the average absolute voting distance between each State and the DPRK, where 0 indicates no ideological proximity and 1 indicates complete alignment.",
f"**Puntaje de alineamiento: {alignment_score:.3f}**. Este puntaje captura la proximidad ideológica a partir de patrones de votación en la Asamblea General de las Naciones Unidas, siguiendo la literatura que utiliza el comportamiento de voto como proxy de las preferencias estatales (Voeten, 2013). Aquí, el puntaje de alineamiento se ha operacionalizado como la distancia absoluta promedio entre el voto de cada Estado y el de la RPDC, donde 0 indica ausencia de proximidad ideológica y 1 indica alineamiento completo.",
)
)
st.divider()
# =========================
# 2. Verb Intensity
# =========================
section_header(t("2. Verb Intensity", "2. Intensidad verbal"))
st.markdown(t(
"Use the scale below to classify how demanding the main verb of the recommendation is.",
"Utilice la escala a continuación para clasificar cuán imperativo es el verbo principal de la recomendación.",
), unsafe_allow_html=True)
verb_options = {
1: t("Low-demand", "Baja exigencia"),
2: t("Continuity", "Continuidad"),
3: t("Consideration", "Consideración"),
4: t("General action", "Acción general"),
5: t("Specific action", "Acción específica")
}
verb_intensity = st.select_slider(
t("Verb intensity", "Intensidad verbal"),
options=list(verb_options.keys()),
format_func=lambda x: verb_options[x]
)
with st.expander(t("See full verb intensity classification guide", "Ver guía completa de clasificación de intensidad verbal")):
st.markdown(t(
"""
### Low demand
Call, request, seek, share
### Continuity
Continue, maintain, persevere, persist, pursue, sustain
### Consideration
Assess, consider, envisage, examine, reconsider, review, study
### General action
Act (general), address, bolster, comply, cooperate, develop, encourage, engage, enhance, ensure, facilitate, foster, improve, increase, intensify, make every effort, pay attention, prioritize, promote, reduce, restrict, step up, strengthen, support, take measures
### Specific action
Abolish, accept, access, adopt, agree, align, allow, amend, become a party, build, carry out, cease, clarify, close, create, criminalize, decriminalize, dismantle, disclose, eliminate, enact, end, enforce, establish, extend, fulfil, guarantee, give, grant, halt, hold accountable, implement, incorporate, introduce, investigate, invest, invite, issue, join, lift, permit, prevent (when concrete), prohibit, prosecute, provide, publish, put an end, ratify, recognize, reform, refrain, release, remove, repatriate, respond, respect, return, revise, secure, sign, stop, submit, train, undertake, withdraw
""",
"""
### Baja exigencia
Call, request, seek, share
### Continuidad
Continue, maintain, persevere, persist, pursue, sustain
### Consideración
Assess, consider, envisage, examine, reconsider, review, study
### Acción general
Act (general), address, bolster, comply, cooperate, develop, encourage, engage, enhance, ensure, facilitate, foster, improve, increase, intensify, make every effort, pay attention, prioritize, promote, reduce, restrict, step up, strengthen, support, take measures
### Acción específica
Abolish, accept, access, adopt, agree, align, allow, amend, become a party, build, carry out, cease, clarify, close, create, criminalize, decriminalize, dismantle, disclose, eliminate, enact, end, enforce, establish, extend, fulfil, guarantee, give, grant, halt, hold accountable, implement, incorporate, introduce, investigate, invest, invite, issue, join, lift, permit, prevent (when concrete), prohibit, prosecute, provide, publish, put an end, ratify, recognize, reform, refrain, release, remove, repatriate, respond, respect, return, revise, secure, sign, stop, submit, train, undertake, withdraw
""",
))
st.divider()
# =========================
# 3. Thematic Area
# =========================
section_header(t("3. Thematic Area", "3. Área temática"))
st.markdown(
t(
"Select the primary thematic area addressed by the recommendation.",
"Seleccione el área temática principal abordada por la recomendación.",
),
unsafe_allow_html=True
)
area = st.selectbox(
t("Thematic area", "Área temática"),
options=areas_for_app
)
with st.expander(
t(
"See thematic area classification guide",
"Ver guía de clasificación de áreas temáticas"
)
):
st.markdown(
t(
"""
The thematic areas below are simplified analytical groupings derived from recurring issue categories across United Nations human rights mechanisms and UPR documentation. They do not correspond to an official UN taxonomy and were created exclusively for analytical and modeling purposes.
### Civil Liberties & Political Rights
Freedom of expression, association and religion, political participation, civil liberties, access to information, restrictions on dissent, and fundamental freedoms.
### Disability Rights
Rights of persons with disabilities, accessibility, inclusion, non-discrimination, social protection, education, health care, and participation.
### Economic & Social Rights
Health, education, food, housing, poverty reduction, labor rights, social protection, welfare, and access to basic services.
### Environment, Climate & Emergencies
Environmental protection, climate change, disaster risk reduction, emergency response, resilience, and humanitarian situations linked to environmental or climate-related crises.
### Equality & Non-Discrimination
General equality protections, anti-discrimination measures, minority rights, inclusion policies, and protection of vulnerable or marginalized groups.
### Gender Rights & Violence
Gender equality, discrimination against women and girls, gender-based violence, reproductive rights, participation, and protection from harmful practices.
### Governance, Institutions & Rule of Law
Institutional reform, legal frameworks, judicial guarantees, due process, public administration, accountability, and rule of law.
### Human Rights Education & Awareness
Human rights education, awareness campaigns, training programs, dissemination of human rights norms, and capacity-building initiatives.
### International Mechanisms & Cooperation
Treaty ratification, reporting obligations, cooperation with UN mechanisms, special procedures, international commitments, and engagement with human rights bodies.
""",
"""
Las áreas temáticas que se presentan a continuación son agrupaciones analíticas simplificadas derivadas de categorías recurrentes utilizadas en los mecanismos internacionales de derechos humanos y en la documentación del Examen Periódico Universal (EPU). No corresponden a una taxonomía oficial de las Naciones Unidas y fueron creadas exclusivamente con fines analíticos y de modelización.
### Libertades civiles y derechos políticos
Libertad de expresión, asociación y religión, participación política, libertades civiles, acceso a la información, restricciones a la disidencia y libertades fundamentales.
### Derechos de las personas con discapacidad
Derechos de las personas con discapacidad, accesibilidad, inclusión, no discriminación, protección social, educación, salud y participación.
### Derechos económicos y sociales
Salud, educación, alimentación, vivienda, reducción de la pobreza, derechos laborales, protección social, bienestar y acceso a servicios básicos.
### Medio ambiente, clima y emergencias
Protección ambiental, cambio climático, reducción del riesgo de desastres, respuesta ante emergencias, resiliencia y situaciones humanitarias vinculadas a crisis ambientales o climáticas.
### Igualdad y no discriminación
Protecciones generales de igualdad, medidas antidiscriminatorias, derechos de minorías, políticas de inclusión y protección de grupos vulnerables o marginados.
### Derechos de género y violencia
Igualdad de género, discriminación contra mujeres y niñas, violencia basada en género, derechos reproductivos, participación y protección frente a prácticas nocivas.
### Gobernanza, instituciones y Estado de derecho
Reformas institucionales, marcos legales, garantías judiciales, debido proceso, administración pública, rendición de cuentas y Estado de derecho.
### Educación y sensibilización en derechos humanos
Educación en derechos humanos, campañas de sensibilización, programas de formación, difusión de normas de derechos humanos e iniciativas de fortalecimiento de capacidades.
### Mecanismos internacionales y cooperación
Ratificación de tratados, obligaciones de reporte, cooperación con mecanismos de Naciones Unidas, procedimientos especiales, compromisos internacionales y vinculación con organismos de derechos humanos.
"""
),
unsafe_allow_html=True
)
st.divider()
# =========================
# 4. Political Sensitivity
# =========================
section_header(t("4. Political Sensitivity", "4. Sensibilidad política"))
st.markdown(t(
"""
Classify how politically sensitive the recommendation is for the DPRK regime. A suggested value is provided based on the thematic area selected above, but you may adjust it if needed.
""",
"""
Clasifique cuán políticamente sensible es la recomendación para el régimen norcoreano. Se ofrece un valor sugerido en función del área temática seleccionada arriba, pero puede ajustarlo si lo considera necesario.
""",
), unsafe_allow_html=True)
suggested_sensitivity = SENSITIVITY_BY_AREA.get(area, 1)
sensitivity_options = {
0: t("Low sensitivity", "Baja sensibilidad"),
1: t("Medium sensitivity", "Sensibilidad media"),
2: t("High sensitivity", "Alta sensibilidad")
}
regime_sensitivity = st.select_slider(
t("Political sensitivity", "Sensibilidad política"),
options=list(sensitivity_options.keys()),
value=suggested_sensitivity,
format_func=lambda x: sensitivity_options[x],
)
with st.expander(t("See full political sensitivity classification guide", "Ver guía completa de clasificación de sensibilidad política")):
st.markdown(t(
"""
### Low sensitivity
Recommendations focused on thematic areas generally perceived as less politically threatening by the DPRK regime.
Typical thematic areas:
- Economic & Social Rights
- Disability Rights
- Environment, Climate & Emergencies
- Human Rights Education & Awareness
<u>Examples</u>: food, health, education, housing, poverty, disability rights, humanitarian cooperation, disaster response, basic services, awareness-raising, training.
### Medium sensitivity
Recommendations focused on thematic areas that may imply institutional, legal, or normative change, but do not necessarily challenge regime control directly.
Typical thematic areas:
- Gender Rights & Violence
- Equality & Non-Discrimination
- Governance, Institutions & Rule of Law
- International Mechanisms & Cooperation
<u>Examples</u>: gender equality, anti-discrimination measures, legal reform, institutional strengthening, treaty ratification, reporting obligations, cooperation with UN mechanisms, capacity-building.
### High sensitivity
Recommendations focused on thematic areas directly linked to political control, repression, accountability, or fundamental civil and political freedoms.
Typical thematic areas:
- Civil Liberties & Political Rights
<u>Examples</u>: torture, prison camps, executions, death penalty, enforced disappearances, freedom of expression, freedom of association, freedom of religion, political participation, access to information, dissent, ICC, COI.
""",
"""
### Baja sensibilidad
Recomendaciones centradas en áreas temáticas generalmente percibidas como menos amenazantes políticamente por el régimen norcoreano.
Áreas temáticas típicas:
- Derechos económicos y sociales
- Derechos de las personas con discapacidad
- Medio ambiente, clima y emergencias
- Educación y sensibilización en derechos humanos
<u>Ejemplos</u>: alimentación, salud, educación, vivienda, pobreza, derechos de las personas con discapacidad, cooperación humanitaria, respuesta ante desastres, servicios básicos, sensibilización, formación.
### Sensibilidad media
Recomendaciones centradas en áreas temáticas que pueden implicar cambios institucionales, legales o normativos, pero que no necesariamente cuestionan directamente el control del régimen.
Áreas temáticas típicas:
- Derechos de género y violencia
- Igualdad y no discriminación
- Gobernanza, instituciones y Estado de derecho
- Mecanismos internacionales y cooperación
<u>Ejemplos</u>: igualdad de género, medidas antidiscriminatorias, reforma legal, fortalecimiento institucional, ratificación de tratados, obligaciones de reporte, cooperación con mecanismos de Naciones Unidas, fortalecimiento de capacidades.
### Alta sensibilidad
Recomendaciones centradas en áreas temáticas directamente vinculadas al control político, la represión, la rendición de cuentas o las libertades civiles y políticas fundamentales.
Área temática típica:
- Libertades civiles y derechos políticos
<u>Ejemplos</u>: tortura, campos de prisioneros, ejecuciones, pena de muerte, desapariciones forzadas, libertad de expresión, libertad de asociación, libertad religiosa, participación política, acceso a la información, disidencia, CPI, COI.
"""
), unsafe_allow_html=True)
st.divider()
# =========================
# 5. External Scrutiny
# =========================
section_header(t("5. External Scrutiny", "5. Escrutinio externo"))
st.markdown(t(
"""
Indicate whether the recommendation includes a concrete request for external access,
monitoring, reporting, visits, accountability mechanisms, or international oversight.
""",
"""
Indique si la recomendación incluye una solicitud concreta de acceso externo,
monitoreo, informes, visitas, mecanismos de rendición de cuentas o supervisión internacional.
""",
), unsafe_allow_html=True)
external_scrutiny = st.toggle(
t("External scrutiny ON", "Escrutinio externo ACTIVADO"),
value=False
)
external_scrutiny = int(external_scrutiny)
with st.expander(t("See full external scrutiny classification guide", "Ver guía completa de clasificación de escrutinio externo")):
st.markdown(t(
"""
### Off · No external scrutiny
No explicit request for monitoring, reporting, visits, accountability mechanisms, or external intervention.
### On · External scrutiny
Explicit mention of external monitoring or accountability mechanisms, including references to: Special Rapporteur, OHCHR, ICC, COI, treaty bodies, humanitarian access, international observers, external investigations, reporting obligations.
""",
"""
### Desactivado · Sin escrutinio externo
No hay solicitud explícita de monitoreo, informes, visitas, mecanismos de rendición de cuentas o intervención externa.
### Activado · Con escrutinio externo
Existe una mención explícita a monitoreo externo o mecanismos de rendición de cuentas, incluidas referencias a: Relator/a Especial, OHCHR, CPI, COI, órganos de tratados, acceso humanitario, observadores internacionales, investigaciones externas u obligaciones de informe.
""",
))
st.divider()
# =========================
# 6. DPRK behavioral scenario
# =========================
section_header(t("6. DPRK behavioral scenario", "6. Escenario de comportamiento de la RPDC"))
st.markdown(t(
"""
The DPRK’s first three UPR cycles suggest a more balanced and less differentiated response pattern, approximating a **50/50 coin flip dynamic** in which acceptance and rejection remain relatively even across recommendation areas.
By contrast, the fourth UPR cycle reflects a more selective and structured response strategy, increasingly resembling a **Pareto style 80/20 logic**. The DPRK accepts a larger share of recommendations overall (~80%), especially in less politically sensitive areas, while continuing to reject recommendations perceived as intrusive, accountability oriented, or directly challenging regime control (~20%).
Select the behavioral scenario that should guide the prediction.
""",
"""
Los tres primeros ciclos del EPU sugieren un patrón de respuesta más equilibrado y menos diferenciado por parte del régimen norcoreano, aproximándose a una **dinámica de moneda 50/50** en la que la aceptación y el rechazo permanecen relativamente parejos entre las distintas áreas de recomendación.
El cuarto ciclo del EPU, por el contrario, refleja una estrategia de respuesta más selectiva y estructurada, cada vez más cercana a una **lógica de Pareto 80/20**. La RPDC acepta una mayor proporción de recomendaciones en términos generales (~80%), especialmente en áreas menos sensibles políticamente, mientras sigue rechazando aquellas percibidas como intrusivas, orientadas a la rendición de cuentas o directamente desafiantes para el control del régimen (~20%).
Seleccione el patrón de comportamiento que servirá de base para la predicción.
""",
))
scenario = st.radio(
"",
options=["coin_flip", "pareto_80_20"],
horizontal=True,
label_visibility="collapsed",
format_func=lambda x: {
"coin_flip": t("50/50 coin flip dynamic", "Dinámica de moneda 50/50"),
"pareto_80_20": t("80/20 Pareto logic", "Lógica de Pareto 80/20")
}[x]
)
if scenario == "coin_flip":
cycle = random.choice([1, 2, 3])
elif scenario == "pareto_80_20":
cycle = 4
st.caption(
t(f"Internal model value: Cycle {cycle}.", f"Valor interno del modelo: Ciclo {cycle}.")
)
st.divider()
# =========================
# Construcción del input
# =========================
input_data = pd.DataFrame([{
"Cycle": cycle,
"Aligment_Score": alignment_score,
"Verb_Intensity": verb_intensity,
"Regime_Sensitivity": regime_sensitivity,
"External_Scrutiny": external_scrutiny,
"Macro_Area": area
}])
input_data["SimplVerb_Intensity"] = input_data["Verb_Intensity"].replace({
1: 1,
2: 1,
3: 2,
4: 2,
5: 3
})
input_data["Pressure_Index"] = (
input_data["Verb_Intensity"]
* input_data["External_Scrutiny"]
* input_data["Regime_Sensitivity"]
)
input_data["Aligned_Pressure"] = (
input_data["Aligment_Score"]
* input_data["Verb_Intensity"]
)
input_data["Adjusted_Intensity"] = (
input_data["Verb_Intensity"]
* input_data["Regime_Sensitivity"]
)
# =========================
# Encoding con las columnas reales del modelo
# =========================
def build_model_input(raw_input, model_columns):
"""
Construye una fila con exactamente las mismas columnas,
nombres y orden que utilizó el modelo durante el entrenamiento.
"""
encoded = pd.DataFrame(
0.0,
index=[0],
columns=model_columns
)
numeric_and_derived_features = [
"Cycle",
"Aligment_Score",
"Verb_Intensity",
"Regime_Sensitivity",
"External_Scrutiny",
"SimplVerb_Intensity",
"Pressure_Index",
"Aligned_Pressure",
"Adjusted_Intensity"
]
for col in numeric_and_derived_features:
if col in raw_input.columns and col in encoded.columns:
encoded.loc[0, col] = float(raw_input.loc[0, col])
selected_area = str(raw_input.loc[0, "Macro_Area"]).strip()
area_dummy_col = f"Macro_Area_{selected_area}"
if area_dummy_col not in encoded.columns:
raise ValueError(
f"The selected area is not present in the model columns: {area_dummy_col}"
)
encoded.loc[0, area_dummy_col] = 1.0
encoded = encoded.reindex(
columns=model_columns,
fill_value=0.0
)
return encoded, area_dummy_col
try:
input_encoded, area_dummy_col = build_model_input(
raw_input=input_data,
model_columns=model_columns
)
except Exception as e:
st.error(t(
f"Error preparing model input: {e}",
f"Error al preparar el input del modelo: {e}"
))
st.stop()
# =========================
# Predicción
# =========================
def find_similar_recommendations(input_data, historical_df, top_n=1):
df_sim = historical_df.copy()
df_sim = df_sim[
df_sim["Macro_Area"] == input_data.loc[0, "Macro_Area"]
].copy()
if len(df_sim) < top_n:
df_sim = historical_df.copy()
numeric_cols = [
"Aligment_Score",
"Verb_Intensity",
"Regime_Sensitivity",
"External_Scrutiny",
"Cycle",
]
for col in numeric_cols + ["Position_Binary"]:
df_sim[col] = pd.to_numeric(df_sim[col], errors="coerce")
df_sim = df_sim.dropna(
subset=numeric_cols + [
"Position_Binary",
"Recommendation",
"Macro_Area"
]
)
if df_sim.empty:
return df_sim
feature_ranges = {}
for col in numeric_cols:
col_min = float(df_sim[col].min())
col_max = float(df_sim[col].max())
feature_ranges[col] = max(col_max - col_min, 1e-9)
normalized_diffs = []
for col in numeric_cols:
diff = (
abs(df_sim[col] - float(input_data.loc[0, col]))
/ feature_ranges[col]
)
normalized_diffs.append(diff)
df_sim["distance"] = sum(normalized_diffs) / len(normalized_diffs)
df_sim["similarity"] = (
(1 - df_sim["distance"]).clip(lower=0, upper=1) * 100
)
df_sim = df_sim.sort_values(
["distance", "similarity"],
ascending=[True, False]
).head(top_n)
return df_sim
st.header(t("Prediction", "Predicción"))
if st.button(t("Run prediction", "Ejecutar predicción"), type="primary"):
if list(input_encoded.columns) != model_columns:
st.error(
t(
"The encoded input columns do not match the model columns.",
"Las columnas del input codificado no coinciden con las columnas del modelo."
)
)
st.write(t("Model columns:", "Columnas del modelo:"), model_columns)
st.write(
t("Input columns:", "Columnas del input:"),
input_encoded.columns.tolist()
)
st.stop()
pred = model.predict(input_encoded)[0]
proba = model.predict_proba(input_encoded)[0]
prob_reject = float(proba[0])
prob_accept = float(proba[1])
st.progress(prob_accept)
if pred == 1:
st.markdown(f"""
<div class="result-card-accept">
<h2 style="margin-bottom:0.5rem;">{t("Likely ACCEPTED", "Probablemente ACEPTADA")}</h2>
<p style="font-size:1.1rem;">
{t("Estimated acceptance probability", "Probabilidad estimada de aceptación")}: <strong>{prob_accept:.1%}</strong>
</p>
</div>
""", unsafe_allow_html=True)
else:
st.markdown(f"""
<div class="result-card-reject">
<h2 style="margin-bottom:0.5rem;">{t("Likely REJECTED", "Probablemente RECHAZADA")}</h2>
<p style="font-size:1.1rem;">
{t("Estimated rejection probability", "Probabilidad estimada de rechazo")}: <strong>{prob_reject:.1%}</strong>
</p>
</div>
""", unsafe_allow_html=True)
col1, col2 = st.columns(2)
with col1:
st.metric(
t("Acceptance probability", "Probabilidad de aceptación"),
f"{prob_accept:.1%}"
)
with col2:
st.metric(
t("Rejection probability", "Probabilidad de rechazo"),
f"{prob_reject:.1%}"
)
st.divider()
st.subheader(
t(
"Most similar historical recommendation",
"Recomendación histórica más similar"
)
)
similar_recs = find_similar_recommendations(
input_data=input_data,
historical_df=historical_recommendations,
top_n=1
)
if similar_recs.empty or int(round(float(similar_recs["similarity"].max()))) <= 0:
st.info(
t(
"No similar historical recommendations were found.",
"No se encontraron recomendaciones históricas similares."
)
)
else:
for _, row in similar_recs.iterrows():
outcome = (
t("Accepted", "Aceptada")
if int(row["Position_Binary"]) == 1
else t("Rejected", "Rechazada")
)
recommending_state_html = html.escape(str(row["Recommending_State"]))
recommendation_html = html.escape(str(row["Recommendation"]))
macro_area_html = html.escape(str(row["Macro_Area"]))
outcome_html = html.escape(outcome)
card_html = "\n".join([
'<div class="similar-card">',
f'<h4 style="margin-bottom:0.4rem;">{recommending_state_html} · {t("Cycle", "Ciclo")} {int(row["Cycle"])}</h4>',
f'<p style="margin-bottom:0.8rem;">“{recommendation_html}”</p>',
'<p style="margin-bottom:0;">',
f'<strong>{t("Outcome", "Resultado")}:</strong> {outcome_html}<br>',
f'<strong>{t("Thematic area", "Área temática")}:</strong> {macro_area_html}<br>',
f'<strong>{t("Alignment score", "Puntaje de alineamiento")}:</strong> {row["Aligment_Score"]:.3f}<br>',
f'<strong>{t("Similarity", "Similitud")}:</strong> {row["similarity"]:.0f}%',
'</p>',
'</div>',
])
st.markdown(card_html, unsafe_allow_html=True)
st.divider()
st.subheader(t("Scenario summary", "Resumen del escenario"))
summary_df = pd.DataFrame({
"Parameter": [
t("Recommending State", "Estado recomendante"),
t("Alignment Score", "Puntaje de alineamiento"),
t("Verb Intensity", "Intensidad verbal"),
t("Regime Sensitivity", "Sensibilidad del régimen"),
t("External Scrutiny", "Escrutinio externo"),
t("Thematic Area", "Área temática"),
t("Behavioral Scenario", "Escenario de comportamiento"),
t("Internal Model Cycle", "Ciclo interno del modelo")
],
"Value": [
recommending_country,
round(float(alignment_score), 3),
verb_intensity,
regime_sensitivity,
external_scrutiny,
area,
{
"coin_flip": t(
"50/50 coin flip dynamic",
"Dinámica de moneda 50/50"
),
"pareto_80_20": t(
"80/20 Pareto logic",
"Lógica de Pareto 80/20"
)
}[scenario],
cycle
]
})
st.dataframe(
summary_df,
hide_index=True,
use_container_width=True
)
with st.expander(
t(
"Technical check: encoded input sent to model",
"Chequeo técnico: input codificado enviado al modelo"
)
):
active_area_cols = [
col for col in input_encoded.columns
if col.startswith("Macro_Area_")
and input_encoded.loc[0, col] == 1
]
st.write(
t(
"Active thematic area column:",
"Columna activa de área temática:"
),
active_area_cols
)
st.write(
t("Input shape:", "Dimensión del input:"),
input_encoded.shape
)
st.dataframe(input_encoded, use_container_width=True)
st.divider()
st.caption(t(
"""
⚠️ This application combines historical UPR data, thematic coding, and machine learning models to simulate possible DPRK response patterns across different political scenarios. **Outputs should be understood as probabilistic behavioral scenarios rather than definitive predictions**.
👩🏻💻 Developed by [María de los Ángeles Lasa](http://marialasa.ar), PhD.
""",
"""
⚠️ Esta aplicación combina datos históricos del EPU, codificación temática y modelos de aprendizaje automático para simular posibles patrones de respuesta de la RPDC en distintos escenarios políticos. **Los resultados deben entenderse como escenarios de comportamiento probabilísticos y no como predicciones definitivas**.
👩🏻💻 Desarrollado por [María de los Ángeles Lasa](http://marialasa.ar), PhD.
""",
))