diff --git a/apps/worker/app/services/document_parser/formats/markdown/parser.py b/apps/worker/app/services/document_parser/formats/markdown/parser.py index 5c9f618c5..2791511d7 100755 --- a/apps/worker/app/services/document_parser/formats/markdown/parser.py +++ b/apps/worker/app/services/document_parser/formats/markdown/parser.py @@ -4,6 +4,8 @@ import re import shutil +import pandas as pd + from app.services.document_parser.support.identifiers import gen_str_codes, get_str_time from app.services.document_parser.formats.markdown.deferred_summary import ( MarkdownDeferredSummaryInput, @@ -78,7 +80,9 @@ def is_skip(line): return f"{prev_text} {next_text}".strip() -def heading_md_relocate(md_lines, heading_preds): +def heading_md_relocate( + md_lines: list[str], heading_preds: pd.DataFrame +) -> list[str]: """Relocate markdown headings based on predicted levels (sxjg simplified logic) When ``_apply_merge_signals`` has merged continuation rows (level='<') @@ -87,26 +91,20 @@ def heading_md_relocate(md_lines, heading_preds): For positive-level headings, we use the DataFrame's ``heading`` to ensure the merged text is emitted. """ - def remove_hash(txt): - return re.sub(r"^\s*(#+)\s*", "", txt) + predictions_by_line: dict[int, tuple[int, object]] = {} + for line_id, level, heading in heading_preds[["id", "level", "heading"]].itertuples( + index=False, name=None + ): + predictions_by_line.setdefault(line_id, (level, heading)) for lid, line_txt in enumerate(md_lines): - pred_level_df = heading_preds[heading_preds["id"] == lid] - - if pred_level_df.empty: # if the line does not enter predicting - line_txt = remove_hash(line_txt) + prediction: tuple[int, object] | None = predictions_by_line.get(lid) + if prediction is None or prediction[0] < 0: + line_txt = re.sub(r"^\s*(#+)\s*", "", line_txt) else: - pred_level = pred_level_df["level"].iloc[0] - if pred_level < 0: - line_txt = remove_hash(line_txt) - else: - # Use the DataFrame heading text which may have been updated - # by _apply_merge_signals (continuation rows appended). - heading_text = str(pred_level_df["heading"].iloc[0]).strip() - if not heading_text: - # Fallback: strip original line's '#' prefix - heading_text = line_txt.lstrip("#").lstrip() - line_txt = f"{'#' * int(pred_level)} {heading_text}" + level, heading = prediction + heading_text: str = str(heading).strip() or line_txt.lstrip("#").lstrip() + line_txt = f"{'#' * int(level)} {heading_text}" # update lines md_lines[lid] = line_txt.strip() diff --git a/apps/worker/app/services/document_parser/structure/heading_candidates.py b/apps/worker/app/services/document_parser/structure/heading_candidates.py index 8e1cb0592..3d0bff91b 100644 --- a/apps/worker/app/services/document_parser/structure/heading_candidates.py +++ b/apps/worker/app/services/document_parser/structure/heading_candidates.py @@ -252,6 +252,12 @@ def postprocess_headings(df: pd.DataFrame, task: str, max_depth: int = -1) -> pd return df +def estimate_heading_rule_levels(predictions: pd.DataFrame) -> pd.DataFrame: + predictions = _judge_negative_headings(predictions) + predictions["level"] = predictions["level"].replace(-2, 1) + return predictions + + def _is_non_heading_markdown_line(line: str) -> bool: return ( ("" in line) @@ -330,19 +336,27 @@ def _is_bold_docx_paragraph(paragraph: Any): def _judge_negative_headings(df: pd.DataFrame) -> pd.DataFrame: - for index, row in df.iterrows(): - neg_code = remove_by_conditions(row["heading"], include_punc=True) - if any(value > 0 for value in neg_code): - current_code = str(df.loc[index, "reason"]) + demote: list[bool] = [] + reasons: list[str] = [] + for heading, reason in df[["heading", "reason"]].itertuples(index=False, name=None): + neg_code: list[int] = remove_by_conditions(heading, include_punc=True) + should_demote: bool = any(neg_code) + demote.append(should_demote) + if not should_demote: + continue - neg_match = re.search(r"(.*NEG\s*)\[[^\]]*\](.*)", current_code) - if neg_match: - updated_code = f"{neg_match.group(1)}{neg_code}{neg_match.group(2)}" - else: - updated_code = f"{current_code} NEG {neg_code}" + current_code: str = str(reason) + neg_match: re.Match[str] | None = re.search(r"(.*NEG\s*)\[[^\]]*\](.*)", current_code) + updated_code: str = ( + f"{neg_match.group(1)}{neg_code}{neg_match.group(2)}" + if neg_match + else f"{current_code} NEG {neg_code}" + ) + reasons.append(updated_code) - df.loc[index, "level"] = -1 - df.loc[index, "reason"] = updated_code + if reasons: + df.loc[demote, "level"] = -1 + df.loc[demote, "reason"] = reasons return df diff --git a/apps/worker/app/services/document_parser/structure/layout_parser.py b/apps/worker/app/services/document_parser/structure/layout_parser.py index 209ae1eaa..dc978e2fc 100755 --- a/apps/worker/app/services/document_parser/structure/layout_parser.py +++ b/apps/worker/app/services/document_parser/structure/layout_parser.py @@ -4,8 +4,8 @@ import gevent import pandas as pd from app.services.document_parser.structure.heading_candidates import ( + estimate_heading_rule_levels, filter_document_headings, - filter_markdown_headings, postprocess_headings, ) from app.services.document_parser.structure.heading_llm_executor import ( @@ -20,6 +20,9 @@ from app.services.document_parser.structure.heading_tree import ( tree_to_dataframe as heading_tree_to_dataframe, ) +from app.services.document_parser.structure.markdown_heading_preparation import ( + prepare_markdown_headings, +) from app.services.document_parser.support.stage_profiler import stage_timer from app.services.document_parser.tables.table_text_parser import df2md from gevent.pool import Pool as GeventPool @@ -341,6 +344,9 @@ def _apply_merge_signals(df: pd.DataFrame) -> pd.DataFrame: Rows that carry ``"<"`` but have no preceding valid heading (e.g. the very first row) are simply demoted to -1 without merging. """ + if not df["level"].eq("<").any(): + return df + merge_count = 0 last_valid_idx: int | None = None # positional index of last positive-level row @@ -447,44 +453,44 @@ def pred_titles( f"Start to predict title hierarchy: doc_type={doc_type}, smart_parse={smart_parse}, candidate titles={len(infos)}" ) - if doc_type == "md": - raw_preds = filter_markdown_headings(infos) - elif doc_type == "docx": - raw_preds = filter_document_headings(infos, enable_regex=enable_regx) - else: - raw_preds = pd.DataFrame(columns=["id", "heading", "level", "reason"]) - # ── Exclude pre-TOC lines from heading prediction ── # When TOC is detected, lines/blocks before the first TOC area are typically # cover/metadata (company name, version, classification marks), not real # headings. Remove them before LLM judging to avoid misjudgment, then # splice back with level=-1 after all processing is done. - pre_toc_rows = None - first_toc_start = None + pre_toc_rows: pd.DataFrame | None = None if doc_type == "md": first_toc_start = _resolve_first_toc_boundary(toc_hierarchies=toc_hierarchies) + with stage_timer("heading.prepare_markdown_candidates", line_count=len(infos)): + raw_preds, pre_toc_rows = prepare_markdown_headings(infos, first_toc_start) + if pre_toc_rows is not None: + logger.info( + f"📌 Excluded {len(pre_toc_rows)} pre-TOC lines " + f"(id < {first_toc_start}) from heading prediction" + ) elif doc_type == "docx": + raw_preds = filter_document_headings(infos, enable_regex=enable_regx) first_toc_start = _resolve_first_toc_boundary( toc_hierarchies=toc_hierarchies, first_toc_ele_num=first_toc_ele_num, ) - - if first_toc_start is not None and first_toc_start > 0: - pre_toc_mask = raw_preds["id"] < first_toc_start - if pre_toc_mask.any(): - pre_toc_rows = raw_preds[pre_toc_mask].copy() - pre_toc_rows["level"] = -1 - raw_preds = raw_preds[~pre_toc_mask].reset_index(drop=True) - if doc_type == "docx": + if first_toc_start is not None and first_toc_start > 0: + pre_toc_mask: pd.Series = raw_preds["id"] < first_toc_start + if pre_toc_mask.any(): + pre_toc_rows = raw_preds[pre_toc_mask].copy() + pre_toc_rows["level"] = -1 + raw_preds = raw_preds[~pre_toc_mask].reset_index(drop=True) logger.info( f"📌 Excluded {len(pre_toc_rows)} pre-TOC blocks " f"(id < {first_toc_start}) from heading prediction" ) - else: - logger.info( - f"📌 Excluded {len(pre_toc_rows)} pre-TOC lines " - f"(id < {first_toc_start}) from heading prediction" - ) + else: + raw_preds = pd.DataFrame(columns=["id", "heading", "level", "reason"]) + + def apply_heading_rules(predictions: pd.DataFrame) -> pd.DataFrame: + if doc_type == "md": + return predictions + return est_hierarchies_naive(predictions) # 2. Zone-based prediction for native Markdown/DOCX coordinates only. if _supports_multi_toc_zones( @@ -523,16 +529,14 @@ def _process_single_zone(zone_idx, zone_start, zone_end, zone_toc): ) # Independent naive + LLM prediction for this zone - zone_heading = est_hierarchies_naive( - zone_preds, smart_parse, output_dir=output_dir - ) zone_heading = est_hierarchies_llm( - zone_heading, + apply_heading_rules(zone_preds), prompt_limt, toc_hierarchies=[zone_toc], # Single TOC for this zone model_name=model_name, output_dir=output_dir, csv_suffix=f"_zone_{zone_idx}", + reuse_rule_levels_on_fallback=doc_type == "md", ) valid_count = ( len(zone_heading[zone_heading["level"] > 0]) @@ -580,9 +584,7 @@ def _process_single_zone(zone_idx, zone_start, zone_end, zone_toc): logger.info("✅ Zone-based LLM hierarchy parsing completed") else: # Single-zone: current behavior - heading_preds = est_hierarchies_naive( - raw_preds, smart_parse, output_dir=output_dir - ) + heading_preds = apply_heading_rules(raw_preds) if smart_parse: heading_preds = est_hierarchies_llm( heading_preds, @@ -590,6 +592,7 @@ def _process_single_zone(zone_idx, zone_start, zone_end, zone_toc): toc_hierarchies, model_name=model_name, output_dir=output_dir, + reuse_rule_levels_on_fallback=doc_type == "md", ) logger.info("✅ LLM hierarchy parsing completed") @@ -660,13 +663,7 @@ def est_hierarchies_naive(raw_preds, proceed_smart=True, output_dir=None): compatibility but have no effect. """ logger.debug("🚀 non-llm parsing => judge_negs filtering") - heading_preds = postprocess_headings(raw_preds, task="judge_negs") - - # legitimate heading candidates; default them to top-level. - heading_preds["level"] = heading_preds["level"].map( - lambda x: 1 if x == -2 else x - ) - return heading_preds + return estimate_heading_rule_levels(raw_preds) def est_hierarchies_llm( @@ -678,6 +675,7 @@ def est_hierarchies_llm( model_name=None, output_dir=None, csv_suffix="", + reuse_rule_levels_on_fallback: bool = False, ): """LLM-based hierarchy detection — all chunks evaluated independently. @@ -704,11 +702,16 @@ def est_hierarchies_llm( csv_suffix: suffix for intermediate CSV filenames """ model_name = _resolve_hierarchy_model_name(model_name) + fallback_hierarchy = ( + (lambda predictions: predictions) + if reuse_rule_levels_on_fallback + else est_hierarchies_naive + ) return execute_llm_heading_hierarchy( raw_preds=raw_preds, prompt_limt=prompt_limt, hierarchy_judge=hiearchy_llm, - fallback_hierarchy=est_hierarchies_naive, + fallback_hierarchy=fallback_hierarchy, save_intermediate_csv=save_intermediate_csv, toc_hierarchies=toc_hierarchies, max_len=max_len, diff --git a/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py b/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py new file mode 100644 index 000000000..b96bbb15f --- /dev/null +++ b/apps/worker/app/services/document_parser/structure/markdown_heading_preparation.py @@ -0,0 +1,98 @@ +"""Run Markdown heading rules without blocking the Worker greenlets.""" + +from __future__ import annotations + +import os +import pickle +import sys +from contextlib import suppress +from typing import TYPE_CHECKING, cast + +from gevent import subprocess +from gevent.lock import BoundedSemaphore + +from shared.core.config import settings +from shared.core.exceptions.domain_exceptions import ( + TimeoutException, + WorkerHandlingException, +) + +if TYPE_CHECKING: + import pandas as pd + + +_HEADING_PROCESS_SLOT: BoundedSemaphore = BoundedSemaphore(1) + + +def prepare_markdown_headings( + lines: list[str], first_toc_start: int | None +) -> tuple[pd.DataFrame, pd.DataFrame | None]: + """Return rule-filtered candidates and the original rows before the TOC.""" + timeout_seconds: int = settings.TASK_TIME_LIMIT_SECONDS + environment: dict[str, str] = os.environ.copy() + # Local callers can register the Worker package through sys.path. + environment["PYTHONPATH"] = os.pathsep.join(sys.path) + with _HEADING_PROCESS_SLOT: + payload: bytes = pickle.dumps( + (lines, first_toc_start), protocol=pickle.HIGHEST_PROTOCOL + ) + with subprocess.Popen( + [sys.executable, "-m", __name__], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + env=environment, + ) as process: + try: + output, _ = process.communicate(payload, timeout=timeout_seconds) + except BaseException as error: + if process.poll() is None: + # The child can exit between poll() and kill(). + with suppress(ProcessLookupError): + process.kill() + # Let gevent's pipe readers finish before Popen closes the streams. + process.communicate() + if isinstance(error, subprocess.TimeoutExpired): + raise TimeoutException( + internal_message=f"Markdown heading preparation exceeded {timeout_seconds}s", + retry_after=settings.DOCUMENT_INGESTION_TASK_RETRY_COUNTDOWN, + ) from error + raise + if process.returncode != 0: + raise WorkerHandlingException( + internal_message=f"Markdown heading preparation exited with code {process.returncode}" + ) + result: tuple[pd.DataFrame, pd.DataFrame | None] = pickle.loads(output) + return result + + +def _run_child() -> None: + from app.core.runtime_limits import apply_native_thread_caps + + apply_native_thread_caps() + + from app.services.document_parser.structure.heading_candidates import ( + estimate_heading_rule_levels, + filter_markdown_headings, + ) + + lines, first_toc_start = pickle.load(sys.stdin.buffer) + predictions: pd.DataFrame = filter_markdown_headings(lines) + pre_toc_rows: pd.DataFrame | None = None + if first_toc_start is not None and first_toc_start > 0: + pre_toc_mask: pd.Series = predictions["id"] < first_toc_start + if pre_toc_mask.any(): + pre_toc_rows = cast("pd.DataFrame", predictions[pre_toc_mask].copy()) + pre_toc_rows["level"] = -1 + predictions = cast( + "pd.DataFrame", predictions[~pre_toc_mask].reset_index(drop=True) + ) + + result: tuple[pd.DataFrame, pd.DataFrame | None] = ( + estimate_heading_rule_levels(predictions), + pre_toc_rows, + ) + pickle.dump(result, sys.stdout.buffer, protocol=pickle.HIGHEST_PROTOCOL) + + +if __name__ == "__main__": + _run_child() diff --git a/apps/worker/tests/unit/test_markdown_heading_isolation.py b/apps/worker/tests/unit/test_markdown_heading_isolation.py new file mode 100644 index 000000000..44f1f398e --- /dev/null +++ b/apps/worker/tests/unit/test_markdown_heading_isolation.py @@ -0,0 +1,115 @@ +from __future__ import annotations + +import sys +from pathlib import Path +from types import SimpleNamespace + +import gevent +import pandas as pd +import pytest + +from app.services.document_parser.structure import layout_parser, markdown_heading_preparation +from app.services.document_parser.structure.heading_candidates import filter_markdown_headings +from app.services.document_parser.structure.heading_hierarchy import ( + HeadingHierarchyInput, + predict_heading_hierarchy, +) +from shared.core.exceptions.domain_exceptions import TimeoutException + + +def test_markdown_heading_prediction_yields_to_the_worker_loop( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + monkeypatch.chdir(tmp_path) + monkeypatch.delenv("PYTHONPATH", raising=False) + heartbeat: gevent.Greenlet = gevent.spawn(lambda: None) + try: + predictions: pd.DataFrame = predict_heading_hierarchy( + HeadingHierarchyInput(infos=["# Heading", "Body text"], doc_type="md") + ) + + assert heartbeat.ready() + assert predictions["level"].tolist() == [1, -1] + finally: + heartbeat.kill() + + +def test_markdown_heading_prediction_keeps_pre_toc_reasons() -> None: + lines: list[str] = ["# Cover.", "Front matter", "# Heading", "# A sentence."] + initial_predictions: pd.DataFrame = filter_markdown_headings(lines) + + predictions: pd.DataFrame = predict_heading_hierarchy( + HeadingHierarchyInput( + infos=lines, + doc_type="md", + toc_hierarchies=[{"toc_range": [2, 2]}], + ) + ) + + assert predictions["id"].tolist() == [0, 1, 2, 3] + assert predictions["level"].tolist() == [-1, -1, 1, -1] + assert ( + predictions["reason"].iloc[:2].tolist() + == initial_predictions["reason"].iloc[:2].tolist() + ) + assert predictions["reason"].iloc[3] != initial_predictions["reason"].iloc[3] + + +def test_markdown_heading_model_error_reuses_prepared_rules( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def fail_model(*args: object, **kwargs: object) -> list[dict[str, int]]: + raise RuntimeError("Model unavailable") + + def reject_repeated_rules(*args: object, **kwargs: object) -> pd.DataFrame: + pytest.fail("Markdown heading rules already ran in the subprocess") + + monkeypatch.setattr(layout_parser, "hiearchy_llm", fail_model) + monkeypatch.setattr(layout_parser, "est_hierarchies_naive", reject_repeated_rules) + + predictions: pd.DataFrame = predict_heading_hierarchy( + HeadingHierarchyInput( + infos=["# Heading", "# A sentence."], doc_type="md", smart_parse=True + ) + ) + + assert predictions["level"].tolist() == [1, -1] + + +def test_markdown_heading_relocation_uses_first_prediction_for_each_line() -> None: + from app.services.document_parser.formats.markdown.parser import heading_md_relocate + + lines: list[str] = ["# First", "# Keep the original text", "# Body", " "] + predictions: pd.DataFrame = pd.DataFrame( + [(0, 2, "First continued"), (0, 3, "Duplicate"), (1, 1, "")], + columns=["id", "level", "heading"], + ) + + assert heading_md_relocate(lines, predictions) == [ + "## First continued", + "# Keep the original text", + "Body", + ] + + +def test_markdown_heading_timeout_reaps_the_child(monkeypatch: pytest.MonkeyPatch) -> None: + subprocess = markdown_heading_preparation.subprocess + start_process = subprocess.Popen + children: list[subprocess.Popen] = [] + + def start_sleeping_child(command: list[str], **kwargs: object) -> subprocess.Popen: + process = start_process([sys.executable, "-c", "import time; time.sleep(60)"], **kwargs) + children.append(process) + return process + + monkeypatch.setattr(subprocess, "Popen", start_sleeping_child) + monkeypatch.setattr( + markdown_heading_preparation, + "settings", + SimpleNamespace(TASK_TIME_LIMIT_SECONDS=0.1, DOCUMENT_INGESTION_TASK_RETRY_COUNTDOWN=120), + ) + + with pytest.raises(TimeoutException): + markdown_heading_preparation.prepare_markdown_headings(["# Heading"], None) + + assert len(children) == 1 and children[0].poll() is not None