### MangaOCR process_and_write_results Examples Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/api-reference/background-runner.md Demonstrates how to use the process_and_write_results function to process images and write the recognized text to the clipboard or a file. Includes examples for single image processing and batch processing in a loop. ```python from manga_ocr import MangaOcr from manga_ocr.run import process_and_write_results from pathlib import Path mocr = MangaOcr() # Process single image and copy result to clipboard process_and_write_results(mocr, "/path/to/manga.jpg", "clipboard") # Process image and append result to file process_and_write_results(mocr, Path("manga.jpg"), "/results/ocr_output.txt") # Can be called in a loop for custom processing images = [Path(f) for f in ["img1.jpg", "img2.jpg", "img3.jpg"]] for img_path in images: process_and_write_results(mocr, img_path, "output.txt") ``` -------------------------------- ### CLI Usage Examples Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/configuration.md Demonstrates common usage patterns for the manga-ocr CLI, including reading from and writing to different sources and specifying CPU usage and delays. ```bash manga_ocr --read_from clipboard --write_to clipboard ``` ```bash manga_ocr --read_from /path/to/images --write_to /path/to/output.txt ``` ```bash manga_ocr --force_cpu True --delay_secs 0.5 ``` -------------------------------- ### Minimal Manga OCR Example Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/QUICK_START.md A basic example demonstrating how to initialize MangaOcr and process a single image file. ```python from manga_ocr import MangaOcr mocr = MangaOcr() text = mocr("image.jpg") print(text) ``` -------------------------------- ### Process Directory and Output to File Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md Use this example to process all images in a directory and save the combined OCR results to a single text file. Specify the input directory and the output file path. ```python from manga_ocr.run import run run( read_from="/path/to/manga/screenshots", write_to="/path/to/recognized_text.txt" ) ``` -------------------------------- ### Install and Use Manga OCR Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/00_START_HERE.md Install the library using pip and then import and use the MangaOcr class to process an image file. This is the primary method for programmatic image OCR. ```python # Install pip install manga-ocr # Use from manga_ocr import MangaOcr mocr = MangaOcr() text = mocr("manga_page.jpg") print(text) # Japanese text ``` -------------------------------- ### Basic Manga OCR Initialization Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md Initializes the Manga OCR with default settings, using the base model and automatically selecting GPU if available. This is the simplest way to get started. ```python # Uses kha-white/manga-ocr-base model # Automatically uses GPU if available mocr = MangaOcr() ``` -------------------------------- ### Batch Process Images in a Directory Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md This example shows how to process all JPG images within a specified directory. It includes basic error handling for individual file processing. ```python from pathlib import Path from manga_ocr import MangaOcr mocr = MangaOcr() for image_file in Path("./manga").glob("*.jpg"): try: text = mocr(image_file) print(f"{image_file.name}: {text}") except Exception as e: print(f"Error: {e}") ``` -------------------------------- ### Handle NotImplementedError on Linux Wayland Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/errors.md Catch NotImplementedError when running on Linux with Wayland and 'wl-clipboard' is not installed for clipboard output. Install 'wl-clipboard' or use file output. ```python from manga_ocr.run import run try: run(read_from="clipboard", write_to="clipboard") except NotImplementedError as e: print(f"System configuration error: {e}") # On Linux Wayland: install wl-clipboard package # On Linux X11: xclip should already be installed # Alternatively, use file output instead: run(read_from="clipboard", write_to="/path/to/output.txt") ``` -------------------------------- ### Handle FileNotFoundError during MangaOcr Initialization Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/errors.md Use this snippet to catch FileNotFoundError, which occurs if the example image file is missing during MangaOcr initialization. This typically indicates a broken installation. ```python from manga_ocr import MangaOcr try: mocr = MangaOcr() except FileNotFoundError as e: print(f"Installation error: {e}") # The example.jpg file is missing from the manga_ocr package # This indicates a broken installation ``` -------------------------------- ### Clipboard Monitor with Manga OCR (Programmatic) Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/QUICK_START.md Programmatically starts the Manga OCR clipboard monitor. Recognized text is outputted directly to the clipboard. ```python from manga_ocr.run import run run() # Monitor clipboard, output to clipboard ``` -------------------------------- ### Configuration Options Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/COMPLETION_SUMMARY.txt All configuration options for the Manga OCR project are documented in a centralized location, including their default values and usage examples. ```APIDOC ## Configuration ### Overview All configuration options for the Manga OCR system are documented comprehensively. ### Details - **Centralized Documentation**: All options are listed in a single document. - **Defaults**: Default values for all options are provided. - **Examples**: Usage examples are included to demonstrate configuration. - **Customization**: The documentation facilitates understanding and customizing settings. ``` -------------------------------- ### Manga OCR Command-Line Interface Options Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md View all available command-line options for the manga_ocr tool. Examples show default behavior, monitoring clipboard, and specifying read/write paths. ```bash # View all options manga_ocr --help # Monitor clipboard (default) manga_ocr # Monitor directory, write to file manga_ocr --read_from /path/to/images --write_to /path/to/output.txt # Force CPU usage manga_ocr --force_cpu True ``` -------------------------------- ### Manga OCR Command-Line Interface Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/QUICK_START.md Example of using the manga_ocr command-line tool with various options. Boolean flags like --force_cpu and --verbose can be set directly to True or False. ```bash manga_ocr \ --read_from "clipboard" \ --write_to "clipboard" \ --pretrained_model_name_or_path "kha-white/manga-ocr-base" \ --force_cpu False \ --delay_secs 0.1 \ --verbose False ``` ```bash manga_ocr --force_cpu True --verbose False ``` -------------------------------- ### Import Version Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/README.md Import the __version__ attribute to check the installed version of the manga-ocr library. ```python from manga_ocr import __version__ ``` -------------------------------- ### Use a Custom OCR Model Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md This example shows how to load and use a custom pre-trained model for OCR. Provide the path to your custom model when instantiating MangaOcr. ```python from manga_ocr import MangaOcr mocr = MangaOcr( pretrained_model_name_or_path="/path/to/custom/model" ) text = mocr("image.jpg") ``` -------------------------------- ### Initialize Manga OCR with PIL Image Object Source: https://github.com/kha-white/manga-ocr/blob/master/README.md Initialize the Manga OCR object and process an image loaded as a PIL.Image object. Ensure PIL is installed. ```python import PIL.Image from manga_ocr import MangaOcr mocr = MangaOcr() img = PIL.Image.open('/path/to/img') text = mocr(img) ``` -------------------------------- ### MangaOCR OCR Examples Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/api-reference/manga-ocr-main.md Demonstrates how to perform OCR using the MangaOCR class with different input types: file path (string), pathlib.Path object, and PIL Image object. Includes basic handling of the recognized text. ```python from manga_ocr import MangaOcr from pathlib import Path mocr = MangaOcr() # OCR from file path (string) text = mocr("/path/to/manga/page.jpg") # OCR from pathlib.Path image_path = Path("./manga") / "chapter_01.png" text = mocr(image_path) # OCR from PIL Image import PIL.Image img = PIL.Image.open("manga_bubble.jpg") text = mocr(img) # Handle results if text: print(f"Recognized text: {text}") else: # No text found in image print("No text detected") ``` -------------------------------- ### Run Manga OCR Background Service Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md Start a background service for Manga OCR that can read from and write to various sources like the clipboard or files. Configure processing delay and verbosity. ```python from manga_ocr.run import run, process_and_write_results # Run background service run( read_from="clipboard", # or "/path/to/directory" write_to="clipboard", # or "/path/to/output.txt" pretrained_model_name_or_path="kha-white/manga-ocr-base", force_cpu=False, delay_secs=0.1, verbose=False ) ``` -------------------------------- ### Version Information Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODULE_STRUCTURE.md Defines the package version string, typically managed by setuptools_scm. ```python __version__ = "0.1.14" ``` -------------------------------- ### MangaOcr CLI Entry Point Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODULE_STRUCTURE.md Demonstrates the command-line interface (CLI) entry point for the manga_ocr tool. This shows how the CLI is structured using fire.Fire. ```python manga_ocr --help ``` ```python fire.Fire(run) ``` -------------------------------- ### Initializing MangaOcr and Accessing Internal Components Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/types.md Demonstrates the initialization of the MangaOcr class and provides comments showing how internal components like the image processor, tokenizer, and model are accessed. These components are managed internally and not typically used directly by library consumers. ```python from manga_ocr import MangaOcr mocr = MangaOcr() # These components are accessed internally: # processor = mocr.processor (ViTImageProcessor) # tokenizer = mocr.tokenizer (AutoTokenizer) # model = mocr.model (MangaOcrModel) ``` -------------------------------- ### Display Manga OCR Help Information Source: https://github.com/kha-white/manga-ocr/blob/master/README.md Run this command to view all available command-line options and arguments for the Manga OCR tool. ```command-line manga_ocr --help ``` -------------------------------- ### Initialize and Use ViTImageProcessor Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODEL_AND_INFERENCE.md Use ViTImageProcessor to preprocess PIL images into tensors suitable for ViT models. It handles resizing and normalization automatically. ```python from transformers import ViTImageProcessor # Creates pixel_values tensor processor = ViTImageProcessor.from_pretrained(model_name) pixel_values = processor(pil_image, return_tensors="pt").pixel_values ``` -------------------------------- ### Background Service: Directory Input to Clipboard Output Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md Configures the background service to monitor a specified directory for new image files and output the OCR results to the clipboard. Ensure the input directory exists and the output is set to 'clipboard'. ```python # Monitors a directory for new images run( read_from="/path/to/screenshots", write_to="clipboard" ) ``` -------------------------------- ### Load MangaOcrModel Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODEL_AND_INFERENCE.md Instantiates the MangaOcrModel using the `from_pretrained` method. This is the standard way to load the model. ```python model = MangaOcrModel.from_pretrained(model_name) ``` -------------------------------- ### Directory Input Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/QUICK_START.md Specify a directory containing screenshots to process using the --read_from flag. ```bash manga_ocr --read_from /path/to/screenshots ``` -------------------------------- ### run() Function Signature Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/types.md Details the parameters and return type for the main execution function. Accepts basic Python types for parameters and returns None. ```python def run( read_from: str = "clipboard", write_to: str = "clipboard", pretrained_model_name_or_path: str = "kha-white/manga-ocr-base", force_cpu: bool = False, delay_secs: float = 0.1, verbose: bool = False ) -> None ``` -------------------------------- ### MangaOcr Class Initialization and Usage Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md Demonstrates how to initialize the MangaOcr class and perform OCR on an image or image path. ```APIDOC ## MangaOcr Class ### Description The `MangaOcr` class is the main interface for performing Optical Character Recognition (OCR) on manga images. It can be initialized with a pre-trained model and then used to process images. ### Initialization ```python from manga_ocr import MangaOcr mocr = MangaOcr( pretrained_model_name_or_path="kha-white/manga-ocr-base", force_cpu=False ) ``` ### Method `__call__` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Usage ```python # img_or_path can be a file path (str), a PIL.Image object, or a Path object text = mocr(img_or_path) ``` ### Response #### Success Response - `text` (str) - The recognized text from the image. ### Request Example ```python # Assuming img_or_path is defined and points to an image file # text = mocr(img_or_path) ``` ### Response Example ```json { "example": "Recognized text from the image" } ``` ### Internal Methods - `_preprocess(img)` → `torch.Tensor` — Internal preprocessing step. ``` -------------------------------- ### Public API Reference Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/COMPLETION_SUMMARY.txt The Manga OCR project exposes a public API consisting of one main class and six public functions. All aspects of the public API, including constructor parameters, method signatures, and return types, are fully documented with examples and type annotations. ```APIDOC ## Public API ### Overview The Manga OCR project provides a primary class and several public functions for OCR operations. The documentation covers all aspects of these public interfaces. ### Classes - **MangaOcr** - All constructor parameters are documented. - Usage examples are provided. ### Functions - **6 Public Functions** - All function signatures are documented. - All parameters are documented with types. - All return types are documented. - Exceptions raised by functions are documented. - Usage examples are provided for each function. ``` -------------------------------- ### Initialize MangaOcr with GPU/CPU Fallback Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/errors.md Wrap MangaOcr initialization in a try-except block to handle potential GPU initialization failures and fall back to CPU. ```python from manga_ocr import MangaOcr try: mocr = MangaOcr(force_cpu=False) except RuntimeError: # Fall back to CPU if GPU initialization fails mocr = MangaOcr(force_cpu=True) except Exception as e: print(f"Failed to initialize OCR: {e}") raise ``` -------------------------------- ### Device Selection Hierarchy Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODULE_STRUCTURE.md Explains the priority order for selecting a computation device (CPU, CUDA, MPS) based on user input and availability. ```text User Input: force_cpu parameter ↓ If force_cpu = True └→ Use CPU ↓ If force_cpu = False ├→ Check torch.cuda.is_available() │ └→ Yes → Use CUDA │ └→ No → Check next ├→ Check torch.backends.mps.is_available() │ └→ Yes → Use MPS │ └→ No → Use CPU ↓ Log device selection ↓ Move model to device ``` -------------------------------- ### Background Service: Clipboard Input to File Output Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md Sets up the background service to read from the clipboard and append the OCR results to a specified text file. This allows for persistent logging of recognized text. ```python # Append results to a text file run( read_from="clipboard", write_to="/path/to/output.txt" ) ``` -------------------------------- ### MangaOcr Class Initialization Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/QUICK_START.md Initializes the MangaOcr model. Use 'kha-white/manga-ocr-base' for the default model. Set 'force_cpu=True' to disable GPU usage. ```python class MangaOcr: def __init__( self, pretrained_model_name_or_path: str = "kha-white/manga-ocr-base", force_cpu: bool = False ) -> None: """Initialize OCR model.""" ``` -------------------------------- ### Directory Input and File Output Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/QUICK_START.md Process screenshots from a directory and save the results to a file. ```bash manga_ocr --read_from /shots --write_to results.txt ``` -------------------------------- ### Using pathlib.Path with MangaOcr Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/types.md Shows how to use `pathlib.Path` objects for image file input to MangaOcr and for specifying output file paths. Supports directory monitoring. ```python from pathlib import Path from manga_ocr import MangaOcr mocr = MangaOcr() # Using Path objects img_path = Path("./manga") / "chapter_1.jpg" text = mocr(img_path) # Directory monitoring output_file = Path.home() / "ocr_results" / "output.txt" ``` -------------------------------- ### CLI Entry Point Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODULE_STRUCTURE.md The main function that serves as the command-line interface entry point for the Manga-OCR package. ```python def main() ``` -------------------------------- ### Initialize and Use MangaOcr Class Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md Initialize the MangaOcr class with a specified model and optionally force CPU usage. Then, perform OCR on an image or image path. ```python from manga_ocr import MangaOcr # Initialize mocr = MangaOcr( pretrained_model_name_or_path="kha-white/manga-ocr-base", force_cpu=False ) # Perform OCR text = mocr(img_or_path) # str, Path, or PIL.Image → str ``` -------------------------------- ### Command-Line Interface (CLI) Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md Instructions on how to use the Manga OCR command-line interface for various operations. ```APIDOC ## Command-Line Interface (CLI) ### Description The Manga OCR library provides a command-line interface for easy access to its features without writing Python code. ### Usage Examples: #### View all options: ```bash manga_ocr --help ``` #### Monitor clipboard (default behavior): ```bash manga_ocr ``` #### Monitor a directory and write results to a file: ```bash manga_ocr --read_from /path/to/images --write_to /path/to/output.txt ``` #### Force CPU usage: ```bash manga_ocr --force_cpu True ``` ### Available Options (from `--help`): - `--read_from`: Specifies the source to read images from (e.g., "clipboard" or a directory path). - `--write_to`: Specifies the destination for OCR results (e.g., "clipboard" or a file path). - `--force_cpu`: Forces the use of CPU for processing. - `--pretrained_model_name_or_path`: Specifies the pre-trained model to use. - `--delay_secs`: Sets the delay in seconds between checks for new images. - `--verbose`: Enables verbose output. ``` -------------------------------- ### Import Run Functions Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/README.md Import the run and process_and_write_results functions from the manga_ocr.run module. ```python from manga_ocr.run import run, process_and_write_results ``` -------------------------------- ### Device Selection Logging Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/configuration.md Logs indicate which device is being used for inference. This helps in verifying that the optimal device (CUDA, MPS, or CPU) has been selected. ```text Using CUDA # NVIDIA GPU Using MPS # Apple Silicon GPU Using CPU # CPU-only ``` -------------------------------- ### Python API Initialization and Usage Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/QUICK_START.md Initialize the MangaOcr model and process images using the Python API. Initialization may take time on the first run. ```python # 1. Import from manga_ocr import MangaOcr # 2. Initialize (takes 10-30 sec first run) mocr = MangaOcr() # 3. Process images text1 = mocr("image1.jpg") text2 = mocr("image2.jpg") # 4. Reuse instance for image in images: text = mocr(image) # Use text... ``` -------------------------------- ### Using PIL.Image.Image with MangaOcr Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/types.md Demonstrates how to load an image using PIL and pass it directly to the MangaOcr for text extraction. Supports in-memory image manipulation before OCR. ```python import PIL.Image from manga_ocr import MangaOcr mocr = MangaOcr() # Load image from file img = PIL.Image.open("manga_page.jpg") # Pass to OCR text = mocr(img) # Or in-memory image operations img_modified = img.crop((0, 0, 500, 500)) text = mocr(img_modified) ``` -------------------------------- ### Run Background OCR from Directory to File Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/api-reference/background-runner.md Monitors a specified directory for new image files and appends the recognized text to a specified text file. Ensure the directory and file paths are correctly set. ```python from manga_ocr.run import run # Monitor directory for new images, append results to file run( read_from="/path/to/manga/screenshots", write_to="/path/to/recognized_text.txt" ) ``` -------------------------------- ### Initialize Manga OCR with Image Path Source: https://github.com/kha-white/manga-ocr/blob/master/README.md Use this method to initialize the Manga OCR object and process an image directly from its file path. ```python from manga_ocr import MangaOcr mocr = MangaOcr() text = mocr('/path/to/img') ``` -------------------------------- ### Force CPU Mode Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/QUICK_START.md Use the --force_cpu flag to run the OCR process on the CPU. ```bash manga_ocr --force_cpu True ``` -------------------------------- ### Run Background OCR from Clipboard Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/api-reference/background-runner.md Monitors the system clipboard for new images and writes recognized text back to the clipboard. This is the default behavior when no arguments are provided. ```python from manga_ocr.run import run # Monitor clipboard, write results to clipboard (default) # Usage: copy image to clipboard, text appears on clipboard run() ``` -------------------------------- ### Define MangaOcrModel Wrapper Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODEL_AND_INFERENCE.md Extends VisionEncoderDecoderModel and GenerationMixin to provide generation capabilities. This class is intended to be loaded via `from_pretrained`. ```python class MangaOcrModel(VisionEncoderDecoderModel, GenerationMixin): pass ``` -------------------------------- ### Automatic Device Selection Logic Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODEL_AND_INFERENCE.md Selects the appropriate device (CUDA, MPS, or CPU) for model inference based on availability and user-defined preferences. Logs the selected device. ```python if not force_cpu and torch.cuda.is_available(): logger.info("Using CUDA") self.model.cuda() elif not force_cpu and torch.backends.mps.is_available(): logger.info("Using MPS") self.model.to("mps") else: logger.info("Using CPU") # Default, no additional setup needed ``` -------------------------------- ### Process Single Image with Background Module Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md How to process a single image using the background processing module. ```APIDOC ## Process Single Image ### Description The `process_and_write_results` function processes a single image using a provided `MangaOcr` instance and writes the results to a specified destination. ### Method `process_and_write_results` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Usage ```python from manga_ocr.run import process_and_write_results # Assuming 'mocr' is an initialized MangaOcr instance and 'img_or_path' is the image source process_and_write_results(mocr, img_or_path, "clipboard") ``` ### Parameters Details: - `mocr` (`MangaOcr`): An initialized instance of the `MangaOcr` class. - `img_or_path` (str, Path, PIL.Image): The image source to process. - `write_to` (str): The destination to write the OCR results (e.g., "clipboard" or a file path). ### Response This function performs an action and does not return a value directly. ``` -------------------------------- ### Manga OCR Initialization with Custom Model Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md Initializes the Manga OCR using a custom fine-tuned model. Provide the path to your model either as a model hub ID or a local file path. ```python # Use a custom fine-tuned model mocr = MangaOcr( pretrained_model_name_or_path="path/to/custom/model" ) ``` -------------------------------- ### Background Service: Clipboard Input/Output Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md Runs the Manga OCR service to read text from the clipboard and write the results back to the clipboard. This is ideal for use with screenshot tools like ShareX or Flameshot. ```python # Reads from clipboard, writes to clipboard # Useful with screenshot tools like ShareX or Flameshot run() ``` -------------------------------- ### Directory Monitor with Manga OCR (Programmatic) Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/QUICK_START.md Programmatically configures Manga OCR to monitor a source directory for images and write recognized text to a specified output file. ```python from manga_ocr.run import run run( read_from="/path/to/images", write_to="/path/to/output.txt" ) ``` -------------------------------- ### Run Manga OCR from Command Line (Clipboard Mode) Source: https://github.com/kha-white/manga-ocr/blob/master/README.md Execute Manga OCR from the command line to process images from the system clipboard and write recognized text back to the clipboard. This is useful for interactive workflows. ```command-line manga_ocr ``` -------------------------------- ### Initialize and Use MangaOcr for Single Image Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/README.md Instantiate the MangaOcr class and process a single image file. Ensure the image file exists at the specified path. ```python from manga_ocr import MangaOcr mocr = MangaOcr() text = mocr("image.jpg") ``` -------------------------------- ### MangaOcr CLI Initialization Dependencies Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODULE_STRUCTURE.md Details the imports used in the manga_ocr CLI's run script, including MangaOcr, logger, Image, and pyperclip. This is relevant for understanding CLI dependencies. ```python from manga_ocr import MangaOcr from loguru import logger from PIL import Image import pyperclip ``` -------------------------------- ### Initialize and Use AutoTokenizer Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODEL_AND_INFERENCE.md Use AutoTokenizer to decode token IDs back into human-readable text, skipping special tokens. This is crucial for interpreting model output. ```python from transformers import AutoTokenizer # Decode token IDs to text tokenizer = AutoTokenizer.from_pretrained(model_name) text = tokenizer.decode(token_ids, skip_special_tokens=True) ``` -------------------------------- ### Initialize Manga OCR in CPU-Only Mode Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/00_START_HERE.md Instantiate the MangaOcr class forcing the use of the CPU, which is useful when a GPU is unavailable or not desired. This ensures the OCR process runs without GPU acceleration. ```python mocr = MangaOcr(force_cpu=True) ``` -------------------------------- ### Run Background OCR with Custom Model and Directory Monitoring Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/api-reference/background-runner.md Uses a custom OCR model path for processing images found in a specified directory, with results appended to a text file. Ensure the custom model path is valid. ```python from manga_ocr.run import run # Use a custom model with directory monitoring run( read_from="/home/user/manga", write_to="/home/user/manga_text.txt", pretrained_model_name_or_path="/custom/model/path" ) ``` -------------------------------- ### Manga OCR Initialization with CPU Only Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md Initializes the Manga OCR forcing CPU usage. This is useful for systems without a GPU or when encountering memory constraints with GPU usage. ```python # For systems without GPU or with memory constraints mocr = MangaOcr(force_cpu=True) ``` -------------------------------- ### Specify Input Directory for Manga OCR Runner Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md Ensure the provided directory path exists when using the `read_from` argument in the background runner. Incorrect paths will result in a ValueError. ```python run(read_from="/correct/path") ``` -------------------------------- ### Run Manga OCR using Python Module Source: https://github.com/kha-white/manga-ocr/blob/master/README.md If the `manga_ocr` command is not found, you can execute the module directly using `python -m manga_ocr`. This is an alternative way to run the command-line interface. ```command-line python -m manga_ocr ``` -------------------------------- ### Load Custom Hugging Face Model Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODEL_AND_INFERENCE.md Load a Manga OCR model from a different Hugging Face repository. Ensure the specified model is compatible. ```python # From different Hugging Face model mocr = MangaOcr( pretrained_model_name_or_path="username/custom-manga-ocr" ) ``` -------------------------------- ### Run Continuous Clipboard Monitoring Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/INDEX.md This snippet demonstrates how to continuously monitor the clipboard for images and perform OCR, outputting the recognized text back to the clipboard. This can be run directly from the terminal or programmatically. ```python from manga_ocr.run import run # Run in terminal: # manga_ocr # Or programmatically: run(read_from="clipboard", write_to="clipboard") ``` -------------------------------- ### Run Background OCR with CPU Force and Slow Polling Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/api-reference/background-runner.md Configures the background OCR to force CPU usage and increase the polling interval for checking new images. This can reduce resource consumption. ```python from manga_ocr.run import run # Force CPU and slow down polling to reduce resource usage run( read_from="clipboard", write_to="clipboard", force_cpu=True, delay_secs=0.5 ) ``` -------------------------------- ### Monitor Clipboard with Manga OCR CLI Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/00_START_HERE.md Use the manga-ocr command-line tool to automatically process images copied to the clipboard. This requires no additional arguments for basic clipboard monitoring. ```bash manga_ocr # That's all! ``` -------------------------------- ### Load Image Input Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODEL_AND_INFERENCE.md Loads an image from a file path or uses an existing PIL Image object. Supports string paths, Path objects, or PIL.Image.Image instances. ```python # Input: img_or_path (str, Path, or PIL.Image) if isinstance(img_or_path, str) or isinstance(img_or_path, Path): img = Image.open(img_or_path) elif isinstance(img_or_path, Image.Image): img = img_or_path ``` -------------------------------- ### Initialize and Use Manga OCR Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/00_START_HERE.md Initialize the MangaOcr class once and then use the instance to process images. This is the primary method for performing OCR on manga pages. ```python from manga_ocr import MangaOcr # Initialize once mocr = MangaOcr() # Use it text = mocr("manga_page.jpg") print(text) # Prints: Japanese text from image ``` -------------------------------- ### Core OCR Implementation Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODULE_STRUCTURE.md Defines the MangaOcrModel and MangaOcr classes for OCR processing, including initialization, preprocessing, and inference. Also includes a post_process function. ```python class MangaOcrModel(VisionEncoderDecoderModel, GenerationMixin) class MangaOcr: def __init__(self, pretrained_model_name_or_path, force_cpu) def __call__(self, img_or_path) def _preprocess(self, img) def post_process(text) ``` -------------------------------- ### Run Manga OCR from Command Line (Folder Mode) Source: https://github.com/kha-white/manga-ocr/blob/master/README.md Execute Manga OCR from the command line to process images within a specified directory. This mode is suitable for automated processing of screenshots or downloaded images. ```command-line manga_ocr "/path/to/sharex/screenshot/folder" ``` -------------------------------- ### Initialize MangaOcr Class Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/api-reference/manga-ocr-main.md Instantiate the MangaOcr class for OCR processing. You can use the default model, force CPU usage, or specify a custom pre-trained model path. ```python from manga_ocr import MangaOcr # Basic initialization with default model mocr = MangaOcr() # Using CPU only mocr_cpu = MangaOcr(force_cpu=True) # Using a custom model mocr_custom = MangaOcr(pretrained_model_name_or_path="/path/to/custom/model") ``` -------------------------------- ### File Output Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/QUICK_START.md Specify a file path to save the OCR results using the --write_to flag. ```bash manga_ocr --write_to output.txt ``` -------------------------------- ### Debug Mode Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/QUICK_START.md Enable verbose output for debugging purposes using the --verbose flag. ```bash manga_ocr --verbose True ``` -------------------------------- ### are_images_identical() Utility Function Signature Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/types.md Signature for a utility function that checks if two images are identical. It accepts optional PIL Image objects and returns a boolean. ```python def are_images_identical( img1: Optional[Image.Image], img2: Optional[Image.Image] ) -> bool ``` -------------------------------- ### Run Model Inference Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/MODEL_AND_INFERENCE.md Performs inference using the model's generate method. It adds a batch dimension, moves the tensor to the model's device, and generates token sequences. ```python # Run model generation output_tokens = self.model.generate( pixel_values[None].to(self.model.device), # Add batch dimension max_length=300 )[0].cpu() ``` -------------------------------- ### Handle UnidentifiedImageError Manually Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/errors.md Demonstrates how to manually catch PIL.UnidentifiedImageError when processing images from a directory if not using the run() function's automatic handling. This is useful for custom image processing loops. ```python # The run() function handles this automatically and logs a warning # without stopping the monitoring process. If you want to process # directories manually and catch these errors: from manga_ocr import MangaOcr from pathlib import Path from PIL import UnidentifiedImageError mocr = MangaOcr() image_dir = Path("/path/to/images") for image_file in image_dir.glob("*"): if image_file.is_file(): try: text = mocr(image_file) print(f"{image_file}: {text}") except UnidentifiedImageError: print(f"Skipped invalid image: {image_file}") ``` -------------------------------- ### Python Type Annotations for Manga OCR Source: https://github.com/kha-white/manga-ocr/blob/master/_autodocs/QUICK_START.md Defines type hints for input images, output text, and file paths. Use these for better code clarity and static analysis. ```python from pathlib import Path from PIL import Image from typing import Union, Optional # Input type for __call__ img_or_path: Union[str, Path, Image.Image] # Output type text: str # For file output output_path: str # Must end with .txt or be "clipboard" # For optional image comparison img: Optional[Image.Image] # Can be None ```