Skip to content

brycewang-stanford/Auto-Empirical-Research-Skills / skills/35-bahayonghang-academic-writing-skills/skills/paper-audit

paper-audit

Verified

Deep-review-first audit for Chinese and English academic papers across LaTeX, Typst, and PDF formats. Use whenever the user wants reviewer-style paper critique, pre-submission readiness checks, pass/fail gate decisions, structured revision roadmaps, or re-audits of revised manuscripts. Trigger even if the user only says "review my paper", "check if this is ready to submit", "audit this PDF", "simulate peer review", "find the biggest problems in this manuscript", or "re-check whether I fixed the review issues". Do not use for direct source editing or compilation-heavy repair; route those to the format-specific writing skills instead.

FileKindSize
SKILL.mdskill md14.3 KB
agents/claims_evidence_reviewer_agent.mdmarkdown354 B
agents/committee_editor_agent.mdmarkdown1.9 KB
agents/committee_literature_agent.mdmarkdown1.9 KB
agents/committee_logic_agent.mdmarkdown1.5 KB
agents/committee_methodology_agent.mdmarkdown1.8 KB
agents/committee_theory_agent.mdmarkdown1.9 KB
agents/critical_reviewer_agent.mdmarkdown8.4 KB
agents/domain_reviewer_agent.mdmarkdown7.1 KB
agents/editor_in_chief_agent.mdmarkdown5.2 KB
agents/evaluation_fairness_reviewer_agent.mdmarkdown371 B
agents/literature_reviewer_agent.mdmarkdown3.6 KB
agents/methodology_reviewer_agent.mdmarkdown7.2 KB
agents/notation_consistency_reviewer_agent.mdmarkdown398 B
agents/prior_art_reviewer_agent.mdmarkdown2.9 KB
agents/section_reviewer_agent.mdmarkdown365 B
agents/self_consistency_reviewer_agent.mdmarkdown420 B
agents/synthesis_agent.mdmarkdown951 B
evals/evals.jsonconfig12.0 KB
evals/fixtures/deep_review_fixture.texother699 B
evals/fixtures/gate_ieee_fixture.texother617 B
evals/fixtures/polish_fixture.texother396 B
evals/fixtures/previous_final_issues.jsonconfig1.1 KB
evals/fixtures/previous_review_report.mdmarkdown205 B
evals/fixtures/quick_audit_fixture.texother538 B
examples/gate_example.mdmarkdown3.5 KB
examples/review_example.mdmarkdown2.5 KB
examples/self_check_example.mdmarkdown2.9 KB
references/AUDIT_GUIDE.mdmarkdown3.4 KB
references/CHANGELOG.mdmarkdown530 B
references/CHECKLIST.mdmarkdown6.0 KB
references/CONSOLIDATION_RULES.mdmarkdown907 B
references/DEEP_REVIEW_CRITERIA.mdmarkdown2.8 KB
references/FORBIDDEN_TERMS.mdmarkdown6.4 KB
references/ISSUE_SCHEMA.mdmarkdown928 B
references/LITERATURE_GROUNDING_GUIDE.mdmarkdown3.3 KB
references/POLISH_GUIDE.mdmarkdown2.3 KB
references/QUALITATIVE_STANDARDS.mdmarkdown5.5 KB
references/QUICK_REFERENCE.mdmarkdown1.1 KB
references/REVIEW_CRITERIA.mdmarkdown2.7 KB
references/REVIEW_LANE_GUIDE.mdmarkdown828 B
references/SCHOLAR_EVAL_GUIDE.mdmarkdown6.4 KB
references/SCORING_SYSTEMS.mdmarkdown1000 B
references/SUBAGENT_TEMPLATES.mdmarkdown987 B
references/TROUBLESHOOTING.mdmarkdown1.4 KB
references/VENUE_RULES.mdmarkdown764 B
references/editorial_decision_standards.mdmarkdown6.7 KB
references/quality_rubrics.mdmarkdown10.8 KB
scripts/audit.pyscript78.4 KB
scripts/build_claim_map.pyscript3.3 KB
scripts/check_citations.pyscript5.6 KB
scripts/check_references.pyscript19.9 KB
scripts/consolidate_review_findings.pyscript5.2 KB
scripts/detect_language.pyscript1.9 KB
scripts/diff_review_issues.pyscript2.0 KB
scripts/literature_compare.pyscript11.4 KB
scripts/literature_search.pyscript22.0 KB
scripts/models/scoring_model.jsonconfig737 B
scripts/parsers.pyscript3.3 KB
scripts/pdf_parser.pyscript11.4 KB
scripts/prepare_review_workspace.pyscript6.8 KB
scripts/render_deep_review_report.pyscript3.5 KB
scripts/report_generator.pyscript36.2 KB
scripts/scholar_eval.pyscript13.7 KB
scripts/scoring_model.pyscript6.2 KB
scripts/verify_quotes.pyscript1.6 KB
scripts/visual_check.pyscript10.7 KB
templates/audit_report_template.mdmarkdown2.8 KB
templates/final_issues_template.jsonconfig498 B
templates/review_report_template.mdmarkdown678 B
templates/revision_roadmap_template.mdmarkdown3.1 KB

