File size: 25,742 Bytes
c6b26a7
ae6a44f
 
 
 
 
c6b26a7
ae6a44f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f27fab3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae6a44f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d50364c
 
 
 
ae6a44f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365bba4
ae6a44f
 
 
 
d50364c
 
 
 
 
 
 
 
ae6a44f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import html
import torch
from transformers import AutoTokenizer, AutoModelForTokenClassification
import streamlit.components.v1 as components
import os

# Force Hugging Face cache to local folder with permissions
os.environ["HF_HOME"] = "/app/hf_cache"
os.environ["TRANSFORMERS_CACHE"] = "/app/hf_cache"
os.makedirs("/app/hf_cache", exist_ok=True)

# Opcional: chunker
try:
    from predictor.document_chunker import DocumentChunker
except Exception:
    DocumentChunker = None

# ============================================================
# PAGE CONFIG
# ============================================================
st.set_page_config(
    page_title="MiNER - Stage 2: Metadata Extraction",
    page_icon="🏷️",
    layout="wide",
    initial_sidebar_state="expanded"
)

# ============================================================
# LABEL STYLES
# ============================================================
LABEL_STYLES = {
    "DATE": {"class": "highlight-date", "name": "📅 Date"},
    "START-TIME": {"class": "highlight-start-time", "name": "🕐 Start time"},
    "END-TIME": {"class": "highlight-end-time", "name": "🕑 End time"},
    "LOCATION": {"class": "highlight-location", "name": "📍 Location"},
    "MINUTE-ID": {"class": "highlight-minute-id", "name": "📋 Minute ID"},
    "MEETING-TYPE": {"class": "highlight-meeting-type", "name": "📌 Meeting type"},

    # President variants
    "PRESIDENT-PRESENT": {"class": "highlight-president", "name": "👔 President (Present)"},
    "PRESIDENT-ABSENT": {"class": "highlight-president-absent", "name": "🚫 President (Absent)"},
    "PRESIDENT-SUBSTITUTED": {"class": "highlight-president-substituted", "name": "🔄 President (Substituted)"},

    # Councilor variants
    "COUNCILOR-PRESENT": {"class": "highlight-councilor", "name": "👥 Councilor (Present)"},
    "COUNCILOR-ABSENT": {"class": "highlight-councilor-absent", "name": "🚫 Councilor (Absent)"},
    "COUNCILOR-SUBSTITUTED": {"class": "highlight-councilor-substituted", "name": "🔄 Councilor (Substituted)"},
}



DEFAULT_CHUNK_SIZE = 800
DEFAULT_OVERLAP = 200
DEFAULT_AGGREGATION = "average"

