OSCR

A four-module neural architecture for the automatic extraction and classification of causal relations in text.

Code ↔ Paper

The paper beside its authors' code: matches between them have not been computed for this paper yet.

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 737 lines · 35 KB · no license

  1. import streamlit as st
  2. import json
  3. import pandas as pd
  4. import numpy as np
  5. from datetime import datetime
  6. import re
  7. # =========================================================
  8. # SAFE IMPORT: интерфейс всегда открывается
  9. # =========================================================
  10. PIPELINE_ERROR = None
  11. analyze_text = None
  12. try:
  13. from pipelineFinal import analyze_text
  14. PIPELINE_READY = True
  15. except Exception as e:
  16. PIPELINE_READY = False
  17. PIPELINE_ERROR = str(e)
  18. # ── Page config ──────────────────────────────────────────────────
  19. st.set_page_config(
  20. page_title="KazCausal",
  21. page_icon="⚡",
  22. layout="wide",
  23. initial_sidebar_state="expanded",
  24. )
  25. # ── DB examples ──────────────────────────────────────────────────
  26. DB_EXAMPLES = [
  27. {
  28. "group": "SYNTHETIC",
  29. "text": "Қысқа да әрі нақты, көпке түсінікті болғандықтан студенттерге бір деммен оқу қиынға соқпауы мүмкін.",
  30. "cause": "Қысқа да әрі нақты, көпке түсінікті болғандықтан",
  31. "effect": "студенттерге бір деммен оқу қиынға соқпауы мүмкін.",
  32. "marker": "болғандықтан",
  33. "tv_form": "Tv=ғандықтан, гендіктен, қандықтан, кендіктен",
  34. },
  35. {
  36. "group": "SYNTHETIC",
  37. "text": "Əрбір тайпа бұл киелі міндетке тек өздерін лайықты деп білгендіктен, араларында дау-жанжал шықты.",
  38. "cause": "Əрбір тайпа бұл киелі міндетке тек өздерін лайықты деп білгендіктен",
  39. "effect": "араларында дау-жанжал шықты.",
  40. "marker": "білгендіктен",
  41. "tv_form": "Tv=ғандықтан, гендіктен, қандықтан, кендіктен",
  42. },
  43. {
  44. "group": "SYNTHETIC",
  45. "text": "Таңдау мүмкіндігі, әралуандық болғандықтан оларды қолдануда едәуір еркіндік бар.",
  46. "cause": "Таңдау мүмкіндігі, әралуандық болғандықтан",
  47. "effect": "оларды қолдануда едәуір еркіндік бар.",
  48. "marker": "болғандықтан",
  49. "tv_form": "Tv=ғандықтан, гендіктен, қандықтан, кендіктен",
  50. },
  51. {
  52. "group": "SYNTHETIC",
  53. "text": "Мен мұғжиза ретінде тамақтың азаймағанын көргендіктен тағы да алпыс адамды шақырып келдім.",
  54. "cause": "Мен мұғжиза ретінде тамақтың азаймағанын көргендіктен",
  55. "effect": "тағы да алпыс адамды шақырып келдім.",
  56. "marker": "көргендіктен",
  57. "tv_form": "Tv=ғандықтан, гендіктен, қандықтан, кендіктен",
  58. },
  59. {
  60. "group": "SYNTHETIC",
  61. "text": "Сұрақ беріледі, оның «дұрыс» жауабы алдын-ала белгілі болғандықтан, ақиқат» сол сұрақтың өзінде.",
  62. "cause": "Сұрақ беріледі, оның «дұрыс» жауабы алдын-ала белгілі болғандықтан",
  63. "effect": "ақиқат» сол сұрақтың өзінде.",
  64. "marker": "болғандықтан",
  65. "tv_form": "Tv=ғандықтан, гендіктен, қандықтан, кендіктен",
  66. },
  67. {
  68. "group": "ANALYTIC",
  69. "text": "Қоғамдық сенім деңгейі төмендеді, себебі мемлекеттік институттардың ашықтығы жеткіліксіз қамтамасыз етілді.",
  70. "cause": "мемлекеттік институттардың ашықтығы жеткіліксіз қамтамасыз етілді.",
  71. "effect": "Қоғамдық сенім деңгейі төмендеді",
  72. "marker": "себебі",
  73. "tv_form": "[(N1) Tv =fin] себебі [(N1) Vfin.]",
  74. },
  75. {
  76. "group": "ANALYTIC",
  77. "text": "Сот шешімдерінің сапасына сын айтылды, себебі дәлелдемелерді бағалау рәсімі бірізді жүргізілмеді.",
  78. "cause": "дәлелдемелерді бағалау рәсімі бірізді жүргізілмеді.",
  79. "effect": "Сот шешімдерінің сапасына сын айтылды",
  80. "marker": "себебі",
  81. "tv_form": "[(N1) Tv =fin] себебі [(N1) Vfin.]",
  82. },
  83. {
  84. "group": "ANALYTIC",
  85. "text": "Әлеуметтік теңсіздік күшейді, себебі ресурстарды бөлу тетіктері тиімді жұмыс істемеді.",
  86. "cause": "ресурстарды бөлу тетіктері тиімді жұмыс істемеді.",
  87. "effect": "Әлеуметтік теңсіздік күшейді",
  88. "marker": "себебі",
  89. "tv_form": "[(N1) Tv =fin] себебі [(N1) Vfin.]",
  90. },
  91. {
  92. "group": "ANALYTIC",
  93. "text": "Білім беру нәтижелері төмендеді, себебі оқу бағдарламалары заманауи талаптарға толық сәйкес келмеді.",
  94. "cause": "оқу бағдарламалары заманауи талаптарға толық сәйкес келмеді.",
  95. "effect": "Білім беру нәтижелері төмендеді",
  96. "marker": "себебі",
  97. "tv_form": "[(N1) Tv =fin] себебі [(N1) Vfin.]",
  98. },
  99. {
  100. "group": "ANALYTIC",
  101. "text": "Ғылыми жарияланым сапасы әркелкі болды, себебі рецензиялау жүйесі қатаң сақталмады.",
  102. "cause": "рецензиялау жүйесі қатаң сақталмады.",
  103. "effect": "Ғылыми жарияланым сапасы әркелкі болды",
  104. "marker": "себебі",
  105. "tv_form": "[(N1) Tv =fin] себебі [(N1) Vfin.]",
  106. },
  107. {
  108. "group": "ANALYTICO_SYNTHETIC",
  109. "text": "Сот шешімінің дәлелді жазылғанына көз жеткізгеніне орай, тараптар апелляциялық шағым беруден бас тартты.",
  110. "cause": "Сот шешімінің дәлелді жазылғанына көз жеткізгеніне орай",
  111. "effect": "тараптар апелляциялық шағым беруден бас тартты.",
  112. "marker": "жазылғанына",
  113. "tv_form": "Tv=ған=//=на, ген=//=не, қан=//=на, кен=//=не",
  114. },
  115. {
  116. "group": "ANALYTICO_SYNTHETIC",
  117. "text": "Сот шешімі заңды күшіне енген соң, атқарушылық іс жүргізу басталды.",
  118. "cause": "Сот шешімі заңды күшіне енген соң",
  119. "effect": "атқарушылық іс жүргізу басталды.",
  120. "marker": "енген соң",
  121. "tv_form": "Tv=ған соң, ген соң, қан соң, кен соң",
  122. },
  123. {
  124. "group": "ANALYTICO_SYNTHETIC",
  125. "text": "Ғылыми зерттеу аяқталған соң, оның нәтижелері халықаралық журналда жарияланды.",
  126. "cause": "Ғылыми зерттеу аяқталған соң",
  127. "effect": "оның нәтижелері халықаралық журналда жарияланды.",
  128. "marker": "аяқталған соң",
  129. "tv_form": "Tv=ған соң, ген соң, қан соң, кен соң",
  130. },
  131. {
  132. "group": "ANALYTICO_SYNTHETIC",
  133. "text": "Заң жобасы қабылданған соң, нормативтік-құқықтық актілерге тиісті өзгерістер енгізілді.",
  134. "cause": "Заң жобасы қабылданған соң",
  135. "effect": "нормативтік-құқықтық актілерге тиісті өзгерістер енгізілді.",
  136. "marker": "қабылданған соң",
  137. "tv_form": "Tv=ған соң, ген соң, қан соң, кен соң",
  138. },
  139. {
  140. "group": "ANALYTICO_SYNTHETIC",
  141. "text": "Әлеуметтік сауалнама жүргізілген соң, деректер кешенді талдаудан өткізілді.",
  142. "cause": "Әлеуметтік сауалнама жүргізілген соң",
  143. "effect": "деректер кешенді талдаудан өткізілді.",
  144. "marker": "жүргізілген соң",
  145. "tv_form": "Tv=ған соң, ген соң, қан соң, кен соң",
  146. },
  147. ]
  148. # ── CSS ──────────────────────────────────────────────────────────
  149. st.markdown("""
  150. <style>
  151. @import url('https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;600;700&family=Syne:wght@400;600;700;800&display=swap');
  152. :root {
  153. --bg: #0D0F14;
  154. --surf: #141720;
  155. --border: #252A36;
  156. --accent: #4F8EF7;
  157. --cause: #3DDC84;
  158. --effect: #F7794F;
  159. --marker: #F7CF4F;
  160. --text: #E8ECF4;
  161. --muted: #6B7590;
  162. --rad: 10px;
  163. }
  164. html, body, [class*="css"] {
  165. font-family: 'Syne', sans-serif;
  166. background: var(--bg); color: var(--text);
  167. }
  168. #MainMenu, footer, header { visibility: hidden; }
  169. .block-container { padding: 1.5rem 2rem 4rem; max-width: 1440px; }
  170. .topbar {
  171. display: flex; align-items: center; gap: 14px;
  172. padding: 14px 0 22px; border-bottom: 1px solid var(--border);
  173. margin-bottom: 28px;
  174. }
  175. .logo {
  176. font-size: 20px; font-weight: 800;
  177. background: linear-gradient(135deg, var(--accent), var(--cause));
  178. -webkit-background-clip: text; -webkit-text-fill-color: transparent;
  179. }
  180. .sub {
  181. font-family: 'JetBrains Mono', monospace; font-size: 11px;
  182. color: var(--muted); text-transform: uppercase;
  183. letter-spacing: .08em; margin-left: auto;
  184. }
  185. .pill {
  186. display: inline-flex; align-items: center;
  187. padding: 3px 10px; border-radius: 20px;
  188. font-size: 10px; font-family: 'JetBrains Mono', monospace;
  189. font-weight: 700; text-transform: uppercase; letter-spacing: .05em;
  190. background: rgba(79,142,247,.12); color: var(--accent);
  191. border: 1px solid rgba(79,142,247,.25);
  192. }
  193. .anno {
  194. font-family: 'JetBrains Mono', monospace; font-size: 15px;
  195. line-height: 2.5; background: var(--surf);
  196. border: 1px solid var(--border); border-radius: var(--rad);
  197. padding: 20px 24px; word-break: break-word;
  198. }
  199. .sp-cause { background: rgba(61,220,132,.18); color:#3DDC84; border-bottom:2px solid #3DDC84; border-radius:3px; padding:1px 2px; }
  200. .sp-effect { background: rgba(247,121,79,.18); color:#F7794F; border-bottom:2px solid #F7794F; border-radius:3px; padding:1px 2px; }
  201. .sp-marker { background: rgba(247,207,79,.28); color:#F7CF4F; border-bottom:2px solid #F7CF4F; border-radius:3px; padding:1px 2px; font-weight:700; }
  202. .sp-lbl { font-size:9px; font-weight:800; vertical-align:super; margin-left:1px; letter-spacing:.04em; opacity:.85; }
  203. .leg { display:flex; gap:18px; margin:10px 0 20px; flex-wrap:wrap; }
  204. .leg-item { display:flex; align-items:center; gap:7px; font-family:'JetBrains Mono',monospace; font-size:11px; font-weight:600; }
  205. .lsq { width:11px; height:11px; border-radius:3px; flex-shrink:0; }
  206. .sec { font-size:10px; font-weight:700; text-transform:uppercase; letter-spacing:.1em; color:var(--muted); margin:18px 0 8px; }
  207. .result-card-header { font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.08em; color:var(--muted); margin-bottom:10px; }
  208. .jblock {
  209. background:#080A0F; border:1px solid var(--border); border-radius:var(--rad);
  210. padding:16px 18px; font-family:'JetBrains Mono',monospace;
  211. font-size:12.5px; line-height:1.9; overflow-x:auto; white-space:pre; color:#8EC07C;
  212. }
  213. .hist-m { font-family:'JetBrains Mono',monospace; font-size:10px; color:var(--muted); margin-top:2px; margin-bottom:6px; }
  214. .divl { height:1px; background:var(--border); margin:18px 0; }
  215. .stButton > button {
  216. background: linear-gradient(135deg,#2563EB,#1E40AF) !important;
  217. color:#fff !important; border:none !important; border-radius:8px !important;
  218. font-family:'Syne',sans-serif !important; font-weight:700 !important;
  219. padding:10px 24px !important; letter-spacing:.03em !important;
  220. }
  221. [data-testid="stSidebar"] { background:var(--surf) !important; border-right:1px solid var(--border) !important; }
  222. [data-testid="stSidebar"] * { color:var(--text) !important; }
  223. textarea {
  224. background:var(--surf) !important; color:var(--text) !important;
  225. border:1px solid var(--border) !important; border-radius:var(--rad) !important;
  226. font-family:'JetBrains Mono',monospace !important; font-size:13.5px !important;
  227. }
  228. </style>
  229. """, unsafe_allow_html=True)
  230. # ── Session state ────────────────────────────────────────────────
  231. for k, v in [("history", []), ("results", []), ("input_text", "")]:
  232. if k not in st.session_state:
  233. st.session_state[k] = v
  234. # ── Helpers ──────────────────────────────────────────────────────
  235. MG_COL = {
  236. "SYNTHETIC": "#4F8EF7",
  237. "ANALYTIC": "#A78BFA",
  238. "ANALYTICO_SYNTHETIC": "#F97316",
  239. }
  240. GROUP_LABEL = {
  241. "SYNTHETIC": "⚙ SYNTHETIC",
  242. "ANALYTIC": "📎 ANALYTIC",
  243. "ANALYTICO_SYNTHETIC": "🔀 ANALYTICO-SYNTHETIC",
  244. }
  245. def make_result_from_db(ex):
  246. return {
  247. "text": ex["text"],
  248. "cause": ex["cause"],
  249. "effect": ex["effect"],
  250. "markers": [ex["marker"]],
  251. "tv_form": ex["tv_form"],
  252. "tv_confidence": 0.997,
  253. "semantic_type": "—",
  254. "semantic_confidence": None,
  255. "semantic_all": {},
  256. "model_group": ex["group"],
  257. "model_group_confidence": 0.999,
  258. "timestamp": datetime.now().strftime("%H:%M:%S"),
  259. "error": None,
  260. "_from_db": True,
  261. }
  262. def annotate_html(text, cause_text, effect_text, markers):
  263. n = len(text)
  264. prio = [None] * n
  265. def mark(substr, css, lbl, p):
  266. if not substr:
  267. return
  268. idx = 0
  269. tl = text.lower()
  270. sl = substr.lower().strip()
  271. while True:
  272. pos = tl.find(sl, idx)
  273. if pos == -1:
  274. break
  275. for i in range(pos, pos + len(sl)):
  276. if prio[i] is None or prio[i][0] < p:
  277. prio[i] = (p, css, lbl)
  278. idx = pos + 1
  279. mark(cause_text, "sp-cause", "CAUSE", 2)
  280. mark(effect_text, "sp-effect", "EFFECT", 1)
  281. for m in (markers or []):
  282. mark(m, "sp-marker", "MRK", 3)
  283. html = ""
  284. i = 0
  285. while i < n:
  286. cell = prio[i]
  287. if cell is None:
  288. j = i
  289. while j < n and prio[j] is None:
  290. j += 1
  291. html += text[i:j].replace("&","&amp;").replace("<","&lt;").replace(">","&gt;")
  292. i = j
  293. else:
  294. _, css, lbl = cell
  295. j = i
  296. while j < n and prio[j] is not None and prio[j][1] == css:
  297. j += 1
  298. chunk = text[i:j].replace("&","&amp;").replace("<","&lt;").replace(">","&gt;")
  299. html += f'<span class="{css}">{chunk}<span class="sp-lbl">{lbl}</span></span>'
  300. i = j
  301. return f'<div class="anno">{html}</div>'
  302. def to_table_rows(r):
  303. markers = r.get("markers") or []
  304. marker_str = ", ".join(str(m) for m in markers) or "—"
  305. def fmt(v):
  306. if v is None:
  307. return "—"
  308. if isinstance(v, float):
  309. return f"{v:.4f}"
  310. return str(v)
  311. rows = [
  312. {"Field": "cause", "Value": fmt(r.get("cause"))},
  313. {"Field": "effect", "Value": fmt(r.get("effect"))},
  314. {"Field": "markers", "Value": marker_str},
  315. {"Field": "tv_form", "Value": fmt(r.get("tv_form"))},
  316. {"Field": "tv_confidence", "Value": fmt(r.get("tv_confidence"))},
  317. {"Field": "semantic_type", "Value": fmt(r.get("semantic_type"))},
  318. {"Field": "semantic_confidence", "Value": fmt(r.get("semantic_confidence"))},
  319. ]
  320. sem_all = r.get("semantic_all") or {}
  321. for label, score in sem_all.items():
  322. rows.append({"Field": f" ↳ {label}", "Value": f"{score:.4f}"})
  323. rows += [
  324. {"Field": "model_group", "Value": fmt(r.get("model_group"))},
  325. {"Field": "mg_confidence", "Value": fmt(r.get("model_group_confidence"))},
  326. ]
  327. return rows
  328. def _serialize(v):
  329. if isinstance(v, (np.floating, np.integer)):
  330. return v.item()
  331. if isinstance(v, dict):
  332. return {dk: _serialize(dv) for dk, dv in v.items()}
  333. if isinstance(v, list):
  334. return [_serialize(item) for item in v]
  335. return v
  336. def clean_json(r):
  337. return {k: _serialize(v) for k, v in r.items() if not k.startswith("_")}
  338. def render_result_card(r, idx=None):
  339. label = f"Sentence {idx + 1}: " if idx is not None else ""
  340. mg = r.get("model_group", "—")
  341. col = MG_COL.get(mg, "#888")
  342. st.markdown(
  343. f'<div class="result-card-header">{label}<span style="color:{col}">{mg}</span></div>',
  344. unsafe_allow_html=True,
  345. )
  346. if r.get("_from_db"):
  347. st.success("✅ Ground-truth annotation from examples")
  348. st.markdown('<div class="sec">Annotated text</div>', unsafe_allow_html=True)
  349. cause_t = r.get("cause")
  350. effect_t = r.get("effect")
  351. markers_l = r.get("markers") or []
  352. if cause_t or effect_t or markers_l:
  353. st.markdown(annotate_html(r["text"], cause_t, effect_t, markers_l), unsafe_allow_html=True)
  354. else:
  355. plain = r["text"].replace("&","&amp;").replace("<","&lt;").replace(">","&gt;")
  356. st.markdown(f'<div class="anno" style="color:var(--muted);">{plain}</div>', unsafe_allow_html=True)
  357. st.markdown('<div class="sec">Extracted fields</div>', unsafe_allow_html=True)
  358. st.dataframe(pd.DataFrame(to_table_rows(r)), width="stretch", hide_index=True, height=420)
  359. st.markdown('<div class="sec">JSON output</div>', unsafe_allow_html=True)
  360. js = json.dumps(clean_json(r), ensure_ascii=False, indent=2)
  361. st.markdown(f'<div class="jblock">{js}</div>', unsafe_allow_html=True)
  362. def demo_annotate_text(txt: str):
  363. sents = [s.strip() for s in re.split(r'(?<=[.!?])\s+|\n', txt) if s.strip()]
  364. results = []
  365. demo_markers_analytic = ["өйткені", "себебі", "неге десең", "неге десеңіз"]
  366. demo_markers_analytic_synth = ["соң", "кейін"]
  367. demo_markers_all = [
  368. "өйткені", "себебі", "сондықтан", "сол себепті", "сол үшін",
  369. "неге десең", "неге десеңіз",
  370. "болғандықтан", "болмағандықтан", "білгендіктен", "көргендіктен",
  371. "жүргізілгендіктен", "алғандықтан", "берілгендіктен", "туғандықтан",
  372. "үшін", "соң", "кейін"
  373. ]
  374. for s in sents:
  375. low = s.lower()
  376. found_marker = None
  377. for m in sorted(demo_markers_all, key=len, reverse=True):
  378. if m in low:
  379. found_marker = m
  380. break
  381. if found_marker:
  382. pos = low.find(found_marker)
  383. left = s[:pos].strip(" ,")
  384. right = s[pos + len(found_marker):].strip(" ,")
  385. if found_marker in demo_markers_analytic:
  386. cause = right
  387. effect = left
  388. model_group = "ANALYTIC"
  389. elif found_marker in demo_markers_analytic_synth or "соң" in found_marker or "кейін" in found_marker:
  390. cause = s[:pos + len(found_marker)].strip(" ,")
  391. effect = right
  392. model_group = "ANALYTICO_SYNTHETIC"
  393. else:
  394. cause = s[:pos + len(found_marker)].strip(" ,")
  395. effect = right
  396. model_group = "SYNTHETIC"
  397. results.append({
  398. "text": s,
  399. "cause": cause,
  400. "effect": effect,
  401. "markers": [found_marker],
  402. "tv_form": "— (demo mode)",
  403. "tv_confidence": None,
  404. "semantic_type": "—",
  405. "semantic_confidence": None,
  406. "semantic_all": {},
  407. "model_group": model_group,
  408. "model_group_confidence": None,
  409. "timestamp": datetime.now().strftime("%H:%M:%S"),
  410. "error": PIPELINE_ERROR if not PIPELINE_READY else None,
  411. })
  412. else:
  413. results.append({
  414. "text": s,
  415. "cause": None,
  416. "effect": None,
  417. "markers": [],
  418. "tv_form": "— (demo mode)",
  419. "tv_confidence": None,
  420. "semantic_type": "—",
  421. "semantic_confidence": None,
  422. "semantic_all": {},
  423. "model_group": "— (demo mode)",
  424. "model_group_confidence": None,
  425. "timestamp": datetime.now().strftime("%H:%M:%S"),
  426. "error": PIPELINE_ERROR if not PIPELINE_READY else None,
  427. "_demo_blank": True,
  428. })
  429. return results
  430. # ══════════════════════════════════════════════════════════════════
  431. # RENDER
  432. # ══════════════════════════════════════════════════════════════════
  433. st.markdown("""
  434. <div class="topbar">
  435. <div class="logo">⚡ KazCausal</div>
  436. <span class="pill">KazBERT</span>
  437. <span class="pill">Streamlit</span>
  438. <div class="sub">Causal Relation Extraction · Kazakh NLP</div>
  439. </div>
  440. """, unsafe_allow_html=True)
  441. # ── Sidebar ──────────────────────────────────────────────────────
  442. with st.sidebar:
  443. st.markdown("### ⚙️ Баптаулар")
  444. if PIPELINE_READY:
  445. demo_mode = st.toggle(
  446. "Demo mode", value=True,
  447. help="Қосулы тұрса — мысалдар және ереже арқылы аннотация. Өшірулі тұрса — real model жұмыс істейді."
  448. )
  449. st.success("Pipeline жүктелді.")
  450. else:
  451. demo_mode = True
  452. st.warning("Pipeline жүктелмеді. Қазір demo mode ғана жұмыс істейді.")
  453. st.markdown("**Қате:**")
  454. st.code(PIPELINE_ERROR)
  455. st.markdown("<div class='divl'></div>", unsafe_allow_html=True)
  456. st.markdown("### 🕓 Тарих")
  457. if not st.session_state.history:
  458. st.markdown('<p style="color:#6B7590;font-size:12px">Әлі сұраныс жоқ.</p>', unsafe_allow_html=True)
  459. else:
  460. for i, h in enumerate(reversed(st.session_state.history[-10:])):
  461. txt, res_list = h
  462. short = txt[:50] + ("…" if len(txt) > 50 else "")
  463. mg = res_list[0].get("model_group", "—") if res_list else "—"
  464. col = MG_COL.get(mg, "#888")
  465. if st.button(short, key=f"h{i}", use_container_width=True):
  466. st.session_state.results = res_list
  467. st.session_state.input_text = txt
  468. st.rerun()
  469. st.markdown(
  470. f'<div class="hist-m">🕐 {res_list[0].get("timestamp","") if res_list else ""}'
  471. f' &nbsp;·&nbsp; <span style="color:{col}">{mg}</span>'
  472. f'{" +" + str(len(res_list)-1) + " more" if len(res_list) > 1 else ""}</div>',
  473. unsafe_allow_html=True,
  474. )
  475. st.markdown("<div class='divl'></div>", unsafe_allow_html=True)
  476. if st.button("🗑 Тарихты тазалау", use_container_width=True):
  477. st.session_state.history = []
  478. st.session_state.results = []
  479. st.rerun()
  480. # ── Two columns ──────────────────────────────────────────────────
  481. left, right = st.columns([1, 1], gap="large")
  482. # ─────────────────── LEFT ───────────────────────────────────────
  483. with left:
  484. st.markdown("#### ✏️ Текст енгізіңіз!")
  485. options = ["— өз мәтініңізді жазыңыз —"]
  486. opt_map = {}
  487. for group, glabel in GROUP_LABEL.items():
  488. for ex in [e for e in DB_EXAMPLES if e["group"] == group]:
  489. preview = ex["text"][:58] + ("…" if len(ex["text"]) > 58 else "")
  490. label = f"[{glabel}] {preview}"
  491. options.append(label)
  492. opt_map[label] = ex
  493. sel = st.selectbox("Мысалдар", options, label_visibility="collapsed")
  494. if "last_sel" not in st.session_state:
  495. st.session_state.last_sel = None
  496. if sel != options[0] and sel in opt_map and sel != st.session_state.last_sel:
  497. chosen_ex = opt_map[sel]
  498. new_r = make_result_from_db(chosen_ex)
  499. st.session_state.input_text = chosen_ex["text"]
  500. st.session_state.results = [new_r]
  501. st.session_state.history.append((chosen_ex["text"], [new_r]))
  502. st.session_state.last_sel = sel
  503. text_input = st.text_area(
  504. "", value=st.session_state.input_text, height=150,
  505. placeholder="Бір немесе бірнеше қазақша сөйлем енгізіңіз…",
  506. label_visibility="collapsed",
  507. key="textarea_input",
  508. )
  509. st.session_state.input_text = text_input
  510. run_clicked = st.button("⚡ Талдау", use_container_width=True)
  511. st.markdown("""
  512. <div class="leg">
  513. <div class="leg-item"><div class="lsq" style="background:#3DDC84;"></div><span style="color:#3DDC84">CAUSE</span></div>
  514. <div class="leg-item"><div class="lsq" style="background:#F7794F;"></div><span style="color:#F7794F">EFFECT</span></div>
  515. <div class="leg-item"><div class="lsq" style="background:#F7CF4F;"></div><span style="color:#F7CF4F">MARKER</span></div>
  516. </div>""", unsafe_allow_html=True)
  517. st.markdown("<div class='divl'></div>", unsafe_allow_html=True)
  518. st.markdown("#### 📂 Batch upload (txt / csv)")
  519. uploaded = st.file_uploader("Бір жолға бір сөйлем", type=["txt","csv"], label_visibility="collapsed")
  520. # ─────────────────── RIGHT ──────────────────────────────────────
  521. with right:
  522. st.markdown("#### 📋 Нәтижесі")
  523. if run_clicked and text_input.strip():
  524. txt = text_input.strip()
  525. db_hit = next((e for e in DB_EXAMPLES if e["text"].strip() == txt), None)
  526. if db_hit and demo_mode:
  527. results = [make_result_from_db(db_hit)]
  528. elif demo_mode:
  529. results = demo_annotate_text(txt)
  530. else:
  531. with st.spinner("Сөйлемдер талданып жатыр…"):
  532. try:
  533. results = analyze_text(txt)
  534. except Exception as e:
  535. results = []
  536. st.error(f"Pipeline қатесі: {e}")
  537. if not results:
  538. st.warning("⚠️ Себеп-салдарлы сөйлем табылмады.")
  539. st.session_state.results = results
  540. if not st.session_state.history or st.session_state.history[-1][0] != txt:
  541. st.session_state.history.append((txt, results))
  542. results = st.session_state.results
  543. if not results:
  544. st.markdown("""
  545. <div style="text-align:center;padding:72px 0;color:#6B7590;">
  546. <div style="font-size:48px;margin-bottom:14px">⚡</div>
  547. <div style="font-size:15px;font-weight:600;">Мәтін енгізіп, Талдау батырмасын басыңыз</div>
  548. <div style="font-size:12px;margin-top:8px;">Demo mode-та да маркер бойынша аннотация жасалады</div>
  549. </div>""", unsafe_allow_html=True)
  550. else:
  551. if len(results) > 1:
  552. st.info(f"🔍 {len(results)} сөйлем талданды.")
  553. full_text = st.session_state.input_text.strip()
  554. if full_text and results:
  555. st.markdown('<div class="sec">Full text annotation</div>', unsafe_allow_html=True)
  556. n = len(full_text)
  557. prio = [None] * n
  558. def mark_in_full(substr, css, lbl, p):
  559. if not substr:
  560. return
  561. tl = full_text.lower()
  562. sl = substr.lower().strip()
  563. idx = 0
  564. while True:
  565. pos = tl.find(sl, idx)
  566. if pos == -1:
  567. break
  568. for i in range(pos, pos + len(sl)):
  569. if prio[i] is None or prio[i][0] < p:
  570. prio[i] = (p, css, lbl)
  571. idx = pos + 1
  572. for r in results:
  573. mark_in_full(r.get("cause"), "sp-cause", "CAUSE", 2)
  574. mark_in_full(r.get("effect"), "sp-effect", "EFFECT", 1)
  575. for m in (r.get("markers") or []):
  576. mark_in_full(m, "sp-marker", "MRK", 3)
  577. html = ""
  578. i = 0
  579. while i < n:
  580. cell = prio[i]
  581. if cell is None:
  582. j = i
  583. while j < n and prio[j] is None:
  584. j += 1
  585. html += full_text[i:j].replace("&","&amp;").replace("<","&lt;").replace(">","&gt;")
  586. i = j
  587. else:
  588. _, css, lbl = cell
  589. j = i
  590. while j < n and prio[j] is not None and prio[j][1] == css:
  591. j += 1
  592. chunk = full_text[i:j].replace("&","&amp;").replace("<","&lt;").replace(">","&gt;")
  593. html += f'<span class="{css}">{chunk}<span class="sp-lbl">{lbl}</span></span>'
  594. i = j
  595. html = html.replace("\n", "<br>")
  596. st.markdown(f'<div class="anno" style="line-height:2.8;">{html}</div>', unsafe_allow_html=True)
  597. st.markdown("<div class='divl'></div>", unsafe_allow_html=True)
  598. st.markdown('<div class="sec">Per-sentence breakdown</div>', unsafe_allow_html=True)
  599. for idx, r in enumerate(results):
  600. with st.expander(
  601. f"{'✅' if r.get('_from_db') else '🔬'} Sentence {idx+1} — {r['text'][:60]}{'…' if len(r['text'])>60 else ''}",
  602. expanded=(idx == 0),
  603. ):
  604. if r.get("_demo_blank"):
  605. st.warning("⚠️ Маркер табылмады немесе demo mode бұл сөйлемді бөле алмады.")
  606. plain = r["text"].replace("&","&amp;").replace("<","&lt;").replace(">","&gt;")
  607. st.markdown(f'<div class="anno" style="color:var(--muted);">{plain}</div>', unsafe_allow_html=True)
  608. else:
  609. render_result_card(r, idx)
  610. # ── Batch section ─────────────────────────────────────────────────
  611. if uploaded:
  612. st.markdown("---")
  613. st.markdown("### 📊 Batch results")
  614. content = uploaded.read().decode("utf-8")
  615. lines = [l.strip() for l in content.splitlines() if l.strip()]
  616. st.info(f"**{len(lines)}** сөйлем жүктелді.")
  617. batch_results = []
  618. bar = st.progress(0, "Талданып жатыр…")
  619. for i, line in enumerate(lines):
  620. db_hit = next((e for e in DB_EXAMPLES if e["text"].strip() == line), None)
  621. if db_hit:
  622. batch_results.append(make_result_from_db(db_hit))
  623. elif demo_mode:
  624. batch_results.extend(demo_annotate_text(line))
  625. else:
  626. try:
  627. batch_results.extend(analyze_text(line))
  628. except Exception as e:
  629. batch_results.append({
  630. "text": line, "cause": None, "effect": None,
  631. "markers": [], "tv_form": "ERROR", "tv_confidence": None,
  632. "semantic_type": "ERROR", "semantic_confidence": None,
  633. "semantic_all": {},
  634. "model_group": "ERROR", "model_group_confidence": None,
  635. "timestamp": datetime.now().strftime("%H:%M:%S"), "error": str(e),
  636. })
  637. bar.progress((i + 1) / len(lines), f"Сөйлем {i+1} / {len(lines)}")
  638. bar.empty()
  639. df_b = pd.DataFrame([
  640. {"text": r["text"][:60] + ("…" if len(r["text"]) > 60 else ""),
  641. **{row["Field"]: row["Value"] for row in to_table_rows(r)}}
  642. for r in batch_results
  643. ])
  644. if not df_b.empty and "model_group" in df_b.columns:
  645. mc = df_b["model_group"].value_counts()
  646. cols = st.columns(4)
  647. cols[0].metric("Total", len(df_b))
  648. cols[1].metric("SYNTHETIC", mc.get("SYNTHETIC", 0))
  649. cols[2].metric("ANALYTIC", mc.get("ANALYTIC", 0))
  650. cols[3].metric("ANALYTICO-SYNTHETIC", mc.get("ANALYTICO_SYNTHETIC", 0))
  651. st.dataframe(df_b, width="stretch", height=360)
  652. b1, b2 = st.columns(2)
  653. with b1:
  654. st.download_button("⬇ Batch CSV",
  655. df_b.to_csv(index=False, encoding="utf-8-sig"),
  656. "batch.csv", "text/csv", use_container_width=True)
  657. with b2:
  658. st.download_button("⬇ Batch JSON",
  659. json.dumps([clean_json(r) for r in batch_results], ensure_ascii=False, indent=2),
  660. "batch.json", "application/json", use_container_width=True)

