### Install dependencies and clone repositories Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/ReadPipeline-GoogleColab.ipynb Install required packages and clone the necessary repositories (SEGM-model, OCR-model, ReadingPipeline) in a Google Colab environment. Run these commands before importing the pipeline modules. ```python ! pip install onnxruntime ! pip install openvino ! pip install huggingface_hub ! pip install git+https://github.com/parlance/ctcdecode ! pip install pyclipper ! git clone https://github.com/ai-forever/SEGM-model.git ! git clone https://github.com/ai-forever/OCR-model.git ! git clone https://github.com/ai-forever/ReadingPipeline.git ``` -------------------------------- ### Get structured text from prediction Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/inference_pipeline.ipynb Extracts structured text from the prediction data, filtering for the 'shrinked_text' class, and prints each line of text per page, separating pages with a blank line. ```python structured_text = get_structured_text(pred_data, ['shrinked_text']) for page_text in structured_text: for line_text in page_text: if line_text: print(' '.join(line_text)) print('\n') ``` -------------------------------- ### Import libraries and set up paths Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/ReadPipeline-GoogleColab.ipynb Add the cloned repositories to the Python path and import the necessary libraries, including the pipeline predictor and linefinder functions. ```python import sys sys.path.append('SEGM-model/') sys.path.append('OCR-model/') sys.path.append('ReadingPipeline/') import cv2 from matplotlib import pyplot as plt import numpy as np import json from huggingface_hub import hf_hub_download from ocrpipeline.predictor import PipelinePredictor from ocrpipeline.linefinder import get_structured_text ``` -------------------------------- ### Download and display demo image Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/ReadPipeline-GoogleColab.ipynb Downloads a sample image from the model repository, reads it with OpenCV, converts from BGR to RGB, and displays it using matplotlib. ```python img_path = hf_hub_download("sberbank-ai/ReadingPipeline-Peter", "0_0.jpg") image = cv2.imread(img_path) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) plt.figure(figsize=(8, 8)) plt.imshow(image) plt.show() ``` -------------------------------- ### Set image and config paths Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/inference_pipeline.ipynb Defines empty string variables for the input image path and the pipeline configuration path. These must be filled in with actual paths before running the pipeline. ```python IMG_PATH = '' PIPELINE_CONFIG_PATH = '' ``` -------------------------------- ### Initialize the pipeline predictor Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/ReadPipeline-GoogleColab.ipynb Initializes the pipeline predictor by downloading the weights and config for the 'sberbank-ai/ReadingPipeline-Peter' model and creating a PipelinePredictor instance. ```python PIPELINE_CONFIG_PATH = get_config_and_download_weights("sberbank-ai/ReadingPipeline-Peter") predictor = PipelinePredictor(pipeline_config_path=PIPELINE_CONFIG_PATH) ``` -------------------------------- ### Download weights and update pipeline config Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/ReadPipeline-GoogleColab.ipynb Downloads model weights and configs from Hugging Face Hub, updates the pipeline_config.json with the downloaded paths, sets runtime to Pytorch, and returns the path to the modified config. The device parameter defaults to 'cuda'. ```python def get_config_and_download_weights(repo_id, device='cuda'): # download weights and configs pipeline_config_path = hf_hub_download(repo_id, "pipeline_config.json") ocr_model_path = hf_hub_download(repo_id, "ocr/ocr_model.ckpt") ocr_config_path = hf_hub_download(repo_id, "ocr/ocr_config.json") segm_model_path = hf_hub_download(repo_id, "segm/segm_model.ckpt") segm_config_path = hf_hub_download(repo_id, "segm/segm_config.json") # change paths to downloaded weights and configs in main pipeline_config with open(pipeline_config_path, 'r') as f: pipeline_config = json.load(f) pipeline_config['main_process']['SegmPrediction']['model_path'] = segm_model_path pipeline_config['main_process']['SegmPrediction']['config_path'] = segm_config_path pipeline_config['main_process']['SegmPrediction']['num_threads'] = 4 pipeline_config['main_process']['SegmPrediction']['device'] = device pipeline_config['main_process']['SegmPrediction']['runtime'] = "Pytorch" pipeline_config['main_process']['OCRPrediction']['model_path'] = ocr_model_path pipeline_config['main_process']['OCRPrediction']['config_path'] = ocr_config_path pipeline_config['main_process']['OCRPrediction']['num_threads'] = 4 pipeline_config['main_process']['OCRPrediction']['device'] = device pipeline_config['main_process']['OCRPrediction']['runtime'] = "Pytorch" # save pipeline_config with open(pipeline_config_path, 'w') as f: json.dump(pipeline_config, f) return pipeline_config_path ``` -------------------------------- ### Set pipeline and data paths Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/inference_pipeline_on_dataset.ipynb Defines configuration paths for the pipeline, dataset annotations, images, and output folder. Fill in the empty strings before running. ```python PIPELINE_CONFIG_PATH = '/workdir/scripts/pipeline_config.json' # Path to json with segmentation dataset annotation in COCO format DATA_JSON_PATH = '' # Path to folder with evaluation images IMAGE_ROOT = '' # Folder to save prediction json (one for each image) SAVE_FOLDER = '' ``` -------------------------------- ### Set model runtime (Pytorch/ONNX/OpenVino) Source: https://github.com/ai-forever/readingpipeline/blob/master/README.md Specifies runtime method for OCR and segmentation models. Options: "Pytorch" (cuda and cpu), "ONNX" (cpu only), or "OpenVino" (cpu only). The comment in the source indicates where to choose the runtime method. ```json "main_process": { "SegmPrediction": { "model_path": "/path/to/model.ckpt", "config_path": "/path/to/config.json", "num_threads": 8, "device": "cuda", "runtime": "Pytorch" # here you can chose runtime method }, ... } ``` -------------------------------- ### Initialize PipelinePredictor Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/inference_pipeline.ipynb Initializes the PipelinePredictor with the specified pipeline configuration path. ```python predictor = PipelinePredictor(pipeline_config_path=PIPELINE_CONFIG_PATH) ``` -------------------------------- ### Evaluate predictions with evaluate.py Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/inference_pipeline_on_dataset.ipynb Runs the evaluation script with the annotation and prediction class names, using the previously defined paths. ```bash ! python evaluate.py \ --annotation_json_path {DATA_JSON_PATH} \ --ann_class_names pupil_text pupil_comment teacher_comment \ --pred_class_names shrinked_pupil_text shrinked_comments \ --pred_jsons_dir {SAVE_FOLDER} ``` -------------------------------- ### Configure main_process pipeline order Source: https://github.com/ai-forever/readingpipeline/blob/master/README.md Defines the order of the main processing methods in the pipeline loop. Classes are initialized with parameters from the config and called sequentially. To add a new class, add it to MAIN_PROCESS_DICT in ocrpipeline/predictor.py and specify it in this dict at the desired chain position. ```json "main_process": { "SegmPrediction": {...}, "RestoreImageAngle": {...}, "ClassContourPosptrocess": {...}, "OCRPrediction": {...}, "LineFinder": {...}, ... } ``` -------------------------------- ### Visualize OCR results Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/inference_pipeline.ipynb Reads the image, converts it from BGR to RGB, generates a visualization with text line contours and shrinked text labels, and displays it using matplotlib with a large figure size. ```python image = cv2.imread(IMG_PATH) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) vis = get_image_visualization( img=image, pred_data=pred_data, draw_contours_classes=['text_line'], draw_text_classes=['shrinked_text'] ) plt.figure(figsize=(40, 40)) plt.imshow(vis) plt.show() ``` -------------------------------- ### Import OCR pipeline modules Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/inference_pipeline.ipynb Imports the required libraries and modules for the OCR pipeline: OpenCV, matplotlib, and the ocrpipeline components (PipelinePredictor, visualization utilities, and get_structured_text). ```python import cv2 from matplotlib import pyplot as plt from ocrpipeline.predictor import PipelinePredictor from ocrpipeline.utils import get_image_visualization, get_line_number_visualization from ocrpipeline.linefinder import get_structured_text ``` -------------------------------- ### Import dependencies and PipelinePredictor Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/inference_pipeline_on_dataset.ipynb Imports required libraries and the PipelinePredictor class from the ocrpipeline package. ```python import cv2 import json from tqdm import tqdm import os from ocrpipeline.predictor import PipelinePredictor from ocrpipeline.utils import get_image_visualization ``` -------------------------------- ### Run pipeline prediction Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/ReadPipeline-GoogleColab.ipynb Runs the pipeline predictor on the image, returning the rotated image and prediction data. ```python image = cv2.imread(img_path) rotated_image, pred_data = predictor(image) ``` -------------------------------- ### Run inference on dataset and save predictions Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/inference_pipeline_on_dataset.ipynb Iterates over images from the COCO annotation JSON, runs the predictor on each image, and saves the prediction data as a JSON file per image in the specified output folder. ```python os.makedirs(SAVE_FOLDER, exist_ok=True) with open(DATA_JSON_PATH, 'r') as f: data = json.load(f) for data_img in tqdm(data['images']): img_name = data_img['file_name'] image = cv2.imread(os.path.join(IMAGE_ROOT, img_name)) rotated_image, pred_data = predictor(image) pred_json_name = os.path.splitext(img_name)[0] + '.json' pred_json_path = os.path.join(SAVE_FOLDER, pred_json_name) with open(pred_json_path, 'w') as f: json.dump(pred_data, f) ``` -------------------------------- ### Run OCR prediction on image Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/inference_pipeline.ipynb Reads the input image using OpenCV and runs the predictor on it, returning the rotated image and prediction data. ```python image = cv2.imread(IMG_PATH) rotated_image, pred_data = predictor(image) ``` -------------------------------- ### Extract and print structured text Source: https://github.com/ai-forever/readingpipeline/blob/master/scripts/ReadPipeline-GoogleColab.ipynb Extracts structured text from the prediction data using the 'shrinked_text' key, joins line words, and prints each line of the resulting text. ```python structured_text = get_structured_text(pred_data, ['shrinked_text']) result_text = [' '.join(line_text) for page_text in structured_text for line_text in page_text] for line in result_text: print(line) ``` -------------------------------- ### Configure class-specific contour processing Source: https://github.com/ai-forever/readingpipeline/blob/master/README.md Sets class-specific parameters for contour processing. The contour_posprocess dict defines the order of contour processing methods. Class names must match the segmentation model's class names. To add a new class, add it to CONTOUR_PROCESS_DICT in ocrpipeline/predictor.py and specify it in this dict. ```json "classes": { "shrinked_pupil_text": { "contour_posptrocess": { "BboxFromContour": {}, "UpscaleBbox": {"upscale_bbox": [1.4, 2.3]} } }, ... } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.