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(""" """, 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"{html.escape(base_text[s:e])}" ) cur = e if cur < len(base_text): out.append(html.escape(base_text[cur:])) return "
" + "".join(out) + "
" def render_legend(): """Render entity legend with same colors as highlight classes.""" legend_html = """
🔖 Entity Legend:

""" for label, info in LABEL_STYLES.items(): css_class = info.get("class", "") name = info.get("name", label) legend_html += f"{name} " legend_html += "
" 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('

đŸ·ïž MiNER — Stage 2: Metadata Extraction Demo

', unsafe_allow_html=True) st.markdown("""

Automatic extraction of structured metadata from municipal meeting minutes

""", 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"
❌ Error loading model:
{error}
", unsafe_allow_html=True) else: st.sidebar.markdown( f"
✅ Loaded automatically: {model_name.split('/')[-1]}
", 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("""

MiNER — Municipal Information Extraction & Recognition

Anonymous research demo for Stage 2 (Metadata Extraction via NER)

Built with ❀ using Streamlit & Transformers

""", unsafe_allow_html=True) if __name__ == "__main__": main()