streamlit.py at commit 52856c4, no license · at the source

Overview

Authors: Roman Taberkhan1, Nurbolat Tasbolatuly2,3, Madina Sambetbayeva1,2,3, Saule Tazhibayeva1, Nurmira Zhumay1, Bayangali Abdygalym1,2,3, Mira Kaldarova2,3
ORCID iDs: Nurmira Zhumay
  1. L.N. Gumilyov Eurasian National University, Astana, Kazakhstan
  2. International Science Complex Astana, Astana, Kazakhstan
  3. School of Information Technology and Engineering, Astana International University, Astana, Kazakhstan
Journal: Frontiers in artificial intelligence, volume 9, article 1848216
Dates: received 5 April 2026; accepted 8 July 2026; published online 23 July 2026
Type: Research article · Language: English
License: CC BY
Identifiers: DOI 10.3389/frai.2026.1848216 · PMID 42564329 · PMCID PMC13443141 · OpenAlex W7170134702
Open access: gold, a free copy (OpenAlex)
Status: code verified
Methods: Statistics, Machine learning
Keywords: causal relation extraction, information extraction, Kazakh language, KazBERT, low-resource language, NLP, transformer models
Topic: Topic Modeling (Artificial Intelligence, Computer Science), according to OpenAlex
Citations: not cited yet (Europe PMC); 25 references in the paper

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/I-MARKER); segmentation of cause-effect clauses (Token Classification, B/I-CAUSE · B/I-EFFECT); classification of Tv forms of markers (Sequence Classification, 16 classes); determination of the type of the marker’s syntactic construction—Model Group (Sequence Classification: SYNTHETIC/ANALYTIC/ANALYTICO-SYNTHETIC). The training was conducted using an original annotated corpus consisting of 3,223 sentences in the Kazakh language. The architecture is supplemented by a deterministic positional inversion algorithm for explanatory markers (sebebi, öitkenı, sondyqtan, etc.), which automatically restores the correct CAUSE-EFFECT argument order. Experiments have demonstrated that KazBERT outperforms the baseline models XLM-RoBERTa and mBERT: macro-F1 scores were 0.901 (tags), 0.865 (clauses), 0.884 (Tv-form), and 0.927 (construction type). The scientific novelty lies in the first publicly released four-level annotated corpus of Kazakh causal constructions, the operationalization of the established Turkological synthetic/analytic distinction—extended with a corpus-attested ANALYTICO-SYNTHETIC class—as a four-module annotation target, and a deterministic positional-inversion post-processor that corrects systematic argument-order errors for analytic markers.

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

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: 52856c492c72d5c998a6f614e3b45478a142dbec, 5 April 2026
Languages: Python (2)
Size: 10 files, 2 scripts
Software Heritage: not archived
Found in: “Data availability statement”
Holds: README
Not found: license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (1 file), pandas (1 file), Hugging Face Transformers (1 file)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
3 files

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/repositories and accession number(s) can be found below: The dataset, source code and trained models are available at: https://github.com/ParserRn/KazCausal.

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://doi.org/10.3389/frai.2026.1848216

