### Example Usage of OPFProcessor Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/OPFProcessor.md A comprehensive example demonstrating the setup and usage of the OPFProcessor class to generate an OPF file for a KF8 ebook. ```python from lib.mobi_sectioner import Sectionizer from lib.mobi_header import MobiHeader from lib.mobi_opf import OPFProcessor from lib.unpack_structure import fileNames # Setup sect = Sectionizer('mybook.azw3') mh = MobiHeader(sect, 0) files = fileNames('mybook.azw3', './output') files.makeK8Struct() # Prepare metadata and file lists metadata = mh.getMetaData() fileinfo = [['skel0', 'Text', 'part0000.xhtml']] rscnames = ['image00001.jpg', 'font00001.ttf'] usedmap = {'image00001.jpg': 'used', 'font00001.ttf': 'used'} # Generate OPF for KF8 opf = OPFProcessor( files, metadata, fileinfo, rscnames, is_k8=True, mh=mh, usedmap=usedmap, epubver='3' # EPUB3 format ) # Write OPF and get UUID uuid = opf.writeOPF(obfuscate=False) print(f"OPF written with UUID: {uuid}") # Check what files are needed if opf.hasNCX(): print("Need to create toc.ncx") if opf.hasNAV(): print("Need to create nav.xhtml") ``` -------------------------------- ### makeEPUB Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/fileNames.md Example usage of makeEPUB. ```python files = fileNames('mybook.azw3', './output') files.makeK8Struct() # ... process ebook contents ... usedmap = {'image00001.jpg': 'used', 'image00002.jpg': 'not used'} obfuscate_data = ['font00001.ttf'] uid = '12345678-1234-1234-1234-123456789012' files.makeEPUB(usedmap, obfuscate_data, uid) ``` -------------------------------- ### buildParts Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Example of how to use the buildParts method. ```python mh = MobiHeader(sect, 0) k8proc = K8Processor(mh, sect, files) rawml = mh.getRawML() k8proc.buildParts(rawml) ``` -------------------------------- ### Get guide information Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Retrieves and prints the guide text from a MOBI8 ebook. ```python guide = k8proc.getGuideText() print("Guide entries:") print(guide) ``` -------------------------------- ### writeOPF Method Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/OPFProcessor.md An example demonstrating how to use the writeOPF method. ```python opf = OPFProcessor(files, metadata, fileinfo, rscnames, True, mh, usedmap) uuid = opf.writeOPF(obfuscate=True) print(f"Generated EPUB with UUID: {uuid}") ``` -------------------------------- ### Example Usage Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/mobi_split.md Full example of splitting a combination mobi file. ```python from lib.mobi_split import mobi_split import os # Check and split a combination file filename = 'mybook.azw' splitter = mobi_split(filename) if splitter.combo: print("This is a combination mobi7/mobi8 file") # Extract mobi7 mobi7_data = splitter.getResult7() with open('mybook_mobi7.mobi', 'wb') as f: f.write(mobi7_data) # Extract mobi8 mobi8_data = splitter.getResult8() with open('mybook_mobi8.azw3', 'wb') as f: f.write(mobi8_data) print("Split complete") else: print("File is not a combination file") ``` -------------------------------- ### Generated Landmarks (Guide) Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/TOC-processors.md This Python dictionary shows examples of automatically generated landmark entries used for navigation in both NCX and nav.xhtml. ```python # Generated guide entries landmarks = { 'cover': 'Cover page', 'toc': 'Table of contents', 'start': 'Start of content', 'bodymatter': 'Body content', } ``` -------------------------------- ### Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/unpackBook.md Example usage of the unpackBook function. ```python from lib.kindleunpack import unpackBook # Unpack a standard azw3 ebook unpackBook('mybook.azw3', './output') # Unpack with specific EPUB version and HD images unpackBook('mybook.azw3', './output', epubver='3', use_hd=True) # Unpack with APNX file for page mapping unpackBook('mybook.azw3', './output', apnxfile='mybook.apnx') # Split combination mobi files unpackBook('mybook.azw', './output', dosplitcombos=True) # Dump debug information unpackBook('mybook.azw3', './output', dodump=True, dowriteraw=True) ``` -------------------------------- ### Example Usage Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/MobiHeader.md Demonstrates how to load an ebook, parse its header, check its format, retrieve metadata, and get raw content. ```python from lib.mobi_sectioner import Sectionizer from lib.mobi_header import MobiHeader # Load ebook sect = Sectionizer('mybook.azw3') # Parse header mh = MobiHeader(sect, 0) # Check format if mh.isK8(): print("This is a KF8 (azw3) ebook") elif mh.isPrintReplica(): print("This is a Print Replica ebook") else: print(f"This is Mobi version {mh.version}") # Get metadata metadata = mh.getMetaData() print(f"Title: {metadata.get('Title', ['N/A'])[0]}") print(f"Author: {metadata.get('Author', ['N/A'])[0]}") print(f"Language: {metadata.get('Language', ['N/A'])[0]}") # Get raw content rawml = mh.getRawML() print(f"Content size: {len(rawml)} bytes") # Check encryption if mh.isEncrypted(): print("ERROR: Ebook is encrypted") ``` -------------------------------- ### Version Detection Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Example usage of version detection constants. ```python from lib.compatibility_utils import PY2, PY3, iswindows if PY2: # Python 2 specific code pass elif PY3: # Python 3 specific code pass if iswindows: # Windows specific code pass ``` -------------------------------- ### writeNAV Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/TOC-processors.md Example usage of the writeNAV method. ```python nav = NAVProcessor(files) nav.writeNAV(ncx_data, guidetext, metadata) ``` -------------------------------- ### getGuideText Method Signature Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Gets guide entries for table of contents and landmark positions. ```python def getGuideText(self): ``` -------------------------------- ### makeK8Struct Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/fileNames.md Example usage of makeK8Struct. ```python files = fileNames('mybook.azw3', './output') files.makeK8Struct() # Create KF8 directory structure ``` -------------------------------- ### List-Producing Versions Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Example of using list-producing versions like lrange and lmap. ```python from lib.compatibility_utils import lrange, lmap # Get list instead of range object numbers = lrange(10) # [0, 1, 2, ..., 9] # Get list instead of map object doubled = lmap(lambda x: x*2, lrange(5)) # [0, 2, 4, 6, 8] ``` -------------------------------- ### Part Info Tuple Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/types.md An example of retrieving and using part information from K8Processor. ```python skelid, dir, filename, begin, end, aid = k8proc.getPartInfo(0) # skelid='skel0', dir='Text', filename='part0000.xhtml' # begin=0, end=5000, aid='' ``` -------------------------------- ### hexlify Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Example of using hexlify to convert bytes to their hex representation. ```python from lib.compatibility_utils import hexlify hex_str = hexlify(b'\x00\xff\x80') print(hex_str) # b'00ff80' ``` -------------------------------- ### parseNCX Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/TOC-processors.md Example usage of the parseNCX method. ```python ncx = ncxExtract(mh, files) ncx_data = ncx.parseNCX() for entry in ncx_data: print(f"{entry['text']} -> {entry['href']}") ``` -------------------------------- ### Get Book Metadata Task Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/API-overview.md Example code for retrieving book metadata such as title, author, and language. ```python from lib.mobi_sectioner import Sectionizer from lib.mobi_header import MobiHeader sect = Sectionizer('mybook.azw3') mh = MobiHeader(sect, 0) metadata = mh.getMetaData() title = metadata.get('Title', ['Unknown'])[0] author = metadata.get('Author', ['Unknown'])[0] language = metadata.get('Language', ['en'])[0] ``` -------------------------------- ### bchar Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Example of using bchar to get a single byte as a bytestring. ```python from lib.compatibility_utils import bchar data = b'hello' # Get first byte as a bytestring (not int) first_byte = bchar(data[0:1]) # Returns b'h' ``` -------------------------------- ### Command-line Interface Usage Source: https://github.com/kevinhendricks/kindleunpack/blob/master/KindleUnpack_ReadMe.htm Example of how to run KindleUnpack from the command line. ```bash python kindleunpack.py \[-r -s -d -h -i\] \[-p APNX_FILE\] INPUT_FILE OUTPUT_FOLDER ``` -------------------------------- ### Example Usage Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/fileNames.md Demonstrates how to use the fileNames class for managing ebook file structures. ```python from lib.unpack_structure import fileNames # Create file manager files = fileNames('mybook.azw3', './output') # Get input filename basename = files.getInputFileBasename() print(basename) # 'mybook' # Check directories print(files.mobi7dir) # './output/mobi7' print(files.imgdir) # './output/mobi7/Images' # For KF8 processing files.makeK8Struct() print(files.k8dir) # './output/mobi8' print(files.k8oebps) # './output/mobi8/OEBPS' # Later: create EPUB files.makeEPUB({'image00001.jpg': 'used'}, [], 'uuid-string') ``` -------------------------------- ### NAV Format Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/TOC-processors.md Example of the NAV (EPUB3) XHTML format. ```xml ... ``` -------------------------------- ### Example Usage Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Demonstrates how to load and process a KF8 ebook using K8Processor. ```python from lib.mobi_sectioner import Sectionizer from lib.mobi_header import MobiHeader from lib.mobi_k8proc import K8Processor from lib.unpack_structure import fileNames # Load KF8 ebook sect = Sectionizer('mybook.azw3') mh = MobiHeader(sect, 0) # Check if it's KF8 if not mh.isK8(): print("Not a KF8 ebook") exit(1) # Setup output files = fileNames('mybook.azw3', './output') files.makeK8Struct() # Process KF8 k8proc = K8Processor(mh, sect, files) # Extract parts rawml = mh.getRawML() k8proc.buildParts(rawml) ``` -------------------------------- ### Command-line Interface Usage Source: https://github.com/kevinhendricks/kindleunpack/blob/master/README.md Example of how to run KindleUnpack from the command line. ```sh python kindleunpack.py [-r -s -d -h -i] [-p APNX_FILE] INPUT_FILE OUTPUT_FOLDER ``` -------------------------------- ### unicode_argv Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Example of using unicode_argv to process command-line arguments as Unicode. ```python from lib.compatibility_utils import unicode_argv argv = unicode_argv() for arg in argv: print(arg) # Guaranteed to be unicode/str ``` -------------------------------- ### getInputFileBasename Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/fileNames.md Example usage of getInputFileBasename. ```python files = fileNames('path/to/mybook.azw3', './output') print(files.getInputFileBasename()) # Output: 'mybook' ``` -------------------------------- ### HTMLProcessor Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/HTMLProcessor.md Example demonstrating how to use the HTMLProcessor class to convert Mobi7 ebook content to HTML. ```python from lib.mobi_html import HTMLProcessor # Process Mobi7 htmlproc = HTMLProcessor(files, metadata, rscnames) srctext = htmlproc.findAnchors(rawML, ncx_data, {}) srctext, usedmap = htmlproc.insertHREFS() # Write HTML with open('output.html', 'wb') as f: f.write(srctext) ``` -------------------------------- ### bstr Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Example of using bstr to convert strings to bytestrings. ```python from lib.compatibility_utils import bstr byte_data = bstr('hello') # Returns b'hello' byte_data = bstr(b'hello') # Returns b'hello' ``` -------------------------------- ### getResult7 Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/mobi_split.md Example of how to use getResult7 to extract mobi7 data. ```python splitter = mobi_split('combo.azw') if splitter.combo: mobi7_bytes = splitter.getResult7() with open('output.mobi', 'wb') as f: f.write(mobi7_bytes) ``` -------------------------------- ### Mobi7 Processing Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/TOC-processors.md Integration example for Mobi7 processing, including TOC parsing and writing. ```python def processMobi7(mh, metadata, sect, files, rscnames): # Parse TOC ncx = ncxExtract(mh, files) ncx_data = ncx.parseNCX() # Write NCX ncx.writeNCX(metadata) ``` -------------------------------- ### KF8 Processing Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/TOC-processors.md Integration example for KF8 processing, including TOC parsing and writing NCX and navigation documents. ```python def processMobi8(mh, metadata, sect, files, rscnames, ...): # Parse TOC ncx = ncxExtract(mh, files) ncx_data = ncx.parseNCX() # Write NCX (for EPUB2 compatibility) ncx.writeK8NCX(ncx_data, metadata) # Write navigation document (for EPUB3) if opf.hasNAV(): nav = NAVProcessor(files) nav.writeNAV(ncx_data, guidetext, metadata) ``` -------------------------------- ### Flow Info Tuple Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/types.md An example of retrieving flow information from K8Processor. ```python ptype, pformat, pdir, filename = k8proc.getFlowInfo(1) # ptype=b'text/css', pformat=b'file' # pdir='Styles', filename='style0001.css' ``` -------------------------------- ### Example Usage Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/Sectionizer.md Demonstrates loading a file, accessing properties, loading a section, and iterating over sections. ```python from lib.mobi_sectioner import Sectionizer # Load file sect = Sectionizer('input.azw3') # Access properties print(f"Type: {sect.ident}") print(f"Sections: {sect.num_sections}") print(f"File size: {sect.filelength} bytes") # Load a specific section mobi_header = sect.loadSection(0) # Iterate over sections for i in range(sect.num_sections): data = sect.loadSection(i) print(f"Section {i}: {len(data)} bytes") ``` -------------------------------- ### NCX Format Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/TOC-processors.md Example of the NCX (EPUB2/Mobi7) XML format. ```xml ... Book Title Chapter 1 ... ``` -------------------------------- ### bchr Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Example of using bchr to convert an integer to a byte. ```python from lib.compatibility_utils import bchr byte_val = bchr(65) # Returns b'A' (cross-platform) ``` -------------------------------- ### Runtime Configuration Pattern Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/configuration.md Example of setting global flags and then unpacking, and how function parameters override global flags. ```python from lib import kindleunpack from lib.kindleunpack import unpackBook # Set global flags kindleunpack.DUMP = True kindleunpack.WRITE_RAW_DATA = False kindleunpack.SPLIT_COMBO_MOBIS = True # Unpack with all flags enabled unpackBook('mybook.azw', './output') # Or use function parameters (overrides global flags) kindleunpack.DUMP = False unpackBook('another.azw3', './output', dodump=True) ``` -------------------------------- ### getResult8 Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/mobi_split.md Example of how to use getResult8 to extract mobi8 data. ```python splitter = mobi_split('combo.azw') if splitter.combo: mobi8_bytes = splitter.getResult8() with open('output.azw3', 'wb') as f: f.write(mobi8_bytes) ``` -------------------------------- ### unicode_str Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Examples of using unicode_str for converting bytes or strings to Unicode. ```python from lib.compatibility_utils import unicode_str # From bytes result = unicode_str(b'hello', 'utf-8') # Already unicode result = unicode_str('hello') # With error handling result = unicode_str(b'hello\xff', encoding='utf-8', errors='replace') ``` -------------------------------- ### Low-Level Processing Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/API-overview.md Demonstrates a step-by-step process for low-level ebook unpacking. ```python from lib.mobi_sectioner import Sectionizer from lib.mobi_header import MobiHeader from lib.unpack_structure import fileNames # 1. Load file sect = Sectionizer('mybook.azw3') # 2. Validate if sect.ident not in [b'BOOKMOBI', b'TEXtREAd']: raise Exception('Invalid file') # 3. Parse header mh = MobiHeader(sect, 0) # 4. Check format if mh.isEncrypted(): raise Exception('Encrypted') if mh.isK8(): print("KF8 format detected") # ... process KF8 ... elif mh.isPrintReplica(): print("Print Replica format detected") # ... process PDF ... else: print(f"Mobi version {mh.version} detected") # ... process HTML ... # 5. Get metadata metadata = mh.getMetaData() print(f"Title: {metadata.get('Title', ['Unknown'])[0]}") # 6. Extract content rawml = mh.getRawML() ``` -------------------------------- ### XHTMLK8Processor Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/HTMLProcessor.md Example demonstrating how to use the XHTMLK8Processor class to process KF8 ebook parts and generate styled XHTML. ```python from lib.mobi_html import XHTMLK8Processor # Process KF8 viewport = None if 'original-resolution' in metadata: if metadata.get('fixed-layout', [''])[0].lower() == 'true': resolution = metadata['original-resolution'][0] width, height = resolution.split('x') viewport = f'width={width}, height={height}' htmlproc = XHTMLK8Processor(rscnames, k8proc, viewport) usedmap = htmlproc.buildXHTML() # Files are automatically written to output structure ``` -------------------------------- ### Resource Name List Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/types.md Example of the resource name list, which contains filenames of images and fonts. ```python rscnames = [ 'image00001.jpg', 'image00002.jpg', 'image00003.jpg', 'font00001.ttf', 'font00002.otf', ] ``` -------------------------------- ### utf8_str Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Examples of using utf8_str to convert to UTF-8 bytestrings. ```python from lib.compatibility_utils import utf8_str # Convert unicode to bytes result = utf8_str('hello') # Returns b'hello' # Already bytes result = utf8_str(b'hello') # Returns b'hello' ``` -------------------------------- ### Integration with unpackBook Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/mobi_split.md Example of using mobi_split with unpackBook. ```python from lib.kindleunpack import unpackBook # Automatically split combination files during unpacking unpackBook('mybook.azw', './output', dosplitcombos=True) # Creates: # ./output/mobi7-mybook.mobi (standalone mobi7) # ./output/mobi8-mybook.azw3 (standalone mobi8) ``` -------------------------------- ### Viewport String Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/types.md Example of generating a viewport string for fixed-layout ebooks based on metadata. ```python if 'original-resolution' in metadata: if metadata.get('fixed-layout', [''])[0].lower() == 'true': resolution = metadata['original-resolution'][0] width, height = resolution.split('x') viewport = f'width={width}, height={height}' else: viewport = None else: viewport = None # Use in K8 processing htmlproc = XHTMLK8Processor(rscnames, k8proc, viewport) ``` -------------------------------- ### Codec String Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/types.md Example of retrieving the text encoding codec and decoding raw markup. ```python mh = MobiHeader(sect, 0) codec = mh.codec text = rawml.decode(codec) ``` -------------------------------- ### Configuration and Flags Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/README.md Example of how to set global flags to control KindleUnpack's behavior programmatically. ```python from lib import kindleunpack kindleunpack.DUMP = True # Debug output kindleunpack.WRITE_RAW_DATA = True # Write raw files kindleunpack.SPLIT_COMBO_MOBIS = True # Split combos kindleunpack.CREATE_COVER_PAGE = True # Generate covers ``` -------------------------------- ### Metadata Dictionary Example Structure Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/types.md Example structure of the metadata dictionary extracted from ebooks. ```python { 'Title': ['My Book Title'], 'Author': ['John Doe'], 'Publisher': ['Publisher Name'], 'ISBN': ['123-4-567890-1'], 'ASIN': ['B001234567'], 'Language': ['en'], 'Published': ['2020-01-15'], 'Description': ['A book description'], 'Subject': ['Fiction', 'Adventure'], 'cdeType': ['EBOK'], 'StartOffset': ['0', '100'], # Can have multiple values 'CoverOffset': ['5'], 'ThumbOffset': ['6'], 'fixed-layout': ['true'], 'original-resolution': ['1024x768'], 'DictInLanguage': ['English'], 'DictOutLanguage': ['French'], } ``` -------------------------------- ### File Info List Example (KF8) Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/types.md Example structure for the file info list when processing KF8 ebooks. ```python fileinfo = [ ['coverpage', 'Text', 'cover.xhtml'], ['skel0', 'Text', 'part0000.xhtml'], ['skel1', 'Text', 'part0001.xhtml'], [None, 'Styles', 'style0001.css'], [None, 'Styles', 'style0002.css'], ] ``` -------------------------------- ### File Info List Example (Mobi7) Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/types.md Example structure for the file info list when processing Mobi7 ebooks. ```python fileinfo = [ [None, '', 'book.html'], # Main content ] ``` -------------------------------- ### Section Offset Tuples Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/types.md Example of iterating through sections in PalmDoc format using Sectionizer. ```python sect = Sectionizer('file.azw3') for i in range(sect.num_sections): start = sect.sectionoffsets[i] end = sect.sectionoffsets[i + 1] length = end - start data = sect.loadSection(i) # Returns bytes of length ``` -------------------------------- ### NCX Entry Dictionary Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/types.md An example of an NCX entry dictionary, representing a table of contents entry. ```python ncx_entry = { 'name': 'toc-entry-1', 'pos': 1024, 'len': 512, 'noffs': 0, 'text': 'Chapter 1: Introduction', 'hlvl': 1, 'kind': 'parent', 'pos_fid': '12:ABCD:0000', 'parent': -1, 'child1': 1, 'childn': 1, 'num': 0, 'filename': 'part0001.xhtml', 'idtag': 'section1', } ``` -------------------------------- ### Enumerate flows (CSS, SVG, etc.) Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Shows how to list and get information about various flows (like CSS, SVG) within a MOBI8 ebook. ```python print(f"Total flows: {k8proc.getNumberOfFlows()}") for i in range(1, k8proc.getNumberOfFlows()): ptype, pformat, pdir, filename = k8proc.getFlowInfo(i) flow_content = k8proc.getFlow(i) print(f" Flow {i}: {pdir}/{filename} - {ptype.decode('ascii')}") ``` -------------------------------- ### getPartInfo Method Signature Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Gets metadata about a specific part. ```python def getPartInfo(self, index): ``` -------------------------------- ### getPart Method Signature Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Gets the XHTML content for a specific part. ```python def getPart(self, index): ``` -------------------------------- ### Resource Usage Map Usage Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/types.md Demonstrates how to update and use the resource usage map during ebook processing. ```python # During processing, mark resources as used usedmap['image00001.jpg'] = 'used' # When creating EPUB, only include used resources for resource in usedmap: if usedmap[resource] == 'used': copy_to_output(resource) ``` -------------------------------- ### Catching Encrypted Ebook Exception Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/errors.md Example of how to catch the unpackException for an encrypted ebook. ```python try: unpackBook('drm_protected.azw', './output') except unpackException as e: if 'encrypted' in str(e).lower(): print("This ebook is protected by DRM and cannot be unpacked") ``` -------------------------------- ### getFragTblInfo Method Signature Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Gets fragment table information for a byte position. ```python def getFragTblInfo(self, pos): ``` -------------------------------- ### Error Handling with unpackException Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/API-overview.md Provides an example of how to use a try-except block to catch `unpackException` and other errors during book unpacking. ```python from lib.kindleunpack import unpackBook, unpackException try: unpackBook('file.azw3', './output') except unpackException as e: if 'encrypted' in str(e).lower(): print("DRM protected") else: print(f"Unpack error: {e}") except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### makeEPUB Method Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/fileNames.md Create EPUB file from prepared directory structure. ```python def makeEPUB(self, usedmap, obfuscate_data, uid): # Create EPUB file from prepared directory structure. # # Parameters: # usedmap (dict): Maps resource filenames to 'used' or 'not used' # obfuscate_data (list): List of font filenames to apply Adobe obfuscation to # uid (str or bytes): Unique identifier (UUID) for the ebook # # Creates: # - EPUB file with META-INF/container.xml # - If obfuscate_data provided: META-INF/encryption.xml # - Copies used images to mobi8/OEBPS/Images/ # - Copies used fonts to mobi8/OEBPS/Fonts/ # - Applies font obfuscation if needed pass ``` -------------------------------- ### Custom TOC Generation Example Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/TOC-processors.md This Python code snippet demonstrates how to extract, modify, and write a custom Table of Contents using the lib.mobi_ncx and lib.mobi_nav modules. ```python from lib.mobi_ncx import ncxExtract from lib.mobi_nav import NAVProcessor # Extract default TOC ncx = ncxExtract(mh, files) ncx_data = ncx.parseNCX() # Modify entries for entry in ncx_data: # Filter, reorder, rename entries if entry['hlvl'] > 1: # Skip nested entries pass # Write modified TOC ncx.writeK8NCX(ncx_data, metadata) # Generate navigation document nav = NAVProcessor(files) nav.writeNAV(ncx_data, guidetext, metadata) ``` -------------------------------- ### makeK8Struct Method Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/fileNames.md Create directory structure for KF8 (mobi8/EPUB) format output. ```python def makeK8Struct(self): # Create directory structure for KF8 (mobi8/EPUB) format output. Called automatically for KF8 ebooks. Creates: # - mobi8/ # - mobi8/META-INF/ # - mobi8/OEBPS/ # - mobi8/OEBPS/Images/ # - mobi8/OEBPS/Fonts/ # - mobi8/OEBPS/Styles/ # - mobi8/OEBPS/Text/ pass ``` -------------------------------- ### Entry Point: unpackBook() Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/API-overview.md Main function for unpacking ebooks. See unpackBook.md ```python unpackBook(infile, outdir, apnxfile=None, epubver='2', use_hd=False, dodump=False, dowriteraw=False, dosplitcombos=False) ``` -------------------------------- ### CREATE_COVER_PAGE Flag Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/configuration.md Create and insert a cover XHTML page in KF8 output. ```python CREATE_COVER_PAGE = True ``` -------------------------------- ### Usage Pattern for Compatibility Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Demonstrates a recommended structure for using the compatibility utilities to handle text and byte data across different Python versions. ```python from lib.compatibility_utils import ( PY2, PY3, text_type, binary_type, unicode_str, utf8_str, bord, bchar, hexlify, unicode_argv ) # Use text_type for string type checking if isinstance(value, text_type): # Handle unicode pass elif isinstance(value, binary_type): # Handle bytes pass # Always use unicode_str for conversion text = unicode_str(data, encoding='utf-8') # For byte operations, use helper functions byte_value = bord(data[0:1]) hex_representation = hexlify(data) ``` -------------------------------- ### zipUpDir Method Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/fileNames.md Recursively add directory contents to ZIP archive. Helper method for EPUB creation. ```python def zipUpDir(self, myzip, tdir, localname): # Recursively add directory contents to ZIP archive. Helper method for EPUB creation. # # Parameters: # myzip (zipfile.ZipFile): Target ZIP file object # tdir (str): Target base directory path # localname (str): Path in ZIP archive to write to pass ``` -------------------------------- ### Configuration Flags Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/API-overview.md Illustrates how to set global flags for debugging and output control in KindleUnpack. ```python from lib import kindleunpack kindleunpack.DUMP = True # Debug output kindleunpack.WRITE_RAW_DATA = True # Raw files kindleunpack.SPLIT_COMBO_MOBIS = True # Split combo files kindleunpack.CREATE_COVER_PAGE = True # Create cover ``` -------------------------------- ### getFlowInfo Method Signature Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Gets metadata about a specific flow. ```python def getFlowInfo(self, index): ``` -------------------------------- ### Base32 Encoding and Decoding Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/API-overview.md Demonstrates converting integers to Base32 and vice versa using `toBase32` and `fromBase32` utility functions. ```python from lib.mobi_utils import toBase32, fromBase32 encoded = toBase32(1234) # b'04IA' value = fromBase32(b'04IA') # 1234 ``` -------------------------------- ### bchar Function Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Get single-byte bytestring from bytestring. ```python def bchar(s): # s: single byte from bytestring # Returns bytes (Python 3) or str (Python 2) ``` -------------------------------- ### getFlow Method Signature Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Gets the content for a specific flow. ```python def getFlow(self, index): ``` -------------------------------- ### KINDLEGENLOG_FILENAME Constant Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/configuration.md Name for kindlegen build log if included in ebook. ```python KINDLEGENLOG_FILENAME = "kindlegenbuild.log" ``` -------------------------------- ### Version Detection Constants Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Detect Python version and platform. ```python PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 iswindows = sys.platform.startswith('win') ``` -------------------------------- ### DictOutLanguage Method Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/MobiHeader.md Gets the output language code for a dictionary. ```python def DictOutLanguage(self): ``` -------------------------------- ### DUMP Flag Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/configuration.md Enable dump of all header information and section descriptions. ```python DUMP = False ``` ```python from lib import kindleunpack # Enable dumping kindleunpack.DUMP = True # Then unpack kindleunpack.unpackBook('mybook.azw3', './output') ``` ```python unpackBook('mybook.azw3', './output', dodump=True) ``` -------------------------------- ### DictInLanguage Method Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/MobiHeader.md Gets the input language code for a dictionary. ```python def DictInLanguage(self): ``` -------------------------------- ### unicode_argv Function Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Get command-line arguments as Unicode strings. ```python def unicode_argv(): ``` -------------------------------- ### bord Function Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/compatibility-utilities.md Get integer value of a byte from bytestring. ```python def bord(s): # s: single byte from bytestring # Python 2: returns int via ord() # Python 3: returns int directly ``` -------------------------------- ### Enumerate XHTML parts Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Demonstrates how to iterate through and retrieve information about XHTML parts within a MOBI8 ebook using K8Processor. ```python print(f"Total parts: {k8proc.getNumberOfParts()}") for i in range(k8proc.getNumberOfParts()): skelid, dir, filename, begin, end, aid = k8proc.getPartInfo(i) part_content = k8proc.getPart(i) print(f" Part {i}: {dir}/{filename} ({len(part_content)} bytes)") ``` -------------------------------- ### getNumberOfParts Method Signature Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Gets the number of XHTML parts extracted. ```python def getNumberOfParts(self): ``` -------------------------------- ### getInputFileBasename Method Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/fileNames.md Get filename without extension or directory path. ```python def getInputFileBasename(self): # Get filename without extension or directory path. # # Returns: str - Input filename without extension (e.g., 'mybook' from 'mybook.azw3') pass ``` -------------------------------- ### Compatibility Helpers Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/API-overview.md Imports various compatibility helpers for Python 2/3, such as type definitions and string conversion functions. ```python from lib.compatibility_utils import ( PY2, PY3, text_type, binary_type, unicode_str, utf8_str, bord, bchar ) ``` -------------------------------- ### Parameter Precedence Logic Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/configuration.md Illustrates how function parameters override global flags during unpacking, using OR logic. ```python # Global flag set kindleunpack.DUMP = True # Parameter overrides: result is DUMP = True (parameter is True) unpackBook('file.azw3', './output', dodump=True) # No parameter: uses global flag value unpackBook('file.azw3', './output') # DUMP = True # Parameter False doesn't unset global: result is DUMP = True # (The logic is: parameter OR global_flag) ``` ```python def unpackBook(infile, outdir, ..., dodump=False, ...): global DUMP if DUMP or dodump: DUMP = True # ... rest of function ``` -------------------------------- ### With Options Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/API-overview.md Unpack an ebook with various options for EPUB version, HD images, and splitting combination files. ```python from lib.kindleunpack import unpackBook unpackBook( infile='mybook.azw3', outdir='./output', epubver='3', # EPUB 3 format use_hd=True, # Use HD images if present dosplitcombos=True # Split mobi7/mobi8 if combination ) ``` -------------------------------- ### File Format Validation Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/Sectionizer.md Example of validating the file format using the 'ident' property. ```python sect = Sectionizer('mybook.mobi') if sect.ident != b'BOOKMOBI' and sect.ident != b'TEXtREAd': raise Exception('Invalid file format') ``` -------------------------------- ### Get metadata Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/README.md Extracting metadata such as Title, Author, and Language from an ebook. ```python metadata = mh.getMetaData() title = metadata.get('Title', ['Unknown'])[0] author = metadata.get('Author', ['Unknown'])[0] language = metadata.get('Language', ['en'])[0] ``` -------------------------------- ### getIDTagByPosFid Method Signature Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Gets filename and internal ID tag for a specific position. ```python def getIDTagByPosFid(self, fid, off): ``` -------------------------------- ### Minimal Usage Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/API-overview.md Unpack an ebook with defaults ```python from lib.kindleunpack import unpackBook # Unpack an ebook with defaults unpackBook('mybook.azw3', './output') ``` -------------------------------- ### getNumberOfFlows Method Signature Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/K8Processor.md Gets the number of content flows (CSS, SVG, etc.). ```python def getNumberOfFlows(self): ``` -------------------------------- ### writeNAV Method Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/TOC-processors.md Method to generate EPUB3 navigation document. ```python def writeNAV(self, ncx_data, guidetext, metadata): # Generate EPUB3 navigation document. # # | Parameter | Type | Description | # |-----------|------|-------------| # | ncx_data | list | TOC entries from ncxExtract.parseNCX() | # | guidetext | str | Guide landmark entries | # | metadata | dict | Ebook metadata | # # **Creates:** `nav.xhtml` in EPUB3 output directory # # **Navigation document includes:** # - Table of contents (toc nav) # - Landmarks (cover, toc, start of book, etc.) # - List of pages (if page-map present) ``` -------------------------------- ### Catching Other ValueError Conditions Source: https://github.com/kevinhendricks/kindleunpack/blob/master/_autodocs/errors.md Example of catching general ValueError exceptions that may be raised during processing. ```python try: unpackBook('questionable.mobi', './output') except ValueError as e: print(f"Validation error: {e}") except unpackException as e: print(f"Unpack error: {e}") ```