# ============================================================
# CUSTOM CSS (adapted from Stage 1)
# ============================================================
st.markdown("""
<style>
    .main-header {
        font-size: 2.5rem;
        font-weight: bold;
        color: #1f77b4;
        text-align: center;
        margin-bottom: 1rem;
    }

    .subtitle {
        text-align: center;
        color: #555;
        font-size: 1rem;
        margin-bottom: 1.5rem;
    }

    /* ======= Entity Highlight Styles ======= */
    .highlight-date {
        background-color: #4CAF50;
        border-bottom: 3px solid #2e7d32;
        padding: 2px 4px;
        border-radius: 3px;
        color: #000;
    }
    .highlight-start-time {
        background-color: #2196F3;
        border-bottom: 3px solid #0d47a1;
        padding: 2px 4px;
        border-radius: 3px;
        color: #000;
    }
    .highlight-end-time {
        background-color: #3F51B5;
        border-bottom: 3px solid #1a237e;
        padding: 2px 4px;
        border-radius: 3px;
        color: #000;
    }
    .highlight-location {
        background-color: #FF9800;
        border-bottom: 3px solid #e65100;
        padding: 2px 4px;
        border-radius: 3px;
        color: #000;
    }
    .highlight-minute-id {
        background-color: #9C27B0;
        border-bottom: 3px solid #4a148c;
        padding: 2px 4px;
        border-radius: 3px;
        color: #000;
    }
    .highlight-meeting-type {
        background-color: #607D8B;
        border-bottom: 3px solid #37474f;
        padding: 2px 4px;
        border-radius: 3px;
        color: #000;
    }
    .highlight-president {
        background-color: #f27e91;
        border-bottom: 3px solid #ad1457;
        padding: 2px 4px;
        border-radius: 3px;
        color: #000;
    }
    .highlight-councilor {
        background-color: #F44336;
        border-bottom: 3px solid #b71c1c;
        padding: 2px 4px;
        border-radius: 3px;
        color: #000;
    }

    .annotation-box {
        padding: 1rem;
        margin: 0.75rem 0;
        border-radius: 0.5rem;
        background-color: #f0f2f6;
        white-space: pre-wrap;
        line-height: 1.8;
        font-family: 'Segoe UI', Roboto, monospace;
    }

    .legend-item {
        display: inline-block;
        padding: 4px 8px;
        margin: 3px;
        border-radius: 4px;
        font-size: 0.8rem;
        font-weight: 500;
    }

    .highlight-president-absent {
        background-color: #f27e91 !important;
        border: 2px solid #050505 !important;
        color: #fff !important;
    }

    .highlight-councilor-absent {
        background-color: #F44336 !important;
        border: 2px solid #050505 !important;
        color: #fff !important;
    }
    .highlight-president-substituted {
        background-color: #f27e91 !important;
        border: 2px solid #7b69c7 !important;
        color: #fff !important;
    }
    .highlight-councilor-substituted {
        background-color: #F44336 !important;
        border: 2px solid #7b69c7 !important;
        color: #fff !important;
    }

    /* ===================== DARK MODE FIX ===================== */
    @media (prefers-color-scheme: dark) {
        /* Garante que o texto dentro das anotações continua legível */
        .annotation-box span,
        .legend-item span,
        .highlight-date,
        .highlight-start-time,
        .highlight-end-time,
        .highlight-location,
        .highlight-minute-id,
        .highlight-meeting-type,
        .highlight-president-present,
        .highlight-president-absent,
        .highlight-president-substituted,
        .highlight-councilor-present,
        .highlight-councilor-absent,
        .highlight-councilor-substituted {
            color: #000 !important; /* texto preto legível em fundo claro */
            mix-blend-mode: normal !important;
        }

        /* Mantém o fundo geral do bloco escuro */
        .annotation-box {
            background-color: #2b2b2b !important;
        }
    }



</style>
""", unsafe_allow_html=True)


LABEL_ALIASES = {
    "NUMERO-ATA": "MINUTE-ID",
    "DATA": "DATE",
    "TIPO-REUNIAO": "MEETING-TYPE",
    "TIPO-REUNIAO-ORDINARIA": "MEETING-TYPE",
    "TIPO-REUNIAO-EXTRAORDINARIA": "MEETING-TYPE",
    "LOCAL": "LOCATION",
    "HORARIO-INICIO": "START-TIME",
    "HORARIO-FIM": "END-TIME",
    "PARTICIPANTE-PRESIDENTE-PRESENTE": "PRESIDENT-PRESENT",
    "PARTICIPANTE-PRESIDENTE-AUSENTE": "PRESIDENT-ABSENT",
    "PARTICIPANTE-PRESIDENTE-SUBSTITUIDO": "PRESIDENT-SUBSTITUTED",
    "PARTICIPANTE-VEREADOR-PRESENTE": "COUNCILOR-PRESENT",
    "PARTICIPANTE-VEREADOR-AUSENTE": "COUNCILOR-ABSENT",
    "PARTICIPANTE-VEREADOR-SUBSTITUIDO": "COUNCILOR-SUBSTITUTED",
}


# ============================================================
# RENDER FUNCTIONS
# ============================================================

def _style_for_label(raw_label: str):
    """Return style dict for a given label."""
    return LABEL_STYLES.get(raw_label, {"bg": "#ddd", "fg": "#000", "name": raw_label})


