6. Gathering và dựng cây hierarchy theo version#

6.1 Thiết kế compilation path và phân cấp AST/Tree#

  • Multi-file Gathering (gather.py): quét các tệp .tex tìm \documentclass/\documentstyle. Khi có nhiều ứng viên root, thuật toán đối chiếu tiêu đề từ metadata M1 (hoặc dùng --root-overrides); bỏ qua các lệnh nằm sau comment % và đi theo \input/\include bắc cầu từ thư mục biên dịch, dừng tại \endinput hoặc \end{document} để loại file .tex thừa.

  • Cây phân cấp (hierarchy.py): nút gốc là document, tới chapter/section/subsection..., paragraph, list/item, và lá nhỏ nhất là sentence, block_formula, figure (gộp cả table thành figure). Bộ tách câu bảo vệ nội dung trong toán $...$, lệnh TeX, URL, số thập phân (3.14) và viết tắt (e.g., i.e., et al., Fig. 1). Mục References/Bibliography tách khỏi cây; Acknowledgements và Appendix (\section*, \appendix) được giữ lại.

6.2 Ví dụ thực thi gathering & hierarchy từ code thật#

Hide code cell source

from pathlib import Path
import json
import pandas as pd
import matplotlib.pyplot as plt
from IPython.display import display, Markdown
data = json.loads((Path.cwd().parent / 'report_summary.json').read_text(encoding='utf-8'))
scope, m1, m2, bench = data['scope'], data['m1'], data['m2'], data['m2_benchmark']
plt.rcParams.update({'figure.figsize': (9.2, 4.2), 'axes.spines.top': False, 'axes.spines.right': False, 'figure.dpi': 120})
print(f"Toàn nhóm (5 thành viên): {scope['papers']:,} paper / {scope['versions']:,} version | Cập nhật: {data['report_date']}")
Toàn nhóm (5 thành viên): 25,000 paper / 41,498 version | Cập nhật: 2026-11-22

Hide code cell source

import tempfile
from parser.gather import gather
from parser.hierarchy import parse_hierarchy
main_tex = r"""\documentclass{article}
\title{Demo Multi-file Paper}
\begin{document}
% \input{ignored_comment}
\input{sections/intro}
\section*{Acknowledgements}
We thank the team.
\appendix
\section{Appendix Proof}
Extra proof detail.
\section*{References}
\begin{thebibliography}{9}
\bibitem{k1} A. Author. Title. 2020.
\end{thebibliography}
\end{document}"""
intro_tex = r"""\section{Introduction}
First sentence with Fig. 1 and value 3.14.
\begin{itemize}\item First point.\item Second point.\end{itemize}
\begin{align}x + y = z\end{align}
\begin{table}[htpb]\centering\begin{tabular}{cc}\toprule A & B \\ \midrule 1 & 2 \\ \bottomrule\end{tabular}\end{table}
"""
with tempfile.TemporaryDirectory() as tmp:
    root = Path(tmp); (root / 'sections').mkdir()
    (root / 'main.tex').write_text(main_tex, encoding='utf-8')
    (root / 'sections/intro.tex').write_text(intro_tex, encoding='utf-8')
    (root / 'redundant.tex').write_text('Ignored standalone file.', encoding='utf-8')
    g = gather(root); tree = parse_hierarchy(g.text)
    print('Root:', g.root, '| Compilation path:', g.files, '| Diagnostics:', g.diagnostics + tree.diagnostics)
    display(pd.DataFrame([{'node_id': n.node_id, 'parent_id': n.parent_id, 'kind': n.kind, 'content': n.content[:90]} for n in tree.nodes]))
Root: main.tex | Compilation path: ['main.tex', 'sections/intro.tex'] | Diagnostics: []
node_id parent_id kind content
0 0 NaN document Demo Multi-file Paper
1 1 0.0 section Introduction
2 2 1.0 paragraph First sentence with Fig. 1 and value 3.14.
3 3 2.0 sentence First sentence with Fig. 1 and value 3.14.
4 4 1.0 list \begin{itemize}\item First point.\item Second ...
5 5 4.0 item First point.
6 6 5.0 paragraph First point.
7 7 6.0 sentence First point.
8 8 4.0 item Second point.
9 9 8.0 paragraph Second point.
10 10 9.0 sentence Second point.
11 11 1.0 block_formula x + y = z
12 12 1.0 figure \centering\begin{tabular}{cc}\toprule A & B \\...
13 13 0.0 section Acknowledgements
14 14 13.0 paragraph We thank the team.
15 15 14.0 sentence We thank the team.
16 16 0.0 section Appendix Proof
17 17 16.0 paragraph Extra proof detail.
18 18 17.0 sentence Extra proof detail.

