A four-module neural architecture for the automatic extraction and classification of causal relations in text.
Paper
Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC
The paper is loaded when this pane is shown.
The authors' code
Python · 737 lines · 35 KB · no license
- import streamlit as st
- import json
- import pandas as pd
- import numpy as np
- from datetime import datetime
- import re
- # =========================================================
- # SAFE IMPORT: интерфейс всегда открывается
- # =========================================================
- PIPELINE_ERROR = None
- analyze_text = None
- try:
- from pipelineFinal import analyze_text
- PIPELINE_READY = True
- except Exception as e:
- PIPELINE_READY = False
- PIPELINE_ERROR = str(e)
- # ── Page config ──────────────────────────────────────────────────
- st.set_page_config(
- page_title="KazCausal",
- page_icon="⚡",
- layout="wide",
- initial_sidebar_state="expanded",
- )
- # ── DB examples ──────────────────────────────────────────────────
- DB_EXAMPLES = [
- {
- "group": "SYNTHETIC",
- "text": "Қысқа да әрі нақты, көпке түсінікті болғандықтан студенттерге бір деммен оқу қиынға соқпауы мүмкін.",
- "cause": "Қысқа да әрі нақты, көпке түсінікті болғандықтан",
- "effect": "студенттерге бір деммен оқу қиынға соқпауы мүмкін.",
- "marker": "болғандықтан",
- "tv_form": "Tv=ғандықтан, гендіктен, қандықтан, кендіктен",
- },
- {
- "group": "SYNTHETIC",
- "text": "Əрбір тайпа бұл киелі міндетке тек өздерін лайықты деп білгендіктен, араларында дау-жанжал шықты.",
- "cause": "Əрбір тайпа бұл киелі міндетке тек өздерін лайықты деп білгендіктен",
- "effect": "араларында дау-жанжал шықты.",
- "marker": "білгендіктен",
- "tv_form": "Tv=ғандықтан, гендіктен, қандықтан, кендіктен",
- },
- {
- "group": "SYNTHETIC",
- "text": "Таңдау мүмкіндігі, әралуандық болғандықтан оларды қолдануда едәуір еркіндік бар.",
- "cause": "Таңдау мүмкіндігі, әралуандық болғандықтан",
- "effect": "оларды қолдануда едәуір еркіндік бар.",
- "marker": "болғандықтан",
- "tv_form": "Tv=ғандықтан, гендіктен, қандықтан, кендіктен",
- },
- {
- "group": "SYNTHETIC",
- "text": "Мен мұғжиза ретінде тамақтың азаймағанын көргендіктен тағы да алпыс адамды шақырып келдім.",
- "cause": "Мен мұғжиза ретінде тамақтың азаймағанын көргендіктен",
- "effect": "тағы да алпыс адамды шақырып келдім.",
- "marker": "көргендіктен",
- "tv_form": "Tv=ғандықтан, гендіктен, қандықтан, кендіктен",
- },
- {
- "group": "SYNTHETIC",
- "text": "Сұрақ беріледі, оның «дұрыс» жауабы алдын-ала белгілі болғандықтан, ақиқат» сол сұрақтың өзінде.",
- "cause": "Сұрақ беріледі, оның «дұрыс» жауабы алдын-ала белгілі болғандықтан",
- "effect": "ақиқат» сол сұрақтың өзінде.",
- "marker": "болғандықтан",
- "tv_form": "Tv=ғандықтан, гендіктен, қандықтан, кендіктен",
- },
- {
- "group": "ANALYTIC",
- "text": "Қоғамдық сенім деңгейі төмендеді, себебі мемлекеттік институттардың ашықтығы жеткіліксіз қамтамасыз етілді.",
- "cause": "мемлекеттік институттардың ашықтығы жеткіліксіз қамтамасыз етілді.",
- "effect": "Қоғамдық сенім деңгейі төмендеді",
- "marker": "себебі",
- "tv_form": "[(N1) Tv =fin] себебі [(N1) Vfin.]",
- },
- {
- "group": "ANALYTIC",
- "text": "Сот шешімдерінің сапасына сын айтылды, себебі дәлелдемелерді бағалау рәсімі бірізді жүргізілмеді.",
- "cause": "дәлелдемелерді бағалау рәсімі бірізді жүргізілмеді.",
- "effect": "Сот шешімдерінің сапасына сын айтылды",
- "marker": "себебі",
- "tv_form": "[(N1) Tv =fin] себебі [(N1) Vfin.]",
- },
- {
- "group": "ANALYTIC",
- "text": "Әлеуметтік теңсіздік күшейді, себебі ресурстарды бөлу тетіктері тиімді жұмыс істемеді.",
- "cause": "ресурстарды бөлу тетіктері тиімді жұмыс істемеді.",
- "effect": "Әлеуметтік теңсіздік күшейді",
- "marker": "себебі",
- "tv_form": "[(N1) Tv =fin] себебі [(N1) Vfin.]",
- },
- {
- "group": "ANALYTIC",
- "text": "Білім беру нәтижелері төмендеді, себебі оқу бағдарламалары заманауи талаптарға толық сәйкес келмеді.",
- "cause": "оқу бағдарламалары заманауи талаптарға толық сәйкес келмеді.",
- "effect": "Білім беру нәтижелері төмендеді",
- "marker": "себебі",
- "tv_form": "[(N1) Tv =fin] себебі [(N1) Vfin.]",
- },
- {
- "group": "ANALYTIC",
- "text": "Ғылыми жарияланым сапасы әркелкі болды, себебі рецензиялау жүйесі қатаң сақталмады.",
- "cause": "рецензиялау жүйесі қатаң сақталмады.",
- "effect": "Ғылыми жарияланым сапасы әркелкі болды",
- "marker": "себебі",
- "tv_form": "[(N1) Tv =fin] себебі [(N1) Vfin.]",
- },
- {
- "group": "ANALYTICO_SYNTHETIC",
- "text": "Сот шешімінің дәлелді жазылғанына көз жеткізгеніне орай, тараптар апелляциялық шағым беруден бас тартты.",
- "cause": "Сот шешімінің дәлелді жазылғанына көз жеткізгеніне орай",
- "effect": "тараптар апелляциялық шағым беруден бас тартты.",
- "marker": "жазылғанына",
- "tv_form": "Tv=ған=//=на, ген=//=не, қан=//=на, кен=//=не",
- },
- {
- "group": "ANALYTICO_SYNTHETIC",
- "text": "Сот шешімі заңды күшіне енген соң, атқарушылық іс жүргізу басталды.",
- "cause": "Сот шешімі заңды күшіне енген соң",
- "effect": "атқарушылық іс жүргізу басталды.",
- "marker": "енген соң",
- "tv_form": "Tv=ған соң, ген соң, қан соң, кен соң",
- },
- {
- "group": "ANALYTICO_SYNTHETIC",
- "text": "Ғылыми зерттеу аяқталған соң, оның нәтижелері халықаралық журналда жарияланды.",
- "cause": "Ғылыми зерттеу аяқталған соң",
- "effect": "оның нәтижелері халықаралық журналда жарияланды.",
- "marker": "аяқталған соң",
- "tv_form": "Tv=ған соң, ген соң, қан соң, кен соң",
- },
- {
- "group": "ANALYTICO_SYNTHETIC",
- "text": "Заң жобасы қабылданған соң, нормативтік-құқықтық актілерге тиісті өзгерістер енгізілді.",
- "cause": "Заң жобасы қабылданған соң",
- "effect": "нормативтік-құқықтық актілерге тиісті өзгерістер енгізілді.",
- "marker": "қабылданған соң",
- "tv_form": "Tv=ған соң, ген соң, қан соң, кен соң",
- },
- {
- "group": "ANALYTICO_SYNTHETIC",
- "text": "Әлеуметтік сауалнама жүргізілген соң, деректер кешенді талдаудан өткізілді.",
- "cause": "Әлеуметтік сауалнама жүргізілген соң",
- "effect": "деректер кешенді талдаудан өткізілді.",
- "marker": "жүргізілген соң",
- "tv_form": "Tv=ған соң, ген соң, қан соң, кен соң",
- },
- ]
- # ── CSS ──────────────────────────────────────────────────────────
- st.markdown("""
- <style>
- @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600;700&family=Syne:wght@400;600;700;800&display=swap');
- :root {
- --bg: #0D0F14;
- --surf: #141720;
- --border: #252A36;
- --accent: #4F8EF7;
- --cause: #3DDC84;
- --effect: #F7794F;
- --marker: #F7CF4F;
- --text: #E8ECF4;
- --muted: #6B7590;
- --rad: 10px;
- }
- html, body, [class*="css"] {
- font-family: 'Syne', sans-serif;
- background: var(--bg); color: var(--text);
- }
- #MainMenu, footer, header { visibility: hidden; }
- .block-container { padding: 1.5rem 2rem 4rem; max-width: 1440px; }
- .topbar {
- display: flex; align-items: center; gap: 14px;
- padding: 14px 0 22px; border-bottom: 1px solid var(--border);
- margin-bottom: 28px;
- }
- .logo {
- font-size: 20px; font-weight: 800;
- background: linear-gradient(135deg, var(--accent), var(--cause));
- -webkit-background-clip: text; -webkit-text-fill-color: transparent;
- }
- .sub {
- font-family: 'JetBrains Mono', monospace; font-size: 11px;
- color: var(--muted); text-transform: uppercase;
- letter-spacing: .08em; margin-left: auto;
- }
- .pill {
- display: inline-flex; align-items: center;
- padding: 3px 10px; border-radius: 20px;
- font-size: 10px; font-family: 'JetBrains Mono', monospace;
- font-weight: 700; text-transform: uppercase; letter-spacing: .05em;
- background: rgba(79,142,247,.12); color: var(--accent);
- border: 1px solid rgba(79,142,247,.25);
- }
- .anno {
- font-family: 'JetBrains Mono', monospace; font-size: 15px;
- line-height: 2.5; background: var(--surf);
- border: 1px solid var(--border); border-radius: var(--rad);
- padding: 20px 24px; word-break: break-word;
- }
- .sp-cause { background: rgba(61,220,132,.18); color:#3DDC84; border-bottom:2px solid #3DDC84; border-radius:3px; padding:1px 2px; }
- .sp-effect { background: rgba(247,121,79,.18); color:#F7794F; border-bottom:2px solid #F7794F; border-radius:3px; padding:1px 2px; }
- .sp-marker { background: rgba(247,207,79,.28); color:#F7CF4F; border-bottom:2px solid #F7CF4F; border-radius:3px; padding:1px 2px; font-weight:700; }
- .sp-lbl { font-size:9px; font-weight:800; vertical-align:super; margin-left:1px; letter-spacing:.04em; opacity:.85; }
- .leg { display:flex; gap:18px; margin:10px 0 20px; flex-wrap:wrap; }
- .leg-item { display:flex; align-items:center; gap:7px; font-family:'JetBrains Mono',monospace; font-size:11px; font-weight:600; }
- .lsq { width:11px; height:11px; border-radius:3px; flex-shrink:0; }
- .sec { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.1em; color:var(--muted); margin:18px 0 8px; }
- .result-card-header { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.08em; color:var(--muted); margin-bottom:10px; }
- .jblock {
- background:#080A0F; border:1px solid var(--border); border-radius:var(--rad);
- padding:16px 18px; font-family:'JetBrains Mono',monospace;
- font-size:12.5px; line-height:1.9; overflow-x:auto; white-space:pre; color:#8EC07C;
- }
- .hist-m { font-family:'JetBrains Mono',monospace; font-size:10px; color:var(--muted); margin-top:2px; margin-bottom:6px; }
- .divl { height:1px; background:var(--border); margin:18px 0; }
- .stButton > button {
- background: linear-gradient(135deg,#2563EB,#1E40AF) !important;
- color:#fff !important; border:none !important; border-radius:8px !important;
- font-family:'Syne',sans-serif !important; font-weight:700 !important;
- padding:10px 24px !important; letter-spacing:.03em !important;
- }
- [data-testid="stSidebar"] { background:var(--surf) !important; border-right:1px solid var(--border) !important; }
- [data-testid="stSidebar"] * { color:var(--text) !important; }
- textarea {
- background:var(--surf) !important; color:var(--text) !important;
- border:1px solid var(--border) !important; border-radius:var(--rad) !important;
- font-family:'JetBrains Mono',monospace !important; font-size:13.5px !important;
- }
- </style>
- """, unsafe_allow_html=True)
- # ── Session state ────────────────────────────────────────────────
- for k, v in [("history", []), ("results", []), ("input_text", "")]:
- if k not in st.session_state:
- st.session_state[k] = v
- # ── Helpers ──────────────────────────────────────────────────────
- MG_COL = {
- "SYNTHETIC": "#4F8EF7",
- "ANALYTIC": "#A78BFA",
- "ANALYTICO_SYNTHETIC": "#F97316",
- }
- GROUP_LABEL = {
- "SYNTHETIC": "⚙ SYNTHETIC",
- "ANALYTIC": "📎 ANALYTIC",
- "ANALYTICO_SYNTHETIC": "🔀 ANALYTICO-SYNTHETIC",
- }
- def make_result_from_db(ex):
- return {
- "text": ex["text"],
- "cause": ex["cause"],
- "effect": ex["effect"],
- "markers": [ex["marker"]],
- "tv_form": ex["tv_form"],
- "tv_confidence": 0.997,
- "semantic_type": "—",
- "semantic_confidence": None,
- "semantic_all": {},
- "model_group": ex["group"],
- "model_group_confidence": 0.999,
- "timestamp": datetime.now().strftime("%H:%M:%S"),
- "error": None,
- "_from_db": True,
- }
- def annotate_html(text, cause_text, effect_text, markers):
- n = len(text)
- prio = [None] * n
- def mark(substr, css, lbl, p):
- if not substr:
- return
- idx = 0
- tl = text.lower()
- sl = substr.lower().strip()
- while True:
- pos = tl.find(sl, idx)
- if pos == -1:
- break
- for i in range(pos, pos + len(sl)):
- if prio[i] is None or prio[i][0] < p:
- prio[i] = (p, css, lbl)
- idx = pos + 1
- mark(cause_text, "sp-cause", "CAUSE", 2)
- mark(effect_text, "sp-effect", "EFFECT", 1)
- for m in (markers or []):
- mark(m, "sp-marker", "MRK", 3)
- html = ""
- i = 0
- while i < n:
- cell = prio[i]
- if cell is None:
- j = i
- while j < n and prio[j] is None:
- j += 1
- html += text[i:j].replace("&","&").replace("<","<").replace(">",">")
- i = j
- else:
- _, css, lbl = cell
- j = i
- while j < n and prio[j] is not None and prio[j][1] == css:
- j += 1
- chunk = text[i:j].replace("&","&").replace("<","<").replace(">",">")
- html += f'<span class="{css}">{chunk}<span class="sp-lbl">{lbl}</span></span>'
- i = j
- return f'<div class="anno">{html}</div>'
- def to_table_rows(r):
- markers = r.get("markers") or []
- marker_str = ", ".join(str(m) for m in markers) or "—"
- def fmt(v):
- if v is None:
- return "—"
- if isinstance(v, float):
- return f"{v:.4f}"
- return str(v)
- rows = [
- {"Field": "cause", "Value": fmt(r.get("cause"))},
- {"Field": "effect", "Value": fmt(r.get("effect"))},
- {"Field": "markers", "Value": marker_str},
- {"Field": "tv_form", "Value": fmt(r.get("tv_form"))},
- {"Field": "tv_confidence", "Value": fmt(r.get("tv_confidence"))},
- {"Field": "semantic_type", "Value": fmt(r.get("semantic_type"))},
- {"Field": "semantic_confidence", "Value": fmt(r.get("semantic_confidence"))},
- ]
- sem_all = r.get("semantic_all") or {}
- for label, score in sem_all.items():
- rows.append({"Field": f" ↳ {label}", "Value": f"{score:.4f}"})
- rows += [
- {"Field": "model_group", "Value": fmt(r.get("model_group"))},
- {"Field": "mg_confidence", "Value": fmt(r.get("model_group_confidence"))},
- ]
- return rows
- def _serialize(v):
- if isinstance(v, (np.floating, np.integer)):
- return v.item()
- if isinstance(v, dict):
- return {dk: _serialize(dv) for dk, dv in v.items()}
- if isinstance(v, list):
- return [_serialize(item) for item in v]
- return v
- def clean_json(r):
- return {k: _serialize(v) for k, v in r.items() if not k.startswith("_")}
- def render_result_card(r, idx=None):
- label = f"Sentence {idx + 1}: " if idx is not None else ""
- mg = r.get("model_group", "—")
- col = MG_COL.get(mg, "#888")
- st.markdown(
- f'<div class="result-card-header">{label}<span style="color:{col}">{mg}</span></div>',
- unsafe_allow_html=True,
- )
- if r.get("_from_db"):
- st.success("✅ Ground-truth annotation from examples")
- st.markdown('<div class="sec">Annotated text</div>', unsafe_allow_html=True)
- cause_t = r.get("cause")
- effect_t = r.get("effect")
- markers_l = r.get("markers") or []
- if cause_t or effect_t or markers_l:
- st.markdown(annotate_html(r["text"], cause_t, effect_t, markers_l), unsafe_allow_html=True)
- else:
- plain = r["text"].replace("&","&").replace("<","<").replace(">",">")
- st.markdown(f'<div class="anno" style="color:var(--muted);">{plain}</div>', unsafe_allow_html=True)
- st.markdown('<div class="sec">Extracted fields</div>', unsafe_allow_html=True)
- st.dataframe(pd.DataFrame(to_table_rows(r)), width="stretch", hide_index=True, height=420)
- st.markdown('<div class="sec">JSON output</div>', unsafe_allow_html=True)
- js = json.dumps(clean_json(r), ensure_ascii=False, indent=2)
- st.markdown(f'<div class="jblock">{js}</div>', unsafe_allow_html=True)
- def demo_annotate_text(txt: str):
- sents = [s.strip() for s in re.split(r'(?<=[.!?])\s+|\n', txt) if s.strip()]
- results = []
- demo_markers_analytic = ["өйткені", "себебі", "неге десең", "неге десеңіз"]
- demo_markers_analytic_synth = ["соң", "кейін"]
- demo_markers_all = [
- "өйткені", "себебі", "сондықтан", "сол себепті", "сол үшін",
- "неге десең", "неге десеңіз",
- "болғандықтан", "болмағандықтан", "білгендіктен", "көргендіктен",
- "жүргізілгендіктен", "алғандықтан", "берілгендіктен", "туғандықтан",
- "үшін", "соң", "кейін"
- ]
- for s in sents:
- low = s.lower()
- found_marker = None
- for m in sorted(demo_markers_all, key=len, reverse=True):
- if m in low:
- found_marker = m
- break
- if found_marker:
- pos = low.find(found_marker)
- left = s[:pos].strip(" ,")
- right = s[pos + len(found_marker):].strip(" ,")
- if found_marker in demo_markers_analytic:
- cause = right
- effect = left
- model_group = "ANALYTIC"
- elif found_marker in demo_markers_analytic_synth or "соң" in found_marker or "кейін" in found_marker:
- cause = s[:pos + len(found_marker)].strip(" ,")
- effect = right
- model_group = "ANALYTICO_SYNTHETIC"
- else:
- cause = s[:pos + len(found_marker)].strip(" ,")
- effect = right
- model_group = "SYNTHETIC"
- results.append({
- "text": s,
- "cause": cause,
- "effect": effect,
- "markers": [found_marker],
- "tv_form": "— (demo mode)",
- "tv_confidence": None,
- "semantic_type": "—",
- "semantic_confidence": None,
- "semantic_all": {},
- "model_group": model_group,
- "model_group_confidence": None,
- "timestamp": datetime.now().strftime("%H:%M:%S"),
- "error": PIPELINE_ERROR if not PIPELINE_READY else None,
- })
- else:
- results.append({
- "text": s,
- "cause": None,
- "effect": None,
- "markers": [],
- "tv_form": "— (demo mode)",
- "tv_confidence": None,
- "semantic_type": "—",
- "semantic_confidence": None,
- "semantic_all": {},
- "model_group": "— (demo mode)",
- "model_group_confidence": None,
- "timestamp": datetime.now().strftime("%H:%M:%S"),
- "error": PIPELINE_ERROR if not PIPELINE_READY else None,
- "_demo_blank": True,
- })
- return results
- # ══════════════════════════════════════════════════════════════════
- # RENDER
- # ══════════════════════════════════════════════════════════════════
- st.markdown("""
- <div class="topbar">
- <div class="logo">⚡ KazCausal</div>
- <span class="pill">KazBERT</span>
- <span class="pill">Streamlit</span>
- <div class="sub">Causal Relation Extraction · Kazakh NLP</div>
- </div>
- """, unsafe_allow_html=True)
- # ── Sidebar ──────────────────────────────────────────────────────
- with st.sidebar:
- st.markdown("### ⚙️ Баптаулар")
- if PIPELINE_READY:
- demo_mode = st.toggle(
- "Demo mode", value=True,
- help="Қосулы тұрса — мысалдар және ереже арқылы аннотация. Өшірулі тұрса — real model жұмыс істейді."
- )
- st.success("Pipeline жүктелді.")
- else:
- demo_mode = True
- st.warning("Pipeline жүктелмеді. Қазір demo mode ғана жұмыс істейді.")
- st.markdown("**Қате:**")
- st.code(PIPELINE_ERROR)
- st.markdown("<div class='divl'></div>", unsafe_allow_html=True)
- st.markdown("### 🕓 Тарих")
- if not st.session_state.history:
- st.markdown('<p style="color:#6B7590;font-size:12px">Әлі сұраныс жоқ.</p>', unsafe_allow_html=True)
- else:
- for i, h in enumerate(reversed(st.session_state.history[-10:])):
- txt, res_list = h
- short = txt[:50] + ("…" if len(txt) > 50 else "")
- mg = res_list[0].get("model_group", "—") if res_list else "—"
- col = MG_COL.get(mg, "#888")
- if st.button(short, key=f"h{i}", use_container_width=True):
- st.session_state.results = res_list
- st.session_state.input_text = txt
- st.rerun()
- st.markdown(
- f'<div class="hist-m">🕐 {res_list[0].get("timestamp","") if res_list else ""}'
- f' · <span style="color:{col}">{mg}</span>'
- f'{" +" + str(len(res_list)-1) + " more" if len(res_list) > 1 else ""}</div>',
- unsafe_allow_html=True,
- )
- st.markdown("<div class='divl'></div>", unsafe_allow_html=True)
- if st.button("🗑 Тарихты тазалау", use_container_width=True):
- st.session_state.history = []
- st.session_state.results = []
- st.rerun()
- # ── Two columns ──────────────────────────────────────────────────
- left, right = st.columns([1, 1], gap="large")
- # ─────────────────── LEFT ───────────────────────────────────────
- with left:
- st.markdown("#### ✏️ Текст енгізіңіз!")
- options = ["— өз мәтініңізді жазыңыз —"]
- opt_map = {}
- for group, glabel in GROUP_LABEL.items():
- for ex in [e for e in DB_EXAMPLES if e["group"] == group]:
- preview = ex["text"][:58] + ("…" if len(ex["text"]) > 58 else "")
- label = f"[{glabel}] {preview}"
- options.append(label)
- opt_map[label] = ex
- sel = st.selectbox("Мысалдар", options, label_visibility="collapsed")
- if "last_sel" not in st.session_state:
- st.session_state.last_sel = None
- if sel != options[0] and sel in opt_map and sel != st.session_state.last_sel:
- chosen_ex = opt_map[sel]
- new_r = make_result_from_db(chosen_ex)
- st.session_state.input_text = chosen_ex["text"]
- st.session_state.results = [new_r]
- st.session_state.history.append((chosen_ex["text"], [new_r]))
- st.session_state.last_sel = sel
- text_input = st.text_area(
- "", value=st.session_state.input_text, height=150,
- placeholder="Бір немесе бірнеше қазақша сөйлем енгізіңіз…",
- label_visibility="collapsed",
- key="textarea_input",
- )
- st.session_state.input_text = text_input
- run_clicked = st.button("⚡ Талдау", use_container_width=True)
- st.markdown("""
- <div class="leg">
- <div class="leg-item"><div class="lsq" style="background:#3DDC84;"></div><span style="color:#3DDC84">CAUSE</span></div>
- <div class="leg-item"><div class="lsq" style="background:#F7794F;"></div><span style="color:#F7794F">EFFECT</span></div>
- <div class="leg-item"><div class="lsq" style="background:#F7CF4F;"></div><span style="color:#F7CF4F">MARKER</span></div>
- </div>""", unsafe_allow_html=True)
- st.markdown("<div class='divl'></div>", unsafe_allow_html=True)
- st.markdown("#### 📂 Batch upload (txt / csv)")
- uploaded = st.file_uploader("Бір жолға бір сөйлем", type=["txt","csv"], label_visibility="collapsed")
- # ─────────────────── RIGHT ──────────────────────────────────────
- with right:
- st.markdown("#### 📋 Нәтижесі")
- if run_clicked and text_input.strip():
- txt = text_input.strip()
- db_hit = next((e for e in DB_EXAMPLES if e["text"].strip() == txt), None)
- if db_hit and demo_mode:
- results = [make_result_from_db(db_hit)]
- elif demo_mode:
- results = demo_annotate_text(txt)
- else:
- with st.spinner("Сөйлемдер талданып жатыр…"):
- try:
- results = analyze_text(txt)
- except Exception as e:
- results = []
- st.error(f"Pipeline қатесі: {e}")
- if not results:
- st.warning("⚠️ Себеп-салдарлы сөйлем табылмады.")
- st.session_state.results = results
- if not st.session_state.history or st.session_state.history[-1][0] != txt:
- st.session_state.history.append((txt, results))
- results = st.session_state.results
- if not results:
- st.markdown("""
- <div style="text-align:center;padding:72px 0;color:#6B7590;">
- <div style="font-size:48px;margin-bottom:14px">⚡</div>
- <div style="font-size:15px;font-weight:600;">Мәтін енгізіп, Талдау батырмасын басыңыз</div>
- <div style="font-size:12px;margin-top:8px;">Demo mode-та да маркер бойынша аннотация жасалады</div>
- </div>""", unsafe_allow_html=True)
- else:
- if len(results) > 1:
- st.info(f"🔍 {len(results)} сөйлем талданды.")
- full_text = st.session_state.input_text.strip()
- if full_text and results:
- st.markdown('<div class="sec">Full text annotation</div>', unsafe_allow_html=True)
- n = len(full_text)
- prio = [None] * n
- def mark_in_full(substr, css, lbl, p):
- if not substr:
- return
- tl = full_text.lower()
- sl = substr.lower().strip()
- idx = 0
- while True:
- pos = tl.find(sl, idx)
- if pos == -1:
- break
- for i in range(pos, pos + len(sl)):
- if prio[i] is None or prio[i][0] < p:
- prio[i] = (p, css, lbl)
- idx = pos + 1
- for r in results:
- mark_in_full(r.get("cause"), "sp-cause", "CAUSE", 2)
- mark_in_full(r.get("effect"), "sp-effect", "EFFECT", 1)
- for m in (r.get("markers") or []):
- mark_in_full(m, "sp-marker", "MRK", 3)
- html = ""
- i = 0
- while i < n:
- cell = prio[i]
- if cell is None:
- j = i
- while j < n and prio[j] is None:
- j += 1
- html += full_text[i:j].replace("&","&").replace("<","<").replace(">",">")
- i = j
- else:
- _, css, lbl = cell
- j = i
- while j < n and prio[j] is not None and prio[j][1] == css:
- j += 1
- chunk = full_text[i:j].replace("&","&").replace("<","<").replace(">",">")
- html += f'<span class="{css}">{chunk}<span class="sp-lbl">{lbl}</span></span>'
- i = j
- html = html.replace("\n", "<br>")
- st.markdown(f'<div class="anno" style="line-height:2.8;">{html}</div>', unsafe_allow_html=True)
- st.markdown("<div class='divl'></div>", unsafe_allow_html=True)
- st.markdown('<div class="sec">Per-sentence breakdown</div>', unsafe_allow_html=True)
- for idx, r in enumerate(results):
- with st.expander(
- f"{'✅' if r.get('_from_db') else '🔬'} Sentence {idx+1} — {r['text'][:60]}{'…' if len(r['text'])>60 else ''}",
- expanded=(idx == 0),
- ):
- if r.get("_demo_blank"):
- st.warning("⚠️ Маркер табылмады немесе demo mode бұл сөйлемді бөле алмады.")
- plain = r["text"].replace("&","&").replace("<","<").replace(">",">")
- st.markdown(f'<div class="anno" style="color:var(--muted);">{plain}</div>', unsafe_allow_html=True)
- else:
- render_result_card(r, idx)
- # ── Batch section ─────────────────────────────────────────────────
- if uploaded:
- st.markdown("---")
- st.markdown("### 📊 Batch results")
- content = uploaded.read().decode("utf-8")
- lines = [l.strip() for l in content.splitlines() if l.strip()]
- st.info(f"**{len(lines)}** сөйлем жүктелді.")
- batch_results = []
- bar = st.progress(0, "Талданып жатыр…")
- for i, line in enumerate(lines):
- db_hit = next((e for e in DB_EXAMPLES if e["text"].strip() == line), None)
- if db_hit:
- batch_results.append(make_result_from_db(db_hit))
- elif demo_mode:
- batch_results.extend(demo_annotate_text(line))
- else:
- try:
- batch_results.extend(analyze_text(line))
- except Exception as e:
- batch_results.append({
- "text": line, "cause": None, "effect": None,
- "markers": [], "tv_form": "ERROR", "tv_confidence": None,
- "semantic_type": "ERROR", "semantic_confidence": None,
- "semantic_all": {},
- "model_group": "ERROR", "model_group_confidence": None,
- "timestamp": datetime.now().strftime("%H:%M:%S"), "error": str(e),
- })
- bar.progress((i + 1) / len(lines), f"Сөйлем {i+1} / {len(lines)}")
- bar.empty()
- df_b = pd.DataFrame([
- {"text": r["text"][:60] + ("…" if len(r["text"]) > 60 else ""),
- **{row["Field"]: row["Value"] for row in to_table_rows(r)}}
- for r in batch_results
- ])
- if not df_b.empty and "model_group" in df_b.columns:
- mc = df_b["model_group"].value_counts()
- cols = st.columns(4)
- cols[0].metric("Total", len(df_b))
- cols[1].metric("SYNTHETIC", mc.get("SYNTHETIC", 0))
- cols[2].metric("ANALYTIC", mc.get("ANALYTIC", 0))
- cols[3].metric("ANALYTICO-SYNTHETIC", mc.get("ANALYTICO_SYNTHETIC", 0))
- st.dataframe(df_b, width="stretch", height=360)
- b1, b2 = st.columns(2)
- with b1:
- st.download_button("⬇ Batch CSV",
- df_b.to_csv(index=False, encoding="utf-8-sig"),
- "batch.csv", "text/csv", use_container_width=True)
- with b2:
- st.download_button("⬇ Batch JSON",
- json.dumps([clean_json(r) for r in batch_results], ensure_ascii=False, indent=2),
- "batch.json", "application/json", use_container_width=True)
streamlit.py at commit 52856c4, no license · at the source
Overview
- L.N. Gumilyov Eurasian National University, Astana, Kazakhstan
- International Science Complex Astana, Astana, Kazakhstan
- School of Information Technology and Engineering, Astana International University, Astana, Kazakhstan
Abstract
This article presents a four-module system for the automatic extraction and classification of causal relationships from texts in the Kazakh language, based on the fine-tuning of the KazBERT transformer language model. The proposed architecture includes four specialized modules: recognition of lexical causality markers (Token Classification, B/
Reproduced under the paper's license (CC BY), from the paper cited above.
Repository
Its files are read in the Code ↔ Paper reader above.
ParserRn/KazCausal
52856c492c72d5c998a6f614e3b45478a142dbec, 5 April 2026Availability: 1 check, the latest on 27 September 2026: the link answers
- 27 September 2026: the link answers
3 files
- Code/
streamlit.py , Python, 737 lines - Code/
train.py , Python, 225 lines - README.md, Text, 16 lines
The paper's code and data availability statement is in the Data section.
Tracing map
Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.
What the map holds:
- 1 repository of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
- 2 scripts, each with its path and the digest of its content;
- no match between paragraphs and code yet;
- neither the text of the paper nor the code itself.
Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.
Data
No dataset and no data link were found in the paper.
Data availability statement
The datasets presented in this study can be found in online repositories. The names of the repository/
Reproduced under the paper's license (CC BY), from the paper cited above.
Versions
The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.
Version 1, 27 September 2026: the first record
Recorded: type, language, journal, volume, pages, dates, 7 authors, 7 keywords, 15 references.
Cite
This paper
Taberkhan, R., Tasbolatuly, N., Sambetbayeva, M., Tazhibayeva, S., Zhumay, N., Abdygalym, B., & Kaldarova, M. (2026). A four-module neural architecture for the automatic extraction and classification of causal relations in text. Frontiers in artificial intelligence, 9, 1848216. https://
BibTeX
@article{taberkhan2026fo
author = {Taberkhan, Roman and Tasbolatuly, Nurbolat and Sambetbayeva, Madina and Tazhibayeva, Saule and Zhumay, Nurmira and Abdygalym, Bayangali and Kaldarova, Mira},
title = {{A four-module neural architecture for the automatic extraction and classification of causal relations in text}},
journal = {Frontiers in artificial intelligence},
year = {2026},
month = jul,
volume = {9},
pages = {1848216},
publisher = {Frontiers Media SA},
issn = {2624-8212},
doi = {10.3389/
url = {https://
pmid = {42564329},
pmcid = {PMC13443141}
}
RIS
TY - JOUR
AU - Taberkhan, Roman
AU - Tasbolatuly, Nurbolat
AU - Sambetbayeva, Madina
AU - Tazhibayeva, Saule
AU - Zhumay, Nurmira
AU - Abdygalym, Bayangali
AU - Kaldarova, Mira
TI - A four-module neural architecture for the automatic extraction and classification of causal relations in text
T2 - Frontiers in artificial intelligence
J2 - Front Artif Intell
PY - 2026
DA - 2026/
VL - 9
SP - 1848216
SN - 2624-8212
PB - Frontiers Media SA
DO - 10.3389/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.3389/
"type": "article-journal",
"title": "A four-module neural architecture for the automatic extraction and classification of causal relations in text",
"container-title": "Frontiers in artificial intelligence",
"author": [
{
"family": "Taberkhan",
"given": "Roman"
},
{
"family": "Tasbolatuly",
"given": "Nurbolat"
},
{
"family": "Sambetbayeva",
"given": "Madina"
},
{
"family": "Tazhibayeva",
"given": "Saule"
},
{
"family": "Zhumay",
"given": "Nurmira"
},
{
"family": "Abdygalym",
"given": "Bayangali"
},
{
"family": "Kaldarova",
"given": "Mira"
}
],
"container-title-short":
"volume": "9",
"page": "1848216",
"DOI": "10.3389/
"PMID": "42564329",
"PMCID": "PMC13443141",
"ISSN": "2624-8212",
"publisher": "Frontiers Media SA",
"URL": "https://
"language": "en",
"issued": {
"date-parts": [
[
2026,
7,
23
]
]
}
}
The tracing map gets a citation of its own once an author has validated it and it has a DOI.
Similar papers
The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.
- [1] doi:10.1016/j.patter.2025.101325 [code]
- Tucano: Advancing neural text generation for Portuguese.Journal: Patterns (New York, N.Y.)In common: Hugging Face Transformers, pandas, NumPy, 1 reference
- [2] doi:10.1016/j.isci.2026.116135 [code]
- Predicting ICU in-hospital mortality from text-encoded structured EHR data using adaptive transformer layer fusion.Journal: iScienceIn common: Hugging Face Transformers, pandas, NumPy, 1 reference
- [3] doi:10.1016/j.scog.2026.100443 [code]
- From thought to language: Comparing schizophrenia spectrum disorders and Wernicke's aphasia with machine learning and LLMs.Journal: Schizophrenia research. CognitionIn common: Hugging Face Transformers, pandas, NumPy, 1 reference
- [4] doi:10.1038/s41597-025-06466-8 [code]
- An EEG Dataset for Multimodal Semantic Alignment and Neural Decoding during Reading and Listening.Journal: Scientific dataIn common: Hugging Face Transformers, pandas, NumPy, 1 reference
- [5] doi:10.1038/s43588-025-00863-0 [code]
- Increasing alignment of large language models with language processing in the human brain.Journal: Nature computational scienceIn common: Hugging Face Transformers, pandas, NumPy, 1 reference
- [6] doi:10.1038/s41598-024-69602-1 [code]
- Neural encoding of linguistic speech cues is unaffected by cognitive decline, but decreases with increasing hearing impairment.Journal: Scientific reportsIn common: Hugging Face Transformers, pandas, NumPy, 1 reference
- [7] doi:10.1093/database/baae066 [code]
- Dataset of miRNA-disease relations extracted from textual data using transformer-based neural networks.Journal: Database : the journal of biological databases and curationIn common: Hugging Face Transformers, pandas, NumPy, 1 reference
- [8] doi:10.1038/s41467-024-49173-5 [code]
- Shared functional specialization in transformer-based language models and the human brain.Journal: Nature communicationsIn common: Hugging Face Transformers, pandas, NumPy, 1 reference
- [9] doi:10.3389/frai.2022.777963 [code]
- Comparison of Structural Parsers and Neural Language Models as Surprisal Estimators.Journal: Frontiers in artificial intelligenceIn common: Hugging Face Transformers, pandas, NumPy, 1 reference
- [10] doi:10.1093/bioinformatics/btaf198 [code]
- NEAR: neural embeddings for amino acid relationships.Journal: Bioinformatics (Oxford, England)In common: Hugging Face Transformers, NumPy, 1 reference
Contribute
The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.
Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 1 repository of the authors' code, each at its verified commit and with its license, 2 scripts, and 0 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:eed4149d4c33e47a…
Add the badge to the code's README
If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.
Markdown
<!-- oscr-badge:start -->
[](https://openscicode.org/badge/doi/10.3389/frai.2026.1848216)
<!-- oscr-badge:end -->reStructuredText
.. oscr-badge:start
.. image:: https://openscicode.org/badge/doi/10.3389/frai.2026.1848216.svg
:target: https://openscicode.org/badge/doi/10.3389/frai.2026.1848216
:alt: OSCR
.. oscr-badge:endHTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.3389/frai.2026.1848216"><img src="https://openscicode.org/badge/doi/10.3389/frai.2026.1848216.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".
If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.
Request its removal
To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).
Discussion, reproductions, activity
Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.
Report a mismatch between the code and the paper · Report a code error (signed in)
Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.
Report a reproduction failure (signed in)
Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.
Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.