def render_html(base_text: str, spans: list, scores: list = None):
    """Render annotated text with colored entity highlights (VotIE-style)."""
    out, cur = [], 0
    for i, (s, e, lbl) in enumerate(spans):
        if cur < s:
            out.append(html.escape(base_text[cur:s]))
        norm_lbl = LABEL_ALIASES.get(lbl, lbl)
        style = LABEL_STYLES.get(norm_lbl, {"class": "", "name": lbl})
        css_class = style.get("class", "")
        title = f"{style['name']} ({scores[i]:.2f})" if scores else style['name']
        out.append(
            f"<span class='{css_class}' title='{title}'>{html.escape(base_text[s:e])}</span>"
        )
        cur = e
    if cur < len(base_text):
        out.append(html.escape(base_text[cur:]))
    return "<div class='annotation-box'>" + "".join(out) + "</div>"


def render_legend():
    """Render entity legend with same colors as highlight classes."""
    legend_html = """
    <div class='legend-box'>
        <strong>🔖 Entity Legend:</strong><br><br>
    """

    for label, info in LABEL_STYLES.items():
        css_class = info.get("class", "")
        name = info.get("name", label)
        legend_html += f"<span class='legend-item {css_class}'>{name}</span> "

    legend_html += "</div>"
    return legend_html





# ============================================================
# MODEL LOADING
# ============================================================

@st.cache_resource
def load_ner_model(model_name: str):
    """Load NER model from Hugging Face"""
    try:
        cache_dir = "/app/hf_cache"  # safe writable path
        tokenizer = AutoTokenizer.from_pretrained(model_name, cache_dir=cache_dir)
        model = AutoModelForTokenClassification.from_pretrained(model_name, cache_dir=cache_dir)
        model.eval()
        device = "cpu"
        model.to(device)
        id2label = model.config.id2label
        return tokenizer, model, device, id2label, None
    except Exception as e:
        return None, None, None, None, f"❌ Error loading model: {str(e)}"


# ============================================================
# INFERENCE FUNCTIONS
# ============================================================

def predict_spans_chunk(text_chunk: str, tokenizer, model, device, id2label, aggregation: str = "average"):
    """Predict entity spans for a single chunk"""
    enc = tokenizer(text_chunk, return_offsets_mapping=True, return_tensors="pt", truncation=True)
    word_ids = enc.word_ids()
    enc = {k: v.to(device) for k, v in enc.items()}

    with torch.no_grad():
        logits = model(**{k: v for k, v in enc.items() if k in {"input_ids", "attention_mask"}}).logits
        probs = torch.softmax(logits, dim=-1)

    pred_ids = probs.argmax(-1).squeeze(0).tolist()
    offsets = enc["offset_mapping"].squeeze(0).tolist()

    spans = []
    curr_label = None
    curr_start = None
    curr_end = None
    curr_scores = []

    def close_span(end_idx=None):
        nonlocal spans, curr_label, curr_start, curr_end, curr_scores
        if curr_label is None or curr_start is None:
            return
        start_char = curr_start
        end_char = curr_end if curr_end is not None else end_idx
        if end_char is None or end_char <= start_char:
            curr_label = curr_start = curr_end = None
            curr_scores = []
            return
        if aggregation == "average" and curr_scores:
            score = sum(curr_scores) / len(curr_scores)
        elif curr_scores:
            score = max(curr_scores)
        else:
            score = 0.0
        spans.append({"label": curr_label, "start": start_char, "end": end_char, "score": float(score)})
        curr_label = curr_start = curr_end = None
        curr_scores = []

    for idx, (pid, (start, end)) in enumerate(zip(pred_ids, offsets)):
        wid = word_ids[idx]
        if start == end or wid is None or (idx > 0 and wid == word_ids[idx - 1]):
            continue

        label = id2label.get(pid, "O")

        last_idx = idx
        for j in range(idx + 1, len(word_ids)):
            if word_ids[j] != wid:
                break
            last_idx = j
        word_start = start
        word_end = offsets[last_idx][1]

        if label == "O":
            if curr_label is not None:
                close_span()
            continue

        if label.startswith("B-"):
            if curr_label is not None:
                close_span()
            curr_label = label[2:]
            curr_start = word_start
            curr_end = word_end
            curr_scores = [float(probs[0, idx, pid].item())]

        elif label.startswith("I-"):
            ent = label[2:]
            if curr_label == ent:
                curr_end = word_end
                curr_scores.append(float(probs[0, idx, pid].item()))
            else:
                if curr_label is not None:
                    close_span()
                curr_label = ent
                curr_start = word_start
                curr_end = word_end
                curr_scores = [float(probs[0, idx, pid].item())]

    last_real = 0
    for (s, e) in offsets[::-1]:
        if s != e:
            last_real = e
            break
    close_span(last_real)
    return spans


