Article Title
Main content here.
### Install Pypub using pip Source: https://github.com/imgurbot12/pypub/blob/master/README.md This command installs the pypub3 package, which is a Python library for creating EPUB files. It has minimal dependencies. ```bash pip install pypub3 ``` -------------------------------- ### Create Chapters from URLs Source: https://context7.com/imgurbot12/pypub/llms.txt Shows how to fetch web content and convert it into ebook chapters. It includes examples for basic extraction and advanced usage with custom XPath selectors. ```python import pypub # Basic URL chapter chapter = pypub.create_chapter_from_url(url='https://en.wikipedia.org/wiki/EPUB') # URL chapter with custom title and content extraction chapter = pypub.create_chapter_from_url( url='https://example.com/article', title='Custom Article Title', title_xpath='.//article//h1', content_xpath='.//article//div[@class="content"]' ) # Create an ebook from multiple web articles book = pypub.Epub('Web Articles Collection', creator='Various Authors') urls = ['https://example.com/article1', 'https://example.com/article2', 'https://example.com/article3'] for url in urls: try: chapter = pypub.create_chapter_from_url(url) book.add_chapter(chapter) except Exception as e: print(f'Failed to add {url}: {e}') book.create('./web-collection.epub') ``` -------------------------------- ### Create and Configure Epub Object with Pypub Source: https://context7.com/imgurbot12/pypub/llms.txt Demonstrates how to instantiate an Epub object with basic and comprehensive metadata. It shows adding a chapter and generating the EPUB file. Requires the pypub library. ```python import pypub # Basic epub creation with just a title book = pypub.Epub('My Ebook Title') # Full epub creation with all metadata options book = pypub.Epub( title='The Complete Guide', creator='John Doe', language='en', rights='Copyright 2024', publisher='My Publishing House', cover='/path/to/cover.png', # Optional custom cover image css_paths=['/path/to/custom.css'], # Optional custom CSS files extern_links=True # Convert relative links to absolute ) # Add chapters and generate the epub chapter = pypub.create_chapter_from_text('Hello World!', title='Introduction') book.add_chapter(chapter) output_path = book.create('./my-ebook.epub') print(f'Epub created at: {output_path}') ``` -------------------------------- ### Creating an EPUB from Multiple File Sources Source: https://context7.com/imgurbot12/pypub/llms.txt Demonstrates how to combine HTML, TXT, and DOCX files into a single EPUB ebook. ```APIDOC ## Creating an EPUB from Multiple File Sources ### Description This section shows how to create an EPUB ebook by adding chapters from different file formats like HTML, TXT, and DOCX. ### Method ```python import pypub # Assuming chapter_html, chapter_txt, chapter_docx are pre-defined chapter objects or content # For example: # chapter_html = pypub.create_chapter_from_html(b'
HTML Content
', title='HTML Chapter') # chapter_txt = pypub.create_chapter_from_txt('Plain text content.', title='TXT Chapter') # chapter_docx = pypub.create_chapter_from_docx('path/to/document.docx', title='DOCX Chapter') # Create a new EPUB with a title book = pypub.Epub('Multi-Source Book') # Add chapters from different sources # book.add_chapter(chapter_html) # book.add_chapter(chapter_txt) # book.add_chapter(chapter_docx) # Create the EPUB file # book.create('./multi-source.epub') ``` ### Parameters * **Epub(title)**: Initializes an Epub object with a given title. * **add_chapter(chapter)**: Adds a chapter to the ebook. * **create(output_path)**: Generates the EPUB file at the specified path. ``` -------------------------------- ### Combine Multiple File Sources into an EPUB Source: https://context7.com/imgurbot12/pypub/llms.txt Demonstrates how to initialize an Epub object and add chapters from various file formats (HTML, TXT, DOCX) before finalizing the ebook. ```python book = pypub.Epub('Multi-Source Book') book.add_chapter(chapter_html) book.add_chapter(chapter_txt) book.add_chapter(chapter_docx) book.create('./multi-source.epub') ``` -------------------------------- ### Configure Epub Generation with EpubSpec Source: https://context7.com/imgurbot12/pypub/llms.txt Demonstrates how to create a fully configured Epub object using the EpubSpec class. This includes setting metadata, cover image, build directory, external links, custom chapter factory, logger, and additional CSS files. It requires the pypub library and datetime module. ```python from pypub import Epub from pypub.factory import SimpleChapterFactory from datetime import datetime import logging # Configure logging to see build progress logging.basicConfig(level=logging.INFO) logger = logging.getLogger('my-epub-builder') # Create fully configured epub book = Epub( # Required title='Complete Configuration Example', # Metadata creator='John Smith', language='en', rights='Creative Commons BY-SA 4.0', publisher='Self Published', date=datetime(2024, 1, 15), # Cover image (None = auto-generate with title/author) cover='/path/to/my-cover.png', # Build directory (None = use temp directory) epub_dir=None, # Convert relative links to absolute URLs extern_links=True, # Custom chapter factory factory=SimpleChapterFactory(), # Custom logger logger=logger, # Additional CSS files to include css_paths=[ '/path/to/custom-fonts.css', '/path/to/custom-styles.css' ] ) ``` -------------------------------- ### Create a basic EPUB from a URL with Pypub Source: https://github.com/imgurbot12/pypub/blob/master/README.md This Python code snippet demonstrates how to create a simple EPUB file using the pypub library. It initializes an EPUB object, creates a chapter from a Wikipedia URL, adds the chapter to the EPUB, and saves the EPUB file. ```python import pypub my_first_epub = pypub.Epub('My First Epub') my_first_chapter = pypub.create_chapter_from_url('https://en.wikipedia.org/wiki/EPUB') my_first_epub.add_chapter(my_first_chapter) my_first_epub.create('./my-first-epub.epub') ``` -------------------------------- ### Create Epub Chapter from Local Files with Pypub Source: https://context7.com/imgurbot12/pypub/llms.txt Demonstrates creating ebook chapters from various local file types (.html, .txt, .docx) using pypub. It handles automatic conversion and allows for XPath-based content extraction. Requires pypub and optionally 'mammoth' for .docx files. ```python import pypub # Create chapter from an HTML file chapter_html = pypub.create_chapter_from_file( fpath='/path/to/chapter.html', title='Custom Title', # Optional: override file's title title_xpath='.//h1', # Optional: XPath to find title content_xpath='.//main' # Optional: XPath to find content ) # Create chapter from a text file (auto-converted to HTML) chapter_txt = pypub.create_chapter_from_file( fpath='/path/to/chapter.txt', title='Text File Chapter' ) # Create chapter from a Word document (requires mammoth package) # pip install mammoth chapter_docx = pypub.create_chapter_from_file( fpath='/path/to/document.docx', title='Word Document Chapter' ) ``` -------------------------------- ### Create Epub Chapter from Plain Text with Pypub Source: https://context7.com/imgurbot12/pypub/llms.txt Illustrates creating an ebook chapter from plain text using pypub. Each line is converted into an HTML paragraph, and empty lines preserve paragraph breaks. Requires the pypub library. ```python import pypub # Create chapter from plain text - each line becomes a paragraph text_content = """ This is the first paragraph of my text chapter. This is the second paragraph. Empty lines are preserved as paragraph breaks. The library automatically escapes HTML characters like <, >, and & to ensure valid output. """ chapter = pypub.create_chapter_from_text( text=text_content, title='My Text Chapter', url='https://example.com/source' # Optional source URL ) # Build a complete ebook from text book = pypub.Epub('Text Compilation', creator='Author Name') book.add_chapter(chapter) book.create('./text-book.epub') ``` -------------------------------- ### Epub Configuration API Source: https://context7.com/imgurbot12/pypub/llms.txt Configures and initializes an EPUB book object with metadata, styling, and custom factory settings. ```APIDOC ## POST /api/epub/create ### Description Initializes a new EPUB document with specified metadata, cover images, and styling configurations. ### Method POST ### Endpoint /api/epub/create ### Parameters #### Request Body - **title** (string) - Required - The title of the EPUB book. - **creator** (string) - Optional - The author of the book. - **language** (string) - Optional - ISO language code. - **cover** (string) - Optional - Path to the cover image file. - **css_paths** (list) - Optional - List of paths to custom CSS files. - **extern_links** (boolean) - Optional - Whether to convert relative links to absolute URLs. ### Request Example { "title": "My Book", "creator": "John Doe", "language": "en", "extern_links": true } ### Response #### Success Response (200) - **status** (string) - Success message. - **book_id** (string) - Unique identifier for the created book instance. #### Response Example { "status": "success", "book_id": "epub_12345" } ``` -------------------------------- ### Create Epub Chapter from HTML Content with Pypub Source: https://context7.com/imgurbot12/pypub/llms.txt Shows how to create an ebook chapter from raw HTML content using pypub. Supports basic HTML and advanced usage with XPath for extracting specific elements. Requires the pypub library. ```python import pypub # Basic HTML chapter html_content = b'''This is the first paragraph of my chapter.
This is the second paragraph with bold text.
''' chapter = pypub.create_chapter_from_html( html=html_content, title='Chapter One', # Optional: override title from HTML url='https://example.com/chapter1' # Optional: source URL for relative links ) # Using XPath to extract specific content html_with_article = b'''Main content here.
This is raw HTML content.
', url='https://example.com/source' ) print(f'Title: {chapter.title}') print(f'Content length: {len(chapter.content)} bytes') ``` -------------------------------- ### Implement Custom Chapter Factory Source: https://context7.com/imgurbot12/pypub/llms.txt Extends the SimpleChapterFactory to customize HTML cleaning and image rendering processes during ebook creation. ```python from pypub import Epub, SimpleChapterFactory from pypub.factory import RenderCtx, render_images class CustomChapterFactory(SimpleChapterFactory): def cleanup_html(self, content: bytes): etree = super().cleanup_html(content) for p in etree.xpath('.//p'): p.attrib['class'] = 'custom-paragraph' return etree def hydrate(self, ctx: RenderCtx): render_images(ctx) book = Epub(title='Custom Processed Book', creator='Author', factory=CustomChapterFactory()) chapter = pypub.create_chapter_from_url('https://example.com/article') book.add_chapter(chapter) book.create('./custom-processed.epub') ``` -------------------------------- ### Creating Chapters from URLs Source: https://context7.com/imgurbot12/pypub/llms.txt Explains how to download and process web pages into ebook chapters, including automatic title extraction and custom content selection using XPath. ```APIDOC ## Creating Chapters from URLs ### Description The `create_chapter_from_url()` function downloads and processes web pages into ebook chapters. It handles HTTP requests, extracts content, downloads images, and converts relative links. ### Method ```python import pypub # Basic URL chapter - automatically extracts title from page chapter = pypub.create_chapter_from_url( url='https://en.wikipedia.org/wiki/EPUB' ) # URL chapter with custom title and content extraction chapter = pypub.create_chapter_from_url( url='https://example.com/article', title='Custom Article Title', title_xpath='.//article//h1', # XPath to find title element content_xpath='.//article//div[@class="content"]' # XPath to find main content ) # Create an ebook from multiple web articles book = pypub.Epub('Web Articles Collection', creator='Various Authors') urls = [ 'https://example.com/article1', 'https://example.com/article2', 'https://example.com/article3' ] for url in urls: try: chapter = pypub.create_chapter_from_url(url) book.add_chapter(chapter) print(f'Added: {chapter.title}') except Exception as e: print(f'Failed to add {url}: {e}') book.create('./web-collection.epub') ``` ### Parameters * **create_chapter_from_url(url, title=None, title_xpath=None, content_xpath=None)**: * `url` (string) - Required - The URL of the web page to process. * `title` (string) - Optional - A custom title for the chapter. * `title_xpath` (string) - Optional - XPath expression to extract the chapter title from the page. * `content_xpath` (string) - Optional - XPath expression to extract the main content of the chapter. ``` -------------------------------- ### Using EpubBuilder for Advanced Control Source: https://context7.com/imgurbot12/pypub/llms.txt Introduces the `EpubBuilder` class for fine-grained control over the EPUB generation process, including incremental rendering and access to the build directory. ```APIDOC ## Using EpubBuilder for Advanced Control ### Description The `EpubBuilder` class provides fine-grained control over the epub generation process, allowing you to render chapters incrementally and access the build directory. ### Method ```python import pypub from pypub import Epub, Assignment from pypub.chapter import create_chapter_from_html # Create epub specification book = Epub( title='Advanced Book', creator='Author Name', language='en', publisher='My Publisher' ) # Use builder as context manager for automatic cleanup with book.builder as builder: # Begin building - creates directory structure dirs = builder.begin() print(f'Building epub at: {dirs.basedir}') print(f'OEBPS directory: {dirs.oebps}') print(f'Images directory: {dirs.images}') # Manually create and render chapters for i in range(1, 4): html = f'Content for chapter {i}
'.encode() chapter = create_chapter_from_html(html, title=f'Chapter {i}') # Get assignment and render assignment = book.assign_chapter() builder.render_chapter(assignment, chapter) # Finalize and compress to epub output_path = builder.finalize('./advanced-book.epub') print(f'Created: {output_path}') # Alternative: manual cleanup book2 = Epub('Manual Cleanup Book') try: book2.builder.begin() chapter = create_chapter_from_html(b'Content
', title='Chapter') book2.add_chapter(chapter) book2.create('./manual-book.epub') finally: book2.builder.cleanup() ``` ### Parameters * **Epub(title, creator, language, publisher)**: Initializes an Epub object with metadata. * **book.builder**: Accesses the EpubBuilder instance. * **builder.begin()**: Initializes the build process and returns directory paths. * **builder.render_chapter(assignment, chapter)**: Renders a chapter to the build directory. * **builder.finalize(output_path)**: Compresses the build directory into an EPUB file. * **builder.cleanup()**: Cleans up the build directory. ``` -------------------------------- ### Custom Chapter Factory Source: https://context7.com/imgurbot12/pypub/llms.txt Explains how to create a custom `ChapterFactory` to modify the HTML cleaning, processing, and rendering pipeline. ```APIDOC ## Custom Chapter Factory ### Description The `ChapterFactory` protocol allows customization of how HTML is cleaned, processed, and rendered. The `SimpleChapterFactory` is the default implementation. ### Method ```python import pypub from pypub import Epub, ChapterFactory, SimpleChapterFactory from pypub.factory import RenderCtx, render_images, xmlprettify, SUPPORTED_TAGS import pyxml.html class CustomChapterFactory(SimpleChapterFactory): """Custom factory with additional HTML processing""" def cleanup_html(self, content: bytes): """Override to customize HTML cleaning""" # Call parent implementation etree = super().cleanup_html(content) # Add custom processing - e.g., add class to all paragraphs for p in etree.xpath('.//p'): p.attrib['class'] = 'custom-paragraph' return etree def hydrate(self, ctx: RenderCtx): """Override to customize image rendering and link processing""" # Download and embed images render_images(ctx) # Add custom processing here # e.g., remove all images: # for img in ctx.etree.xpath('.//img'): # img.getparent().remove(img) # Use custom factory book = Epub( title='Custom Processed Book', creator='Author', factory=CustomChapterFactory() ) chapter = pypub.create_chapter_from_url('https://example.com/article') book.add_chapter(chapter) book.create('./custom-processed.epub') ``` ### Parameters * **CustomChapterFactory(SimpleChapterFactory)**: Inherits from `SimpleChapterFactory` to override methods. * **cleanup_html(content)**: Processes the raw HTML content before rendering. * **hydrate(ctx)**: Processes the parsed HTML tree (etree) for rendering, including image embedding and link processing. ``` -------------------------------- ### Advanced EPUB Generation with EpubBuilder Source: https://context7.com/imgurbot12/pypub/llms.txt Utilizes the EpubBuilder class for granular control over the build process, including directory management and manual chapter rendering. ```python import pypub from pypub import Epub, Assignment from pypub.chapter import create_chapter_from_html book = Epub(title='Advanced Book', creator='Author Name', language='en', publisher='My Publisher') with book.builder as builder: dirs = builder.begin() for i in range(1, 4): html = f'Content for chapter {i}
'.encode() chapter = create_chapter_from_html(html, title=f'Chapter {i}') assignment = book.assign_chapter() builder.render_chapter(assignment, chapter) output_path = builder.finalize('./advanced-book.epub') ``` -------------------------------- ### View Supported HTML Tags in Pypub Source: https://context7.com/imgurbot12/pypub/llms.txt This snippet shows how to access and print the SUPPORTED_TAGS dictionary from pypub.factory. This dictionary defines which HTML tags and attributes are preserved during the HTML sanitization process for ebook compatibility. It requires the SUPPORTED_TAGS object from pypub.factory. ```python from pypub.factory import SUPPORTED_TAGS # View all supported tags print('Supported HTML tags:') for tag, attrs in sorted(SUPPORTED_TAGS.items()): print(f' <{tag}> - attributes: {attrs if attrs else "(none)"}' ) ``` -------------------------------- ### Print Chapter Representation Source: https://context7.com/imgurbot12/pypub/llms.txt This code snippet demonstrates how to print the string representation of a chapter object, which typically shows summary information like title, URL, and content length. It assumes a 'chapter' object is already defined. ```python print(repr(chapter)) ``` -------------------------------- ### HTML Sanitization API Source: https://context7.com/imgurbot12/pypub/llms.txt Retrieves the list of supported HTML tags and attributes allowed during the EPUB generation process. ```APIDOC ## GET /api/epub/supported-tags ### Description Returns the configuration dictionary defining which HTML tags and attributes are preserved during content sanitization. ### Method GET ### Endpoint /api/epub/supported-tags ### Parameters None ### Request Example GET /api/epub/supported-tags ### Response #### Success Response (200) - **tags** (object) - A map of tags to their allowed attributes. #### Response Example { "tags": { "p": ["align", "id"], "img": ["src", "width", "height"] } } ``` -------------------------------- ### Chapter Data Class Source: https://context7.com/imgurbot12/pypub/llms.txt Describes the `Chapter` data class, which holds the title, HTML content, and optional source URL for each chapter. ```APIDOC ## Chapter Data Class ### Description The `Chapter` class is a dataclass that holds chapter information. It stores the title, HTML content as bytes, and an optional source URL. ### Method ```python from pypub.chapter import Chapter # Create a chapter directly chapter = Chapter( title='Direct Chapter', content=b'This is raw HTML content.
', url='https://example.com/source' # Optional: used for resolving relative links ) # Access chapter properties print(f'Title: {chapter.title}') print(f'Content length: {len(chapter.content)} bytes') print(f'Source URL: {chapter.url}') ``` ### Parameters * **Chapter(title, content, url=None)**: * `title` (string) - The title of the chapter. * `content` (bytes) - The HTML content of the chapter as bytes. * `url` (string) - Optional - The source URL of the chapter, used for resolving relative links. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.