scripts/visual_check.py

View on GitHub
#!/usr/bin/env python3
"""
PDF Visual Layout Checker.
Detects margin overflows, text block overlaps, font inconsistencies,
low-resolution images, and blank pages in PDF documents.

Usage:
    python visual_check.py paper.pdf
    python visual_check.py paper.pdf --margin 72 --min-dpi 150
    python visual_check.py paper.pdf --json
"""

from __future__ import annotations

import argparse
import json
import sys
from pathlib import Path

# Module-level availability check — safe to import as library without pymupdf installed
try:
    import pymupdf as _pymupdf_module

    _PYMUPDF_AVAILABLE = True
except ImportError:
    _pymupdf_module = None  # type: ignore[assignment]
    _PYMUPDF_AVAILABLE = False


def _calc_overlap_area(r1: tuple, r2: tuple) -> float:
    """Calculate overlap area between two rectangles (x0, y0, x1, y1)."""
    x_overlap = max(0, min(r1[2], r2[2]) - max(r1[0], r2[0]))
    y_overlap = max(0, min(r1[3], r2[3]) - max(r1[1], r2[1]))
    return x_overlap * y_overlap


class VisualChecker:
    """PDF visual layout checker."""

    def __init__(
        self,
        pdf_path: str,
        margin_pt: float = 72.0,
        min_dpi: int = 150,
        margin_tolerance: float = 5.0,
        overlap_threshold: float = 100.0,
    ) -> None:
        if not _PYMUPDF_AVAILABLE:
            raise ImportError("visual_check requires pymupdf: pip install pymupdf")
        self.doc = _pymupdf_module.open(pdf_path)  # type: ignore[union-attr]
        self.margin = margin_pt
        self.min_dpi = min_dpi
        self.margin_tolerance = margin_tolerance
        self.overlap_threshold = overlap_threshold
        self.issues: list[dict] = []

    def __enter__(self) -> VisualChecker:
        return self

    def __exit__(self, *_: object) -> None:
        self.close()

    def check_margins(self) -> None:
        """Detect text blocks overflowing page margins."""
        tolerance = self.margin_tolerance
        for page_num, page in enumerate(self.doc):
            blocks = page.get_text("dict")["blocks"]
            rect = page.rect
            for block in blocks:
                bbox = block["bbox"]  # (x0, y0, x1, y1)
                # Left margin
                if bbox[0] < self.margin - tolerance:
                    self._add_issue(
                        page_num,
                        "Major",
                        "P1",
                        f"Content overflows left margin (x={bbox[0]:.1f}pt, margin={self.margin}pt)",
                    )
                # Right margin
                if bbox[2] > rect.width - self.margin + tolerance:
                    self._add_issue(
                        page_num,
                        "Major",
                        "P1",
                        f"Content overflows right margin (x={bbox[2]:.1f}pt, page_width={rect.width:.1f}pt)",
                    )
                # Top margin
                if bbox[1] < self.margin - tolerance:
                    self._add_issue(
                        page_num,
                        "Major",
                        "P1",
                        f"Content overflows top margin (y={bbox[1]:.1f}pt, margin={self.margin}pt)",
                    )
                # Bottom margin
                if bbox[3] > rect.height - self.margin + tolerance:
                    self._add_issue(
                        page_num,
                        "Major",
                        "P1",
                        f"Content overflows bottom margin (y={bbox[3]:.1f}pt, page_height={rect.height:.1f}pt)",
                    )

    def check_overlaps(self) -> None:
        """Detect overlapping text/image blocks (sorted X-axis with early exit)."""
        for page_num, page in enumerate(self.doc):
            blocks = page.get_text("dict")["blocks"]
            rects = [
                b["bbox"]
                for b in blocks
                if b.get("type") in (0, 1)  # 0=text, 1=image
            ]
            # Sort by x0: once b2.x0 > b1.x1, no further overlap is possible on X axis
            rects.sort(key=lambda r: r[0])
            for i, r1 in enumerate(rects):
                for r2 in rects[i + 1 :]:
                    if r2[0] > r1[2]:  # Early exit: b2 starts after b1 ends
                        break
                    overlap_area = _calc_overlap_area(r1, r2)
                    if overlap_area > self.overlap_threshold:
                        self._add_issue(
                            page_num,
                            "Critical",
                            "P0",
                            f"Block overlap detected: {overlap_area:.0f} sq pt",
                        )

    def check_fonts(self) -> None:
        """Detect body font inconsistency (>2 main fonts in body text range)."""
        font_counter: dict[str, int] = {}
        for page in self.doc:
            blocks = page.get_text("dict")["blocks"]
            for block in blocks:
                for line in block.get("lines", []):
                    for span in line.get("spans", []):
                        size = span["size"]
                        # Body text font size range (9-13pt)
                        if 9 <= size <= 13:
                            font_name = span["font"]
                            font_counter[font_name] = font_counter.get(font_name, 0) + len(
                                span["text"]
                            )
        # Filter to significant fonts (>100 chars)
        main_fonts = [f for f, c in font_counter.items() if c > 100]
        if len(main_fonts) > 2:
            font_list = ", ".join(main_fonts[:5])
            if len(main_fonts) > 5:
                font_list += f" (+{len(main_fonts) - 5} more)"
            self._add_issue(
                0,
                "Minor",
                "P2",
                f"Inconsistent body fonts ({len(main_fonts)} detected): {font_list}",
            )

    def check_image_resolution(self) -> None:
        """Detect low-resolution embedded images."""
        for page_num, page in enumerate(self.doc):
            for img_info in page.get_images(full=True):
                xref = img_info[0]
                try:
                    base_image = self.doc.extract_image(xref)
                except Exception:
                    continue
                if not base_image:
                    continue
                width = base_image.get("width", 0)
                height = base_image.get("height", 0)
                if width == 0 or height == 0:
                    continue
                # Calculate effective DPI from rendered size
                for img_rect in page.get_image_rects(xref):
                    render_width_in = img_rect.width / 72
                    if render_width_in > 0:
                        effective_dpi = width / render_width_in
                        if effective_dpi < self.min_dpi:
                            self._add_issue(
                                page_num,
                                "Major",
                                "P1",
                                f"Low resolution image: {effective_dpi:.0f} DPI "
                                f"(minimum: {self.min_dpi} DPI, "
                                f"pixel size: {width}x{height})",
                            )

    def check_blank_pages(self) -> None:
        """Detect blank pages (no text and no images)."""
        for page_num, page in enumerate(self.doc):
            text = page.get_text("text").strip()
            images = page.get_images()
            if not text and not images:
                self._add_issue(
                    page_num,
                    "Minor",
                    "P2",
                    "Blank page detected",
                )

    def run_all(self) -> list[dict]:
        """Run all visual checks and return issues."""
        self.check_margins()
        self.check_overlaps()
        self.check_fonts()
        self.check_image_resolution()
        self.check_blank_pages()
        return self.issues

    def _add_issue(
        self,
        page: int,
        severity: str,
        priority: str,
        message: str,
    ) -> None:
        self.issues.append(
            {
                "module": "VISUAL",
                "page": page + 1,  # 1-indexed
                "severity": severity,
                "priority": priority,
                "message": message,
            }
        )

    def close(self) -> None:
        """Close the PDF document."""
        self.doc.close()


