跳到正文
DEV Community· Sid Mishra·· 41 分鐘前AI 評分57

《Attention Is All You Need》轉成 Markdown 後的問題與 30 行 Python 修正方法

A 15-page paper converted to Markdown: what broke, and 30 lines of Python that fix it

AI 導讀

作者示範將《Attention Is All You Need》的 15 頁 PDF 轉成 Markdown,並用 Python 修復標題、斷行、頁碼等結構問題。轉換結果為 39,594 bytes、6,036 words;文中提供逐頁清理、保留頁碼及以 350 words、40-word overlap 分塊的程式。文字層抽取不保留表格結構,掃描檔則需要先經 OCR 工具處理。

正文

A PDF describes where ink goes on a printed page. It never says "this is a heading" or "these cells are a table"; it says "draw these glyphs at these coordinates". So every converter is guessing the structure back from the layout, and in my experience building a crawler that reads them, how well it guesses depends far more on the PDF than on the tool.

That's why the same tool gives you clean Markdown from a policy document and garbage from a financial report. Below is a real conversion with its numbers, the things that broke, and a small standard-library script that cleans the output before you chunk it.

First, which kind of PDF do you have?

Three questions, in this order:

  1. Does it have a text layer? Try to select a sentence. If you can't, it's a scan, and nothing reads it without OCR first.
  2. Do the tables, equations or columns carry your answers? Prose (policies, manuals, contracts) converts fine with a text-layer extractor. Rate cards and financial statements need a layout model such as Docling or Marker, or your retriever sees cell values with no row or column attached.
  3. One file, a folder, or a website full of them? One file: a free converter. A folder: a local library. A site that keeps publishing and replacing PDFs: a crawler.

A real run: "Attention Is All You Need"

On 30 November 2026 we converted the arXiv copy of "Attention Is All You Need" (15 pages, with equations, figures and results tables) through MeshArc's scrape, reading only its text layer.

Result
PDF 15 pages, 2,215,244 bytes
Markdown 39,594 bytes (about 56 times smaller), 6,036 words
How it was read Plain fetch of the text layer, no browser
Time About 2 seconds
Cost 2 credits (a fetched PDF is 2, whatever its page count)
Page breaks A --- rule between every page

The numbers are the boring part. This is the useful part, the first lines of page 2 as returned:

1 Introduction
Recurrent neural networks, long short-term memory [13] and gated recurrent [7] neural networks
in particular, have been firmly established as state of the art approaches in sequence modeling and
...
Attention mechanisms have become an integral part of compelling sequence modeling and transduc-
tion models in various tasks, ...

Four problems in one page:

  • The heading is plain text. "1 Introduction" is an ordinary line, not a heading, so a chunker that splits on headings has nothing to split on.
  • Lines end where the printed lines ended, so one sentence is spread over several lines.
  • "transduc-tion" is split into two tokens a search won't match.
  • The page closes with a bare 2, its printed page number, which would land in your chunk.

Further on, equation (1) came back as softmax(QK T / √dk / )V across three lines. And because this file declares no title in its metadata, there was no # heading at all: MeshArc returns the text layer page by page, and only a title the PDF itself declares becomes #.

The text was complete and in reading order, so for prose questions it's good RAG input once cleaned. For the results tables it isn't: a text-layer read gives you their cells, not their structure.

Clean each page, then chunk

Clean each page, chunk it, and keep the page number with every chunk. Standard library only. We ran it on an excerpt of the output above: the page numbers went, "transduction" was re-joined, and "1 Introduction", "3 Model Architecture" and "3.1 Encoder and Decoder Stacks" came back as headings.

import re

# a numbered heading such as "3.1 Encoder and Decoder Stacks"
HEADING = re.compile(r"^(\d+(\.\d+)*)\s+[A-Z][^.]{0,80}$")

def clean_page(text: str) -> str:
    lines = text.strip().splitlines()
    if lines and re.fullmatch(r"\d{1,4}", lines[-1].strip()):
        lines = lines[:-1]                       # the printed page number
    out = []
    for line in lines:
        line = line.rstrip()
        if HEADING.match(line):
            out.append("\n## " + line)           # restore the heading the PDF lost
        elif out and out[-1].endswith("-") and line[:1].islower():
            out[-1] = out[-1][:-1] + line        # "transduc-" + "tion"
        elif out and not out[-1].startswith("\n## ") and not out[-1].endswith((".", ":", "?")):
            out[-1] += " " + line                # re-join a wrapped line
        else:
            out.append(line)
    return "\n".join(out).strip()

def chunks(markdown: str, source: str, size: int = 350, overlap: int = 40):
    for n, page in enumerate(markdown.split("\n\n---\n\n"), start=1):
        words = clean_page(page).split(" ")
        for start in range(0, len(words), size - overlap):
            text = " ".join(words[start:start + size])
            if text.strip():
                yield {"source": source, "page": n, "text": text}

What I'd change for your own documents:

  • The heading pattern only catches numbered headings. For reports with unnumbered ones, a layout tool's real heading levels are worth more than any regex.
  • Running headers differ per document. The dependable trick is to count lines that appear on most pages and drop those.
  • 350 words with a 40-word overlap is a default, not a law. It's also what MeshArc uses when it writes chunks to a vector store, but tune it against your own retrieval tests.

And keep page in the chunk's metadata. "See page 7 of the 2026 policy" is the difference between an answer someone trusts and one they have to check.

If your PDF is already online, paste its link into our free converter (no account) and look for the four problems above before you write any code.

When it's a whole site of PDFs

One PDF is a tool. A regulator's guidance library or a manufacturer's manuals is a crawl: new PDFs appear, old ones get replaced under the same URL or quietly withdrawn. With the Python SDK (pip install mesharc, then arc = MeshArc()):

job = arc.crawl(
    "https://example.gov/guidance/",
    limit=500,
    includePaths=["/guidance/*"],
    config={"parse_documents": True},
    wait=True,
)
for page in job.pages():
    print(page["url"], page["words"], page["credits"])

project = job.keep(name="Guidance PDFs", schedule="weekly", max_pages=500)

The crawl follows the PDF and Word files the site links to and converts each one from its text layer. Kept as a project, every later run compares each document with the last version and records it as added, modified or removed. That's what saves money in a RAG pipeline: you re-chunk and re-embed only the documents that changed, and a document the site failed to serve one week is held back, not deleted from your index. The re-embedding side is in the guide to keeping a RAG knowledge base fresh.

When to use something else

  • Your answers live in tables. A text-layer read, ours included, gives you the cells' text in reading order, not Markdown tables. Run those PDFs through Docling or Marker.
  • They're scans. MeshArc reads the text layer only, so put scans through an OCR-capable tool such as Docling, Marker or PyMuPDF with RapidOCR first.
  • They're files on your laptop. MeshArc reads PDFs by URL; a local folder wants a local library.

What's the worst PDF you've had to get into a RAG index, and what finally worked on it?


Originally published on mesharc.dev.

來源:DEV Community · dev.to