Latex formula extraction

From XuShuwenn/RedAct · View interactive version

Latex formula extraction is an AI agent skill from the GitHub repository XuShuwenn/RedAct. Extract LaTeX formulas from PDF research papers, fixing display syntax errors while preserving original content.

How to use this skill

Skill file

LaTeX Formula Extraction from PDF

When to Use

When to Use

Environment Protocol and Deliverable Discipline

Execution Priorities

Input

Runtime Checks

Extraction Steps

  1. Review the PDF page by page and identify every standalone display formula candidate, including unnumbered and multi-line formulas.

1a. Keep an explicit page inventory while scanning: for each page, record whether it has zero or more standalone display formulas and whether the page evidence was readable. Do not infer completeness from grep, equation numbering, regex hits, or a single flattened text dump.

1aa. Do not claim complete extraction from a sample page, truncated preview, or initial chunk alone. For a completeness claim, the workflow must show a full document coverage pass or an explicit page-by-page accounting.

1ab. If a built-in reader/search tool can already access the PDF contents, use page-sized or chunked reads plus targeted search to drive that inventory before attempting external conversion.

1ac. When chunked native reading works, keep using it systematically across the document instead of returning to converter experimentation; use search hits only as navigation aids, then read enough surrounding content to verify the full displayed formula and record its page/source evidence.

1b. For each retained formula, record a stable source reference from the current run: page number plus the text extraction, OCR result, or crop/region that actually showed it.

1c. If a page read, crop, render, or OCR result is empty, wrong-region, unreadable, or truncated, treat that as insufficient evidence and switch methods rather than transcribing from memory, context, or prior guesses.

1d. If an image file exists but reading or inspection returns empty, blank, non-informative, or non-readable content, treat that exactly like a failed extraction path; do not claim you "inspected," "saw," "read," or "verified" formulas from that image.

1e. Do not treat successful file creation, page rendering, image export, or crop generation as evidence by itself; evidence requires readable formula content from the actual tool output or direct inspectable page/region content.

1f. If an image read, render/crop inspection, or preview returns blank content, only metadata, or no readable symbols, you have not visually verified the formula. Do not say you can "see," "read," or "confirm" it from that image; switch to OCR, another crop/render path, page-text extraction, or a different extractor.

1g. Before saying a formula was identified, found, or verified, ensure the current run contains the exact supporting observation that exposed it. If no tool output in the session actually shows the formula text, omit that formula and continue with another extraction path.

  1. Extract each formula as raw LaTeX in $$ ... $$.

2a. Never use placeholder formulas such as $$...$$, TODO, dummy text, guessed stand-ins, or scaffold lines. Every saved formula line must contain an evidence-backed transcription of an actually observed displayed formula.

2b. If a formula cannot yet be reconstructed faithfully, leave it out until you obtain better evidence; partial progress is acceptable, placeholder output is not.

2c. Do not create /root/latex_formula_extraction.md with scaffold content such as $$...$$, empty blocks, or provisional stand-ins just to satisfy the artifact requirement. Wait until you have at least one evidence-backed formula, then write only real verified $$...$$ lines.

2d. Before any write to /root/latex_formula_extraction.md, inspect the exact payload you are about to save and confirm every line contains a concrete evidence-backed formula, not placeholders, filler, ellipses, or guessed stand-ins.

  1. Preserve the exact displayed content from the PDF only when symbols and structure are clearly supported by readable extraction output or direct page inspection.

3a. Apply an evidence gate before keeping any formula: only write it if a specific page/region shows the full displayed expression in readable text extraction, OCR, or direct visual inspection.

3a.i. Before scaling automation or writing helper scripts around an extractor, verify on 1-2 sample pages that equation boundaries and symbols are preserved well enough to separate display math from surrounding prose. If sample output merges prose with equations, drops equations, or corrupts layout, treat that extractor as unfit for direct transcription and pivot.

3aa. If an image/file read shows only metadata, blank content, or no readable symbols, treat that as no visual evidence. Do not say you can "see," "read," or "verify" the formula from that observation; switch to OCR, a different render/crop, or another extraction path.

3b. Do not identify formulas by symbol density, line length, centering, equation-number regexes, or similar heuristics unless a human-verifiable page view already confirmed those lines are actual display equations.

3c. If extraction is partial, fragmented, page-misaligned, truncated, merged with prose, drops superscripts/subscripts/operators, shows Unicode fragments/OCR noise, reorders symbols, breaks fractions, or is otherwise ambiguous, treat it only as a lead for where to inspect next; re-extract, switch methods, or omit the formula rather than reconstructing missing math from context.

