Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a1111a6bb | ||
|
|
220f19fe46 | ||
|
|
bbab9ba3b3 | ||
|
|
5824a8428a | ||
|
|
23f7e37561 | ||
|
|
5cc4732238 | ||
|
|
9d5d539311 | ||
|
|
f8274ae26b | ||
|
|
c045c548de | ||
|
|
7355e5edc0 | ||
|
|
5eee972d75 | ||
|
|
3604a4e98f | ||
|
|
19c1b01ea6 | ||
|
|
7e599a1adb | ||
|
|
312eb2da13 | ||
|
|
b7d1b631b9 | ||
|
|
fe43024656 | ||
|
|
58a5256dc1 | ||
|
|
7d0f004345 | ||
|
|
6aeabc2047 | ||
|
|
46b508adf8 | ||
|
|
6d771e3bf8 | ||
|
|
0c4aa34f8f | ||
|
|
48c99ba44f | ||
|
|
8af1c47e15 | ||
|
|
6aa6b0da21 | ||
|
|
526fee3617 | ||
|
|
6354c1d3bb | ||
|
|
3a80dfe47b | ||
|
|
58ef27f227 | ||
|
|
36b76f6d9e | ||
|
|
3c53f16d07 | ||
|
|
8161551ab6 | ||
|
|
8ab1b37332 | ||
|
|
784f698044 | ||
|
|
fc1e693e67 | ||
|
|
4d831f28a9 | ||
|
|
195fca4370 | ||
|
|
758e54fa4d | ||
|
|
7f1a0724e1 | ||
|
|
f015d998e1 | ||
|
|
7d82752546 | ||
|
|
e8e6eaf3ae | ||
|
|
4f777bc9bf | ||
|
|
c48d64cbe0 |
@@ -0,0 +1,11 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "pip"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "weekly"
|
||||
@@ -0,0 +1,27 @@
|
||||
name: Tests
|
||||
|
||||
on: [ push, pull_request ]
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
python-version: [ "3.8", "3.9", "3.10", "3.11", "3.12", "3.13" ]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v5
|
||||
|
||||
- name: Set up Python ${{ matrix.python-version }}
|
||||
uses: actions/setup-python@v6
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pip install poetry
|
||||
poetry install --no-interaction --no-root --with dev
|
||||
|
||||
- name: Run tests with pytest
|
||||
run: |
|
||||
poetry run pytest tests/ -v --cov=cbz --cov-report=xml --cov-report=term-missing
|
||||
@@ -173,4 +173,5 @@ pyrightconfig.json
|
||||
### CBZ ###
|
||||
*.cbz
|
||||
*.pdf
|
||||
*.zip
|
||||
*.zip
|
||||
*cbr
|
||||
@@ -4,6 +4,60 @@ All notable changes to this project will be documented in this file.
|
||||
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [3.4.4] - 2025-09-21
|
||||
|
||||
### Added
|
||||
|
||||
- Added `[pillow]` extension to support `.jxl` and `.avif` images.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Files in the input archives are now sorted alphabetically.
|
||||
|
||||
## [3.4.3] - 2025-08-31
|
||||
|
||||
### Changed
|
||||
|
||||
- Bump actions/checkout from 4 to 5.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix ComicInfo XML parsing for single page comic.
|
||||
|
||||
## [3.4.2] - 2025-07-26
|
||||
|
||||
### Added
|
||||
|
||||
- Adding CI tests.
|
||||
|
||||
## [3.4.1] - 2025-07-11
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix installation instructions.
|
||||
|
||||
## [3.4.0] - 2025-07-09
|
||||
|
||||
### Added
|
||||
|
||||
- Support for PDF files.
|
||||
- Support for CBR (Comic Book RAR) files.
|
||||
|
||||
### Changed
|
||||
|
||||
- Replaced `PyMuPDF` with `pypdf` for PDF handling.
|
||||
- Updated third-party license documentation for bundled libraries.
|
||||
|
||||
### New Contributors
|
||||
|
||||
- [tssujt](https://github.com/tssujt)
|
||||
|
||||
## [3.3.7] - 2025-01-04
|
||||
|
||||
### Fixed
|
||||
|
||||
- Import error on Unix systems for the comic player.
|
||||
|
||||
## [3.3.6] - 2024-12-22
|
||||
|
||||
### Added
|
||||
@@ -171,6 +225,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
|
||||
- Initial release.
|
||||
|
||||
[3.4.4]: https://github.com/hyugogirubato/cbz/releases/tag/v3.4.4
|
||||
[3.4.3]: https://github.com/hyugogirubato/cbz/releases/tag/v3.4.3
|
||||
[3.4.2]: https://github.com/hyugogirubato/cbz/releases/tag/v3.4.2
|
||||
[3.4.1]: https://github.com/hyugogirubato/cbz/releases/tag/v3.4.1
|
||||
[3.4.0]: https://github.com/hyugogirubato/cbz/releases/tag/v3.4.0
|
||||
[3.3.7]: https://github.com/hyugogirubato/cbz/releases/tag/v3.3.7
|
||||
[3.3.6]: https://github.com/hyugogirubato/cbz/releases/tag/v3.3.6
|
||||
[3.3.5]: https://github.com/hyugogirubato/cbz/releases/tag/v3.3.5
|
||||
[3.3.4]: https://github.com/hyugogirubato/cbz/releases/tag/v3.3.4
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024 hyugogirubato
|
||||
Copyright (c) 2025 hyugogirubato
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# CBZ
|
||||
|
||||
CBZ is a Python library designed for creating, manipulating, and viewing comic book files in CBZ format. It offers a straightforward interface to pack comic pages into CBZ archives, extract metadata, and display comics using a built-in player.
|
||||
CBZ is a Python library designed for creating, manipulating, and viewing comic book files in CBZ, CBR, and PDF formats. It offers a straightforward interface to pack comic pages into CBZ archives, extract metadata from CBZ and CBR files, and display comics using a built-in player.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -8,13 +8,14 @@ CBZ is a Python library designed for creating, manipulating, and viewing comic b
|
||||
- 📚 Pack images into CBZ format for comics and manga
|
||||
- 📝 Extract and manage title, series, format, and more
|
||||
- 🖼️ Handle comic pages with attributes like type and format
|
||||
- 📦 Unpack CBZ files to retrieve comic information
|
||||
- 🛠️ Built-in player for viewing CBZ comics
|
||||
- 📦 Unpack CBZ and CBR files to retrieve comic information, or extract images from PDF files
|
||||
- 🛠️ Built-in player for viewing CBZ, CBR, and PDF comics
|
||||
- 📚 Full CBR (RAR) format support for reading existing archives
|
||||
- ❤️ Fully Open-Source! Pull Requests Welcome
|
||||
|
||||
## Installation
|
||||
|
||||
Install KeyDive from PyPI using Poetry:
|
||||
Install CBZ from PyPI using pip:
|
||||
|
||||
```shell
|
||||
pip install cbz
|
||||
@@ -73,7 +74,15 @@ if __name__ == '__main__':
|
||||
|
||||
## Player
|
||||
|
||||
CBZ includes a command-line player for viewing CBZ comic book files. Simply run cbzplayer <file> to launch the player with the specified CBZ file.
|
||||
CBZ includes a command-line player for viewing comic book files in multiple formats. Simply run `cbzplayer <file>` to launch the player with the specified comic book file.
|
||||
|
||||
### Supported Formats
|
||||
|
||||
- **CBZ** (Comic Book ZIP) - Standard ZIP archives containing images and metadata
|
||||
- **CBR** (Comic Book RAR) - RAR archives containing images and metadata
|
||||
- **PDF** - Portable Document Format files with embedded images (images only, no metadata)
|
||||
|
||||
### Usage
|
||||
|
||||
````shell
|
||||
usage: cbzplayer [-h] <file>
|
||||
@@ -81,13 +90,37 @@ usage: cbzplayer [-h] <file>
|
||||
Launch CBZ player with a comic book file
|
||||
|
||||
positional arguments:
|
||||
<file> Path to the CBZ comic book file.
|
||||
<file> Path to the CBZ, CBR, or PDF comic book file.
|
||||
|
||||
options:
|
||||
-h, --help show this help message and exit
|
||||
|
||||
````
|
||||
|
||||
### Examples
|
||||
|
||||
```shell
|
||||
# View a CBZ file
|
||||
cbzplayer my_comic.cbz
|
||||
|
||||
# View a CBR file
|
||||
cbzplayer my_comic.cbr
|
||||
|
||||
# View a PDF file
|
||||
cbzplayer my_comic.pdf
|
||||
```
|
||||
|
||||
### Requirements for CBR Support
|
||||
|
||||
CBR file support requires:
|
||||
|
||||
- The `rarfile` Python package (automatically installed with CBZ)
|
||||
- An external RAR extraction tool such as:
|
||||
- `unrar` (recommended) - Available in most package managers
|
||||
- `rar` - Commercial RAR archiver
|
||||
- `7zip` - Free alternative with RAR support
|
||||
|
||||
For installation instructions and compatibility details, see the [rarfile documentation](https://github.com/markokr/rarfile).
|
||||
|
||||
## Detailed Usage
|
||||
|
||||
### Creating a ComicInfo Object
|
||||
@@ -96,6 +129,7 @@ The `ComicInfo` class represents a comic book with metadata and pages. It suppor
|
||||
|
||||
```python
|
||||
from cbz.comic import ComicInfo
|
||||
from cbz.constants import PageType, YesNo, Manga, AgeRating, Format
|
||||
from cbz.page import PageInfo
|
||||
|
||||
# Example usage:
|
||||
@@ -135,30 +169,59 @@ Pack the comic into a CBZ file format:
|
||||
cbz_content = comic.pack()
|
||||
```
|
||||
|
||||
### Unpacking from CBZ
|
||||
### Loading from Different Formats
|
||||
|
||||
Load a comic from an existing CBZ file:
|
||||
Load a comic from an existing CBZ file (with metadata):
|
||||
|
||||
```python
|
||||
comic_from_cbz = ComicInfo.from_cbz('/path/to/your_comic.cbz')
|
||||
```
|
||||
|
||||
Load a comic from an existing CBR file (with metadata):
|
||||
|
||||
```python
|
||||
comic_from_cbr = ComicInfo.from_cbr('/path/to/your_comic.cbr')
|
||||
```
|
||||
|
||||
Load a comic from a PDF file (images only, no metadata):
|
||||
|
||||
```python
|
||||
comic_from_pdf = ComicInfo.from_pdf('/path/to/your_comic.pdf')
|
||||
```
|
||||
|
||||
**Notes**:
|
||||
|
||||
- CBR support requires an external RAR extraction tool. For detailed compatibility information and advanced configuration, see the [rarfile documentation](https://github.com/markokr/rarfile).
|
||||
- PDF files only provide image content; comic metadata (title, series, etc.) is not available from PDF files.
|
||||
|
||||
## Contributors
|
||||
|
||||
<a href="https://github.com/hyugogirubato"><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/65763543?v=4&h=25&w=25&fit=cover&mask=circle&maxage=7d" alt="hyugogirubato"/></a>
|
||||
<a href="https://github.com/piskunqa"><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/38443069?v=4&h=25&w=25&fit=cover&mask=circle&maxage=7d" alt="piskunqa"/></a>
|
||||
<a href="https://github.com/OleskiiPyskun"><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/75667382?v=4&h=25&w=25&fit=cover&mask=circle&maxage=7d" alt="OleskiiPyskun"/></a>
|
||||
<a href="https://github.com/tssujt"><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/17313425?v=4&h=25&w=25&fit=cover&mask=circle&maxage=7d" alt="tssujt"/></a>
|
||||
<a href="https://github.com/gokender"><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3709740?v=4&h=25&w=25&fit=cover&mask=circle&maxage=7d" alt="gokender"/></a>
|
||||
<a href="https://github.com/domenicoblanco"><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/9018104?v=4&h=25&w=25&fit=cover&mask=circle&maxage=7d" alt="domenicoblanco"/></a>
|
||||
<a href="https://github.com/RivMt"><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/40086827?v=4&h=25&w=25&fit=cover&mask=circle&maxage=7d" alt="RivMt"/></a>
|
||||
<a href="https://github.com/flolep2607"><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/24566964?v=4&h=25&w=25&fit=cover&mask=circle&maxage=7d" alt="flolep2607"/></a>
|
||||
<a href="https://github.com/gokender"><img src="https://images.weserv.nl/?url=avatars.githubusercontent.com/u/3709740?v=4&h=25&w=25&fit=cover&mask=circle&maxage=7d" alt="gokender"/></a>
|
||||
|
||||
|
||||
## Licensing
|
||||
|
||||
This software is licensed under the terms of [MIT License](https://github.com/hyugogirubato/cbz/blob/main/LICENSE).
|
||||
This software is licensed under the terms of [MIT License](https://github.com/hyugogirubato/cbz/blob/main/LICENSE).
|
||||
You can find a copy of the license in the LICENSE file in the root folder.
|
||||
|
||||
* * *
|
||||
### Third-Party Licenses
|
||||
|
||||
© hyugogirubato 2024
|
||||
This project uses the following third-party libraries:
|
||||
|
||||
- **[langcodes](https://pypi.org/project/langcodes/)** - MIT License
|
||||
- **[Pillow](https://pypi.org/project/Pillow/)** - HPND License
|
||||
- **[pillow-avif-plugin](https://pypi.org/project/pillow-avif-plugin/)** - MIT License
|
||||
- **[pillow-jxl-plugin](https://pypi.org/project/pillow-jxl-plugin/)** - MIT License
|
||||
- **[pypdf](https://pypi.org/project/pypdf/)** - BSD License
|
||||
- **[rarfile](https://pypi.org/project/rarfile/)** - ISC License
|
||||
- **[xmltodict](https://pypi.org/project/xmltodict/)** - MIT License
|
||||
|
||||
---
|
||||
|
||||
© hyugogirubato 2025
|
||||
|
||||
@@ -1,2 +1,9 @@
|
||||
from .comic import ComicInfo
|
||||
from .page import PageInfo
|
||||
|
||||
# Register optional Pillow plugins
|
||||
for _plugin in ('pillow_avif', 'pillow_jxl'):
|
||||
try:
|
||||
__import__(_plugin)
|
||||
except ImportError:
|
||||
pass
|
||||
|
||||
@@ -8,7 +8,7 @@ from cbz.comic import ComicInfo
|
||||
def main() -> None:
|
||||
# Parse command-line arguments
|
||||
parser = argparse.ArgumentParser(description='Launch CBZ player with a comic book file')
|
||||
parser.add_argument('comic_path', type=Path, metavar='<file>', help='Path to the CBZ comic book file.')
|
||||
parser.add_argument('comic_path', type=Path, metavar='<file>', help='Path to the CBZ, CBR, or PDF comic book file.')
|
||||
args = parser.parse_args()
|
||||
|
||||
# Validate the provided path
|
||||
@@ -17,9 +17,15 @@ def main() -> None:
|
||||
print(f'Error: The file "{comic_path}" does not exist or is not a valid file.')
|
||||
exit(1)
|
||||
|
||||
# Create ComicInfo object from CBZ file
|
||||
# Create ComicInfo object from comic file
|
||||
try:
|
||||
comic_info = ComicInfo.from_pdf(comic_path) if comic_path.suffix == '.pdf' else ComicInfo.from_cbz(comic_path)
|
||||
if comic_path.suffix == '.pdf':
|
||||
comic_info = ComicInfo.from_pdf(comic_path)
|
||||
elif comic_path.suffix == '.cbr':
|
||||
comic_info = ComicInfo.from_cbr(comic_path)
|
||||
else:
|
||||
comic_info = ComicInfo.from_cbz(comic_path)
|
||||
|
||||
# Launch the CBZ player
|
||||
comic_info.show()
|
||||
except Exception as e:
|
||||
|
||||
@@ -5,12 +5,14 @@ import zipfile
|
||||
from datetime import datetime, timezone
|
||||
from enum import Enum
|
||||
from io import BytesIO
|
||||
from typing import Union
|
||||
from typing import Union, List
|
||||
from pathlib import Path
|
||||
|
||||
import fitz
|
||||
import rarfile
|
||||
import xmltodict
|
||||
|
||||
from pypdf import PdfReader
|
||||
|
||||
from cbz.constants import XML_NAME, COMIC_FIELDS, IMAGE_FORMAT, PAGE_FIELDS
|
||||
from cbz.models import ComicModel
|
||||
from cbz.page import PageInfo
|
||||
@@ -22,27 +24,27 @@ class ComicInfo(ComicModel):
|
||||
ComicInfo class that represents the comic book information and pages.
|
||||
"""
|
||||
|
||||
def __init__(self, pages: list[PageInfo], **kwargs):
|
||||
def __init__(self, pages: List[PageInfo], **kwargs):
|
||||
"""
|
||||
Initialize the ComicInfo instance with pages and additional attributes.
|
||||
|
||||
Args:
|
||||
pages (list[PageInfo]): List of PageInfo objects representing the comic pages.
|
||||
pages (List[PageInfo]): List of PageInfo objects representing the comic pages.
|
||||
**kwargs: Additional attributes for the comic.
|
||||
|
||||
Attributes:
|
||||
pages (list[PageInfo]): Stores the comic pages.
|
||||
pages (List[PageInfo]): Stores the comic pages.
|
||||
"""
|
||||
super(ComicInfo, self).__init__(**kwargs)
|
||||
self.pages = pages
|
||||
|
||||
@classmethod
|
||||
def from_pages(cls, pages: list[PageInfo], **kwargs) -> ComicInfo:
|
||||
def from_pages(cls, pages: List[PageInfo], **kwargs) -> ComicInfo:
|
||||
"""
|
||||
Create a ComicInfo instance from pages and additional attributes.
|
||||
|
||||
Args:
|
||||
pages (list[PageInfo]): List of PageInfo objects representing the comic pages.
|
||||
pages (List[PageInfo]): List of PageInfo objects representing the comic pages.
|
||||
**kwargs: Additional attributes for the comic.
|
||||
|
||||
Returns:
|
||||
@@ -66,7 +68,25 @@ class ComicInfo(ComicModel):
|
||||
"""
|
||||
if not isinstance(path, (Path, str)):
|
||||
raise ValueError(f'Expecting Path object or path string, got {path!r}')
|
||||
return cls.__unpack_zip(path)
|
||||
return cls.__unpack_zip(Path(path))
|
||||
|
||||
@classmethod
|
||||
def from_cbr(cls, path: Union[Path, str]) -> ComicInfo:
|
||||
"""
|
||||
Create a ComicInfo instance from a CBR file.
|
||||
|
||||
Args:
|
||||
path (Union[Path, str]): Path to the CBR file.
|
||||
|
||||
Returns:
|
||||
ComicInfo: An instance of ComicInfo.
|
||||
|
||||
Raises:
|
||||
ValueError: If the provided path is not a Path object or a string.
|
||||
"""
|
||||
if not isinstance(path, (Path, str)):
|
||||
raise ValueError(f'Expecting Path object or path string, got {path!r}')
|
||||
return cls.__unpack_rar(Path(path))
|
||||
|
||||
@classmethod
|
||||
def from_pdf(cls, path: Union[Path, str]) -> ComicInfo:
|
||||
@@ -84,7 +104,7 @@ class ComicInfo(ComicModel):
|
||||
"""
|
||||
if not isinstance(path, (Path, str)):
|
||||
raise ValueError(f'Expecting Path object or path string, got {path!r}')
|
||||
return cls.__unpack_pdf(path)
|
||||
return cls.__unpack_pdf(Path(path))
|
||||
|
||||
@staticmethod
|
||||
def __unpack_pdf(path: Path) -> ComicInfo:
|
||||
@@ -97,18 +117,89 @@ class ComicInfo(ComicModel):
|
||||
Returns:
|
||||
ComicInfo: An instance of ComicInfo.
|
||||
"""
|
||||
pages: list[PageInfo] = []
|
||||
with fitz.open(path) as pf:
|
||||
for element in pf:
|
||||
# Check if the page has images
|
||||
images = element.get_images(full=True)
|
||||
for i, image in enumerate(images):
|
||||
base = pf.extract_image(image[0])
|
||||
pages.append(PageInfo.loads(data=base['image']))
|
||||
pages: List[PageInfo] = []
|
||||
reader = PdfReader(path)
|
||||
for page in reader.pages:
|
||||
for image in page.images:
|
||||
pages.append(PageInfo.loads(data=image.data))
|
||||
|
||||
assert pages, 'No valid images present in file'
|
||||
return ComicInfo.from_pages(pages=pages)
|
||||
|
||||
@staticmethod
|
||||
def __extract_info(items: dict, fields: dict) -> dict:
|
||||
"""
|
||||
Extract and convert field information from the provided items and fields.
|
||||
|
||||
Args:
|
||||
items (dict): Dictionary containing item attributes.
|
||||
fields (dict): Dictionary containing field mappings and types.
|
||||
|
||||
Returns:
|
||||
dict: Dictionary with extracted and converted field information.
|
||||
"""
|
||||
content = {}
|
||||
for key, (field_key, field_type) in fields.items():
|
||||
if field_key in items:
|
||||
content[key] = field_type(items[field_key])
|
||||
return content
|
||||
|
||||
@staticmethod
|
||||
def __process_archive(archive_file: Union[zipfile.ZipFile, rarfile.RarFile]) -> ComicInfo:
|
||||
"""
|
||||
Common logic for processing archive files (CBZ/CBR).
|
||||
|
||||
Args:
|
||||
archive_file (Union[ZipFile, RarFile]): Archive file object (ZipFile or RarFile)
|
||||
|
||||
Returns:
|
||||
ComicInfo: An instance of ComicInfo.
|
||||
"""
|
||||
pages = []
|
||||
names = sorted(archive_file.namelist())
|
||||
comic_info = {}
|
||||
|
||||
if XML_NAME in names:
|
||||
with archive_file.open(XML_NAME, 'r') as f:
|
||||
comic_info = xmltodict.parse(f.read(), force_list=('Page',)).get('ComicInfo', {})
|
||||
names.remove(XML_NAME)
|
||||
|
||||
comic = ComicInfo.__extract_info(
|
||||
items=comic_info,
|
||||
fields=COMIC_FIELDS
|
||||
)
|
||||
|
||||
pages_info = comic_info.get('Pages', {}).get('Page', [])
|
||||
for i, name in enumerate(names):
|
||||
suffix = Path(name).suffix
|
||||
if suffix:
|
||||
assert suffix in IMAGE_FORMAT, f'Unsupported image format: {suffix}'
|
||||
with archive_file.open(name, 'r') as f:
|
||||
page_info = {}
|
||||
if i < len(pages_info):
|
||||
page_info = ComicInfo.__extract_info(
|
||||
items=pages_info[i],
|
||||
fields=PAGE_FIELDS
|
||||
)
|
||||
page_info['name'] = Path(name).name
|
||||
pages.append(PageInfo.loads(data=f.read(), **page_info))
|
||||
|
||||
return ComicInfo.from_pages(pages=pages, **comic)
|
||||
|
||||
@staticmethod
|
||||
def __unpack_rar(path: Path) -> ComicInfo:
|
||||
"""
|
||||
Unpack a CBR file and create a ComicInfo instance.
|
||||
|
||||
Args:
|
||||
path (Path): Path to the CBR file.
|
||||
|
||||
Returns:
|
||||
ComicInfo: An instance of ComicInfo.
|
||||
"""
|
||||
with rarfile.RarFile(path, 'r') as rf:
|
||||
return ComicInfo.__process_archive(rf)
|
||||
|
||||
@staticmethod
|
||||
def __unpack_zip(path: Path) -> ComicInfo:
|
||||
"""
|
||||
@@ -120,56 +211,8 @@ class ComicInfo(ComicModel):
|
||||
Returns:
|
||||
ComicInfo: An instance of ComicInfo.
|
||||
"""
|
||||
|
||||
def __info(items: dict, fields: dict) -> dict:
|
||||
"""
|
||||
Extract and convert field information from the provided items and fields.
|
||||
|
||||
Args:
|
||||
items (dict): Dictionary containing item attributes.
|
||||
fields (dict): Dictionary containing field mappings and types.
|
||||
|
||||
Returns:
|
||||
dict: Dictionary with extracted and converted field information.
|
||||
"""
|
||||
content = {}
|
||||
for key, (field_key, field_type) in fields.items():
|
||||
if field_key in items:
|
||||
content[key] = field_type(items[field_key])
|
||||
return content
|
||||
|
||||
pages = []
|
||||
|
||||
with zipfile.ZipFile(path, 'r', zipfile.ZIP_STORED) as zf:
|
||||
names = zf.namelist()
|
||||
comic_info = {}
|
||||
|
||||
if XML_NAME in names:
|
||||
with zf.open(XML_NAME, 'r') as f:
|
||||
comic_info = xmltodict.parse(f.read()).get('ComicInfo', {})
|
||||
names.remove(XML_NAME)
|
||||
|
||||
comic = __info(
|
||||
items=comic_info,
|
||||
fields=COMIC_FIELDS
|
||||
)
|
||||
|
||||
pages_info = comic_info.get('Pages', {}).get('Page', [])
|
||||
for i, name in enumerate(names):
|
||||
suffix = Path(name).suffix
|
||||
if suffix:
|
||||
assert suffix in IMAGE_FORMAT, f'Unsupported image format: {suffix}'
|
||||
with zf.open(name, 'r') as f:
|
||||
page_info = {}
|
||||
if i < len(pages_info):
|
||||
page_info = __info(
|
||||
items=pages_info[i],
|
||||
fields=PAGE_FIELDS
|
||||
)
|
||||
page_info['name'] = Path(f.name).name
|
||||
pages.append(PageInfo.loads(data=f.read(), **page_info))
|
||||
|
||||
return ComicInfo.from_pages(pages=pages, **comic)
|
||||
return ComicInfo.__process_archive(zf)
|
||||
|
||||
def get_info(self) -> dict:
|
||||
"""
|
||||
|
||||
@@ -5,12 +5,14 @@ from langcodes import Language
|
||||
|
||||
XML_NAME = 'ComicInfo.xml'
|
||||
IMAGE_FORMAT = {
|
||||
'.jpeg', '.jpg', # Joint Photographic Experts Group
|
||||
'.png', # Portable Network Graphics
|
||||
'.gif', # Graphics Interchange Format
|
||||
'.bmp', # Bitmap Image File
|
||||
'.tiff', '.tif', # Tagged Image File Format
|
||||
'.webp' # Web Picture Format
|
||||
'.jpeg', '.jpg', # JPEG (Joint Photographic Experts Group)
|
||||
'.png', # PNG (Portable Network Graphics)
|
||||
'.gif', # GIF (Graphics Interchange Format)
|
||||
'.bmp', # BMP (Bitmap Image File)
|
||||
'.tiff', '.tif', # TIFF (Tagged Image File Format)
|
||||
'.webp', # WebP (Web Picture Format, by Google)
|
||||
'.jxl', # JPEG XL (Next-generation JPEG format)
|
||||
'.avif' # AVIF (AV1 Image File Format, based on AV1 codec)
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -3,10 +3,13 @@ import tkinter as tk
|
||||
|
||||
from io import BytesIO
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import DISABLED, NORMAL
|
||||
from ctypes import windll
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from ctypes import windll
|
||||
except ImportError:
|
||||
windll = None # windll is not available on this platform
|
||||
|
||||
from PIL import Image, ImageTk
|
||||
|
||||
from cbz.comic import ComicInfo
|
||||
@@ -203,7 +206,7 @@ class Player:
|
||||
self.summary_text = tk.Text(self.canvas, wrap=tk.WORD, bg='white', bd=0, padx=10, pady=10)
|
||||
self.summary_text.tag_configure('bold', font=('Arial', 13, 'bold'))
|
||||
self.summary_text.tag_configure('normal', font=('Arial', 12), lmargin1=10, lmargin2=10)
|
||||
self.summary_text.config(state=DISABLED)
|
||||
self.summary_text.config(state=tk.DISABLED)
|
||||
|
||||
def show_page(self) -> None:
|
||||
"""
|
||||
@@ -219,8 +222,8 @@ class Player:
|
||||
self._show_image_page()
|
||||
|
||||
# Update navigation button states based on current page index
|
||||
self.prev_button.config(state=DISABLED if self.current_page == -1 else NORMAL)
|
||||
self.next_button.config(state=DISABLED if self.current_page + 1 == len(self.comic_info.pages) else NORMAL)
|
||||
self.prev_button.config(state=tk.DISABLED if self.current_page == -1 else tk.NORMAL)
|
||||
self.next_button.config(state=tk.DISABLED if self.current_page + 1 == len(self.comic_info.pages) else tk.NORMAL)
|
||||
|
||||
# Update page index label text
|
||||
self.page_index_label.config(text=f'{self.current_page + 1}/{len(self.comic_info.pages)}')
|
||||
@@ -235,7 +238,7 @@ class Player:
|
||||
# Display summary for the first page
|
||||
infos = self.comic_info.get_info()
|
||||
|
||||
self.summary_text.config(state=NORMAL)
|
||||
self.summary_text.config(state=tk.NORMAL)
|
||||
self.summary_text.delete('1.0', tk.END)
|
||||
|
||||
for key, value in infos.items():
|
||||
@@ -245,7 +248,7 @@ class Player:
|
||||
self.summary_text.insert(tk.END, f'{key}\n', 'bold')
|
||||
self.summary_text.insert(tk.END, f'{value}\n\n', 'normal')
|
||||
|
||||
self.summary_text.config(state=DISABLED)
|
||||
self.summary_text.config(state=tk.DISABLED)
|
||||
self.summary_text.place(relwidth=1, relheight=1)
|
||||
|
||||
def _show_image_page(self) -> None:
|
||||
|
||||
@@ -8,7 +8,7 @@ from PIL.IcoImagePlugin import IcoFile
|
||||
|
||||
def default_attr(value: any) -> any:
|
||||
"""
|
||||
Provides a default value based on the expected type of an attribute.
|
||||
Provides a default value based on the expected type of attribute.
|
||||
|
||||
Args:
|
||||
value (any): Expected type or class of the attribute.
|
||||
|
||||
@@ -4,12 +4,22 @@ build-backend = "poetry.core.masonry.api"
|
||||
|
||||
[tool.poetry]
|
||||
name = "cbz"
|
||||
version = "3.3.6"
|
||||
description = "CBZ simplifies creating, managing, and viewing comic book files in CBZ format, offering seamless packaging, metadata handling, and built-in viewing capabilities"
|
||||
version = "3.4.4"
|
||||
description = "CBZ simplifies creating, managing, and viewing comic book files in CBZ, CBR, and PDF formats, offering seamless packaging, metadata handling and built-in viewing capabilities."
|
||||
license = "MIT"
|
||||
authors = ["hyugogirubato <65763543+hyugogirubato@users.noreply.github.com>"]
|
||||
readme = "README.md"
|
||||
keywords = ["python", "cbz", "ebooks", "manga", "comics", "webtoons"]
|
||||
repository = "https://github.com/hyugogirubato/cbz"
|
||||
keywords = [
|
||||
"python",
|
||||
"cbz",
|
||||
"cbr",
|
||||
"pdf",
|
||||
"ebooks",
|
||||
"manga",
|
||||
"comics",
|
||||
"webtoons",
|
||||
]
|
||||
classifiers = [
|
||||
"Development Status :: 5 - Production/Stable",
|
||||
"Intended Audience :: Developers",
|
||||
@@ -17,12 +27,12 @@ classifiers = [
|
||||
"Natural Language :: English",
|
||||
"Operating System :: OS Independent",
|
||||
"Topic :: Utilities",
|
||||
"Topic :: Software Development :: Libraries :: Python Modules"
|
||||
"Topic :: Software Development :: Libraries :: Python Modules",
|
||||
]
|
||||
include = [
|
||||
{ path = "CHANGELOG.md", format = "sdist" },
|
||||
{ path = "README.md", format = "sdist" },
|
||||
{ path = "LICENSE", format = "sdist" }
|
||||
{ path = "LICENSE", format = "sdist" },
|
||||
]
|
||||
|
||||
[tool.poetry.urls]
|
||||
@@ -30,11 +40,18 @@ include = [
|
||||
"Changelog" = "https://github.com/hyugogirubato/cbz/blob/main/CHANGELOG.md"
|
||||
|
||||
[tool.poetry.dependencies]
|
||||
python = ">=3.8"
|
||||
xmltodict = ">=0.13.0"
|
||||
python = ">=3.8,<4.0"
|
||||
langcodes = ">=3.4.0"
|
||||
Pillow = ">=10.4.0"
|
||||
PyMuPDF = ">=1.24.7"
|
||||
pypdf = ">=5.7.0"
|
||||
rarfile = ">=4.2"
|
||||
xmltodict = ">=0.14.2"
|
||||
pillow-avif-plugin = { version = ">=1.5.2", optional = true, markers = "python_version >= '3.9'" }
|
||||
pillow-jxl-plugin = { version = ">=1.3.4", optional = true, markers = "python_version >= '3.9'" }
|
||||
|
||||
|
||||
[tool.poetry.extras]
|
||||
pillow = ["pillow-avif-plugin", "pillow-jxl-plugin"]
|
||||
|
||||
[tool.poetry.scripts]
|
||||
cbzplayer = "cbz.__main__:main"
|
||||
@@ -44,5 +61,15 @@ name = "localpypi"
|
||||
url = "https://pypi.org/simple/"
|
||||
priority = "primary"
|
||||
|
||||
[tool.poetry.group.dev.dependencies]
|
||||
pytest = ">=7.4.0,<9.0.0"
|
||||
pytest-cov = ">=5.0.0"
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
addopts = [
|
||||
"--cov=cbz",
|
||||
]
|
||||
|
||||
[certificates]
|
||||
localpypi = { cert = false }
|
||||
localpypi = { cert = false }
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from cbz.comic import ComicInfo
|
||||
from cbz.page import PageInfo
|
||||
from cbz.constants import PageType
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fixtures_dir() -> Path:
|
||||
"""Fixture that provides the path to the test fixtures directory."""
|
||||
return Path(__file__).parent / 'fixtures'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def images_dir(fixtures_dir: Path) -> Path:
|
||||
"""Fixture that provides the path to the test images directory."""
|
||||
return fixtures_dir / 'images'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_image_path(images_dir: Path) -> Path:
|
||||
"""Fixture that provides a sample image path."""
|
||||
return images_dir / 'page-000.jpg'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def sample_cbz_file(tmp_path: Path, images_dir: Path) -> Path:
|
||||
"""Fixture that creates a sample CBZ file for testing."""
|
||||
# Load sample pages
|
||||
image_paths = sorted(list(images_dir.iterdir()))[:3] # Use first 3 images
|
||||
pages = []
|
||||
|
||||
for i, path in enumerate(image_paths):
|
||||
page_type = PageType.FRONT_COVER if i == 0 else PageType.STORY
|
||||
page = PageInfo.load(path=path, type=page_type)
|
||||
pages.append(page)
|
||||
|
||||
# Create comic from pages
|
||||
comic = ComicInfo.from_pages(
|
||||
pages=pages,
|
||||
title='Test Comic',
|
||||
series='Test Series',
|
||||
number=1,
|
||||
volume=1,
|
||||
year=2024
|
||||
)
|
||||
|
||||
# Save to temporary file
|
||||
cbz_path = tmp_path / 'test_comic.cbz'
|
||||
cbz_content = comic.pack()
|
||||
cbz_path.write_bytes(cbz_content)
|
||||
|
||||
return cbz_path
|
||||
@@ -7,7 +7,7 @@ from cbz.page import PageInfo
|
||||
PARENT = Path(__file__).parent
|
||||
|
||||
if __name__ == '__main__':
|
||||
paths = list((PARENT / 'images').iterdir())
|
||||
paths = list((PARENT / 'fixtures' / 'images').iterdir())
|
||||
|
||||
# Load each page from the 'images' folder into a list of PageInfo objects
|
||||
pages = [
|
||||
|
Before Width: | Height: | Size: 247 KiB After Width: | Height: | Size: 247 KiB |
|
Before Width: | Height: | Size: 32 KiB After Width: | Height: | Size: 32 KiB |
|
Before Width: | Height: | Size: 143 KiB After Width: | Height: | Size: 143 KiB |
|
Before Width: | Height: | Size: 120 KiB After Width: | Height: | Size: 120 KiB |
|
Before Width: | Height: | Size: 619 KiB After Width: | Height: | Size: 619 KiB |
|
Before Width: | Height: | Size: 592 KiB After Width: | Height: | Size: 592 KiB |
|
Before Width: | Height: | Size: 680 KiB After Width: | Height: | Size: 680 KiB |
|
Before Width: | Height: | Size: 590 KiB After Width: | Height: | Size: 590 KiB |
|
Before Width: | Height: | Size: 492 KiB After Width: | Height: | Size: 492 KiB |
|
Before Width: | Height: | Size: 479 KiB After Width: | Height: | Size: 479 KiB |
|
Before Width: | Height: | Size: 549 KiB After Width: | Height: | Size: 549 KiB |
@@ -0,0 +1,179 @@
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import List
|
||||
|
||||
from cbz.comic import ComicInfo
|
||||
from cbz.page import PageInfo
|
||||
from cbz.constants import PageType, YesNo, Manga, AgeRating, Format
|
||||
|
||||
|
||||
class TestComicInfo:
|
||||
"""Test cases for ComicInfo class."""
|
||||
|
||||
def test_from_pages_creation(self, images_dir: Path) -> None:
|
||||
"""Test creating ComicInfo from pages."""
|
||||
# Load sample pages
|
||||
image_paths = sorted(list(images_dir.iterdir()))[:3] # Use first 3 images
|
||||
pages: List[PageInfo] = []
|
||||
|
||||
for i, path in enumerate(image_paths):
|
||||
page_type = PageType.FRONT_COVER if i == 0 else PageType.STORY
|
||||
page = PageInfo.load(path=path, type=page_type)
|
||||
pages.append(page)
|
||||
|
||||
# Create comic from pages
|
||||
comic = ComicInfo.from_pages(
|
||||
pages=pages,
|
||||
title='Test Comic',
|
||||
series='Test Series',
|
||||
number=1,
|
||||
volume=1,
|
||||
year=2024
|
||||
)
|
||||
|
||||
assert comic.title == 'Test Comic'
|
||||
assert comic.series == 'Test Series'
|
||||
assert comic.number == 1
|
||||
assert comic.volume == 1
|
||||
assert comic.year == 2024
|
||||
assert len(comic.pages) == 3
|
||||
assert comic.pages[0].type == PageType.FRONT_COVER
|
||||
assert comic.pages[1].type == PageType.STORY
|
||||
|
||||
def test_from_cbz_file(self, sample_cbz_file: Path) -> None:
|
||||
"""Test loading ComicInfo from CBZ file."""
|
||||
comic = ComicInfo.from_cbz(sample_cbz_file)
|
||||
|
||||
assert comic is not None
|
||||
assert hasattr(comic, 'pages')
|
||||
assert len(comic.pages) > 0
|
||||
assert all(isinstance(page, PageInfo) for page in comic.pages)
|
||||
|
||||
def test_pack_cbz(self, images_dir: Path) -> None:
|
||||
"""Test packing comic into CBZ format."""
|
||||
# Create a simple comic
|
||||
image_paths = sorted(list(images_dir.iterdir()))[:2]
|
||||
pages = [PageInfo.load(path=path) for path in image_paths]
|
||||
|
||||
comic = ComicInfo.from_pages(
|
||||
pages=pages,
|
||||
title='Pack Test',
|
||||
series='Test Series'
|
||||
)
|
||||
|
||||
# Pack to CBZ
|
||||
cbz_content = comic.pack()
|
||||
|
||||
assert isinstance(cbz_content, bytes)
|
||||
assert len(cbz_content) > 0
|
||||
|
||||
def test_pack_with_rename(self, images_dir: Path) -> None:
|
||||
"""Test packing comic with page renaming."""
|
||||
image_paths = sorted(list(images_dir.iterdir()))[:2]
|
||||
pages = [PageInfo.load(path=path) for path in image_paths]
|
||||
|
||||
comic = ComicInfo.from_pages(
|
||||
pages=pages,
|
||||
title='Rename Test'
|
||||
)
|
||||
|
||||
# Pack with rename option
|
||||
cbz_content = comic.pack(rename=True)
|
||||
|
||||
assert isinstance(cbz_content, bytes)
|
||||
assert len(cbz_content) > 0
|
||||
|
||||
def test_comic_metadata_properties(self, images_dir: Path) -> None:
|
||||
"""Test comic metadata properties."""
|
||||
image_paths = sorted(list(images_dir.iterdir()))[:1]
|
||||
pages = [PageInfo.load(path=path) for path in image_paths]
|
||||
|
||||
comic = ComicInfo.from_pages(
|
||||
pages=pages,
|
||||
title='Metadata Test',
|
||||
series='Test Series',
|
||||
number=5,
|
||||
count=10,
|
||||
volume=2,
|
||||
summary='Test summary',
|
||||
year=2023,
|
||||
month=6,
|
||||
day=15,
|
||||
writer='Test Writer',
|
||||
penciller='Test Penciller',
|
||||
inker='Test Inker',
|
||||
colorist='Test Colorist',
|
||||
letterer='Test Letterer',
|
||||
cover_artist='Test Cover Artist',
|
||||
editor='Test Editor',
|
||||
publisher='Test Publisher',
|
||||
imprint='Test Imprint',
|
||||
genre='Test Genre',
|
||||
language_iso='en',
|
||||
format=Format.SERIES,
|
||||
black_white=YesNo.NO,
|
||||
manga=Manga.RIGHT_LEFT,
|
||||
age_rating=AgeRating.TEEN,
|
||||
community_rating=4
|
||||
)
|
||||
|
||||
assert comic.title == 'Metadata Test'
|
||||
assert comic.series == 'Test Series'
|
||||
assert comic.number == 5
|
||||
assert comic.count == 10
|
||||
assert comic.volume == 2
|
||||
assert comic.summary == 'Test summary'
|
||||
assert comic.year == 2023
|
||||
assert comic.month == 6
|
||||
assert comic.day == 15
|
||||
assert comic.writer == 'Test Writer'
|
||||
assert comic.penciller == 'Test Penciller'
|
||||
assert comic.inker == 'Test Inker'
|
||||
assert comic.colorist == 'Test Colorist'
|
||||
assert comic.letterer == 'Test Letterer'
|
||||
assert comic.cover_artist == 'Test Cover Artist'
|
||||
assert comic.editor == 'Test Editor'
|
||||
assert comic.publisher == 'Test Publisher'
|
||||
assert comic.imprint == 'Test Imprint'
|
||||
assert comic.genre == 'Test Genre'
|
||||
assert comic.language_iso == 'en'
|
||||
assert comic.format == Format.SERIES
|
||||
assert comic.black_white == YesNo.NO
|
||||
assert comic.manga == Manga.RIGHT_LEFT
|
||||
assert comic.age_rating == AgeRating.TEEN
|
||||
assert comic.community_rating == 4
|
||||
|
||||
def test_page_count_property(self, images_dir: Path) -> None:
|
||||
"""Test that page count returns correct count."""
|
||||
image_paths = sorted(list(images_dir.iterdir()))[:4]
|
||||
pages = [PageInfo.load(path=path) for path in image_paths]
|
||||
|
||||
comic = ComicInfo.from_pages(pages=pages, title='Count Test')
|
||||
|
||||
assert len(comic.pages) == 4
|
||||
|
||||
def test_empty_pages_list(self) -> None:
|
||||
"""Test creating comic with empty pages list."""
|
||||
comic = ComicInfo.from_pages(pages=[], title='Empty Test')
|
||||
|
||||
assert comic.title == 'Empty Test'
|
||||
assert len(comic.pages) == 0
|
||||
|
||||
def test_single_page_comic_load(self, images_dir):
|
||||
"""Test loading comic with a single page."""
|
||||
image_paths = sorted(list(images_dir.iterdir()))[:1]
|
||||
pages = [PageInfo.load(path=path) for path in image_paths]
|
||||
|
||||
comic = ComicInfo.from_pages(pages=pages, title="Single Page Test")
|
||||
|
||||
with tempfile.TemporaryDirectory() as temp_dir:
|
||||
temp_path = Path(temp_dir) / "single_page.cbz"
|
||||
data = comic.pack()
|
||||
with open(temp_path, "wb") as f:
|
||||
f.write(data)
|
||||
|
||||
assert temp_path.exists()
|
||||
|
||||
comic_loaded = ComicInfo.from_cbz(temp_path)
|
||||
assert comic_loaded.title == "Single Page Test"
|
||||
assert len(comic_loaded.pages) == 1
|
||||
@@ -0,0 +1,265 @@
|
||||
from cbz.models import BaseModel, ComicModel, PageModel
|
||||
from cbz.constants import Format, YesNo, Manga, AgeRating, PageType
|
||||
|
||||
|
||||
class TestBaseModel:
|
||||
"""Test cases for BaseModel class."""
|
||||
|
||||
def test_base_model_creation(self) -> None:
|
||||
"""Test creating BaseModel with fields."""
|
||||
test_fields = {
|
||||
'test_str': ('Test String', str),
|
||||
'test_int': ('Test Integer', int),
|
||||
'test_bool': ('Test Boolean', bool)
|
||||
}
|
||||
|
||||
model = BaseModel(fields=test_fields)
|
||||
|
||||
# Check default values are set
|
||||
assert hasattr(model, 'test_str')
|
||||
assert hasattr(model, 'test_int')
|
||||
assert hasattr(model, 'test_bool')
|
||||
|
||||
def test_base_model_with_kwargs(self) -> None:
|
||||
"""Test creating BaseModel with keyword arguments."""
|
||||
test_fields = {
|
||||
'title': ('Title', str),
|
||||
'number': ('Number', int),
|
||||
'published': ('Published', bool)
|
||||
}
|
||||
|
||||
model = BaseModel(
|
||||
fields=test_fields,
|
||||
title='Test Title',
|
||||
number=42,
|
||||
published=True
|
||||
)
|
||||
|
||||
assert model.title == 'Test Title'
|
||||
assert model.number == 42
|
||||
assert model.published
|
||||
|
||||
def test_attribute_type_verification(self) -> None:
|
||||
"""Test that attribute types are verified on assignment."""
|
||||
test_fields = {
|
||||
'count': ('Count', int),
|
||||
'name': ('Name', str)
|
||||
}
|
||||
|
||||
model = BaseModel(fields=test_fields)
|
||||
|
||||
# Valid assignments
|
||||
model.count = 10
|
||||
model.name = 'Test'
|
||||
|
||||
assert model.count == 10
|
||||
assert model.name == 'Test'
|
||||
|
||||
def test_repr_method(self) -> None:
|
||||
"""Test string representation of BaseModel."""
|
||||
test_fields = {
|
||||
'title': ('Title', str)
|
||||
}
|
||||
|
||||
model = BaseModel(fields=test_fields, title='Test')
|
||||
repr_str = repr(model)
|
||||
|
||||
assert isinstance(repr_str, str)
|
||||
assert 'BaseModel' in repr_str
|
||||
|
||||
|
||||
class TestComicModel:
|
||||
"""Test cases for ComicModel class."""
|
||||
|
||||
def test_comic_model_creation(self) -> None:
|
||||
"""Test creating ComicModel with default values."""
|
||||
model = ComicModel()
|
||||
|
||||
# Check that comic-specific attributes exist
|
||||
assert hasattr(model, 'title')
|
||||
assert hasattr(model, 'series')
|
||||
assert hasattr(model, 'number')
|
||||
assert hasattr(model, 'volume')
|
||||
assert hasattr(model, 'year')
|
||||
assert hasattr(model, 'month')
|
||||
assert hasattr(model, 'day')
|
||||
|
||||
def test_comic_model_with_values(self) -> None:
|
||||
"""Test creating ComicModel with specific values."""
|
||||
model = ComicModel(
|
||||
title='Test Comic',
|
||||
series='Test Series',
|
||||
number=1,
|
||||
volume=1,
|
||||
year=2024,
|
||||
month=6,
|
||||
day=15,
|
||||
writer='Test Writer',
|
||||
publisher='Test Publisher',
|
||||
language_iso='en',
|
||||
format=Format.SERIES,
|
||||
black_white=YesNo.NO,
|
||||
manga=Manga.RIGHT_LEFT,
|
||||
age_rating=AgeRating.EVERYONE
|
||||
)
|
||||
|
||||
assert model.title == 'Test Comic'
|
||||
assert model.series == 'Test Series'
|
||||
assert model.number == 1
|
||||
assert model.volume == 1
|
||||
assert model.year == 2024
|
||||
assert model.month == 6
|
||||
assert model.day == 15
|
||||
assert model.writer == 'Test Writer'
|
||||
assert model.publisher == 'Test Publisher'
|
||||
assert model.language_iso == 'en'
|
||||
assert model.format == Format.SERIES
|
||||
assert model.black_white == YesNo.NO
|
||||
assert model.manga == Manga.RIGHT_LEFT
|
||||
assert model.age_rating == AgeRating.EVERYONE
|
||||
|
||||
def test_comic_model_enum_properties(self) -> None:
|
||||
"""Test that enum properties work correctly."""
|
||||
model = ComicModel()
|
||||
|
||||
# Test format enum
|
||||
model.format = Format.PREVIEW
|
||||
assert model.format == Format.PREVIEW
|
||||
|
||||
# Test yes/no enum
|
||||
model.black_white = YesNo.YES
|
||||
assert model.black_white == YesNo.YES
|
||||
|
||||
# Test manga enum
|
||||
model.manga = Manga.RIGHT_LEFT
|
||||
assert model.manga == Manga.RIGHT_LEFT
|
||||
|
||||
# Test age rating enum
|
||||
model.age_rating = AgeRating.TEEN
|
||||
assert model.age_rating == AgeRating.TEEN
|
||||
|
||||
def test_comic_model_metadata_fields(self) -> None:
|
||||
"""Test comic metadata fields."""
|
||||
model = ComicModel(
|
||||
summary='Test summary',
|
||||
notes='Test notes',
|
||||
genre='Adventure',
|
||||
web='http://example.com',
|
||||
ean='1234567890123',
|
||||
community_rating=5,
|
||||
main_character_or_team='Hero',
|
||||
characters='Hero, Villain',
|
||||
teams='Justice League',
|
||||
locations='Metropolis',
|
||||
scan_information='Scanned by Test',
|
||||
story_arc='Origin Story',
|
||||
series_group='DC Comics',
|
||||
alternate_series='Alternate Universe',
|
||||
alternate_number=2,
|
||||
alternate_count=10
|
||||
)
|
||||
|
||||
assert model.summary == 'Test summary'
|
||||
assert model.notes == 'Test notes'
|
||||
assert model.genre == 'Adventure'
|
||||
assert model.web == 'http://example.com'
|
||||
assert model.ean == '1234567890123'
|
||||
assert model.community_rating == 5
|
||||
assert model.main_character_or_team == 'Hero'
|
||||
assert model.characters == 'Hero, Villain'
|
||||
assert model.teams == 'Justice League'
|
||||
assert model.locations == 'Metropolis'
|
||||
assert model.scan_information == 'Scanned by Test'
|
||||
assert model.story_arc == 'Origin Story'
|
||||
assert model.series_group == 'DC Comics'
|
||||
assert model.alternate_series == 'Alternate Universe'
|
||||
assert model.alternate_number == 2
|
||||
assert model.alternate_count == 10
|
||||
|
||||
|
||||
class TestPageModel:
|
||||
"""Test cases for PageModel class."""
|
||||
|
||||
def test_page_model_creation(self) -> None:
|
||||
"""Test creating PageModel with default values."""
|
||||
model = PageModel()
|
||||
|
||||
# Check that page-specific attributes exist
|
||||
assert hasattr(model, 'image')
|
||||
assert hasattr(model, 'type')
|
||||
assert hasattr(model, 'double')
|
||||
assert hasattr(model, 'image_size')
|
||||
assert hasattr(model, 'key')
|
||||
assert hasattr(model, 'bookmark')
|
||||
assert hasattr(model, 'image_width')
|
||||
assert hasattr(model, 'image_height')
|
||||
assert hasattr(model, 'image_size')
|
||||
# Note: format is not a base field in PageModel
|
||||
|
||||
def test_page_model_with_values(self) -> None:
|
||||
"""Test creating PageModel with specific values."""
|
||||
model = PageModel(
|
||||
type=PageType.FRONT_COVER,
|
||||
double=True,
|
||||
image_size=1024000,
|
||||
key='cover',
|
||||
bookmark='Chapter 1',
|
||||
image_width=800,
|
||||
image_height=1200,
|
||||
)
|
||||
|
||||
assert model.type == PageType.FRONT_COVER
|
||||
assert model.double
|
||||
assert model.image_size == 1024000
|
||||
assert model.key == 'cover'
|
||||
assert model.bookmark == 'Chapter 1'
|
||||
assert model.image_width == 800
|
||||
assert model.image_height == 1200
|
||||
|
||||
def test_page_model_page_types(self) -> None:
|
||||
"""Test different page types."""
|
||||
page_types = [
|
||||
PageType.FRONT_COVER,
|
||||
PageType.INNER_COVER,
|
||||
PageType.ROUNDUP,
|
||||
PageType.STORY,
|
||||
PageType.ADVERTISEMENT,
|
||||
PageType.EDITORIAL,
|
||||
PageType.LETTERS,
|
||||
PageType.PREVIEW,
|
||||
PageType.BACK_COVER,
|
||||
PageType.OTHER,
|
||||
PageType.DELETED
|
||||
]
|
||||
|
||||
for page_type in page_types:
|
||||
model = PageModel(type=page_type)
|
||||
assert model.type == page_type
|
||||
|
||||
def test_page_model_boolean_properties(self) -> None:
|
||||
"""Test boolean properties in PageModel."""
|
||||
model = PageModel()
|
||||
|
||||
# Test double property
|
||||
model.double = True
|
||||
assert model.double
|
||||
|
||||
model.double = False
|
||||
assert not model.double
|
||||
|
||||
def test_page_model_numeric_properties(self) -> None:
|
||||
"""Test numeric properties in PageModel."""
|
||||
model = PageModel(
|
||||
image_size=2048000,
|
||||
image_width=1920,
|
||||
image_height=1080
|
||||
)
|
||||
|
||||
assert model.image_size == 2048000
|
||||
assert model.image_width == 1920
|
||||
assert model.image_height == 1080
|
||||
|
||||
# Test that they're integers
|
||||
assert isinstance(model.image_size, int)
|
||||
assert isinstance(model.image_width, int)
|
||||
assert isinstance(model.image_height, int)
|
||||
@@ -0,0 +1,143 @@
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from cbz.page import PageInfo
|
||||
from cbz.constants import PageType
|
||||
|
||||
|
||||
class TestPageInfo:
|
||||
"""Test cases for PageInfo class."""
|
||||
|
||||
def test_load_from_file(self, sample_image_path: Path) -> None:
|
||||
"""Test loading PageInfo from image file."""
|
||||
page = PageInfo.load(path=sample_image_path)
|
||||
|
||||
assert page is not None
|
||||
assert isinstance(page.content, bytes)
|
||||
assert len(page.content) > 0
|
||||
assert page.name == sample_image_path.name
|
||||
assert page.image_width > 0
|
||||
assert page.image_height > 0
|
||||
assert page.image_size > 0
|
||||
assert page.suffix is not None
|
||||
|
||||
def test_load_with_page_type(self, sample_image_path: Path) -> None:
|
||||
"""Test loading PageInfo with specific page type."""
|
||||
page = PageInfo.load(path=sample_image_path, type=PageType.FRONT_COVER)
|
||||
|
||||
assert page.type == PageType.FRONT_COVER
|
||||
|
||||
def test_load_with_custom_name(self, sample_image_path: Path) -> None:
|
||||
"""Test loading PageInfo with custom name."""
|
||||
custom_name = 'custom_page.jpg'
|
||||
page = PageInfo.load(path=sample_image_path, name=custom_name)
|
||||
|
||||
assert page.name == custom_name
|
||||
|
||||
def test_page_content_property(self, sample_image_path: Path) -> None:
|
||||
"""Test page content property getter and setter."""
|
||||
page = PageInfo.load(path=sample_image_path)
|
||||
original_content = page.content
|
||||
|
||||
# Test getter
|
||||
assert page.content == original_content
|
||||
assert isinstance(page.content, bytes)
|
||||
|
||||
# Test that content is properly set and metadata extracted
|
||||
assert page.image_width > 0
|
||||
assert page.image_height > 0
|
||||
assert page.image_size > 0
|
||||
|
||||
def test_image_metadata_extraction(self, sample_image_path: Path) -> None:
|
||||
"""Test that image metadata is correctly extracted."""
|
||||
page = PageInfo.load(path=sample_image_path)
|
||||
|
||||
# Check that all image metadata properties are set
|
||||
assert hasattr(page, 'image_width') and page.image_width > 0
|
||||
assert hasattr(page, 'image_height') and page.image_height > 0
|
||||
assert hasattr(page, 'image_size') and page.image_size > 0
|
||||
assert hasattr(page, 'suffix') and page.suffix is not None
|
||||
|
||||
# Verify dimensions make sense for an image
|
||||
assert isinstance(page.image_width, int)
|
||||
assert isinstance(page.image_height, int)
|
||||
assert isinstance(page.image_size, int)
|
||||
|
||||
def test_multiple_image_formats(self, images_dir: Path) -> None:
|
||||
"""Test loading different image formats."""
|
||||
image_files = list(images_dir.glob('*.jpg'))
|
||||
|
||||
if not image_files:
|
||||
pytest.skip('No image files found in example directory')
|
||||
|
||||
for image_path in image_files[:3]: # Test first 3 images
|
||||
page = PageInfo.load(path=image_path)
|
||||
|
||||
assert page is not None
|
||||
assert isinstance(page.content, bytes)
|
||||
assert len(page.content) > 0
|
||||
assert page.image_width > 0
|
||||
assert page.image_height > 0
|
||||
assert page.image_size > 0
|
||||
|
||||
def test_page_type_assignment(self, sample_image_path: Path) -> None:
|
||||
"""Test different page type assignments."""
|
||||
page_types = [
|
||||
PageType.FRONT_COVER,
|
||||
PageType.INNER_COVER,
|
||||
PageType.ROUNDUP,
|
||||
PageType.STORY,
|
||||
PageType.ADVERTISEMENT,
|
||||
PageType.EDITORIAL,
|
||||
PageType.LETTERS,
|
||||
PageType.PREVIEW,
|
||||
PageType.BACK_COVER,
|
||||
PageType.OTHER,
|
||||
PageType.DELETED
|
||||
]
|
||||
|
||||
for page_type in page_types:
|
||||
page = PageInfo.load(path=sample_image_path, type=page_type)
|
||||
assert page.type == page_type
|
||||
|
||||
def test_page_creation_from_bytes(self, sample_image_path: Path) -> None:
|
||||
"""Test creating PageInfo directly from bytes."""
|
||||
# Read image file as bytes
|
||||
with open(sample_image_path, 'rb') as f:
|
||||
image_bytes = f.read()
|
||||
|
||||
# Create page from bytes
|
||||
page = PageInfo(content=image_bytes, name='test_page.jpg')
|
||||
|
||||
assert page.content == image_bytes
|
||||
assert page.name == 'test_page.jpg'
|
||||
assert page.image_width > 0
|
||||
assert page.image_height > 0
|
||||
assert page.image_size > 0
|
||||
|
||||
def test_repr_string(self, sample_image_path: Path) -> None:
|
||||
"""Test string representation of PageInfo."""
|
||||
page = PageInfo.load(path=sample_image_path, type=PageType.STORY)
|
||||
|
||||
repr_str = repr(page)
|
||||
assert 'PageInfo' in repr_str
|
||||
assert isinstance(repr_str, str)
|
||||
|
||||
def test_page_bookmark_property(self, sample_image_path: Path) -> None:
|
||||
"""Test page bookmark property."""
|
||||
# Test with bookmark
|
||||
page = PageInfo.load(path=sample_image_path, bookmark='Chapter 1')
|
||||
assert page.bookmark == 'Chapter 1'
|
||||
|
||||
# Test without bookmark
|
||||
page_no_bookmark = PageInfo.load(path=sample_image_path)
|
||||
assert hasattr(page_no_bookmark, 'bookmark')
|
||||
|
||||
def test_page_double_page_property(self, sample_image_path: Path) -> None:
|
||||
"""Test page double_page property."""
|
||||
page = PageInfo.load(path=sample_image_path, double=True)
|
||||
assert page.double
|
||||
|
||||
page_no_double = PageInfo.load(path=sample_image_path)
|
||||
assert hasattr(page_no_double, 'double')
|
||||