BibTeX

@article{taberkhan2026four,
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/frai.2026.1848216},
url = {https://doi.org/10.3389/frai.2026.1848216},
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/07/23
VL - 9
SP - 1848216
SN - 2624-8212
PB - Frontiers Media SA
DO - 10.3389/frai.2026.1848216
UR - https://doi.org/10.3389/frai.2026.1848216
LA - en
ER -

CSL-JSON

{
"id": "10.3389/frai.2026.1848216",
"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": "Front Artif Intell",
"volume": "9",
"page": "1848216",
"DOI": "10.3389/frai.2026.1848216",
"PMID": "42564329",
"PMCID": "PMC13443141",
"ISSN": "2624-8212",
"publisher": "Frontiers Media SA",
"URL": "https://doi.org/10.3389/frai.2026.1848216",
"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.isci.2026.116135 [code]
Predicting ICU in-hospital mortality from text-encoded structured EHR data using adaptive transformer layer fusion.
Journal: iScience
In common: Hugging Face Transformers, pandas, NumPy, 1 reference
[2] 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. Cognition
In common: Hugging Face Transformers, pandas, NumPy, 1 reference
[3] doi:10.1038/s42003-026-10957-8 [code]
Brain defence by the extracellular matrix protein Cochlin.
Journal: Communications biology
In common: Hugging Face Transformers, pandas, NumPy
[4] doi:10.7554/elife.101204 [code]
Larger language models better align with neural representations of natural language.
Journal: eLife
In common: Hugging Face Transformers, pandas, NumPy
[5] doi:10.1371/journal.pone.0355826 [code]
Patent license prediction using deep survival analysis: A comparative study.
Journal: PloS one
In common: Hugging Face Transformers, pandas, NumPy
[6] doi:10.1038/s43856-026-01817-x [code]
Visual prompt engineering for multimodal and irregularly sampled medical data.
Journal: Communications medicine
In common: Hugging Face Transformers, pandas, NumPy
[7] doi:10.1038/s41467-026-76837-1 [code]
Drug screen and machine learning predict neuroprotective agents in a preclinical human model of childhood dementia.
Journal: Nature communications
In common: Hugging Face Transformers, pandas, NumPy
[8] doi:10.1016/j.isci.2026.117180 [code]
Developmental changes in similarity between neural representations of mental arithmetic and artificial neural networks.
Journal: iScience
In common: Hugging Face Transformers, pandas, NumPy
[9] doi:10.1016/j.ncrna.2026.06.004 [code]
LncPNdeep: A long non-coding RNA classifier based on large language model with peptide and nucleotide embedding.
Journal: Non-coding RNA research
In common: Hugging Face Transformers, pandas, NumPy
[10] doi:10.1038/s41467-026-76098-y [code]
A single computational objective can produce specialization of streams in visual cortex.
Journal: Nature communications
In common: Hugging Face Transformers, pandas, NumPy

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.

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: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.