Update repo
Python CI / test (push) Failing after 6m22s

This commit is contained in:
2025-11-04 19:25:44 +01:00
parent 25e7f1423e
commit 993095caf9
10 changed files with 525 additions and 59 deletions
+71
View File
@@ -0,0 +1,71 @@
# PyWebLayout Examples
This directory contains example scripts demonstrating the pyWebLayout library.
## EbookReader Examples
The EbookReader provides a high-level, user-friendly API for building ebook reader applications.
### Quick Start Example
**`simple_ereader_example.py`** - Simple example showing basic EbookReader usage:
```bash
python simple_ereader_example.py path/to/book.epub
```
This demonstrates:
- Loading an EPUB file
- Rendering pages to images
- Basic navigation (next/previous page)
- Saving positions
- Chapter navigation
- Font size adjustment
### Comprehensive Demo
**`ereader_demo.py`** - Full feature demonstration:
```bash
python ereader_demo.py path/to/book.epub
```
This showcases all EbookReader features:
- Page navigation (forward/backward)
- Position save/load with bookmarks
- Chapter navigation (by index or title)
- Font size control
- Line and block spacing adjustments
- Reading progress tracking
- Book information retrieval
**Tip:** You can use the test EPUB files in `tests/data/` for testing:
```bash
python simple_ereader_example.py tests/data/test.epub
python ereader_demo.py tests/data/test.epub
```
## Other Examples
### HTML Rendering
These examples demonstrate rendering HTML content to multi-page layouts:
**`html_line_breaking_demo.py`** - Basic HTML line breaking demonstration
**`html_multipage_simple.py`** - Simple single-page HTML rendering
**`html_multipage_demo.py`** - Multi-page HTML layout
**`html_multipage_demo_final.py`** - Complete multi-page HTML rendering with headers/footers
For detailed information about HTML rendering, see `README_HTML_MULTIPAGE.md`.
### Advanced Topics
**`recursive_position_demo.py`** - Demonstrates the recursive position tracking system
## Documentation
- `README_EREADER.md` - Detailed EbookReader API documentation
- `README_HTML_MULTIPAGE.md` - HTML multi-page rendering guide
- `pyWebLayout/layout/README_EREADER_API.md` - EbookReader API reference (in source)
## Debug/Development Scripts
Low-level debug and rendering scripts have been moved to the `scripts/` directory.
+363
View File
@@ -0,0 +1,363 @@
# EbookReader - Simple EPUB Reader Application
The `EbookReader` class provides a complete, user-friendly interface for building ebook reader applications with pyWebLayout. It wraps all the complex ereader infrastructure into a simple API.
## Features
- 📖 **EPUB Loading** - Load EPUB files with automatic content extraction
- ⬅️➡️ **Page Navigation** - Forward and backward page navigation
- 🔖 **Position Management** - Save/load reading positions (stable across font changes)
- 📑 **Chapter Navigation** - Jump to chapters by title or index
- 🔤 **Font Size Control** - Increase/decrease font size with live re-rendering
- 📏 **Spacing Control** - Adjust line and block spacing
- 📊 **Progress Tracking** - Get reading progress and position information
- 💾 **Context Manager Support** - Automatic cleanup with `with` statement
## Quick Start
```python
from pyWebLayout.layout.ereader_application import EbookReader
# Create reader
reader = EbookReader(page_size=(800, 1000))
# Load an EPUB
reader.load_epub("mybook.epub")
# Get current page as PIL Image
page_image = reader.get_current_page()
page_image.save("current_page.png")
# Navigate
reader.next_page()
reader.previous_page()
# Close reader
reader.close()
```
## API Reference
### Initialization
```python
reader = EbookReader(
page_size=(800, 1000), # Page dimensions (width, height) in pixels
margin=40, # Page margin in pixels
background_color=(255, 255, 255), # RGB background color
line_spacing=5, # Line spacing in pixels
inter_block_spacing=15, # Space between blocks in pixels
bookmarks_dir="ereader_bookmarks", # Directory for bookmarks
buffer_size=5 # Number of pages to cache
)
```
### Loading EPUB
```python
# Load EPUB file
success = reader.load_epub("path/to/book.epub")
# Check if book is loaded
if reader.is_loaded():
print("Book loaded successfully")
# Get book information
book_info = reader.get_book_info()
# Returns: {
# 'title': 'Book Title',
# 'author': 'Author Name',
# 'document_id': 'book',
# 'total_blocks': 5000,
# 'total_chapters': 20,
# 'page_size': (800, 1000),
# 'font_scale': 1.0
# }
```
### Page Navigation
```python
# Get current page as PIL Image
page = reader.get_current_page()
# Navigate to next page
page = reader.next_page() # Returns None at end of book
# Navigate to previous page
page = reader.previous_page() # Returns None at beginning
# Save current page to file
reader.render_to_file("page.png")
```
### Position Management
Positions are saved based on abstract document structure (chapter/block/word indices), making them stable across font size and styling changes.
```python
# Save current position
reader.save_position("my_bookmark")
# Load saved position
page = reader.load_position("my_bookmark")
# List all saved positions
positions = reader.list_saved_positions()
# Returns: ['my_bookmark', 'chapter_2', ...]
# Delete a position
reader.delete_position("my_bookmark")
# Get detailed position info
info = reader.get_position_info()
# Returns: {
# 'position': {'chapter_index': 0, 'block_index': 42, 'word_index': 15, ...},
# 'chapter': {'title': 'Chapter 1', 'level': 'H1', ...},
# 'progress': 0.15, # 15% through the book
# 'font_scale': 1.0,
# 'book_title': 'Book Title',
# 'book_author': 'Author Name'
# }
# Get reading progress (0.0 to 1.0)
progress = reader.get_reading_progress()
print(f"You're {progress*100:.1f}% through the book")
```
### Chapter Navigation
```python
# Get all chapters
chapters = reader.get_chapters()
# Returns: [('Chapter 1', 0), ('Chapter 2', 1), ...]
# Get chapters with positions
chapter_positions = reader.get_chapter_positions()
# Returns: [('Chapter 1', RenderingPosition(...)), ...]
# Jump to chapter by index
page = reader.jump_to_chapter(1) # Jump to second chapter
# Jump to chapter by title
page = reader.jump_to_chapter("Chapter 1")
# Get current chapter info
chapter_info = reader.get_current_chapter_info()
# Returns: {'title': 'Chapter 1', 'level': HeadingLevel.H1, 'block_index': 0}
```
### Font Size Control
```python
# Get current font size scale
scale = reader.get_font_size() # Default: 1.0
# Set specific font size scale
page = reader.set_font_size(1.5) # 150% of normal size
# Increase font size by 10%
page = reader.increase_font_size()
# Decrease font size by 10%
page = reader.decrease_font_size()
```
### Spacing Control
```python
# Set line spacing (spacing between lines within a paragraph)
page = reader.set_line_spacing(10) # 10 pixels
# Set inter-block spacing (spacing between paragraphs, headings, etc.)
page = reader.set_inter_block_spacing(20) # 20 pixels
```
### Context Manager
The reader supports Python's context manager protocol for automatic cleanup:
```python
with EbookReader(page_size=(800, 1000)) as reader:
reader.load_epub("book.epub")
page = reader.get_current_page()
# ... do stuff
# Automatically saves position and cleans up resources
```
## Complete Example
```python
from pyWebLayout.layout.ereader_application import EbookReader
# Create reader with custom settings
with EbookReader(
page_size=(800, 1000),
margin=50,
line_spacing=8,
inter_block_spacing=20
) as reader:
# Load EPUB
if not reader.load_epub("my_novel.epub"):
print("Failed to load EPUB")
exit(1)
# Get book info
info = reader.get_book_info()
print(f"Reading: {info['title']} by {info['author']}")
print(f"Total chapters: {info['total_chapters']}")
# Navigate through first few pages
for i in range(5):
page = reader.get_current_page()
page.save(f"page_{i+1:03d}.png")
reader.next_page()
# Save current position
reader.save_position("page_5")
# Jump to a chapter
chapters = reader.get_chapters()
if len(chapters) > 2:
print(f"Jumping to: {chapters[2][0]}")
reader.jump_to_chapter(2)
reader.render_to_file("chapter_3_start.png")
# Return to saved position
reader.load_position("page_5")
# Adjust font size
reader.increase_font_size()
reader.render_to_file("page_5_larger_font.png")
# Get progress
progress = reader.get_reading_progress()
print(f"Reading progress: {progress*100:.1f}%")
```
## Demo Script
Run the comprehensive demo to see all features in action:
```bash
python examples/ereader_demo.py path/to/book.epub
```
This will demonstrate:
- Basic page navigation
- Position save/load
- Chapter navigation
- Font size adjustments
- Spacing adjustments
- Book information retrieval
The demo generates multiple PNG files showing different pages and settings.
## Position Storage Format
Positions are stored as JSON files in the `bookmarks_dir` (default: `ereader_bookmarks/`):
```json
{
"chapter_index": 0,
"block_index": 42,
"word_index": 15,
"table_row": 0,
"table_col": 0,
"list_item_index": 0,
"remaining_pretext": null,
"page_y_offset": 0
}
```
This format is tied to the abstract document structure, making positions stable across:
- Font size changes
- Line spacing changes
- Inter-block spacing changes
- Page size changes
## Integration Example: Simple GUI
Here's a minimal example of integrating with Tkinter:
```python
import tkinter as tk
from tkinter import filedialog
from PIL import ImageTk
from pyWebLayout.layout.ereader_application import EbookReader
class SimpleEreaderGUI:
def __init__(self, root):
self.root = root
self.reader = EbookReader(page_size=(600, 800))
# Create UI
self.image_label = tk.Label(root)
self.image_label.pack()
btn_frame = tk.Frame(root)
btn_frame.pack()
tk.Button(btn_frame, text="Open EPUB", command=self.open_epub).pack(side=tk.LEFT)
tk.Button(btn_frame, text="Previous", command=self.prev_page).pack(side=tk.LEFT)
tk.Button(btn_frame, text="Next", command=self.next_page).pack(side=tk.LEFT)
tk.Button(btn_frame, text="Font+", command=self.increase_font).pack(side=tk.LEFT)
tk.Button(btn_frame, text="Font-", command=self.decrease_font).pack(side=tk.LEFT)
def open_epub(self):
filepath = filedialog.askopenfilename(filetypes=[("EPUB files", "*.epub")])
if filepath:
self.reader.load_epub(filepath)
self.display_page()
def display_page(self):
page = self.reader.get_current_page()
if page:
photo = ImageTk.PhotoImage(page)
self.image_label.config(image=photo)
self.image_label.image = photo
def next_page(self):
if self.reader.next_page():
self.display_page()
def prev_page(self):
if self.reader.previous_page():
self.display_page()
def increase_font(self):
self.reader.increase_font_size()
self.display_page()
def decrease_font(self):
self.reader.decrease_font_size()
self.display_page()
root = tk.Tk()
root.title("Simple Ereader")
app = SimpleEreaderGUI(root)
root.mainloop()
```
## Performance Notes
- The reader uses intelligent page caching for fast navigation
- First page load may take ~1 second, subsequent pages are typically < 0.1 seconds
- Background rendering attempts to pre-cache upcoming pages (you may see pickle warnings, which can be ignored)
- Font size changes invalidate the cache and require re-rendering from the current position
- Position save/load is nearly instantaneous
## Limitations
- Currently supports EPUB files only (no PDF, MOBI, etc.)
- Images in EPUBs may not render in some cases
- Tables are skipped in rendering
- Complex HTML layouts may not render perfectly
- No text selection or search functionality (these would need to be added separately)
## See Also
- `examples/ereader_demo.py` - Comprehensive feature demonstration
- `pyWebLayout/layout/ereader_manager.py` - Underlying manager class
- `pyWebLayout/layout/ereader_layout.py` - Core layout engine
- `examples/README_EPUB_RENDERERS.md` - Lower-level EPUB rendering
-434
View File
@@ -1,434 +0,0 @@
#!/usr/bin/env python3
"""
Simple EPUB page renderer tool.
This tool uses the pyWebLayout epub_reader and layout modules to:
1. Load an EPUB file
2. Render the first X pages according to command line arguments
3. Save the pages as PNG images
Usage:
python epub_page_renderer.py book.epub --pages 5 --output-dir rendered_pages
"""
import os
import sys
import argparse
from pathlib import Path
from typing import Optional, List
# Add the parent directory to sys.path to import pyWebLayout
sys.path.insert(0, str(Path(__file__).parent.parent))
try:
from pyWebLayout.io.readers.epub_reader import read_epub
from pyWebLayout.layout.ereader_layout import BidirectionalLayouter, RenderingPosition
from pyWebLayout.layout.document_layouter import paragraph_layouter
from pyWebLayout.concrete.page import Page
from pyWebLayout.style.page_style import PageStyle
from pyWebLayout.style.fonts import Font
from pyWebLayout.abstract.block import Block
from PIL import Image, ImageDraw
except ImportError as e:
print(f"Error importing required modules: {e}")
print("Make sure pyWebLayout is properly installed and PIL is available")
sys.exit(1)
def render_page_to_image(page: Page) -> Image.Image:
"""
Render a Page object to a PIL Image using pyWebLayout's built-in rendering.
Args:
page: The Page object to render
Returns:
PIL Image object
"""
try:
# Use the Page's built-in render method
rendered_image = page.render()
if isinstance(rendered_image, Image.Image):
return rendered_image
else:
# If render() doesn't return a PIL Image, create error image
error_image = Image.new('RGB', page.size, 'white')
draw = ImageDraw.Draw(error_image)
draw.text((20, 20), "Error: Page.render() did not return PIL Image", fill='red')
return error_image
except Exception as e:
# Create error image if rendering fails
error_image = Image.new('RGB', page.size, 'white')
draw = ImageDraw.Draw(error_image)
draw.text((20, 20), f"Rendering error: {str(e)}", fill='red')
print(f"Warning: Error rendering page: {e}")
return error_image
def extract_text_from_page(page: Page) -> str:
"""
Extract text content from a Page object for verification purposes.
Args:
page: The Page object to extract text from
Returns:
String containing the page's text content
"""
text_lines = []
text_lines.append(f"=== PAGE CONTENT ===")
text_lines.append("")
try:
# Recursively extract text from page children
def extract_from_element(element, indent_level=0):
indent = " " * indent_level
# Import abstract block types
from pyWebLayout.abstract.block import Paragraph, Heading, HList, Table, Image as AbstractImage
from pyWebLayout.concrete.text import Line
# Handle Line objects (concrete)
if isinstance(element, Line):
line_text = []
if hasattr(element, '_text_objects') and element._text_objects:
for text_obj in element._text_objects:
if hasattr(text_obj, 'text'):
line_text.append(str(text_obj.text))
if line_text:
text_lines.append(f"{indent}{' '.join(line_text)}")
# Handle abstract block objects
elif isinstance(element, (Paragraph, Heading)):
# Extract text from paragraph/heading
paragraph_text = extract_text_from_paragraph(element)
if paragraph_text:
block_type = "HEADING" if isinstance(element, Heading) else "PARAGRAPH"
text_lines.append(f"{indent}{block_type}: {paragraph_text}")
elif isinstance(element, HList):
text_lines.append(f"{indent}LIST:")
# Extract text from list items
try:
for item in element.items():
item_text = extract_text_from_paragraph(item)
if item_text:
text_lines.append(f"{indent} - {item_text}")
except:
text_lines.append(f"{indent} (List content extraction failed)")
elif isinstance(element, Table):
text_lines.append(f"{indent}[TABLE]")
elif isinstance(element, AbstractImage):
alt_text = getattr(element, 'alt_text', '')
src = getattr(element, 'source', 'Unknown')
text_lines.append(f"{indent}[IMAGE: {alt_text or src}]")
# Handle containers with children
elif hasattr(element, '_children') and element._children:
for child in element._children:
extract_from_element(child, indent_level + 1)
# Handle text elements
elif hasattr(element, 'text'):
text = str(element.text).strip()
if text:
text_lines.append(f"{indent}{text}")
# Handle other object types by showing their class name
else:
class_name = element.__class__.__name__
text_lines.append(f"{indent}[{class_name}]")
# Helper function to extract text from paragraph-like objects
def extract_text_from_paragraph(para_obj):
words = []
try:
# Try to get words from the paragraph
if hasattr(para_obj, 'words_iter') and callable(para_obj.words_iter):
for _, word in para_obj.words_iter():
if hasattr(word, 'text'):
words.append(word.text)
else:
words.append(str(word))
elif hasattr(para_obj, '_words'):
# Direct access to words list
for word in para_obj._words:
if hasattr(word, 'text'):
words.append(word.text)
else:
words.append(str(word))
except Exception as e:
return f"(Text extraction error: {str(e)})"
return ' '.join(words) if words else "(No text)"
# Extract text from page children
if hasattr(page, '_children'):
for child in page._children:
extract_from_element(child)
# If no text was extracted, add a note
if len(text_lines) <= 2: # Only header and empty line
text_lines.append("(No text content found)")
except Exception as e:
text_lines.append(f"Error extracting text: {str(e)}")
import traceback
text_lines.append(traceback.format_exc())
return "\n".join(text_lines)
def get_all_blocks_from_book(book) -> List[Block]:
"""
Extract all blocks from all chapters in the book.
Args:
book: The Book object from epub_reader
Returns:
List of all Block objects
"""
all_blocks = []
# Iterate through all chapters
for chapter in book.chapters:
# Get blocks from the chapter
if hasattr(chapter, '_blocks'):
all_blocks.extend(chapter._blocks)
return all_blocks
def main():
"""Main function to handle command line arguments and process the EPUB."""
parser = argparse.ArgumentParser(
description='Render EPUB pages to images using pyWebLayout',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python epub_page_renderer.py book.epub --pages 5
python epub_page_renderer.py book.epub --pages 10 --output-dir my_output --width 600 --height 800
"""
)
parser.add_argument(
'epub_file',
help='Path to the EPUB file to render'
)
parser.add_argument(
'--pages', '-p',
type=int,
default=5,
help='Number of pages to render (default: 5)'
)
parser.add_argument(
'--output-dir', '-o',
default='rendered_pages',
help='Output directory for rendered images (default: rendered_pages)'
)
parser.add_argument(
'--width', '-w',
type=int,
default=800,
help='Page width in pixels (default: 800)'
)
parser.add_argument(
'--height', '-t',
type=int,
default=1000,
help='Page height in pixels (default: 1000)'
)
parser.add_argument(
'--margin', '-m',
type=int,
default=40,
help='Page margin in pixels (default: 40)'
)
parser.add_argument(
'--align', '-a',
choices=['left', 'justify'],
default='left',
help='Text alignment: left or justify (default: left)'
)
args = parser.parse_args()
# Validate arguments
if not os.path.exists(args.epub_file):
print(f"Error: EPUB file '{args.epub_file}' not found")
return 1
if args.pages <= 0:
print("Error: Number of pages must be positive")
return 1
# Create output directory
try:
os.makedirs(args.output_dir, exist_ok=True)
except OSError as e:
print(f"Error creating output directory: {e}")
return 1
print(f"Loading EPUB file: {args.epub_file}")
# Load the EPUB file
try:
book = read_epub(args.epub_file)
print(f"Successfully loaded EPUB: {book.get_title() or 'Unknown Title'}")
# Print book information
author = book.get_metadata('AUTHOR')
if author:
print(f"Author: {author}")
print(f"Chapters: {len(book.chapters) if hasattr(book, 'chapters') else 'Unknown'}")
except Exception as e:
print(f"Error loading EPUB file: {e}")
import traceback
traceback.print_exc()
return 1
# Extract all blocks from the book
print("Extracting content blocks...")
try:
all_blocks = get_all_blocks_from_book(book)
print(f"Extracted {len(all_blocks)} content blocks")
if not all_blocks:
print("No content blocks found in EPUB. The book might be empty.")
return 1
# Apply alignment setting to all paragraphs and headings
from pyWebLayout.abstract.block import Paragraph, Heading
from pyWebLayout.style.alignment import Alignment
alignment = Alignment.JUSTIFY if args.align == 'justify' else Alignment.LEFT
print(f"Applying {args.align} alignment to all text blocks...")
# Note: We'll pass alignment to the layouter which will handle it during rendering
# The alignment is applied at the Line level in paragraph_layouter
except Exception as e:
print(f"Error extracting blocks: {e}")
import traceback
traceback.print_exc()
return 1
# Set up page style and layouter
page_size = (args.width, args.height)
page_style = PageStyle(
background_color=(255, 255, 255),
border_width=args.margin,
border_color=(200, 200, 200),
padding=(10, 10, 10, 10), # top, right, bottom, left
line_spacing=5,
inter_block_spacing=15
)
print(f"Setting up layouter with page size {page_size} and {args.align} alignment")
try:
layouter = BidirectionalLayouter(
blocks=all_blocks,
page_style=page_style,
page_size=page_size,
alignment_override=alignment
)
except Exception as e:
print(f"Error setting up layouter: {e}")
import traceback
traceback.print_exc()
return 1
# Render pages
print(f"Rendering up to {args.pages} pages...")
try:
pages = []
current_position = RenderingPosition() # Start from beginning
for page_num in range(args.pages):
print(f"Rendering page {page_num + 1}/{args.pages}...")
try:
# Render the page
page, next_position = layouter.render_page_forward(current_position)
pages.append(page)
# Check if we've reached the end of the document
if next_position.block_index >= len(all_blocks):
print(f"Reached end of document after {page_num + 1} pages")
break
# Update position for next page
current_position = next_position
except Exception as e:
print(f"Error rendering page {page_num + 1}: {e}")
import traceback
traceback.print_exc()
break
if not pages:
print("No pages were generated.")
return 1
print(f"Generated {len(pages)} pages")
# Save each page to an image and extract text
for i, page in enumerate(pages):
print(f"Saving page {i + 1}/{len(pages)}...")
try:
# Create image from page using pyWebLayout's built-in rendering
image = render_page_to_image(page)
# Save the image
output_filename = f"page_{i + 1:03d}.png"
output_path = os.path.join(args.output_dir, output_filename)
image.save(output_path, 'PNG')
# Extract and save text content for verification
page_text = extract_text_from_page(page)
text_filename = f"page_{i + 1:03d}.txt"
text_path = os.path.join(args.output_dir, text_filename)
with open(text_path, 'w', encoding='utf-8') as f:
f.write(page_text)
print(f"Saved: {output_path} and {text_path}")
except Exception as e:
print(f"Error saving page {i + 1}: {e}")
import traceback
traceback.print_exc()
continue
print(f"\nCompleted! Rendered {len(pages)} pages to {args.output_dir}")
# Calculate progress through the book
if len(all_blocks) > 0:
progress = (current_position.block_index / len(all_blocks)) * 100
print(f"Progress through book: {progress:.1f}%")
except Exception as e:
print(f"Error during pagination/rendering: {e}")
import traceback
traceback.print_exc()
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -1,380 +0,0 @@
#!/usr/bin/env python3
"""
EPUB page renderer using DocumentLayouter.
This tool uses pyWebLayout's DocumentLayouter to render EPUB content:
1. Load an EPUB file
2. Extract all blocks (paragraphs, images, etc.)
3. Use DocumentLayouter to layout blocks on pages
4. Save the pages as PNG images
Usage:
python epub_page_renderer_documentlayouter.py book.epub --pages 5 --output-dir rendered_pages
"""
import os
import sys
import argparse
from pathlib import Path
from typing import Optional, List, Tuple
# Add the parent directory to sys.path to import pyWebLayout
sys.path.insert(0, str(Path(__file__).parent.parent))
try:
from pyWebLayout.io.readers.epub_reader import read_epub
from pyWebLayout.layout.document_layouter import DocumentLayouter, paragraph_layouter, image_layouter
from pyWebLayout.concrete.page import Page
from pyWebLayout.style.page_style import PageStyle
from pyWebLayout.style.fonts import Font
from pyWebLayout.style.alignment import Alignment
from pyWebLayout.abstract.block import Block, Paragraph, Heading, HList, Table, Image as AbstractImage
from pyWebLayout.style.concrete_style import RenderingContext, StyleResolver
from PIL import Image, ImageDraw
except ImportError as e:
print(f"Error importing required modules: {e}")
print("Make sure pyWebLayout is properly installed and PIL is available")
sys.exit(1)
def get_all_blocks_from_book(book) -> List[Block]:
"""
Extract all blocks from all chapters in the book.
Args:
book: The Book object from epub_reader
Returns:
List of all Block objects
"""
all_blocks = []
# Iterate through all chapters
for chapter in book.chapters:
# Get blocks from the chapter
if hasattr(chapter, '_blocks'):
all_blocks.extend(chapter._blocks)
return all_blocks
def create_page(page_style: PageStyle, page_size: Tuple[int, int]) -> Page:
"""
Create a new Page with the given style and size.
Args:
page_style: Style configuration for the page
page_size: (width, height) tuple
Returns:
A new Page object
"""
page = Page(
size=page_size,
style=page_style
)
return page
def layout_blocks_on_pages(blocks: List[Block], page_style: PageStyle,
page_size: Tuple[int, int], max_pages: int,
alignment_override: Optional[Alignment] = None) -> List[Page]:
"""
Layout blocks across multiple pages using DocumentLayouter.
Args:
blocks: List of abstract blocks to layout
page_style: Style configuration for pages
page_size: (width, height) tuple for pages
max_pages: Maximum number of pages to generate
alignment_override: Optional alignment to override paragraph alignment
Returns:
List of rendered Page objects
"""
pages = []
current_block_index = 0
continuation_word_index = 0
continuation_pretext = None
# Create rendering context
rendering_context = RenderingContext(base_font_size=16)
while current_block_index < len(blocks) and len(pages) < max_pages:
# Create a new page
page = create_page(page_style, page_size)
page_has_content = False
# Try to layout blocks on this page
while current_block_index < len(blocks):
block = blocks[current_block_index]
if isinstance(block, (Paragraph, Heading)):
# Layout paragraph/heading
success, failed_word_index, remaining_pretext = paragraph_layouter(
block,
page,
start_word=continuation_word_index,
pretext=continuation_pretext,
alignment_override=alignment_override
)
if success:
# Block fully laid out, move to next block
page_has_content = True
current_block_index += 1
continuation_word_index = 0
continuation_pretext = None
else:
# Block partially laid out or page is full
if failed_word_index is not None:
# Partial layout - continue on next page
page_has_content = True
continuation_word_index = failed_word_index
continuation_pretext = remaining_pretext
# Break to create a new page
break
elif isinstance(block, AbstractImage):
# Layout image
success = image_layouter(block, page)
if success:
page_has_content = True
current_block_index += 1
continuation_word_index = 0
continuation_pretext = None
else:
# Image doesn't fit, try on next page
break
elif isinstance(block, HList):
# Layout list items as paragraphs
try:
list_items = list(block.items())
for item in list_items:
if isinstance(item, Paragraph):
success, failed_word_index, remaining_pretext = paragraph_layouter(
item,
page,
start_word=continuation_word_index,
pretext=continuation_pretext,
alignment_override=alignment_override
)
if not success:
# Can't fit more on this page
page_has_content = True
break
continuation_word_index = 0
continuation_pretext = None
# Move to next block after processing list
page_has_content = True
current_block_index += 1
except Exception as e:
print(f"Warning: Error processing list: {e}")
current_block_index += 1
elif isinstance(block, Table):
# Skip tables for now (not implemented)
print(f"Warning: Skipping table (not yet implemented)")
current_block_index += 1
else:
# Unknown block type, skip
print(f"Warning: Skipping unknown block type: {type(block).__name__}")
current_block_index += 1
# Add page if it has content
if page_has_content:
pages.append(page)
else:
# No content could be added to this page, stop
break
return pages
def main():
"""Main function to handle command line arguments and process the EPUB."""
parser = argparse.ArgumentParser(
description='Render EPUB pages using DocumentLayouter',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python epub_page_renderer_documentlayouter.py book.epub --pages 5
python epub_page_renderer_documentlayouter.py book.epub --pages 10 --output-dir my_output --width 600 --height 800
"""
)
parser.add_argument(
'epub_file',
help='Path to the EPUB file to render'
)
parser.add_argument(
'--pages', '-p',
type=int,
default=5,
help='Number of pages to render (default: 5)'
)
parser.add_argument(
'--output-dir', '-o',
default='rendered_pages',
help='Output directory for rendered images (default: rendered_pages)'
)
parser.add_argument(
'--width', '-w',
type=int,
default=800,
help='Page width in pixels (default: 800)'
)
parser.add_argument(
'--height', '-t',
type=int,
default=1000,
help='Page height in pixels (default: 1000)'
)
parser.add_argument(
'--margin', '-m',
type=int,
default=40,
help='Page margin in pixels (default: 40)'
)
parser.add_argument(
'--align', '-a',
choices=['left', 'justify'],
default='left',
help='Text alignment: left or justify (default: left)'
)
args = parser.parse_args()
# Validate arguments
if not os.path.exists(args.epub_file):
print(f"Error: EPUB file '{args.epub_file}' not found")
return 1
if args.pages <= 0:
print("Error: Number of pages must be positive")
return 1
# Create output directory
try:
os.makedirs(args.output_dir, exist_ok=True)
except OSError as e:
print(f"Error creating output directory: {e}")
return 1
print(f"Loading EPUB file: {args.epub_file}")
# Load the EPUB file
try:
book = read_epub(args.epub_file)
print(f"Successfully loaded EPUB: {book.get_title() or 'Unknown Title'}")
# Print book information
author = book.get_metadata('AUTHOR')
if author:
print(f"Author: {author}")
print(f"Chapters: {len(book.chapters) if hasattr(book, 'chapters') else 'Unknown'}")
except Exception as e:
print(f"Error loading EPUB file: {e}")
import traceback
traceback.print_exc()
return 1
# Extract all blocks from the book
print("Extracting content blocks...")
try:
all_blocks = get_all_blocks_from_book(book)
print(f"Extracted {len(all_blocks)} content blocks")
if not all_blocks:
print("No content blocks found in EPUB. The book might be empty.")
return 1
except Exception as e:
print(f"Error extracting blocks: {e}")
import traceback
traceback.print_exc()
return 1
# Set up page style
page_size = (args.width, args.height)
page_style = PageStyle(
background_color=(255, 255, 255),
border_width=args.margin,
border_color=(200, 200, 200),
padding=(10, 10, 10, 10), # top, right, bottom, left
line_spacing=5,
inter_block_spacing=15
)
# Set alignment
alignment = Alignment.JUSTIFY if args.align == 'justify' else Alignment.LEFT
print(f"Setting up layouter with page size {page_size} and {args.align} alignment")
# Layout blocks on pages
print(f"Rendering up to {args.pages} pages using DocumentLayouter...")
try:
pages = layout_blocks_on_pages(
all_blocks,
page_style,
page_size,
args.pages,
alignment_override=alignment
)
if not pages:
print("No pages were generated.")
return 1
print(f"Generated {len(pages)} pages")
# Save each page to an image
for i, page in enumerate(pages):
print(f"Saving page {i + 1}/{len(pages)}...")
try:
# Render the page
image = page.render()
# Save the image
output_filename = f"page_{i + 1:03d}.png"
output_path = os.path.join(args.output_dir, output_filename)
image.save(output_path, 'PNG')
print(f"Saved: {output_path}")
except Exception as e:
print(f"Error saving page {i + 1}: {e}")
import traceback
traceback.print_exc()
continue
print(f"\nCompleted! Rendered {len(pages)} pages to {args.output_dir}")
except Exception as e:
print(f"Error during pagination/rendering: {e}")
import traceback
traceback.print_exc()
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+2 -2
View File
@@ -262,8 +262,8 @@ def main():
if len(sys.argv) < 2:
print("Usage: python ereader_demo.py path/to/book.epub")
print("\nExample EPUBs to try:")
print(" - test.epub (if available in project root)")
print(" - test2.epub (if available in project root)")
print(" - tests/data/test.epub")
print(" - tests/data/test2.epub")
sys.exit(1)
epub_path = sys.argv[1]