remove application from library
Python CI / test (push) Failing after 6m29s

This commit is contained in:
2025-11-07 18:48:36 +01:00
parent 6bb43db8d5
commit 33e2cbc363
21 changed files with 1747 additions and 2656 deletions
+7 -3
View File
@@ -77,12 +77,16 @@ class LinkText(Text, Interactable, Queriable):
return None
return self._callback() # Don't pass the point to the callback
def render(self):
def render(self, next_text: Optional['Text'] = None, spacing: int = 0):
"""
Render the link text with optional hover effects.
Args:
next_text: The next Text object in the line (if any)
spacing: The spacing to the next text object
"""
# Call the parent Text render method
super().render()
# Call the parent Text render method with parameters
super().render(next_text, spacing)
# Add hover effect if needed
if self._hovered:
+122 -6
View File
@@ -3,6 +3,7 @@ import numpy as np
from PIL import Image, ImageDraw
from pyWebLayout.core.base import Renderable, Layoutable, Queriable
from pyWebLayout.core.query import QueryResult, SelectionRange
from pyWebLayout.style.page_style import PageStyle
from pyWebLayout.style import Alignment
from .box import Box
@@ -264,24 +265,41 @@ class Page(Renderable, Queriable):
# Default to origin
return (0, 0)
def query_point(self, point: Tuple[int, int]) -> Optional[Renderable]:
def query_point(self, point: Tuple[int, int]) -> Optional[QueryResult]:
"""
Query a point to determine which child it belongs to.
Query a point to find the deepest object at that location.
Traverses children and uses Queriable.in_object() for hit-testing.
Args:
point: The (x, y) coordinates to query
Returns:
The child object that contains the point, or None if no child contains it
QueryResult with metadata about what was found, or None if nothing hit
"""
point_array = np.array(point)
# Check each child (in reverse order so topmost child is found first)
for child in reversed(self._children):
if self._point_in_child(point_array, child):
return child
# Use Queriable mixin's in_object() for hit-testing
if isinstance(child, Queriable) and child.in_object(point_array):
# If child can also query (has children of its own), recurse
if hasattr(child, 'query_point'):
result = child.query_point(point)
if result:
result.parent_page = self
return result
# If child's query returned None, continue to next child
continue
return None
# Otherwise, package this child as the result
return self._make_query_result(child, point)
# Nothing hit - return empty result
return QueryResult(
object=self,
object_type="empty",
bounds=(int(point[0]), int(point[1]), 0, 0)
)
def _point_in_child(self, point: np.ndarray, child: Renderable) -> bool:
"""
@@ -337,6 +355,104 @@ class Page(Renderable, Queriable):
return None
def _make_query_result(self, obj, point: Tuple[int, int]) -> QueryResult:
"""
Package an object into a QueryResult with metadata.
Args:
obj: The object to package
point: The query point
Returns:
QueryResult with extracted metadata
"""
from .text import Text
from .functional import LinkText, ButtonText
# Extract bounds
origin = getattr(obj, '_origin', np.array([0, 0]))
size = getattr(obj, 'size', np.array([0, 0]))
bounds = (
int(origin[0]),
int(origin[1]),
int(size[0]) if hasattr(size, '__getitem__') else 0,
int(size[1]) if hasattr(size, '__getitem__') else 0
)
# Determine type and extract metadata
if isinstance(obj, LinkText):
return QueryResult(
object=obj,
object_type="link",
bounds=bounds,
text=obj._text,
is_interactive=True,
link_target=obj._link.location if hasattr(obj, '_link') else None
)
elif isinstance(obj, ButtonText):
return QueryResult(
object=obj,
object_type="button",
bounds=bounds,
text=obj._text,
is_interactive=True,
callback=obj._callback if hasattr(obj, '_callback') else None
)
elif isinstance(obj, Text):
return QueryResult(
object=obj,
object_type="text",
bounds=bounds,
text=obj._text if hasattr(obj, '_text') else None
)
else:
return QueryResult(
object=obj,
object_type="unknown",
bounds=bounds
)
def query_range(self, start: Tuple[int, int], end: Tuple[int, int]) -> SelectionRange:
"""
Query all text objects between two points (for text selection).
Uses Queriable.in_object() to determine which objects are in range.
Args:
start: Starting (x, y) point
end: Ending (x, y) point
Returns:
SelectionRange with all text objects between the points
"""
results = []
in_selection = False
start_result = self.query_point(start)
end_result = self.query_point(end)
if not start_result or not end_result:
return SelectionRange(start, end, [])
# Walk through all children (Lines) and their text objects
from .text import Line, Text
for child in self._children:
if isinstance(child, Line) and hasattr(child, '_text_objects'):
for text_obj in child._text_objects:
# Check if this text is the start or is between start and end
if text_obj == start_result.object:
in_selection = True
if in_selection and isinstance(text_obj, Text):
result = self._make_query_result(text_obj, start)
results.append(result)
if text_obj == end_result.object:
in_selection = False
break
return SelectionRange(start, end, results)
def in_object(self, point: Tuple[int, int]) -> bool:
"""
Check if a point is within this page's bounds.
+65
View File
@@ -560,3 +560,68 @@ class Line(Box):
# Render with next text information for continuous underline/strikethrough
text.render(next_text, self._spacing_render)
x_cursor += self._spacing_render + text.width # x-spacing + width of text object
def query_point(self, point: Tuple[int, int]) -> Optional['QueryResult']:
"""
Find which Text object contains the given point.
Uses Queriable.in_object() mixin for hit-testing.
Args:
point: (x, y) coordinates to query
Returns:
QueryResult from the text object at that point, or None
"""
from pyWebLayout.core.query import QueryResult
from .functional import LinkText, ButtonText
point_array = np.array(point)
# Check each text object in this line
for text_obj in self._text_objects:
# Use Queriable mixin's in_object() for hit-testing
if isinstance(text_obj, Queriable) and text_obj.in_object(point_array):
# Extract metadata based on text type
origin = text_obj._origin
size = text_obj.size
# Text origin is at baseline (anchor="ls"), so visual top is origin[1] - ascent
# Bounds should be (x, visual_top, width, height) for proper highlighting
visual_top = int(origin[1] - text_obj._ascent)
bounds = (
int(origin[0]),
visual_top,
int(size[0]) if hasattr(size, '__getitem__') else 0,
int(size[1]) if hasattr(size, '__getitem__') else 0
)
if isinstance(text_obj, LinkText):
result = QueryResult(
object=text_obj,
object_type="link",
bounds=bounds,
text=text_obj._text,
is_interactive=True,
link_target=text_obj._link.location if hasattr(text_obj, '_link') else None
)
elif isinstance(text_obj, ButtonText):
result = QueryResult(
object=text_obj,
object_type="button",
bounds=bounds,
text=text_obj._text,
is_interactive=True,
callback=text_obj._callback if hasattr(text_obj, '_callback') else None
)
else:
result = QueryResult(
object=text_obj,
object_type="text",
bounds=bounds,
text=text_obj._text if hasattr(text_obj, '_text') else None
)
result.parent_line = self
return result
return None
+7
View File
@@ -1,8 +1,12 @@
from abc import ABC
from typing import Optional, Tuple, List, TYPE_CHECKING
import numpy as np
from pyWebLayout.style.alignment import Alignment
if TYPE_CHECKING:
from pyWebLayout.core.query import QueryResult
class Renderable(ABC):
"""
@@ -17,6 +21,9 @@ class Renderable(ABC):
PIL.Image: The rendered image
"""
pass
@property
def origin(self):
return self._origin
class Interactable(ABC):
"""
+248
View File
@@ -0,0 +1,248 @@
"""
Text highlighting system for ebook reader.
Provides data structures and utilities for highlighting text regions,
managing highlight collections, and rendering highlights on pages.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Tuple, Optional, Dict, Any
from enum import Enum
import json
from pathlib import Path
class HighlightColor(Enum):
"""Predefined highlight colors with RGBA values"""
YELLOW = (255, 255, 0, 100) # Classic highlight yellow
GREEN = (100, 255, 100, 100) # Green for verified/correct
BLUE = (100, 200, 255, 100) # Blue for important
PINK = (255, 150, 200, 100) # Pink for questions
ORANGE = (255, 180, 100, 100) # Orange for warnings
PURPLE = (200, 150, 255, 100) # Purple for definitions
RED = (255, 100, 100, 100) # Red for errors/concerns
@dataclass
class Highlight:
"""
Represents a highlighted text region.
Highlights are stored with both pixel bounds (for rendering) and
semantic bounds (text content, for persistence across font changes).
"""
# Identification
id: str # Unique identifier
# Visual properties
bounds: List[Tuple[int, int, int, int]] # List of (x, y, w, h) rectangles
color: Tuple[int, int, int, int] # RGBA color
# Semantic properties (for persistence)
text: str # The highlighted text
start_word_index: Optional[int] = None # Word index in document (if available)
end_word_index: Optional[int] = None
# Metadata
note: Optional[str] = None # Optional annotation
tags: List[str] = None # Optional categorization tags
timestamp: Optional[float] = None # When created
def __post_init__(self):
"""Initialize default values"""
if self.tags is None:
self.tags = []
def to_dict(self) -> Dict[str, Any]:
"""Serialize to dictionary"""
return {
'id': self.id,
'bounds': self.bounds,
'color': self.color,
'text': self.text,
'start_word_index': self.start_word_index,
'end_word_index': self.end_word_index,
'note': self.note,
'tags': self.tags,
'timestamp': self.timestamp
}
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> 'Highlight':
"""Deserialize from dictionary"""
return cls(
id=data['id'],
bounds=[tuple(b) for b in data['bounds']],
color=tuple(data['color']),
text=data['text'],
start_word_index=data.get('start_word_index'),
end_word_index=data.get('end_word_index'),
note=data.get('note'),
tags=data.get('tags', []),
timestamp=data.get('timestamp')
)
class HighlightManager:
"""
Manages highlights for a document.
Handles adding, removing, listing, and persisting highlights.
"""
def __init__(self, document_id: str, highlights_dir: str = "highlights"):
"""
Initialize highlight manager.
Args:
document_id: Unique identifier for the document
highlights_dir: Directory to store highlight data
"""
self.document_id = document_id
self.highlights_dir = Path(highlights_dir)
self.highlights: Dict[str, Highlight] = {} # id -> Highlight
# Create directory if it doesn't exist
self.highlights_dir.mkdir(parents=True, exist_ok=True)
# Load existing highlights
self._load_highlights()
def add_highlight(self, highlight: Highlight) -> None:
"""
Add a highlight.
Args:
highlight: Highlight to add
"""
self.highlights[highlight.id] = highlight
self._save_highlights()
def remove_highlight(self, highlight_id: str) -> bool:
"""
Remove a highlight by ID.
Args:
highlight_id: ID of highlight to remove
Returns:
True if removed, False if not found
"""
if highlight_id in self.highlights:
del self.highlights[highlight_id]
self._save_highlights()
return True
return False
def get_highlight(self, highlight_id: str) -> Optional[Highlight]:
"""Get a highlight by ID"""
return self.highlights.get(highlight_id)
def list_highlights(self) -> List[Highlight]:
"""Get all highlights"""
return list(self.highlights.values())
def clear_all(self) -> None:
"""Remove all highlights"""
self.highlights.clear()
self._save_highlights()
def get_highlights_for_page(self, page_bounds: Tuple[int, int, int, int]) -> List[Highlight]:
"""
Get highlights that appear on a specific page.
Args:
page_bounds: Page bounds (x, y, width, height)
Returns:
List of highlights on this page
"""
page_x, page_y, page_w, page_h = page_bounds
page_highlights = []
for highlight in self.highlights.values():
# Check if any highlight bounds overlap with page
for hx, hy, hw, hh in highlight.bounds:
if (hx < page_x + page_w and hx + hw > page_x and
hy < page_y + page_h and hy + hh > page_y):
page_highlights.append(highlight)
break
return page_highlights
def _get_filepath(self) -> Path:
"""Get filepath for this document's highlights"""
return self.highlights_dir / f"{self.document_id}_highlights.json"
def _save_highlights(self) -> None:
"""Persist highlights to disk"""
try:
filepath = self._get_filepath()
data = {
'document_id': self.document_id,
'highlights': [h.to_dict() for h in self.highlights.values()]
}
with open(filepath, 'w') as f:
json.dump(data, f, indent=2)
except Exception as e:
print(f"Error saving highlights: {e}")
def _load_highlights(self) -> None:
"""Load highlights from disk"""
try:
filepath = self._get_filepath()
if not filepath.exists():
return
with open(filepath, 'r') as f:
data = json.load(f)
self.highlights = {
h['id']: Highlight.from_dict(h)
for h in data.get('highlights', [])
}
except Exception as e:
print(f"Error loading highlights: {e}")
self.highlights = {}
def create_highlight_from_query_result(
result,
color: Tuple[int, int, int, int] = HighlightColor.YELLOW.value,
note: Optional[str] = None,
tags: Optional[List[str]] = None
) -> Highlight:
"""
Create a highlight from a QueryResult.
Args:
result: QueryResult from query_pixel or query_range
color: RGBA color tuple
note: Optional annotation
tags: Optional categorization tags
Returns:
Highlight instance
"""
from time import time
import uuid
# Handle single result or SelectionRange
if hasattr(result, 'results'): # SelectionRange
bounds = result.bounds_list
text = result.text
else: # Single QueryResult
bounds = [result.bounds]
text = result.text or ""
return Highlight(
id=str(uuid.uuid4()),
bounds=bounds,
color=color,
text=text,
note=note,
tags=tags or [],
timestamp=time()
)
+87
View File
@@ -0,0 +1,87 @@
"""
Query system for pixel-to-content mapping.
This module provides data structures for querying rendered content,
enabling interactive features like link clicking, word definition lookup,
and text selection.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, Tuple, List, Any, TYPE_CHECKING
import numpy as np
if TYPE_CHECKING:
from pyWebLayout.core.base import Queriable
@dataclass
class QueryResult:
"""
Result of querying a point on a rendered page.
This encapsulates all information about what was found at a pixel location,
including geometry, content, and interaction capabilities.
"""
# What was found
object: 'Queriable' # The object at this point
object_type: str # "link", "text", "image", "button", "word", "empty"
# Geometry
bounds: Tuple[int, int, int, int] # (x, y, width, height) in page coordinates
# Content (for text/words)
text: Optional[str] = None
word_index: Optional[int] = None # Index in abstract document structure
block_index: Optional[int] = None # Block index in document
# Interaction (for links/buttons)
is_interactive: bool = False
link_target: Optional[str] = None # URL or internal reference
callback: Optional[Any] = None # Interaction callback
# Hierarchy (for debugging/traversal)
parent_line: Optional[Any] = None
parent_page: Optional[Any] = None
def to_dict(self) -> dict:
"""Convert to dictionary for serialization"""
return {
'object_type': self.object_type,
'bounds': self.bounds,
'text': self.text,
'is_interactive': self.is_interactive,
'link_target': self.link_target,
'word_index': self.word_index,
'block_index': self.block_index
}
@dataclass
class SelectionRange:
"""
Represents a range of selected text between two points.
"""
start_point: Tuple[int, int]
end_point: Tuple[int, int]
results: List[QueryResult] # All query results in the range
@property
def text(self) -> str:
"""Get concatenated text from all results"""
return " ".join(r.text for r in self.results if r.text)
@property
def bounds_list(self) -> List[Tuple[int, int, int, int]]:
"""Get list of all bounding boxes for highlighting"""
return [r.bounds for r in self.results]
def to_dict(self) -> dict:
"""Convert to dictionary for serialization"""
return {
'start': self.start_point,
'end': self.end_point,
'text': self.text,
'word_count': len(self.results),
'bounds': self.bounds_list
}
+124
View File
@@ -0,0 +1,124 @@
"""
Gesture event types for touch input.
This module defines touch gestures that can be received from a HAL (Hardware Abstraction Layer)
or touch input system, and the response format for actions to be performed.
"""
from __future__ import annotations
from enum import Enum
from dataclasses import dataclass
from typing import Optional, Dict, Any
class GestureType(Enum):
"""Touch gesture types from HAL"""
TAP = "tap" # Single finger tap
LONG_PRESS = "long_press" # Hold for 500ms+
SWIPE_LEFT = "swipe_left" # Swipe left (page forward)
SWIPE_RIGHT = "swipe_right" # Swipe right (page back)
SWIPE_UP = "swipe_up" # Swipe up (scroll down)
SWIPE_DOWN = "swipe_down" # Swipe down (scroll up)
PINCH_IN = "pinch_in" # Pinch fingers together (zoom out)
PINCH_OUT = "pinch_out" # Spread fingers apart (zoom in)
DRAG_START = "drag_start" # Start dragging/selection
DRAG_MOVE = "drag_move" # Continue dragging
DRAG_END = "drag_end" # End dragging/selection
@dataclass
class TouchEvent:
"""
Touch event from HAL.
Represents a single touch gesture with its coordinates and metadata.
"""
gesture: GestureType
x: int # Primary touch point X coordinate
y: int # Primary touch point Y coordinate
x2: Optional[int] = None # Secondary point X (for pinch/drag)
y2: Optional[int] = None # Secondary point Y (for pinch/drag)
timestamp_ms: float = 0 # Timestamp in milliseconds
@classmethod
def from_hal(cls, hal_data: dict) -> 'TouchEvent':
"""
Parse a touch event from HAL format.
Args:
hal_data: Dictionary with gesture data from HAL
Expected keys: 'gesture', 'x', 'y', optionally 'x2', 'y2', 'timestamp'
Returns:
TouchEvent instance
Example:
>>> event = TouchEvent.from_hal({
... 'gesture': 'tap',
... 'x': 450,
... 'y': 320
... })
"""
return cls(
gesture=GestureType(hal_data['gesture']),
x=hal_data['x'],
y=hal_data['y'],
x2=hal_data.get('x2'),
y2=hal_data.get('y2'),
timestamp_ms=hal_data.get('timestamp', 0)
)
def to_dict(self) -> dict:
"""Convert to dictionary for serialization"""
return {
'gesture': self.gesture.value,
'x': self.x,
'y': self.y,
'x2': self.x2,
'y2': self.y2,
'timestamp_ms': self.timestamp_ms
}
@dataclass
class GestureResponse:
"""
Response from handling a gesture.
This encapsulates the action that should be performed by the UI
in response to a gesture, keeping all business logic in the library.
"""
action: str # Action type: "navigate", "define", "select", "zoom", "page_turn", "none", etc.
data: Dict[str, Any] # Action-specific data
def to_dict(self) -> dict:
"""
Convert to dictionary for Flask JSON response.
Returns:
Dictionary with action and data
"""
return {
'action': self.action,
'data': self.data
}
# Action type constants for clarity
class ActionType:
"""Constants for gesture response action types"""
NONE = "none"
PAGE_TURN = "page_turn"
NAVIGATE = "navigate"
DEFINE = "define"
SELECT = "select"
ZOOM = "zoom"
BOOK_LOADED = "book_loaded"
WORD_SELECTED = "word_selected"
SHOW_MENU = "show_menu"
SELECTION_START = "selection_start"
SELECTION_UPDATE = "selection_update"
SELECTION_COMPLETE = "selection_complete"
AT_START = "at_start"
AT_END = "at_end"
ERROR = "error"
-632
View File
@@ -1,632 +0,0 @@
#!/usr/bin/env python3
"""
Simple ereader application interface for pyWebLayout.
This module provides a user-friendly wrapper around the ereader infrastructure,
making it easy to build ebook reader applications with all essential features.
Example:
from pyWebLayout.layout.ereader_application import EbookReader
# Create reader
reader = EbookReader(page_size=(800, 1000))
# Load an EPUB
reader.load_epub("mybook.epub")
# Navigate
reader.next_page()
reader.previous_page()
# Get current page
page_image = reader.get_current_page()
# Modify styling
reader.increase_font_size()
reader.set_line_spacing(8)
# Chapter navigation
chapters = reader.get_chapters()
reader.jump_to_chapter("Chapter 1")
# Position management
reader.save_position("bookmark1")
reader.load_position("bookmark1")
"""
from __future__ import annotations
from typing import List, Tuple, Optional, Dict, Any, Union
from pathlib import Path
import os
from PIL import Image
from pyWebLayout.io.readers.epub_reader import read_epub
from pyWebLayout.abstract.block import Block, HeadingLevel
from pyWebLayout.layout.ereader_manager import EreaderLayoutManager
from pyWebLayout.layout.ereader_layout import RenderingPosition
from pyWebLayout.style.page_style import PageStyle
from pyWebLayout.concrete.page import Page
class EbookReader:
"""
Simple ereader application with all essential features.
Features:
- Load EPUB files
- Forward/backward page navigation
- Position save/load (based on abstract document structure)
- Chapter navigation
- Font size and spacing control
- Current page retrieval as PIL Image
The reader maintains position using abstract document structure (chapter/block/word indices),
ensuring positions remain valid across font size and styling changes.
"""
def __init__(self,
page_size: Tuple[int, int] = (800, 1000),
margin: int = 40,
background_color: Tuple[int, int, int] = (255, 255, 255),
line_spacing: int = 5,
inter_block_spacing: int = 15,
bookmarks_dir: str = "ereader_bookmarks",
buffer_size: int = 5):
"""
Initialize the ebook reader.
Args:
page_size: Page dimensions (width, height) in pixels
margin: Page margin in pixels
background_color: Background color as RGB tuple
line_spacing: Spacing between lines in pixels
inter_block_spacing: Spacing between blocks in pixels
bookmarks_dir: Directory to store bookmarks and positions
buffer_size: Number of pages to cache for performance
"""
self.page_size = page_size
self.bookmarks_dir = bookmarks_dir
self.buffer_size = buffer_size
# Create page style
self.page_style = PageStyle(
background_color=background_color,
border_width=margin,
border_color=(200, 200, 200),
padding=(10, 10, 10, 10),
line_spacing=line_spacing,
inter_block_spacing=inter_block_spacing
)
# State
self.manager: Optional[EreaderLayoutManager] = None
self.blocks: Optional[List[Block]] = None
self.document_id: Optional[str] = None
self.book_title: Optional[str] = None
self.book_author: Optional[str] = None
# Font scale state
self.base_font_scale = 1.0
self.font_scale_step = 0.1 # 10% change per step
def load_epub(self, epub_path: str) -> bool:
"""
Load an EPUB file into the reader.
Args:
epub_path: Path to the EPUB file
Returns:
True if loaded successfully, False otherwise
"""
try:
# Validate path
if not os.path.exists(epub_path):
raise FileNotFoundError(f"EPUB file not found: {epub_path}")
# Load the EPUB
book = read_epub(epub_path)
# Extract metadata
self.book_title = book.get_title() or "Unknown Title"
self.book_author = book.get_metadata('AUTHOR') or "Unknown Author"
# Create document ID from filename
self.document_id = Path(epub_path).stem
# Extract all blocks from chapters
self.blocks = []
for chapter in book.chapters:
if hasattr(chapter, '_blocks'):
self.blocks.extend(chapter._blocks)
if not self.blocks:
raise ValueError("No content blocks found in EPUB")
# Initialize the ereader manager
self.manager = EreaderLayoutManager(
blocks=self.blocks,
page_size=self.page_size,
document_id=self.document_id,
buffer_size=self.buffer_size,
page_style=self.page_style,
bookmarks_dir=self.bookmarks_dir
)
return True
except Exception as e:
print(f"Error loading EPUB: {e}")
return False
def is_loaded(self) -> bool:
"""Check if a book is currently loaded."""
return self.manager is not None
def get_current_page(self) -> Optional[Image.Image]:
"""
Get the current page as a PIL Image.
Returns:
PIL Image of the current page, or None if no book is loaded
"""
if not self.manager:
return None
try:
page = self.manager.get_current_page()
return page.render()
except Exception as e:
print(f"Error rendering page: {e}")
return None
def next_page(self) -> Optional[Image.Image]:
"""
Navigate to the next page.
Returns:
PIL Image of the next page, or None if at end of book
"""
if not self.manager:
return None
try:
page = self.manager.next_page()
if page:
return page.render()
return None
except Exception as e:
print(f"Error navigating to next page: {e}")
return None
def previous_page(self) -> Optional[Image.Image]:
"""
Navigate to the previous page.
Returns:
PIL Image of the previous page, or None if at beginning of book
"""
if not self.manager:
return None
try:
page = self.manager.previous_page()
if page:
return page.render()
return None
except Exception as e:
print(f"Error navigating to previous page: {e}")
return None
def save_position(self, name: str = "current_position") -> bool:
"""
Save the current reading position with a name.
The position is saved based on abstract document structure (chapter, block, word indices),
making it stable across font size and styling changes.
Args:
name: Name for this saved position
Returns:
True if saved successfully, False otherwise
"""
if not self.manager:
return False
try:
self.manager.add_bookmark(name)
return True
except Exception as e:
print(f"Error saving position: {e}")
return False
def load_position(self, name: str = "current_position") -> Optional[Image.Image]:
"""
Load a previously saved reading position.
Args:
name: Name of the saved position
Returns:
PIL Image of the page at the loaded position, or None if not found
"""
if not self.manager:
return None
try:
page = self.manager.jump_to_bookmark(name)
if page:
return page.render()
return None
except Exception as e:
print(f"Error loading position: {e}")
return None
def list_saved_positions(self) -> List[str]:
"""
Get a list of all saved position names.
Returns:
List of position names
"""
if not self.manager:
return []
try:
bookmarks = self.manager.list_bookmarks()
return [name for name, _ in bookmarks]
except Exception as e:
print(f"Error listing positions: {e}")
return []
def delete_position(self, name: str) -> bool:
"""
Delete a saved position.
Args:
name: Name of the position to delete
Returns:
True if deleted, False otherwise
"""
if not self.manager:
return False
return self.manager.remove_bookmark(name)
def get_chapters(self) -> List[Tuple[str, int]]:
"""
Get a list of all chapters with their indices.
Returns:
List of (chapter_title, chapter_index) tuples
"""
if not self.manager:
return []
try:
toc = self.manager.get_table_of_contents()
# Convert to simplified format (title, index)
chapters = []
for i, (title, level, position) in enumerate(toc):
chapters.append((title, i))
return chapters
except Exception as e:
print(f"Error getting chapters: {e}")
return []
def get_chapter_positions(self) -> List[Tuple[str, RenderingPosition]]:
"""
Get chapter titles with their exact rendering positions.
Returns:
List of (title, position) tuples
"""
if not self.manager:
return []
try:
toc = self.manager.get_table_of_contents()
return [(title, position) for title, level, position in toc]
except Exception as e:
print(f"Error getting chapter positions: {e}")
return []
def jump_to_chapter(self, chapter: Union[str, int]) -> Optional[Image.Image]:
"""
Navigate to a specific chapter by title or index.
Args:
chapter: Chapter title (string) or chapter index (integer)
Returns:
PIL Image of the first page of the chapter, or None if not found
"""
if not self.manager:
return None
try:
if isinstance(chapter, int):
page = self.manager.jump_to_chapter_index(chapter)
else:
page = self.manager.jump_to_chapter(chapter)
if page:
return page.render()
return None
except Exception as e:
print(f"Error jumping to chapter: {e}")
return None
def set_font_size(self, scale: float) -> Optional[Image.Image]:
"""
Set the font size scale and re-render current page.
Args:
scale: Font scale factor (1.0 = normal, 2.0 = double size, 0.5 = half size)
Returns:
PIL Image of the re-rendered page with new font size
"""
if not self.manager:
return None
try:
self.base_font_scale = max(0.5, min(3.0, scale)) # Clamp between 0.5x and 3.0x
page = self.manager.set_font_scale(self.base_font_scale)
return page.render()
except Exception as e:
print(f"Error setting font size: {e}")
return None
def increase_font_size(self) -> Optional[Image.Image]:
"""
Increase font size by one step and re-render.
Returns:
PIL Image of the re-rendered page
"""
new_scale = self.base_font_scale + self.font_scale_step
return self.set_font_size(new_scale)
def decrease_font_size(self) -> Optional[Image.Image]:
"""
Decrease font size by one step and re-render.
Returns:
PIL Image of the re-rendered page
"""
new_scale = self.base_font_scale - self.font_scale_step
return self.set_font_size(new_scale)
def get_font_size(self) -> float:
"""
Get the current font size scale.
Returns:
Current font scale factor
"""
return self.base_font_scale
def set_line_spacing(self, spacing: int) -> Optional[Image.Image]:
"""
Set line spacing and re-render current page.
Args:
spacing: Line spacing in pixels
Returns:
PIL Image of the re-rendered page
"""
if not self.manager:
return None
try:
# Update page style
self.page_style.line_spacing = max(0, spacing)
# Need to recreate the manager with new page style
current_pos = self.manager.current_position
current_font_scale = self.base_font_scale
self.manager.shutdown()
self.manager = EreaderLayoutManager(
blocks=self.blocks,
page_size=self.page_size,
document_id=self.document_id,
buffer_size=self.buffer_size,
page_style=self.page_style,
bookmarks_dir=self.bookmarks_dir
)
# Restore position
self.manager.current_position = current_pos
# Restore font scale using the method (not direct assignment)
if current_font_scale != 1.0:
self.manager.set_font_scale(current_font_scale)
page = self.manager.get_current_page()
return page.render()
except Exception as e:
print(f"Error setting line spacing: {e}")
return None
def set_inter_block_spacing(self, spacing: int) -> Optional[Image.Image]:
"""
Set spacing between blocks (paragraphs, headings, etc.) and re-render.
Args:
spacing: Inter-block spacing in pixels
Returns:
PIL Image of the re-rendered page
"""
if not self.manager:
return None
try:
# Update page style
self.page_style.inter_block_spacing = max(0, spacing)
# Need to recreate the manager with new page style
current_pos = self.manager.current_position
current_font_scale = self.base_font_scale
self.manager.shutdown()
self.manager = EreaderLayoutManager(
blocks=self.blocks,
page_size=self.page_size,
document_id=self.document_id,
buffer_size=self.buffer_size,
page_style=self.page_style,
bookmarks_dir=self.bookmarks_dir
)
# Restore position
self.manager.current_position = current_pos
# Restore font scale using the method (not direct assignment)
if current_font_scale != 1.0:
self.manager.set_font_scale(current_font_scale)
page = self.manager.get_current_page()
return page.render()
except Exception as e:
print(f"Error setting inter-block spacing: {e}")
return None
def get_position_info(self) -> Dict[str, Any]:
"""
Get detailed information about the current position.
Returns:
Dictionary with position details including:
- position: RenderingPosition details (chapter_index, block_index, word_index)
- chapter: Current chapter info (title, level)
- progress: Reading progress (0.0 to 1.0)
- font_scale: Current font scale
- book_title: Book title
- book_author: Book author
"""
if not self.manager:
return {}
try:
info = self.manager.get_position_info()
info['book_title'] = self.book_title
info['book_author'] = self.book_author
return info
except Exception as e:
print(f"Error getting position info: {e}")
return {}
def get_reading_progress(self) -> float:
"""
Get reading progress as a percentage.
Returns:
Progress from 0.0 (beginning) to 1.0 (end)
"""
if not self.manager:
return 0.0
return self.manager.get_reading_progress()
def get_current_chapter_info(self) -> Optional[Dict[str, Any]]:
"""
Get information about the current chapter.
Returns:
Dictionary with chapter info (title, level) or None
"""
if not self.manager:
return None
try:
chapter = self.manager.get_current_chapter()
if chapter:
return {
'title': chapter.title,
'level': chapter.level,
'block_index': chapter.block_index
}
return None
except Exception as e:
print(f"Error getting current chapter: {e}")
return None
def render_to_file(self, output_path: str) -> bool:
"""
Save the current page to an image file.
Args:
output_path: Path where to save the image (e.g., "page.png")
Returns:
True if saved successfully, False otherwise
"""
page_image = self.get_current_page()
if page_image:
try:
page_image.save(output_path)
return True
except Exception as e:
print(f"Error saving image: {e}")
return False
return False
def get_book_info(self) -> Dict[str, Any]:
"""
Get information about the loaded book.
Returns:
Dictionary with book information
"""
return {
'title': self.book_title,
'author': self.book_author,
'document_id': self.document_id,
'total_blocks': len(self.blocks) if self.blocks else 0,
'total_chapters': len(self.get_chapters()),
'page_size': self.page_size,
'font_scale': self.base_font_scale
}
def close(self):
"""
Close the reader and save current position.
Should be called when done with the reader.
"""
if self.manager:
self.manager.shutdown()
self.manager = None
def __enter__(self):
"""Context manager support."""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Context manager cleanup."""
self.close()
def __del__(self):
"""Cleanup on deletion."""
self.close()
# Convenience function
def create_ebook_reader(page_size: Tuple[int, int] = (800, 1000), **kwargs) -> EbookReader:
"""
Create an ebook reader with sensible defaults.
Args:
page_size: Page dimensions (width, height) in pixels
**kwargs: Additional arguments passed to EbookReader
Returns:
Configured EbookReader instance
"""
return EbookReader(page_size=page_size, **kwargs)