def extract_metadata(base_text: str, tokenizer, model, device, id2label):
    """Main extraction function"""
    if not base_text or len(base_text.strip()) < 10:
        return None, None, "Please enter text to analyze (minimum 10 characters)."

    if DocumentChunker is None:
        spans_chunk = predict_spans_chunk(base_text, tokenizer, model, device, id2label, DEFAULT_AGGREGATION)
        spans_all = [(sp["start"], sp["end"], sp["label"]) for sp in spans_chunk]
        scores_all = [sp["score"] for sp in spans_chunk]
    else:
        chunker = DocumentChunker(chunk_size=DEFAULT_CHUNK_SIZE, chunk_overlap=DEFAULT_OVERLAP)
        chunks = chunker.chunk_document(base_text)

        spans_all, scores_all = [], []
        cursor = 0
        for ch in chunks:
            start_ch = base_text.find(ch, cursor)
            if start_ch == -1:
                start_ch = cursor
            spans_chunk = predict_spans_chunk(ch, tokenizer, model, device, id2label, DEFAULT_AGGREGATION)
            for sp in spans_chunk:
                spans_all.append((sp["start"] + start_ch, sp["end"] + start_ch, sp["label"]))
                scores_all.append(sp["score"])
            cursor = start_ch + 1

    # Sort and remove overlaps
    paired = sorted(zip(spans_all, scores_all), key=lambda x: (x[0][0], x[0][1]))
    kept, kept_scores, last_e = [], [], -1
    for (s, e, lbl), sc in paired:
        if s >= last_e:
            kept.append((s, e, lbl))
            kept_scores.append(sc)
            last_e = e

    return kept, kept_scores, None


