Skip to content

yzsp-studio/mediakit-shared-suite / artifact-preview

artifact-preview

Verified

Render workspace artifacts (pdf/pptx/docx/xlsx/html/png/jpg/txt/zip) into text + page screenshots + thumbnail + multi-page collages, saved under ./.preview/{hash}/. Use Read on the resulting jpg/png files to visually inspect your own deliverables before delivering them; it catches what a structural checker cannot — text truncation, colour clashes, clipped chart titles, layout drift, blank slides, CJK rendered as boxes. Triggered by: "看看产物长什么样", "视觉自检", "preview pptx", "render artifact", "screenshot pdf", "渲染产物", "我的报告画出来好看吗", "图表是否完整".

FileKindSize
README.mdmarkdown7.6 KB
SKILL.mdskill md10.1 KB
bin/previewother2.0 KB
bin/preview.cmdscript482 B
lib/__init__.pyscript1.7 KB
lib/_common.pyscript13.1 KB
lib/_types.pyscript3.5 KB
lib/cache.pyscript3.3 KB
lib/cli.pyscript10.2 KB
lib/collage.pyscript4.6 KB
lib/dispatch.pyscript8.3 KB
lib/docx.pyscript1.1 KB
lib/html.pyscript2.1 KB
lib/image.pyscript1.4 KB
lib/manifest.pyscript2.7 KB
lib/pdf.pyscript2.2 KB
lib/pptx.pyscript2.5 KB
lib/render/__init__.pyscript2.4 KB
lib/render/collage.pyscript10.9 KB
lib/render/constants.pyscript1.4 KB
lib/render/docx.pyscript2.2 KB
lib/render/html.pyscript12.4 KB
lib/render/pdf.pyscript3.4 KB
lib/render/pptx.pyscript5.6 KB
lib/render/types.pyscript1.3 KB
lib/render/xlsx.pyscript2.9 KB
lib/text.pyscript1.4 KB
lib/xlsx.pyscript1.1 KB
lib/zip_.pyscript1.4 KB
requirements.txtmanifest4.2 KB

lib/render/pdf.py

View on GitHub
"""PDF text + per-page PNG extraction via PyMuPDF."""

from __future__ import annotations

import logging
from typing import Sequence

from .constants import DEFAULT_MAX_PAGES_RENDER, DEFAULT_PDF_DPI
from .types import PageImage

logger = logging.getLogger(__name__)


def extract_pdf(
    pdf_bytes: bytes,
    *,
    dpi: int = DEFAULT_PDF_DPI,
    max_pages: int = DEFAULT_MAX_PAGES_RENDER,
    page_indices: Sequence[int] | None = None,
    render_images: bool = True,
) -> tuple[str, list[PageImage], int]:
    """Extract text + (optionally) per-page PNG screenshots from PDF bytes.

    Parameters
    ----------
    pdf_bytes
        Raw PDF byte string.
    dpi
        Render resolution. 150 dpi yields ~1500x1125 PNGs for A4 pages —
        a good balance of legibility vs prompt-token cost when fed to a
        multimodal LLM.
    max_pages
        Cap on the number of pages rendered (when ``page_indices`` is
        None) and on the number of indices honored (when it is set).
    page_indices
        Optional explicit 1-indexed page list. When provided,
        ``max_pages`` is applied AFTER filtering. Out-of-range values
        are silently skipped.
    render_images
        When False, only text is extracted; the returned page list is
        empty. Useful for ``--text-only`` callers that don't need the
        PIL/PyMuPDF image roundtrip cost.

    Returns
    -------
    (text, pages, total_pages)
        ``text`` is per-page concatenation with ``--- Page N/total ---``
        headers. ``pages`` is the list of :class:`PageImage`. Empty +
        empty + ``0`` if PyMuPDF is missing or the bytes won't parse —
        callers should handle the degraded case explicitly.
    """
    try:
        import fitz  # PyMuPDF
    except ImportError:
        logger.warning("PyMuPDF (fitz) not installed — pdf extract skipped")
        return "", [], 0

    text_parts: list[str] = []
    pages: list[PageImage] = []

    try:
        doc = fitz.open(stream=pdf_bytes, filetype="pdf")
    except Exception as exc:
        logger.warning("[pdf] open failed: %s", exc)
        return "", [], 0

    try:
        total_pages = len(doc)

        if page_indices is None:
            selected = list(range(1, min(total_pages, max_pages) + 1))
        else:
            seen: set[int] = set()
            selected = []
            for p in page_indices:
                if 1 <= p <= total_pages and p not in seen:
                    seen.add(p)
                    selected.append(p)
                if len(selected) >= max_pages:
                    break

        for page_no in selected:
            page = doc.load_page(page_no - 1)
            page_text = page.get_text()
            if page_text.strip():
                text_parts.append(
                    f"--- Page {page_no}/{total_pages} ---\n{page_text.strip()}"
                )
            if not render_images:
                continue
            try:
                mat = fitz.Matrix(dpi / 72, dpi / 72)
                pix = page.get_pixmap(matrix=mat)
                pages.append(PageImage(
                    page=page_no,
                    png_bytes=pix.tobytes("png"),
                    width=pix.width,
                    height=pix.height,
                ))
            except Exception as exc:
                logger.debug("[pdf] page %d render failed: %s", page_no, exc)
    finally:
        try:
            doc.close()
        except Exception:
            pass

    return "\n\n".join(text_parts), pages, total_pages
canvas-designanthropics/skillsCreate beautiful visual art in .png and .pdf documents using design philosophy. You should use this skill when the user asks to create a poster, piece of art, design, or other static piece. Create original visual designs, never copying existing artists' work to avoid copyright violations.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
docxanthropics/skillsUse this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include: any mention of 'Word doc', 'word document', '.docx', '.dotx', or requests to produce professional documents with formatting like tables of contents, headings, page numbers, or letterheads. Also use when extracting or reorganizing content from .docx or .dotx files, inserting or replacing images in documents, performing find-and-replace in Word files, working with tracked changes or comments, or converting content into a polished Word document. If the user asks for a 'report', 'memo', 'letter', 'template', or similar deliverable as a Word or .docx file, use this skill. Do NOT use for PDFs, spreadsheets, Google Docs, or general coding tasks unrelated to document generation.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
pdfanthropics/skillsUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple PDFs into one, splitting PDFs apart, rotating pages, adding watermarks, creating new PDFs, filling PDF forms, encrypting/decrypting PDFs, extracting images, and OCR on scanned PDFs to make them searchable. If the user mentions a .pdf file or asks to produce one, use this skill.Stars: 198kUpdated Claude CodeCodexVerifiedInstall
pptxanthropics/skillsUse this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or presentations; reading, parsing, or extracting text from any .pptx or .potx file (even if the extracted content will be used elsewhere, like in an email or summary); editing, modifying, or updating existing presentations; combining or splitting slide files; working with templates (.potx), layouts, speaker notes, or comments. Trigger whenever the user mentions "deck," "slides," "presentation," or references a .pptx or .potx filename, regardless of what they plan to do with the content afterward. If a .pptx or .potx file needs to be opened, created, or touched, use this skill.Stars: 198kUpdated Claude CodeCodexVerifiedInstall