3d. Do not write a formula to /root/latex_formula_extraction.md unless the session has a concrete supporting observation for it: readable page text, OCR output, or visible page/region content that exposes that formula.

3e. If all attempted source-inspection paths are empty, unreadable, truncated, wrong-region, or mixed with metadata/prose in a way that obscures the formula, do not claim the formula was identified or verified; switch methods or omit it.

3f. If any earlier step showed truncation, encoding artifacts, cut-off formulas, missing operators, or other reliability warnings, do NOT promote a later reconstructed or "cleaned" formula into the final file unless you directly re-check that exact formula against readable page text, OCR, or visible page/region evidence.

3g. Treat post-processed outputs (for example "corrected", "rendered", or reformatted formulas produced by your own scripts/tools) as unverified drafts unless the underlying source formula was independently observed from the PDF evidence in the current run.

3h. If earlier steps showed truncation, encoding artifacts, cut-off equations, or other noisy extraction signals for a formula, do not save a later reconstructed, syntax-checked, or corrected version until you re-check that exact full formula against a direct source observation from the PDF in the current run.

  1. Remove equation tags, commas, and periods at the end of formulas only when they are not part of the math content.
  2. Check each extracted formula for syntax/display issues only after the displayed formula has been reliably identified from the PDF.
  3. Append corrected versions only for formulas with clear syntax/display problems.

6a. Before concluding that no fixes are needed, run an explicit formula-by-formula validation pass for delimiter balance and obvious LaTeX display syntax problems; bracket counting or successful rendering alone does not prove fidelity or completeness.

6aa. Treat syntax/render validation as a secondary negative check only: balanced braces, successful parsing, or plausible LaTeX never justify choosing a disputed symbol, subscript, left-hand side, or bound.

6ab. If OCR/text extraction is noisy and two plausible readings exist, do not pick the more conventional-looking reconstruction. Re-inspect the source page/region or omit that formula until one reading is directly supported.

6b. Before writing or overwriting /root/latex_formula_extraction.md, require a final evidence check for every formula: the full expression must be directly supported by a readable page/region observation from the current run.

6c. Do NOT complete a truncated, fragmented, or OCR-corrupted formula from neighboring prose, prior knowledge, equation numbering, or a later guess; re-extract it or omit it.

6d. Do not replace source math with a conventionally "fixed" version based on assumption. If a delimiter, operator, or symbol looks wrong but is not clearly readable in the source evidence, preserve only what is directly supported or omit the formula rather than normalizing it from domain expectations.

  1. If output is blank, truncated, garbled, fragmented, or mixes prose into equations, switch methods instead of inferring missing math.

7x. If repeated candidate "formulas" contain author names, metadata, full prose sentences, or other clearly non-equation text, stop tuning regexes/heuristics on that output. Treat the underlying representation as untrustworthy and move to a different extraction family or direct page/region inspection.

7a. If a tool fails twice for the same structural reason (for example timeout, missing dependency, unreadable output, flattened math, or no inspectable files), stop retrying it and pivot to a materially different method.

7aa. Materially different means a different extraction family, not the same converter rerun in background/foreground, with longer timeout, extra polling, minor flag changes, or a near-identical wrapper.

7ab. Treat repeated zero-byte outputs, repeated timeouts, background jobs that keep running without producing inspectable artifacts, repeated non-readable conversions, or help-only/probe-only runs without extracted text as decisive failure evidence; once those signals accumulate, switch tool families entirely.

7ac. When a fallback tool is confirmed present, prefer executing that direct extractor next over introducing another untested script or dependency path.

7b. Do not keep rerunning near-identical converter or command variants, adding long wait loops, or primarily polling ps/pgrep/output directories once a method has not produced usable text quickly.

7b.i. After one diagnostic rerun confirms the same stall/no-output condition, stop monitoring that pipeline; repeated status checks without new inspectable artifacts do not count as progress.

7b.ii. Replace vague intentions with explicit fallback actions: run a different extractor, inspect a specific page with another library, render a page image, or write verified formulas already recovered.

7c. Prefer direct page-level extraction, page rendering plus visual inspection, OCR, or manual transcription from verified page regions over continued process management.

7d. If delegation is used, require the subtask to try a materially different extraction path rather than retrying the same failing workflow.

7e. Maintain at most one active stateful conversion job per input/output target. Before any restart, confirm the prior run has finished or been intentionally terminated; do not launch overlapping runs of the same converter against the same files.

7f. When an alternate path already yields readable page text or visible formula regions, promote that path to the main workflow immediately instead of waiting for the original pipeline to finish.

  1. As soon as you have a workable draft, write /root/latex_formula_extraction.md, then verify the file exists and that each formula is in its own $$...$$ block.
  2. After writing, reopen and read back the saved file contents in manageable chunks if needed; confirm the contents match the intended formulas, the last formula closes with $$, and no line is cut off.

