Skip to content

AI turns documents or topics into real, native PowerPoint decks—with native shapes, transitions and animations, data-backed charts and tables on demand, audio narration from speaker notes, and support for your own .pptx templates. · by Hugo He

fix(pdf_to_md): stop rewriting table cells from one sample paper's layout

hugohe33aa2ec62bfd2
diff --git a/skills/ppt-master/scripts/source_to_md/pdf_to_md.py b/skills/ppt-master/scripts/source_to_md/pdf_to_md.py
index da5cccb9..f7559d2b 100644
--- a/skills/ppt-master/scripts/source_to_md/pdf_to_md.py
+++ b/skills/ppt-master/scripts/source_to_md/pdf_to_md.py
@@ -913,136 +913,10 @@ def _merge_single_cell_continuations(rows: list[list[str]]) -> list[list[str]]:
return merged
-def _looks_like_model_row(row: list[str]) -> bool:
- """Return whether a row contains model-number table headings."""
- values = [cell for cell in row[1:] if cell]
- return len(values) >= 2 and all(MODEL_COLUMN_RE.match(cell) for cell in values)
-
-
-def _looks_like_outcome_row(row: list[str]) -> bool:
- """Return whether a row contains regression outcome labels."""
- values = [cell for cell in row[1:] if cell]
- if len(values) < 2:
- return False
- short_values = [cell for cell in values if len(cell) <= 12 and not NUMBER_RE.search(cell)]
- return len(short_values) == len(values)
-
-
-def _flatten_regression_header(rows: list[list[str]]) -> list[list[str]]:
- """Flatten multi-line regression headings into one Markdown header row."""
- if len(rows) < 3:
- return rows
-
- if (
- len(rows) >= 2
- and rows[0][0]
- and not any(rows[0][1:])
- and _looks_like_model_row(rows[1])
- ):
- outcome = rows[0][0]
- header = ["变量"]
- header.extend(
- f"{model} {outcome}".strip()
- for model in rows[1][1:]
- )
- return [header] + rows[2:]
-
- header_offset = 0
- if not _looks_like_model_row(rows[0]) and _looks_like_model_row(rows[1]):
- header_offset = 1
-
- if not _looks_like_model_row(rows[header_offset]):
- return rows
- if len(rows) <= header_offset + 1 or not _looks_like_outcome_row(rows[header_offset + 1]):
- return rows
-
- model_row = rows[header_offset]
- outcome_row = rows[header_offset + 1]
- header = ["变量"]
- for idx, model in enumerate(model_row[1:]):
- pieces = []
- if model:
- pieces.append(model)
- if idx + 1 < len(outcome_row) and outcome_row[idx + 1]:
- pieces.append(outcome_row[idx + 1])
- header.append(" ".join(pieces).strip())
- return [header] + rows[header_offset + 2:]
-
-
-def _fix_paired_sample_t_table(rows: list[list[str]]) -> list[list[str]]:
- """Collapse multi-row paired-sample T-test headings into readable columns."""
- if not rows or not any("成对差分" in cell for cell in rows[0]):
- return rows
- body = [row for row in rows if row and row[0].startswith("对")]
- if len(body) < 1:
- return rows
- header = [
- "配对",
- "变量",
- "均值",
- "标准差",
- "均值的标准误",
- "差分95%置信区间下限",
- "差分95%置信区间上限",
- "t",
- "Df",
- "Sig.(双侧)",
- ]
- fixed_rows = [header]
- for row in body:
- fixed_rows.append(row[:len(header)] + [""] * max(0, len(header) - len(row)))
- return fixed_rows
-
-
-def _fix_variable_definition_table(rows: list[list[str]]) -> list[list[str]]:
- """Repeat variable-category labels for common variable definition tables."""
- if not rows or rows[0] != ["变量类型", "变量名称", "符号", "变量说明"]:
- return rows
-
- fixed = [rows[0]]
- for row in rows[1:]:
- if not any(row):
- continue
- name = row[1] if len(row) > 1 else ""
- symbol = row[2] if len(row) > 2 else ""
- description = row[3] if len(row) > 3 else ""
- if not name or not symbol:
- continue
-
- if symbol in {"R&D", "Fixed", "Hc"}:
- category = "被解释变量"
- elif symbol == "Vat":
- category = "解释变量"
- else:
- category = "控制变量"
- fixed.append([category, name, symbol, description])
- return fixed
-
-
-def _fix_correlation_triangle(rows: list[list[str]]) -> list[list[str]]:
- """Restore the missing last self-correlation column in triangular tables."""
- if len(rows) < 4 or not rows[0] or rows[0][0] != "变量":
- return rows
- body_names = [row[0] for row in rows[1:] if row and row[0]]
- header_names = rows[0][1:]
- if len(body_names) != len(header_names) + 1:
- return rows
- missing_name = body_names[-1]
- fixed = [rows[0] + [missing_name]]
- for row in rows[1:-1]:
- fixed.append(row + [""])
- fixed.append(rows[-1] + ["1"])
- return fixed
-
-
def _postprocess_table_rows(rows: list[list[str]]) -> list[list[str]]:
"""Apply Markdown-oriented cleanup to extracted table rows."""
rows = _merge_label_underscore_rows(rows)
rows = _merge_single_cell_continuations(rows)
- rows = _fix_variable_definition_table(rows)
- rows = _fix_paired_sample_t_table(rows)
- rows = _flatten_regression_header(rows)
- rows = _fix_correlation_triangle(rows)
return rows
diff --git a/skills/ppt-master/scripts/tests/test_pdf_content_preservation.py b/skills/ppt-master/scripts/tests/test_pdf_content_preservation.py
new file mode 100644
index 00000000..29b28ad7
--- /dev/null
+++ b/skills/ppt-master/scripts/tests/test_pdf_content_preservation.py
@@ -0,0 +1,124 @@
+#!/usr/bin/env python3
+"""Regression tests: PDF table extraction keeps extracted cells as extracted.
+
+All fixtures are PDFs constructed in memory or a temporary directory. Exercise
+the public table finder without document-specific source files.
+"""
+
+from __future__ import annotations
+
+import sys
+import unittest
+from pathlib import Path
+
+SCRIPTS_DIR = Path(__file__).resolve().parents[1]
+BACKEND_DIR = SCRIPTS_DIR / "source_to_md"
+if str(BACKEND_DIR) not in sys.path:
+ sys.path.insert(0, str(BACKEND_DIR))
+
+import fitz # noqa: E402
+import pdf_to_md # noqa: E402
+
+
+class TableContentPreservationTests(unittest.TestCase):
+ def _extract_table(self, rows: list[list[str]]) -> str:
+ column_width = 140
+ row_height = 40
+ width = len(rows[0]) * column_width
+ height = len(rows) * row_height
+ with fitz.open() as doc:
+ page = doc.new_page(width=width + 80, height=height + 300)
+ for column in range(len(rows[0]) + 1):
+ x = 40 + column * column_width
+ page.draw_line((x, 150), (x, 150 + height))
+ for row in range(len(rows) + 1):
+ y = 150 + row * row_height
+ page.draw_line((40, y), (40 + width, y))
+ for row_index, row in enumerate(rows):
+ for column_index, value in enumerate(row):
+ if value:
+ page.insert_text(
+ (45 + column_index * column_width, 165 + row_index * row_height),
+ value,
+ fontname="china-s",
+ fontsize=10,
+ )
+ tables, _ = pdf_to_md.find_page_tables(page)
+ self.assertEqual(len(tables), 1)
+ return tables[0]["content"]
+
+ def _assert_rows_preserved(self, rows: list[list[str]]) -> None:
+ lines = ["|" + "|".join(row) + "|" for row in rows]
+ lines.insert(1, "|" + "|".join(["---"] * len(rows[0])) + "|")
+ self.assertEqual(self._extract_table(rows), "\n".join(lines))
+
+ def test_variable_categories_are_not_inferred_from_symbols(self) -> None:
+ self._assert_rows_preserved([
+ ["变量类型", "变量名称", "符号", "变量说明"],
+ ["原始分类甲", "研发", "R&D", "研发说明"],
+ ["原始分类乙", "固定资本", "Fixed", "资本说明"],
+ ["原始分类丙", "人力", "Hc", "人力说明"],
+ ["原始分类丁", "税额", "Vat", "税额说明"],
+ ["原始分类戊", "未知量", "Other", "未知说明"],
+ ["", "无分类量", "Unknown", "分类留空"],
+ ])
+
+ def test_variable_rows_with_missing_fields_are_kept(self) -> None:
+ self._assert_rows_preserved([
+ ["变量类型", "变量名称", "符号", "变量说明"],
+ ["有符号", "", "X", "没有名称"],
+ ["无符号", "保留名称", "", "没有符号"],
+ ["仅分类", "", "", ""],
+ ])
+
+ def test_paired_table_keeps_custom_headers_rows_and_extra_column(self) -> None:
+ self._assert_rows_preserved([
+ ["样本", "成对差分", "中位数", "离散度", "误差", "范围", "概率", "统计量", "自由度", "检验", "附加列"],
+ ["次级头", "自定义名称", "甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "次级备注"],
+ ["对一", "A", "2", "3", "4", "5", "6", "7", "8", "9", "额外数据"],
+ ["合计", "B", "12", "13", "14", "15", "16", "17", "18", "19", "合计备注"],
+ ])
+
+ def test_regression_headers_and_first_column_text_are_kept(self) -> None:
+ cases = {
+ "single_outcome": [
+ ["原始结果名称", "", ""],
+ ["原始模型列", "(1)", "(2)"],
+ ["x", "0.2", "0.3"],
+ ],
+ "model_first": [
+ ["原始模型列", "(1)", "(2)"],
+ ["原始结果列", "收入", "成本"],
+ ["x", "0.2", "0.3"],
+ ],
+ "preface_before_model": [
+ ["分组说明", "甲组", "乙组"],
+ ["原始模型列", "(1)", "(2)"],
+ ["原始结果列", "收入", "成本"],
+ ["x", "0.2", "0.3"],
+ ],
+ }
+ for name, rows in cases.items():
+ with self.subTest(name=name):
+ self._assert_rows_preserved(rows)
+
+ def test_correlation_table_does_not_invent_a_column_or_diagonal(self) -> None:
+ self._assert_rows_preserved([
+ ["变量", "A", "B"],
+ ["A", "0.95", ""],
+ ["B", "0.25", "0.96"],
+ ["C", "0.35", "0.45"],
+ ])
+
+ def test_empty_rows_and_columns_are_removed_without_losing_text(self) -> None:
+ rows = [
+ ["Label", "", "Value"],
+ ["", "", ""],
+ ["First", "", "alpha\nbeta"],
+ ["Pipe", "", "left|right"],
+ ]
+ self.assertEqual(
+ self._extract_table(rows),
+ "|Label|Value|\n|---|---|\n|First|alpha<br>beta|\n|Pipe|left\\|right|",
+ )
+