# ============================================================
# EXAMPLE TEXTS
# ============================================================
EXAMPLE_TEXT_PT_INTRO = "ATA Nº 10 REUNIÃO ORDINÁRIA DA CÂMARA MUNICIPAL DE CAMPO MAIOR, REALIZADA EM 4 DE MAIO DE 2022 .\nAos quatro dias do mês de maio do ano de dois mil e vinte e dois, no Edifício dos Paços do Concelho, nesta Vila, realizou-se, pelas nove horas e trinta minutos, a reunião Ordinária da Câmara Municipal, comparecendo os Excelentíssimos Senhores Luis Fernando Martins Rosinha, Paulo Ivo Sabino Martins de Almeida, Paulo Jorge Furtado Pinheiro, Maria da Encarnação Grifo Silveirinha e Fátima do Rosário Pingo Vitorino Pereira, respetivamente, Presidente e Vereadores efetivos deste Órgão Autárquico.\n-Verificada a presença dos respectivos membros, o Senhor Presidente declarou aberta a reunião:\n-Estava presente o Dirigente Intermédio de 3º Grau na Área***********, Dr. *************************, e a Assistente Técnico **************************************.\n\n-ORDEM DO DIA:\n-INICIANDO A ORDEM DO DIA, ENTREGUE A TODO O EXECUTIVO E ELABORADA NOS TERMOS DO ARTIGO 53º DA LEI Nº 75/2013, DE 12 DE SETEMBRO, A CÂMARA TRATOU OS SEGUINTES ASSUNTOS:\n-ORDEM DO DIA:\n-FINANÇAS MUNICIPAIS:\n"
EXAMPLE_TEXT_PT_CLOSING = "\n-ENCERRAMENTO\n-DESTA REUNIÃO FOI ELABORADA A PRESENTE ATA, SOB A RESPONSABILIDADE DO CHEFE DE DIVISÃO ADMINISTRATIVA E FINANCEIRA, QUE A ASSINARÁ JUNTAMENTE COM O PRESIDENTE, NOS TERMOS DO NÚMERO 2 DO ARTIGO 57º DA LEI 75/2013, DE 12 DE SETEMBRO, TENDO SIDO DISPENSADA A SUA LEITURA EM VIRTUDE DE A TODOS OS MEMBROS TER SIDO ENTREGUE FOTOCÓPIA DA MESMA, NOS TERMOS DO\nDISPOSTO NO ARTIGO 4º DO DECRETO-LEI Nº 45.362, DE 21/11/1963, ERAM DEZ HORAS E VINTE MINUTOS.\n_______________________________________________ "
EXAMPLE_TEXT_EN_INTRO = "MINUTES NO. 10 ORDINARY MEETING OF THE MUNICIPALITY OF CAMPO MAIOR, HELD ON MAY 4, 2022.\nOn the fourth day of May in the year two thousand and twenty-two, in the Town Hall Building, in this village, the Ordinary Meeting of the City Council was held at nine o'clock and thirty minutes, attended by Messrs. Luis Fernando Martins Rosinha, Paulo Ivo Sabino Martins de Almeida, Paulo Jorge Furtado Pinheiro, Maria da Encarnação Grifo Silveirinha and Fátima do Rosário Pingo Vitorino Pereira,  respectively, President and Councilors of this Municipal Body.\n-After the presence of the respective members, the President declared the meeting open:\n-The 3rd Degree Intermediate Leader in the Area***********, Dr. *************************, and the Technical Assistant ************************************** were present.\n\n-AGENDA:\n-STARTING THE AGENDA, DELIVERED TO THE ENTIRE EXECUTIVE AND PREPARED UNDER THE TERMS OF ARTICLE 53 OF LAW NO. 75/2013, OF SEPTEMBER 12, THE CHAMBER DEALT WITH THE FOLLOWING MATTERS:\n-AGENDA:\n-MUNICIPAL FINANCES:\n"
EXAMPLE_TEXT_EN_CLOSING = "\n-CLOSURE\n-THESE MINUTES WERE DRAWN UP AT THIS MEETING, UNDER THE RESPONSIBILITY OF THE HEAD OF THE ADMINISTRATIVE AND FINANCIAL DIVISION, WHO WILL SIGN THEM TOGETHER WITH THE PRESIDENT, UNDER THE TERMS OF NUMBER 2 OF ARTICLE 57 OF LAW 75/2013, OF 12 SEPTEMBER, AND THEIR READING WAS WAIVED DUE TO THE FACT THAT A PHOTOCOPY OF THE SAME WAS GIVEN TO ALL MEMBERS,  UNDER THE\nPROVIDED FOR IN ARTICLE 4 OF DECREE-LAW NO. 45,362, OF 11/21/1963, IT WAS TEN HOURS AND TWENTY MINUTES.\n_______________________________________________ "

# Pre-load models
load_ner_model("anonymous13542/BERTimbau-large-metadata-council-pt")
load_ner_model("anonymous13542/XLMR-large-metadata-council-en")


# ============================================================
# MAIN APP
# ============================================================