9a. Make the final artifact auditable: ensure the actual $$...$$ lines written to /root/latex_formula_extraction.md are visible in the workflow, either by printing the constructed content before writing or by reading back the saved file contents fully enough to expose every formula line.

9b. Do not rely on opaque statements like "formatted formula lines" or on uninspected writes as evidence that the correct formulas were saved.

  1. If extraction is incomplete but evidence-backed, still write the verified formulas you have now rather than delaying file creation while debugging one failing toolchain.
  2. Do not declare completion until all pages have been inspected or explicitly ruled out and every page containing standalone formulas has been accounted for.

11a. Do NOT say or imply "all formulas found," "complete extraction," or equivalent unless your actions established whole-document coverage by page-by-page inspection, source-wide search with follow-up inspection, or another observable full-source review.

11b. If coverage is incomplete, state that the output is partial and limited to the formulas directly verified from the inspected pages/regions.

11c. Do not upgrade a partial recovery into a completeness claim just because numbered-equation searches, syntax checks, or reconstructed drafts seem to account for the likely formulas. Completeness requires observable whole-document coverage evidence plus direct support for each retained formula.

11d. If any page remains unreadable, uninspected, or only fragmentarily extracted, do not say or imply that all formulas were found; deliver the verified subset and label it partial.

Evidence and Verification

Output Format

Markdown file /root/latex_formula_extraction.md:

$$original_formula_1$$
$$original_formula_2$$

$$fixed_formula_1$$
$$fixed_formula_2$$
...

Write the final result to exactly /root/latex_formula_extraction.md; do not substitute JSON, reports, or code files for this artifact.

Write one formula per line in $$...$$ markdown display form, with extracted originals first and fixed versions after them only when needed.

When writing /root/latex_formula_extraction.md, the file content must be the actual formula lines themselves. Do NOT write placeholders, dummy $$...$$ blocks, summaries, prose notes, ellipses standing in for unresolved content, or descriptions such as "wrote the extracted formulas".

Treat the write payload as literal deliverable content: before executing the write, check that the body already contains the full $$...$$ formula lines and not a description of them.

If you accidentally wrote descriptive or placeholder text, overwrite the file immediately with the actual formulas, then reread the saved file before continuing.

If the file would otherwise contain only placeholders or unresolved stand-ins, do not write that draft as the final artifact; continue extracting or save only the smaller set of formulas that are fully evidenced.

Before finishing, verify the file exists, is non-empty, and contains only the extracted display formulas in the required $$...$$ format.

After any write or rewrite, read back the entire saved file (in chunks if needed), checking every line for truncation, unmatched delimiters, unfinished $$...$$ blocks, and mismatches with the verified source evidence.

Make the actual formula payload auditable: either print/show the exact $$...$$ lines before writing or immediately read back the saved file in full so the concrete written formulas are visible in the workflow.

If any readback shows placeholder text, prose such as "wrote the extracted formulas", truncated lines, or a mismatch with the intended formulas, treat the write as failed: rewrite /root/latex_formula_extraction.md with the literal formula lines and reread the full file before finishing.

If you rewrite /root/latex_formula_extraction.md late in the workflow, do not finalize from a partial preview. Re-read the full saved file after that last rewrite, covering every formula line through end of file, before emitting the completion signal.

Verification must inspect the actual /root/latex_formula_extraction.md contents on disk and confirm the saved formulas are the ones you intend to submit; reading the saved file verifies persistence only, not fidelity to the PDF.

Treat the readback literally: check for placeholders, stray markers, extra lines, numbering prefixes, shell artifacts, truncated fragments, or unrelated trailing text. If any unexpected text appears, rewrite the file and reread it before finishing.

Do not describe formulas in the final response that are not literally present in /root/latex_formula_extraction.md when you reread it.

Do not leave the final content in JSON, Python, scratch notes, or alternate output files. If you used intermediate structures, convert them into the required markdown-only $$...$$ lines in /root/latex_formula_extraction.md before finishing.

Fix Types

Tips

Completion Checklist

Completion Checklist

Execution Workflow

  1. Before writing helper scripts, confirm the approach is viable in this runtime and preserves formula fidelity on a small sample.
  2. Treat any new extraction tool as untrusted until it produces inspectable output on disk or in stdout/stderr; verify that first.

8a. If you just confirmed a tool exists via which or --help, the next step should usually be a real extraction command on the PDF or a sample page, followed by inspection of its output.