6.3 Tác động nâng cấp parser qua Pilot (v1 -> v2) và phân bố 25.000 bài#

Trước khi chạy toàn bộ 25.000 bài, nhóm chạy Pilot phân tầng 250 bài (536 version) trên Colab CPU, phát hiện và vá 4 nhóm lỗi thực tế (tách nhánh \cite{{k1},{k2}}, deduplicate khóa trùng trong cùng version theo độ ưu tiên .bib > inline > .bbl, chặn crash khoảng nửa mở [0, 1) sau \item, phân giải đa root theo tiêu đề M1, mở rộng tập môi trường list như compactitem/enumerate*/inparaenum, tối ưu parse_bibtex bằng lazy field parsing cho các file .bib khổng lồ như anthology.bib 43,8 MB).

Hide code cell source

pv = m2['pilot_v1_vs_v2']
comp = pd.DataFrame({
    'Pilot v1 (trước vá)': pv['v1']['status_counts'],
    'Pilot v2 (sau vá)': pv['v2']['status_counts'],
}).fillna(0).astype(int)
display(Markdown('**Bảng 6.1. So sánh Pilot 250 bài / 536 version trên Colab CPU trước & sau nâng cấp parser.**'))
display(comp)
comp.plot.bar(title='Tác động nâng cấp parser trên Pilot 250 bài (Colab CPU)', ylabel='Số version')
plt.tight_layout(); plt.show()

tiers = pd.Series(m2['coverage_tiers'], name='Số bài báo')
display(Markdown('**Bảng 6.2. Phân tầng mức độ hoàn thiện trên toàn bộ 25.000 bài.**'))
display(tiers.to_frame())
cov_buckets = pd.Series(m2['parsed_coverage_buckets'], name='Số bài báo')
display(Markdown('**Bảng 6.3. Phân bố tỷ lệ version TeX parse được trên mỗi bài báo (25.000 bài).**'))
display(cov_buckets.to_frame())
cov_sorted = cov_buckets.sort_values()
ax_cov = cov_sorted.plot.barh(color='#2f628e', title='Độ phủ version parse được theo từng bài báo (25.000 bài)', xlabel='Số bài báo')
for i, v in enumerate(cov_sorted):
    ax_cov.text(v + 250, i, f'{v:,}', va='center', fontsize=9)
ax_cov.set_xlim(0, cov_sorted.max() * 1.18)
plt.tight_layout(); plt.show()
diag = pd.Series(m2['diagnostic_categories'], name='Số version có diagnostic').sort_values()
ax = diag.plot.barh(color='#b57b36', title='Nhóm diagnostic trên 41.498 version', xlabel='Số version')
for i, v in enumerate(diag):
    ax.text(v + 120, i, f'{v:,}', va='center', fontsize=9)
ax.set_xlim(0, diag.max() * 1.18)
plt.tight_layout(); plt.show()

Bảng 6.1. So sánh Pilot 250 bài / 536 version trên Colab CPU trước & sau nâng cấp parser.

Pilot v1 (trước vá) Pilot v2 (sau vá)
success 352 407
error 70 14
empty_no_tex 32 32
error_missing_source 17 19
partial 65 64
../_images/6d3846ae14d95d1dfb7a341737081bc70c384147c58b21493803eacaecddac70.png

Bảng 6.2. Phân tầng mức độ hoàn thiện trên toàn bộ 25.000 bài.

Số bài báo
Mọi version empty (PDF-only / no LaTeX) 2006
Parsed đủ (không lỗi, có partial) 2946
Hoàn toàn sạch (mọi version success/empty) 19168
Có ít nhất 1 version lỗi/thiếu nguồn 880

Bảng 6.3. Phân bố tỷ lệ version TeX parse được trên mỗi bài báo (25.000 bài).

Số bài báo
Không có TeX (chỉ empty) 2006
100% version TeX parse được 22027
0% (lỗi/thiếu hết) 426
50% - <100% 484
>0% - <50% 57
../_images/3154cad43c67339bf3d6bdf6af9726db02eb3786c0667b9866c1a2308fb456ba.png ../_images/f421922a53ebbfa044a9462bd1f320788c950091a5109827399fc59f7a6b61ee.png

Tài liệu và mã nguồn tham chiếu#