def main():
    # Header
    st.markdown('<h1 class="main-header">🏷️ MiNER — Stage 2: Metadata Extraction Demo</h1>', unsafe_allow_html=True)
    st.markdown("""
    <p class="subtitle">
    Automatic extraction of structured metadata from municipal meeting minutes
    </p>
    """, unsafe_allow_html=True)

    # Sidebar
    st.sidebar.header("⚙️ Configuration")

    example_choice = st.sidebar.selectbox(
        "Choose an example or enter your own text:",
        ["Custom Text", "Portuguese Example - Intro", "Portuguese Example - Closing",
         "English Example - Intro", "English Example - Closing"],
        index=0
    )

    # Auto-select model based on example (English/multilingual as default)
    if "Portuguese" in example_choice:
        model_name = "anonymous13542/BERTimbau-large-metadata-council-pt"
    else:
        model_name = "anonymous13542/XLMR-large-metadata-council-en"

    tokenizer, model, device, id2label, error = load_ner_model(model_name)

    if error or model is None:
        st.sidebar.markdown(f"<div class='status-box error'>❌ Error loading model:<br>{error}</div>",
                            unsafe_allow_html=True)
    else:
        st.sidebar.markdown(
            f"<div class='status-box success'>✅ Loaded automatically: <strong>{model_name.split('/')[-1]}</strong></div>",
            unsafe_allow_html=True)

    st.sidebar.markdown("---")
    st.sidebar.markdown("### 📊 About")
    st.sidebar.info("""
    **MiNER Stage 2** uses Named Entity Recognition models to automatically extract metadata from meeting minutes.

    - **Model**: BERTimbau / XLM-RoBERTa fine-tuned
    - **Languages**: Portuguese and English
    - **Method**: Token Classification (NER) with BIO tagging
    """)

    st.sidebar.markdown("---")
    st.sidebar.markdown(render_legend(), unsafe_allow_html=True)

    st.sidebar.markdown("---")
    st.sidebar.markdown("### 🔗 Resources")
    st.sidebar.markdown("""
    - [📖 Model Card (PT)](https://huggingface.co/anonymous13542/BERTimbau-large-metadata-council-pt)
    - [📖 Model Card (EN)](https://huggingface.co/anonymous13542/XLMR-large-metadata-council-en)
    """)

    # Main layout
    col1, col2 = st.columns([1, 1])

    with col1:
        st.subheader("📄 Input Document")

        if example_choice == "Portuguese Example - Intro":
            input_text = st.text_area("Input", value=EXAMPLE_TEXT_PT_INTRO, height=400, label_visibility="collapsed")
        elif example_choice == "Portuguese Example - Closing":
            input_text = st.text_area("Input", value=EXAMPLE_TEXT_PT_CLOSING, height=400, label_visibility="collapsed")
        elif example_choice == "English Example - Intro":
            input_text = st.text_area("Input", value=EXAMPLE_TEXT_EN_INTRO, height=400, label_visibility="collapsed")
        elif example_choice == "English Example - Closing":
            input_text = st.text_area("Input", value=EXAMPLE_TEXT_EN_CLOSING, height=400, label_visibility="collapsed")
        else:
            input_text = st.text_area("Input", placeholder="Paste your document text here…", height=400,
                                      label_visibility="collapsed")

        extract_button = st.button("🏷️ Extract Metadata", type="primary", use_container_width=True)

    with col2:
        st.subheader("📊 Extraction Results")

        results_placeholder = st.empty()

        if extract_button:
            with st.spinner("🔄 Analyzing document..."):
                if model is None:
                    results_placeholder.warning("⚠️ Model could not be loaded. Please refresh and try again.")
                elif not input_text or len(input_text.strip()) < 10:
                    results_placeholder.warning("⚠️ Please enter a longer text (minimum 10 characters).")
                else:
                    spans, scores, err = extract_metadata(input_text, tokenizer, model, device, id2label)
                    if err:
                        results_placeholder.error(f"❌ {err}")
                    elif not spans:
                        results_placeholder.info("ℹ️ No entities found in the text.")
                    else:
                        with results_placeholder.container():
                            st.markdown(
                                f"**Found {len(spans)} entities** with average confidence: **{sum(scores) / len(scores):.2%}**")
                            st.markdown("---")
                            st.markdown("**📝 Annotated Text**")
                            annotated_html = render_html(input_text, spans, scores)
                            #st.write(annotated_html)
                            st.markdown(annotated_html, unsafe_allow_html=True)
        else:
            results_placeholder.info("👈 Enter text in the input box and click 'Extract Metadata' to begin.")

        # How it works
        st.markdown("---")
        st.subheader("🎯 How It Works")
        st.markdown("""
        The model analyzes the **meeting minutes** to automatically extract **structured metadata** using a *Named Entity Recognition (NER)* approach.

        Each token in the document is classified, identifying information such as:
        - 📅 **Date**
        - 🕐 **Start / End time**
        - 📍 **Location**
        - 📋 **Minute ID**
        - 📌 **Meeting type**
        - 👔 **President** (present / absent / substituted)
        - 👥 **Councilors** (present / absent / substituted)

        The model uses the **BIO tagging scheme** (*Begin, Inside, Outside*) to mark entity boundaries, and the final spans are reconstructed from token-level predictions.
        """)

        st.markdown("**Example:**")
        st.code("""
Introduction text: "ATA Nº 10 REUNIÃO ORDINÁRIA DA CÂMARA MUNICIPAL DE CAMPO MAIOR, REALIZADA EM 4 DE MAIO DE 2022 . Aos quatro dias do mês de maio do ano de dois mil e vinte e dois, no Edifício dos Paços do Concelho, nesta Vila, realizou-se, pelas nove horas e trinta minutos, a reunião Ordinária da Câmara Municipal, comparecendo os Excelentíssimos Senhores Luis Fernando Martins Rosinha, Paulo Ivo Sabino Martins de Almeida, Paulo Jorge Furtado Pinheiro, Maria da Encarnação Grifo Silveirinha e Fátima do Rosário Pingo Vitorino Pereira, respetivamente, Presidente e Vereadores efetivos deste Órgão Autárquico. -Verificada a presença dos respectivos membros, o Senhor Presidente declarou aberta a reunião: -Estava presente o Dirigente Intermédio de 3º Grau na Área***********, Dr. *************************, e a Assistente Técnico **************************************.  -ORDEM DO DIA: -INICIANDO A ORDEM DO DIA, ENTREGUE A TODO O EXECUTIVO E ELABORADA NOS TERMOS DO ARTIGO 53º DA LEI Nº 75/2013, DE 12 DE SETEMBRO, A CÂMARA TRATOU OS SEGUINTES ASSUNTOS: -ORDEM DO DIA: -FINANÇAS MUNICIPAIS: "

Predicted entities:
- MINUTE-ID → "10"
- MEETING-TYPE → "ORDINÁRIA"
- DATE → "4 DE MAIO DE 2022"
- LOCATION → "o Edifício dos Paços do Concelho"
- START-TIME → "nove horas e trinta minutos"
- PRESIDENT-PRESENT → "Luis Fernando Martins Rosinha"
- COUNCILOR-PRESENT → "Paulo Ivo Sabino Martins de Almeida"
- COUNCILOR-PRESENT → "Paulo Jorge Furtado Pinheiro"
- COUNCILOR-PRESENT → "Maria da Encarnação Grifo Silveirinha"
- COUNCILOR-PRESENT → "Fátima do Rosário Pingo Vitorino Pereira"
        """)

    # Footer
    st.markdown("---")
    st.markdown("""
    <div style='text-align:center; color:#64748b; font-size:0.875rem; padding:2rem 0;'>
        <p style='margin:0 0 8px 0;'><strong style='color:#667eea;'>MiNER</strong> — Municipal Information Extraction & Recognition</p>
        <p style='margin:0;'>Anonymous research demo for Stage 2 (Metadata Extraction via NER)</p>
        <p style='margin:12px 0 0 0; opacity:0.7;'>Built with ❤️ using Streamlit & Transformers</p>
    </div>
    """, unsafe_allow_html=True)


if __name__ == "__main__":
    main()