Spaces:
Runtime error
Runtime error
| 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 | |
| # ============================================================ | |
| 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() |