### Install epubcheck Package Source: https://github.com/titusz/epubcheck/blob/master/README.md Install the epubcheck package using pip. Ensure Python and Java are installed on your system. ```bash pip install epubcheck ``` -------------------------------- ### Install Project Dependencies with Poetry Source: https://github.com/titusz/epubcheck/blob/master/README.md Install project dependencies using Poetry after checking out the repository. ```shell poetry install ``` -------------------------------- ### Validate EPUB using Python Library Source: https://github.com/titusz/epubcheck/blob/master/README.md Use the EpubCheck class from the library to validate an EPUB file and access its messages. Requires the 'epubcheck' package to be installed. ```python from epubcheck import EpubCheck result = EpubCheck('src/epubcheck/samples/invalid.epub') print(result.valid) print(result.messages) ``` -------------------------------- ### Display EPUBCheck Help Source: https://github.com/titusz/epubcheck/blob/master/epubcheck/README.txt Access the command-line help documentation for available arguments. ```bash > java -jar epubcheck.jar --help ``` -------------------------------- ### Run EPUBCheck via Command Line Source: https://github.com/titusz/epubcheck/blob/master/epubcheck/README.txt Execute the tool to validate an EPUB file, outputting errors to the standard error stream. ```bash > java -jar epubcheck.jar file.epub ``` -------------------------------- ### Run Code Formatting, Coverage, and Tests Source: https://github.com/titusz/epubcheck/blob/master/README.md Execute all development checks including formatting, coverage, and tests using the 'poe' command. ```shell poe all ``` -------------------------------- ### Basic EPUB Validation with EpubCheck Class Source: https://context7.com/titusz/epubcheck/llms.txt Use the EpubCheck class for detailed validation. It automatically runs on instantiation and provides access to checker metadata, publication metadata, and individual validation messages. Requires the path to the EPUB file. ```python from epubcheck import EpubCheck # Basic validation - runs automatically on instantiation result = EpubCheck('/path/to/book.epub') # Check if EPUB is valid if result.valid: print("EPUB is valid!") else: print(f"EPUB has {result.checker.nError} errors and {result.checker.nWarning} warnings") # Access checker metadata print(f"EPUBCheck version: {result.checker.checkerVersion}") print(f"Check date: {result.checker.checkDate}") print(f"Processing time: {result.checker.elapsedTime}ms") print(f"Fatal errors: {result.checker.nFatal}") print(f"Errors: {result.checker.nError}") print(f"Warnings: {result.checker.nWarning}") # Access publication metadata print(f"Title: {result.meta.title}") print(f"Creator: {result.meta.creator}" ) # Returns list of creators print(f"Language: {result.meta.language}") print(f"EPUB Version: {result.meta.ePubVersion}") print(f"Publisher: {result.meta.publisher}") print(f"Identifier: {result.meta.identifier}") print(f"Character count: {result.meta.charsCount}") print(f"Has audio: {result.meta.hasAudio}") print(f"Has video: {result.meta.hasVideo}") print(f"Is scripted: {result.meta.isScripted}") print(f"Rendition layout: {result.meta.renditionLayout}") # Iterate through validation messages for msg in result.messages: print(f"{msg.level} - {msg.id} - {msg.location} - {msg.message}") if msg.suggestion: print(f" Suggestion: {msg.suggestion}") ``` -------------------------------- ### Run EpubCheck CLI Source: https://context7.com/titusz/epubcheck/llms.txt Execute validation commands for single files or directories, including report generation options. ```bash # Validate a single EPUB file epubcheck /path/to/book.epub # Validate all EPUB files in current directory epubcheck # Validate all EPUB files in a specific folder epubcheck /path/to/epub/folder # Validate recursively in subfolders epubcheck /path/to/folder --recursive epubcheck /path/to/folder -r # Generate Excel report with validation results epubcheck /path/to/folder --xls report.xls epubcheck /path/to/folder -x report.xls # Generate CSV report with validation messages epubcheck /path/to/folder --csv report.csv epubcheck /path/to/folder -c report.csv # Combine options: recursive validation with Excel report epubcheck /path/to/folder -r --xls validation_report.xls # Show help epubcheck -h epubcheck --help ``` -------------------------------- ### Validate All EPUBs in Current Directory (CLI) Source: https://github.com/titusz/epubcheck/blob/master/README.md Use the command-line tool to validate all EPUB files in the current directory. ```bash epubcheck ``` -------------------------------- ### Execute CLI Programmatically Source: https://context7.com/titusz/epubcheck/llms.txt Integrate the EpubCheck CLI functionality directly into Python scripts using the main function. ```python from epubcheck.cli import main # Validate single file exit_code = main(['/path/to/book.epub']) # Returns 0 if valid, 1 if invalid # Validate folder exit_code = main(['/path/to/epub/folder']) # Generate CSV report exit_code = main(['/path/to/folder', '--csv', 'report.csv']) # Generate Excel report exit_code = main(['/path/to/folder', '--xls', 'report.xls']) # Recursive validation with report exit_code = main(['/path/to/folder', '-r', '--xls', 'report.xls']) # Use in testing import sys from io import StringIO ``` -------------------------------- ### Validate EPUBs and Generate Excel Report (CLI) Source: https://github.com/titusz/epubcheck/blob/master/README.md Validate all EPUB files in a specified folder and generate a detailed Excel report. ```bash epubcheck /path/epubfolder --xls report.xls ``` -------------------------------- ### EPUB Validation with Different Profiles and Languages Source: https://context7.com/titusz/epubcheck/llms.txt Configure EpubCheck with specific validation profiles (e.g., EDUPUB, DICT) or set the language for validation messages. Supports deferred execution by setting `autorun=False` and calling `.run()` manually. ```python from epubcheck import EpubCheck # Validate with default profile result = EpubCheck('/path/to/book.epub', profile=EpubCheck.DEFAULT) # Validate educational publication result = EpubCheck('/path/to/educational.epub', profile=EpubCheck.EDUPUB) # Validate dictionary/glossary EPUB result = EpubCheck('/path/to/dictionary.epub', profile=EpubCheck.DICT) # Validate index publication result = EpubCheck('/path/to/index.epub', profile=EpubCheck.IDX) # Validate preview content result = EpubCheck('/path/to/preview.epub', profile=EpubCheck.PREVIEW) # Specify language for validation messages result = EpubCheck('/path/to/book.epub', lang='de') # German messages result = EpubCheck('/path/to/book.epub', lang='fr') # French messages # Deferred execution (don't run on instantiation) checker = EpubCheck('/path/to/book.epub', autorun=False) # ... do other setup ... checker.run() # Run validation manually print(checker.valid) ``` -------------------------------- ### EpubCheck Utility Functions Source: https://context7.com/titusz/epubcheck/llms.txt Utilize helper functions for checking Java and EpubCheck versions, and iterating over EPUB files in a directory. Supports non-recursive and recursive file searching with custom extensions. ```python from epubcheck.utils import java_version, epubcheck_version, epubcheck_help, iter_files # Check Java installation print(java_version()) # e.g., 'java version "17.0.1" 2021-10-19 LTS' # Get EpubCheck version print(epubcheck_version()) # e.g., 'EpubCheck v5.1.0' # Get full EpubCheck help text help_text = epubcheck_help() print(help_text) ``` ```python from epubcheck import EpubCheck # Non-recursive - only current directory for epub_path in iter_files('/path/to/folder', exts=('epub',)): result = EpubCheck(epub_path) print(f"{epub_path}: {'Valid' if result.valid else 'Invalid'}") ``` ```python from epubcheck import EpubCheck # Recursive - include subdirectories for epub_path in iter_files('/path/to/folder', exts=('epub',), recursive=True): result = EpubCheck(epub_path) if not result.valid: print(f"Invalid: {epub_path}") for msg in result.messages: if msg.level == 'ERROR': print(f" {msg.short}") ``` ```python # Filter multiple extensions for file_path in iter_files('/path/to/folder', exts=('epub', 'kepub')): print(file_path) ``` -------------------------------- ### Batch Processing and Reporting with tablib Source: https://context7.com/titusz/epubcheck/llms.txt Process multiple EPUB files in batch, generate structured reports using tablib, and export them to various formats like Excel, CSV, and JSON. This is ideal for large-scale validation tasks. ```python import tablib from epubcheck import EpubCheck from epubcheck.models import Checker, Meta, Message from epubcheck.utils import iter_files # Create datasets for reporting metas = tablib.Dataset(headers=Checker._fields + Meta._fields) messages = tablib.Dataset(headers=Message._fields) # Process all EPUBs in folder epub_folder = '/path/to/epubs' for epub_path in iter_files(epub_folder, exts=('epub',), recursive=True): result = EpubCheck(epub_path) # Add metadata row (flattened for lists) metas.append(result.checker + result.meta.flatten()) # Add all messages for msg in result.messages: messages.append(msg) # Export to Excel (two sheets: metadata and messages) databook = tablib.Databook((metas, messages)) with open('validation_report.xls', 'wb') as f: f.write(bytes(databook.export('xls'))) # Export messages to CSV with open('validation_messages.csv', 'wb') as f: f.write(messages.export('csv', delimiter=';').encode()) # Export to JSON with open('validation_report.json', 'w') as f: f.write(metas.export('json')) # Summary statistics total = len(metas) valid = sum(1 for row in metas if row[metas.headers.index('nError')] == 0) print(f"Validated {total} EPUBs: {valid} valid, {total - valid} invalid") ``` -------------------------------- ### EpubCheck Class - With Profiles and Options Source: https://context7.com/titusz/epubcheck/llms.txt Utilize the EpubCheck class with different validation profiles, specify message language, or defer the validation execution. ```APIDOC ## EpubCheck Class - With Profiles and Options ### Description The `EpubCheck` class supports various validation profiles for specialized EPUB types, allows specifying the language for validation messages, and offers deferred execution. ### Method Instantiation of `EpubCheck` class with optional arguments. ### Endpoint N/A (Python Library) ### Parameters #### Path Parameters - **epub_path** (str) - Required - The file path to the EPUB file to be validated. #### Query Parameters - **profile** (str) - Optional - The validation profile to use. Options: 'default', 'dict', 'edupub', 'idx', 'preview'. Defaults to 'default'. - **lang** (str) - Optional - The language code for validation messages (e.g., 'de', 'fr'). Defaults to 'en'. - **autorun** (bool) - Optional - If True (default), validation runs automatically on instantiation. If False, validation must be manually triggered with `.run()`. ### Request Example ```python from epubcheck import EpubCheck # Validate with default profile result = EpubCheck('/path/to/book.epub', profile=EpubCheck.DEFAULT) # Validate educational publication result = EpubCheck('/path/to/educational.epub', profile=EpubCheck.EDUPUB) # Validate dictionary/glossary EPUB result = EpubCheck('/path/to/dictionary.epub', profile=EpubCheck.DICT) # Validate index publication result = EpubCheck('/path/to/index.epub', profile=EpubCheck.IDX) # Validate preview content result = EpubCheck('/path/to/preview.epub', profile=EpubCheck.PREVIEW) # Specify language for validation messages result = EpubCheck('/path/to/book.epub', lang='de') # German messages result = EpubCheck('/path/to/book.epub', lang='fr') # French messages # Deferred execution (don't run on instantiation) checker = EpubCheck('/path/to/book.epub', autorun=False) # ... do other setup ... checker.run() # Run validation manually print(checker.valid) ``` ### Response #### Success Response (200) - **valid** (bool) - True if the EPUB is valid, False otherwise. - **checker** (Checker Model) - Metadata about the validation process. - **meta** (Publication Metadata) - Metadata about the EPUB publication. - **messages** (list of Validation Message) - A list of validation messages (errors, warnings, etc.). #### Response Example ```json { "valid": true, "checker": { "path": "/path/to/educational.epub", "filename": "educational.epub", "checkerVersion": "5.1.0", "checkDate": "2023-10-27T10:05:00Z", "elapsedTime": 1200, "nFatal": 0, "nError": 0, "nWarning": 1, "nUsage": 0 }, "meta": { "title": "Educational EPUB", "creator": ["Educator"], "language": "en", "ePubVersion": "3.3", "publisher": "Edu Inc.", "identifier": "urn:uuid:67890", "charsCount": 5000, "hasAudio": false, "hasVideo": false, "isScripted": false, "renditionLayout": "reflowable" }, "messages": [ { "level": "WARNING", "id": "DUPLICATE-ID", "location": "/path/to/content.xhtml", "message": "Duplicate ID found in the document." } ] } ``` ``` -------------------------------- ### EpubCheck Class - Basic Validation Source: https://context7.com/titusz/epubcheck/llms.txt Instantiate the EpubCheck class to perform basic validation on an EPUB file and access detailed results. ```APIDOC ## EpubCheck Class - Basic Validation ### Description Instantiate the `EpubCheck` class to perform basic validation on an EPUB file and access detailed results including checker metadata, publication metadata, and validation messages. ### Method Instantiation of `EpubCheck` class. ### Endpoint N/A (Python Library) ### Parameters #### Path Parameters - **epub_path** (str) - Required - The file path to the EPUB file to be validated. #### Query Parameters None #### Request Body None ### Request Example ```python from epubcheck import EpubCheck # Basic validation - runs automatically on instantiation result = EpubCheck('/path/to/book.epub') # Check if EPUB is valid if result.valid: print("EPUB is valid!") else: print(f"EPUB has {result.checker.nError} errors and {result.checker.nWarning} warnings") # Access checker metadata print(f"EPUBCheck version: {result.checker.checkerVersion}") print(f"Check date: {result.checker.checkDate}") print(f"Processing time: {result.checker.elapsedTime}ms") print(f"Fatal errors: {result.checker.nFatal}") print(f"Errors: {result.checker.nError}") print(f"Warnings: {result.checker.nWarning}") # Access publication metadata print(f"Title: {result.meta.title}") print(f"Creator: {result.meta.creator}") # Returns list of creators print(f"Language: {result.meta.language}") print(f"EPUB Version: {result.meta.ePubVersion}") print(f"Publisher: {result.meta.publisher}") print(f"Identifier: {result.meta.identifier}") print(f"Character count: {result.meta.charsCount}") print(f"Has audio: {result.meta.hasAudio}") print(f"Has video: {result.meta.hasVideo}") print(f"Is scripted: {result.meta.isScripted}") print(f"Rendition layout: {result.meta.renditionLayout}") # Iterate through validation messages for msg in result.messages: print(f"{msg.level} - {msg.id} - {msg.location} - {msg.message}") if msg.suggestion: print(f" Suggestion: {msg.suggestion}") ``` ### Response #### Success Response (200) - **valid** (bool) - True if the EPUB is valid, False otherwise. - **checker** (Checker Model) - Metadata about the validation process. - **meta** (Publication Metadata) - Metadata about the EPUB publication. - **messages** (list of Validation Message) - A list of validation messages (errors, warnings, etc.). #### Response Example ```json { "valid": false, "checker": { "path": "/path/to/book.epub", "filename": "book.epub", "checkerVersion": "5.1.0", "checkDate": "2023-10-27T10:00:00Z", "elapsedTime": 1500, "nFatal": 0, "nError": 2, "nWarning": 5, "nUsage": 0 }, "meta": { "title": "My EPUB Book", "creator": ["Author Name"], "language": "en", "ePubVersion": "3.3", "publisher": "Publisher Name", "identifier": "urn:uuid:12345", "charsCount": 10000, "hasAudio": false, "hasVideo": false, "isScripted": false, "renditionLayout": "reflowable" }, "messages": [ { "level": "ERROR", "id": "EPUBTYPE-001", "location": "/path/to/content.xhtml", "message": "The EPUB type is not specified.", "suggestion": "Add a meta tag for EPUB type." } ] } ``` ``` -------------------------------- ### Validate Single EPUB File (CLI) Source: https://github.com/titusz/epubcheck/blob/master/README.md Validate a specific EPUB file using its path. ```bash epubcheck /path/to/book.epub ``` -------------------------------- ### Capture EpubCheck Output Source: https://context7.com/titusz/epubcheck/llms.txt Redirect stdout and stderr to capture the output of the main EpubCheck function. Useful for integrating EpubCheck into applications where direct console output is not desired. ```python import sys from io import StringIO # Assuming 'main' is imported from epubcheck # from epubcheck import main old_stdout, old_stderr = sys.stdout, sys.stderr sys.stdout, sys.stderr = StringIO(), StringIO() # Replace with actual call to main function # exit_code = main(['/path/to/book.epub']) exit_code = 0 # Placeholder for demonstration stdout_output = sys.stdout.getvalue() stderr_output = sys.stderr.getvalue() sys.stdout, sys.stderr = old_stdout, old_stderr # Errors go to stderr, warnings to stdout if exit_code != 0: print(f"Validation failed:\n{stderr_output}") ``` -------------------------------- ### Quick EPUB Validation with validate Function Source: https://context7.com/titusz/epubcheck/llms.txt Use the `validate` function for a simple boolean check of EPUB validity. It returns `True` if valid and `False` otherwise. Useful for batch processing or conditional logic. ```python from epubcheck import validate # Quick validation - returns True or False is_valid = validate('/path/to/book.epub') if is_valid: print("EPUB passed validation") else: print("EPUB failed validation") # Use in conditional logic epub_files = ['/path/to/book1.epub', '/path/to/book2.epub', '/path/to/book3.epub'] valid_epubs = [f for f in epub_files if validate(f)] invalid_epubs = [f for f in epub_files if not validate(f)] print(f"Valid: {len(valid_epubs)}, Invalid: {len(invalid_epubs)}") ``` -------------------------------- ### Extract EPUB Metadata Source: https://context7.com/titusz/epubcheck/llms.txt Access publication metadata, structure, and media features from an EPUB file using the meta attribute. ```python from epubcheck import EpubCheck result = EpubCheck('/path/to/book.epub') meta = result.meta # Basic publication info print(f"Title: {meta.title}") print(f"Publisher: {meta.publisher}") print(f"Date: {meta.date}") print(f"Description: {meta.description}") print(f"Rights: {meta.rights}") print(f"Identifier: {meta.identifier}") print(f"Language: {meta.language}") # Creators and contributors (returns lists) print(f"Creators: {', '.join(meta.creator)}") print(f"Contributors: {', '.join(meta.contributors)}") print(f"Subjects: {', '.join(meta.subject)}") # EPUB structure info print(f"EPUB Version: {meta.ePubVersion}") print(f"Spine items: {meta.nSpines}") print(f"Character count: {meta.charsCount}") print(f"Checksum: {meta.checkSum}") # Media and features print(f"Has Audio: {meta.hasAudio}") print(f"Has Video: {meta.hasVideo}") print(f"Is Scripted: {meta.isScripted}") print(f"Has Encryption: {meta.hasEncryption}") print(f"Has Signatures: {meta.hasSignatures}") # Rendition properties print(f"Layout: {meta.renditionLayout}") # 'reflowable' or 'pre-paginated' print(f"Orientation: {meta.renditionOrientation}") print(f"Spread: {meta.renditionSpread}") print(f"Has Fixed Format: {meta.hasFixedFormat}") print(f"Is Backward Compatible: {meta.isBackwardCompatible}") # Font information (returns lists) print(f"Embedded Fonts: {meta.embeddedFonts}") print(f"Referenced Fonts: {meta.refFonts}") # Flatten for tabular export (converts lists to semicolon-separated strings) flattened = meta.flatten() ``` -------------------------------- ### validate Function Source: https://context7.com/titusz/epubcheck/llms.txt Use the `validate` function for a quick boolean check of EPUB validity without detailed results. ```APIDOC ## validate Function ### Description A simple function for quick boolean validation of EPUB files. It returns `True` if the EPUB is valid and `False` otherwise, without providing detailed error messages. ### Method Call the `validate` function. ### Endpoint N/A (Python Library) ### Parameters #### Path Parameters - **epub_path** (str) - Required - The file path to the EPUB file to be validated. #### Query Parameters None #### Request Body None ### Request Example ```python from epubcheck import validate # Quick validation - returns True or False is_valid = validate('/path/to/book.epub') if is_valid: print("EPUB passed validation") else: print("EPUB failed validation") # Use in conditional logic epub_files = ['/path/to/book1.epub', '/path/to/book2.epub', '/path/to/book3.epub'] valid_epubs = [f for f in epub_files if validate(f)] invalid_epubs = [f for f in epub_files if not validate(f)] print(f"Valid: {len(valid_epubs)}, Invalid: {len(invalid_epubs)}") ``` ### Response #### Success Response (200) - **return_value** (bool) - `True` if the EPUB is valid, `False` otherwise. #### Response Example ```json { "return_value": true } ``` ``` -------------------------------- ### Accessing Checker Model Metadata Source: https://context7.com/titusz/epubcheck/llms.txt The Checker Model, accessible via `result.checker`, provides metadata about the validation process itself, such as file path, checker version, check date, and error/warning counts. This is distinct from publication metadata. ```python from epubcheck import EpubCheck result = EpubCheck('/path/to/book.epub') # Access Checker fields checker = result.checker print(f"Path: {checker.path}") print(f"Filename: {checker.filename}") print(f"Checker Version: {checker.checkerVersion}") print(f"Check Date: {checker.checkDate}") print(f"Elapsed Time (ms): {checker.elapsedTime}") print(f"Fatal Errors: {checker.nFatal}") print(f"Errors: {checker.nError}") print(f"Warnings: {checker.nWarning}") print(f"Usage Messages: {checker.nUsage}") ``` -------------------------------- ### Report Validation Status Source: https://context7.com/titusz/epubcheck/llms.txt Check the validation results of an EpubCheck instance based on error counts. ```python if checker.nFatal > 0: print("CRITICAL: Fatal errors found!") elif checker.nError > 0: print("ERROR: Validation errors found") elif checker.nWarning > 0: print("WARNING: Validation warnings found") else: print("OK: No issues found") ``` -------------------------------- ### Access Raw JSON Result Data Source: https://context7.com/titusz/epubcheck/llms.txt Access the raw JSON output from EpubCheck as a Python dictionary for advanced processing or custom integrations. This allows detailed inspection of checker information, publication metadata, messages, and item details. ```python from epubcheck import EpubCheck import json result = EpubCheck('/path/to/book.epub') # Access raw JSON data as Python dict data = result.result_data # Checker info print(json.dumps(data['checker'], indent=2)) # Publication metadata print(json.dumps(data['publication'], indent=2)) # All messages for msg in data['messages']: print(f"ID: {msg['ID']}") print(f"Severity: {msg['severity']}") print(f"Message: {msg['message']}") for loc in msg['locations']: print(f" File: {loc['path']}, Line: {loc['line']}, Column: {loc['column']}") # Item details (manifest entries) for item in data['items']: print(f"ID: {item['id']}") print(f"File: {item['fileName']}") print(f"Media Type: {item['media_type']}") print(f"Size: {item['uncompressedSize']} bytes") print(f"Is Spine Item: {item['isSpineItem']}") if item['isSpineItem']: print(f"Spine Index: {item['spineIndex']}") # Save raw output with open('epubcheck_output.json', 'w') as f: json.dump(result.result_data, f, indent=2) ``` -------------------------------- ### Checker Model Source: https://context7.com/titusz/epubcheck/llms.txt Access validation process metadata using the Checker Model, a namedtuple containing information about the check itself. ```APIDOC ## Checker Model ### Description The `Checker` model is a namedtuple that contains metadata about the EPUB validation process itself, extracted from the epubcheck JSON output. It provides information about the check execution, not the publication content. ### Method Access the `checker` attribute of an `EpubCheck` result object. ### Endpoint N/A (Python Library) ### Parameters None (Accessed via `EpubCheck` result object) ### Request Example ```python from epubcheck import EpubCheck result = EpubCheck('/path/to/book.epub') # Access Checker fields checker = result.checker print(f"Path: {checker.path}") print(f"Filename: {checker.filename}") print(f"Checker Version: {checker.checkerVersion}") print(f"Check Date: {checker.checkDate}") print(f"Elapsed Time (ms): {checker.elapsedTime}") print(f"Fatal Errors: {checker.nFatal}") print(f"Errors: {checker.nError}") print(f"Warnings: {checker.nWarning}") print(f"Usage Messages: {checker.nUsage}") ``` ### Response #### Success Response (200) - **path** (str) - The path to the EPUB file that was checked. - **filename** (str) - The filename of the EPUB file. - **checkerVersion** (str) - The version of the EpubCheck Java validator used. - **checkDate** (str) - The date and time when the check was performed. - **elapsedTime** (int) - The time taken for the validation in milliseconds. - **nFatal** (int) - The number of fatal errors encountered. - **nError** (int) - The total number of errors encountered. - **nWarning** (int) - The total number of warnings encountered. - **nUsage** (int) - The number of usage messages. #### Response Example ```json { "path": "/path/to/book.epub", "filename": "book.epub", "checkerVersion": "5.1.0", "checkDate": "2023-10-27T10:00:00Z", "elapsedTime": 1500, "nFatal": 0, "nError": 2, "nWarning": 5, "nUsage": 0 } ``` ``` -------------------------------- ### Process Validation Messages Source: https://context7.com/titusz/epubcheck/llms.txt Iterate through validation messages to inspect details, filter by severity, or group by error ID. ```python from epubcheck import EpubCheck result = EpubCheck('/path/to/invalid.epub') for msg in result.messages: # Access message fields print(f"ID: {msg.id}") # e.g., "OPF-049", "RSC-005" print(f"Level: {msg.level}") # "FATAL", "ERROR", "WARNING", "USAGE" print(f"Location: {msg.location}") # e.g., "book.epub/EPUB/package.opf:40:29" print(f"Message: {msg.message}") print(f"Suggestion: {msg.suggestion}") # Short format for logging print(msg.short) # "ERROR - OPF-049 - book.epub/EPUB/package.opf:40:29 - Item id..." # Full string representation print(str(msg)) # All fields pipe-separated # Filter messages by severity errors = [m for m in result.messages if m.level == 'ERROR'] warnings = [m for m in result.messages if m.level == 'WARNING'] fatal = [m for m in result.messages if m.level == 'FATAL'] # Group messages by error ID from collections import defaultdict by_id = defaultdict(list) for msg in result.messages: by_id[msg.id].append(msg) for error_id, msgs in by_id.items(): print(f"{error_id}: {len(msgs)} occurrence(s)") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.