def _format_issues(issues: list[dict], as_json: bool = False) -> str:
    """Format issues for output."""
    if as_json:
        return json.dumps(issues, indent=2, ensure_ascii=False)

    if not issues:
        return "# VISUAL: No layout issues detected."

    lines = []
    for issue in issues:
        lines.append(
            f"% VISUAL (Page {issue['page']}) "
            f"[Severity: {issue['severity']}] "
            f"[Priority: {issue['priority']}]: "
            f"{issue['message']}"
        )
    return "\n".join(lines)


def main() -> int:
    """CLI entry point."""
    parser = argparse.ArgumentParser(
        description="PDF Visual Layout Checker",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  python visual_check.py paper.pdf
  python visual_check.py paper.pdf --margin 72 --min-dpi 150
  python visual_check.py paper.pdf --json
        """,
    )
    parser.add_argument("pdf_file", help="Path to PDF file")
    parser.add_argument(
        "--margin",
        type=float,
        default=72.0,
        help="Page margin in points (default: 72 = 1 inch)",
    )
    parser.add_argument(
        "--min-dpi",
        type=int,
        default=150,
        help="Minimum image DPI threshold (default: 150)",
    )
    parser.add_argument(
        "--json",
        action="store_true",
        help="Output results in JSON format",
    )

    args = parser.parse_args()

    pdf_path = Path(args.pdf_file)
    if not pdf_path.exists():
        print(f"[ERROR] File not found: {args.pdf_file}", file=sys.stderr)
        return 1

    if pdf_path.suffix.lower() != ".pdf":
        print(f"[ERROR] Not a PDF file: {args.pdf_file}", file=sys.stderr)
        return 1

    try:
        with VisualChecker(
            str(pdf_path),
            margin_pt=args.margin,
            min_dpi=args.min_dpi,
        ) as checker:
            issues = checker.run_all()
    except ImportError as e:
        print(f"[ERROR] {e}", file=sys.stderr)
        return 1
    except Exception as e:
        print(f"[ERROR] Failed to process PDF: {e}", file=sys.stderr)
        return 1

    print(_format_issues(issues, as_json=args.json))

    # Exit 1 if critical issues found
    has_critical = any(i["severity"] == "Critical" for i in issues)
    return 1 if has_critical else 0


if __name__ == "__main__":
    sys.exit(main())
rea-analysis-optimizationmorluto/reaOptimize REA providers and shared analysis workflows for agent context, latency, CPU, and memory while preserving correctness and Evidence. Use for analysis bottlenecks and cache or query design; CI/test-suite optimization belongs to rea-ci-tests-audit.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-ci-tests-auditmorluto/reaAudit REA CI and test suites for correctness, fixture drift, false passes, and measured performance; use for suite or workflow investigations and efficiency changes, rather than ordinary feature testing or a single test failure.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
rea-tool-designmorluto/reaAudit, investigate, design, or change REA investigation tools, CLI/MCP contracts, provider capabilities, and Evidence semantics.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
ponytail-auditDietrichGebert/ponytailQuality audit of the whole repo: bugs, security, real load, missing tests, speed, and what to delete. Most important first.Stars: 194kUpdated Claude CodeCodexVerifiedInstall