Skip to content

K-Dense-AI/scientific-agent-skills / skills/scientific-slides

scientific-slides

Verified

Builds slide decks and presentations for research talks. Used for making PowerPoint slides, conference presentations, seminar talks, research presentations, thesis defense slides, or any scientific talk. Provides slide structure, design templates, timing guidance, and visual validation. Works with PowerPoint and LaTeX Beamer.

scripts/pdf_to_images.py

View on GitHub
#!/usr/bin/env python3
"""
PDF to Images Converter for Presentations

Converts presentation PDFs to images for visual inspection and review.
Supports multiple output formats and resolutions.

Uses PyMuPDF (fitz) as the primary conversion method - no external
dependencies required (no poppler, ghostscript, or ImageMagick needed).
"""

import sys
import argparse
from pathlib import Path
from typing import Optional, List

# Try to import pymupdf (preferred - no external dependencies)
try:
    import pymupdf as fitz  # Avoid the unrelated PyPI package named fitz
    HAS_PYMUPDF = True
except ImportError:
    HAS_PYMUPDF = False


class PDFToImagesConverter:
    """Converts PDF presentations to images."""
    
    def __init__(
        self,
        pdf_path: str,
        output_prefix: str,
        dpi: int = 150,
        format: str = 'jpg',
        first_page: Optional[int] = None,
        last_page: Optional[int] = None
    ):
        self.pdf_path = Path(pdf_path)
        self.output_prefix = output_prefix
        self.dpi = dpi
        self.format = format.lower()
        self.first_page = first_page
        self.last_page = last_page
        
        if dpi <= 0:
            raise ValueError("dpi must be positive")
        if first_page is not None and first_page < 1:
            raise ValueError("first_page must be at least 1")
        if last_page is not None and last_page < 1:
            raise ValueError("last_page must be at least 1")
        if first_page is not None and last_page is not None and first_page > last_page:
            raise ValueError("first_page must not exceed last_page")

        # Validate format
        if self.format not in ['jpg', 'jpeg', 'png']:
            raise ValueError(f"Unsupported format: {format}. Use jpg or png.")
    
    def convert(self) -> List[Path]:
        """Convert PDF to images using PyMuPDF."""
        if not self.pdf_path.exists():
            raise FileNotFoundError(f"PDF not found: {self.pdf_path}")
        
        print(f"Converting: {self.pdf_path.name}")
        print(f"Output prefix: {self.output_prefix}")
        print(f"DPI: {self.dpi}")
        print(f"Format: {self.format}")
        
        if HAS_PYMUPDF:
            return self._convert_with_pymupdf()
        else:
            raise RuntimeError(
                "PyMuPDF not installed. Install it with:\n"
                "  uv pip install pymupdf\n\n"
                "PyMuPDF is a self-contained library - no external dependencies needed."
            )
    
    def _convert_with_pymupdf(self) -> List[Path]:
        """Convert using PyMuPDF library (no external dependencies)."""
        print("Using PyMuPDF (no external dependencies required)...")
        
        with fitz.open(self.pdf_path) as doc:
            start_page = self.first_page - 1 if self.first_page is not None else 0
            end_page = self.last_page if self.last_page is not None else doc.page_count
            if not 0 <= start_page < end_page <= doc.page_count:
                raise ValueError(f"Page range must be within 1-{doc.page_count}")
            output_files = []
            Path(self.output_prefix).parent.mkdir(parents=True, exist_ok=True)
            for page_num in range(start_page, end_page):
                # dpi records resolution metadata as well as setting pixel dimensions.
                pixmap = doc[page_num].get_pixmap(dpi=self.dpi)
                output_path = Path(f"{self.output_prefix}-{page_num + 1:03d}.{self.format}")
                pixmap.save(str(output_path), output="jpeg" if self.format in ("jpg", "jpeg") else "png")
                output_files.append(output_path)
                print(f"  Created: {output_path.name}")
            return output_files


def main():
    parser = argparse.ArgumentParser(
        description='Convert presentation PDFs to images',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog="""
Examples:
  %(prog)s presentation.pdf slides
    -> Creates slides-001.jpg, slides-002.jpg, ...
  
  %(prog)s presentation.pdf output/slide --dpi 300 --format png
    -> Creates output/slide-001.png, slide-002.png, ... at high resolution
  
  %(prog)s presentation.pdf review/s --first 5 --last 10
    -> Converts only slides 5-10

Output:
  Images are named: PREFIX-001.FORMAT, PREFIX-002.FORMAT, etc.
  
Resolution:
  - 150 DPI: Good for screen review (default)
  - 200 DPI: Higher quality for detailed inspection
  - 300 DPI: Print quality (larger files)

Requirements:
  Install PyMuPDF (no external dependencies needed):
    uv pip install pymupdf
        """
    )
    
    parser.add_argument(
        'pdf_path',
        help='Path to PDF presentation'
    )
    
    parser.add_argument(
        'output_prefix',
        help='Output filename prefix (e.g., "slides" or "output/slide")'
    )
    
    parser.add_argument(
        '--dpi', '-r',
        type=int,
        default=150,
        help='Resolution in DPI (default: 150)'
    )
    
    parser.add_argument(
        '--format', '-f',
        choices=['jpg', 'jpeg', 'png'],
        default='jpg',
        help='Output format (default: jpg)'
    )
    
    parser.add_argument(
        '--first',
        type=int,
        help='First page to convert (1-indexed)'
    )
    
    parser.add_argument(
        '--last',
        type=int,
        help='Last page to convert (1-indexed)'
    )
    
    args = parser.parse_args()
    
    # Create output directory if needed
    output_dir = Path(args.output_prefix).parent
    if output_dir != Path('.'):
        output_dir.mkdir(parents=True, exist_ok=True)
    
    # Convert
    try:
        converter = PDFToImagesConverter(
            pdf_path=args.pdf_path,
            output_prefix=args.output_prefix,
            dpi=args.dpi,
            format=args.format,
            first_page=args.first,
            last_page=args.last
        )
        
        output_files = converter.convert()
        
        print()
        print("=" * 60)
        print(f"[OK] Success! Created {len(output_files)} image(s)")
        print("=" * 60)
        
        if output_files:
            print(f"\nFirst image: {output_files[0]}")
            print(f"Last image: {output_files[-1]}")
            
            # Calculate total size
            total_size = sum(f.stat().st_size for f in output_files)
            size_mb = total_size / (1024 * 1024)
            print(f"Total size: {size_mb:.2f} MB")
            
            print("\nNext steps:")
            print("  1. Review images for layout issues")
            print("  2. Check for text overflow or element overlap")
            print("  3. Verify readability from distance")
            print("  4. Document issues with slide numbers")
        
        sys.exit(0)
        
    except Exception as e:
        print(f"\n[FAIL] Error: {str(e)}", file=sys.stderr)
        sys.exit(1)


if __name__ == '__main__':
    main()
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