8b. Do not spend additional turns on process checks, wrapper variants, or alternate scripts when a documented installed extractor is already available and not yet actually tried.

  1. Do not keep polling, rerunning, or extending timeouts on the same failing conversion pipeline once you have two clear failures or no inspectable output.
  2. For opaque converters or background jobs, allow at most one diagnostic foreground rerun to capture stderr or a traceback before abandoning that path.
  3. After each major step, ask whether it produced readable formula evidence or updated /root/latex_formula_extraction.md; if not, change approach.

11c. If the current path is only improving an intermediate artifact (for example markdown conversion output) without exposing verified formulas or updating /root/latex_formula_extraction.md, demote that path and switch to a more direct extractor.

11a. If two consecutive diagnostic actions still do not reveal a concrete error or produce readable formula evidence, stop investigating that path and switch to a different extraction method.

11b. Prefer the next action that can create or append to /root/latex_formula_extraction.md over additional peripheral diagnostics.

  1. Keep a simple coverage log: page number, whether it contains standalone display math, and which extraction/viewing method verified each retained formula.
  2. Once any verified formulas are available, start writing /root/latex_formula_extraction.md immediately and continue filling it as you inspect remaining pages.
  3. When output is clipped by the shell or tool display, save the extraction to a file or inspect smaller page/region chunks; do not treat clipped console text as complete evidence.
  4. If multiple tools fail or only part of the paper is recoverable, still save every directly verified formula, verify the file on disk, and continue expanding coverage only if time permits.
  1. Before locking in a plan, run a minimal end-to-end viability probe with the exact toolchain you intend to use: executable present, library import succeeds if needed, sample page access works, and output is inspectable.
  2. If the environment exposes a working built-in file reader or search facility for the PDF, use it first for chunked/page-level inspection and formula discovery; only escalate if that path is demonstrably insufficient for readable formula evidence.
  3. If you create a helper script intended to produce /root/latex_formula_extraction.md, execute it promptly unless a concrete runtime error blocks execution.

18a. Do not return to open-ended tool exploration after writing such a script until you have either run it once and inspected /root/latex_formula_extraction.md or observed a concrete execution error that forces a change of plan.

18b. Use the checkpoint: script saved -> script executed -> output file created/updated -> file read back. Treat anything short of that as incomplete progress, not completion.

  1. Treat "script written" as incomplete progress; the checkpoint is: script run, /root/latex_formula_extraction.md created or updated, file read back, contents verified.
  2. When you decide on a fallback or corrective plan, execute that next step immediately and validate its result; do not stop at describing the new plan.
  3. If a backgrounded converter/job disappears quickly, has empty logs, or creates no inspectable output, immediately rerun the same command in the foreground once; use that result to decide whether to abandon the tool.
  4. If smoke testing and environment checks leave no credible path for that converter family, abandon it early and move to a simpler inspectable method rather than managing retries.
  5. Never start a second run of the same converter on the same document/output location just to see if it behaves differently; inspect or terminate the first run before deciding the next step.
  6. If no new artifact has appeared after a brief wait, do one diagnostic check at most, then pivot; do not spend the session monitoring a stuck job.
  7. Anti-stall fallback sequence: (a) run one simple inspectable extractor on a sample page, (b) if it yields readable formula evidence, start or update /root/latex_formula_extraction.md immediately, (c) if it fails twice or produces no inspectable output, switch to a materially different extraction family rather than more diagnostics.
  8. If a long-running converter still has not produced an inspectable artifact after the predeclared stop point, terminate or abandon it and immediately execute the fallback extraction path; do not end the turn with more monitoring.
  9. Never start a second instance of the same converter for the same PDF or output target while the first is still active or unresolved; first inspect artifacts, then either keep exactly one run or pivot away from that tool family entirely.
  10. Prefer the next action that can expose page text or a visible formula region over any action that only reports process state, tool metadata, or converter status.
  11. If coverage is still limited, write the verified formulas already recovered to /root/latex_formula_extraction.md before any further experimentation.

Execution Workflow

  1. Start with a lightweight, inspectable method first (for example, pdfplumber or PyMuPDF).
  2. Validate on 1-2 sample pages before scaling up: confirm displayed formulas are readable and not corrupted prose, Unicode fragments, or flattened layout.
  3. If direct/full-file reading hits size limits, switch to page-by-page, chunked, or region-level extraction instead of retrying the same full read.
  4. If a tool produces empty output, stalls, times out, or gives unusable formula text after 1-2 attempts, stop retrying it and switch to a materially different method.
  5. If text extraction loses equation structure, use page rendering, OCR, or manual page-level transcription from verified PDF evidence rather than adding more heuristics.
  6. Track which pages have been inspected so completeness claims are evidence-based.
Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.