Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 16 additions & 18 deletions apps/worker/app/services/document_parser/formats/markdown/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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='<')
Expand All @@ -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()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 and "-->" in line)
Expand Down Expand Up @@ -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


Expand Down
79 changes: 41 additions & 38 deletions apps/worker/app/services/document_parser/structure/layout_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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])
Expand Down Expand Up @@ -580,16 +584,15 @@ 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,
prompt_limt,
toc_hierarchies,
model_name=model_name,
output_dir=output_dir,
reuse_rule_levels_on_fallback=doc_type == "md",
)
logger.info("✅ LLM hierarchy parsing completed")

Expand Down Expand Up @@ -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(
Expand All @@ -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.

Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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()
Loading
Loading