### Install img2table with OCR Support Source: https://github.com/xavctn/img2table/blob/main/README.md Installs the img2table library with optional support for various OCR (Optical Character Recognition) engines. Choose the installation command based on the desired OCR engine for text extraction from images. ```bash pip install img2table pip install img2table[paddle] pip install img2table[easyocr] pip install img2table[surya] pip install img2table[gcp] pip install img2table[aws] pip install img2table[azure] ``` -------------------------------- ### Configure Tesseract OCR with Python Source: https://github.com/xavctn/img2table/blob/main/README.md Shows how to initialize the Tesseract OCR engine for text extraction. This includes setting the number of threads, language, page segmentation mode (PSM), and the directory for Tesseract's trained data files. Tesseract OCR requires prior installation. ```python from img2table.ocr import TesseractOCR ocr = TesseractOCR(n_threads=1, lang="eng", psm=11, tessdata_dir="...") ``` -------------------------------- ### Install img2table and PaddleOCR dependencies Source: https://github.com/xavctn/img2table/blob/main/README.md Commands to install the necessary packages for img2table and PaddleOCR, including GPU support via CUDA 11.8. ```bash pip install paddlepaddle-gpu==2.5.0rc1.post118 -f https://www.paddlepaddle.org.cn/whl/linux/mkl/avx/stable.html pip install paddleocr img2table ``` -------------------------------- ### Configure PaddleOCR with Python Source: https://github.com/xavctn/img2table/blob/main/README.md Illustrates the initialization of PaddleOCR for text recognition. Users can specify the language for text extraction and pass additional keyword arguments to the PaddleOCR constructor. Language models are downloaded on first use. For GPU usage, a specific CUDA version of paddlepaddle-gpu must be installed manually. ```python from img2table.ocr import PaddleOCR ocr = PaddleOCR(lang="en", kw={"kwarg": kw_value, ...}) ``` -------------------------------- ### Initialize docTR for img2table Source: https://github.com/xavctn/img2table/blob/main/README.md Initializes the docTR OCR engine. Requires prior installation of docTR and supports language detection toggling. ```python from img2table.ocr import DocTR ocr = DocTR(detect_language=False, kw={"kwarg": kw_value}) ``` -------------------------------- ### Implicit Row and Column Detection in img2table Source: https://context7.com/xavctn/img2table/llms.txt Shows how to enable implicit row and column detection to split cells containing multiple logical rows or columns based on text positioning. This example uses TesseractOCR to process an image and compares the results with and without implicit detection. ```python from img2table.document import Image from img2table.ocr import TesseractOCR ocr = TesseractOCR() image = Image("complex_table.png") # Without implicit detection tables_basic = image.extract_tables(ocr=ocr) print(f"Basic: {tables_basic[0].df.shape}") # With implicit row/column detection tables_implicit = image.extract_tables( ocr=ocr, implicit_rows=True, # Split cells with multiple text lines implicit_columns=True # Split cells with separated text blocks ) print(f"Implicit: {tables_implicit[0].df.shape}") ``` -------------------------------- ### Complete img2table Extraction Pipeline for PDFs Source: https://context7.com/xavctn/img2table/llms.txt A comprehensive example demonstrating the full extraction pipeline using img2table for PDF documents. It initializes TesseractOCR and a PDF document object, extracts all tables with advanced options, processes the results into a list of dictionaries, saves individual tables to CSV, and exports all tables to a single Excel file. ```python from img2table.document import PDF from img2table.ocr import TesseractOCR import pandas as pd # Initialize components ocr = TesseractOCR(n_threads=4, lang="eng") pdf = PDF( src="financial_report.pdf", pages=None, # Process all pages detect_rotation=True, pdf_text_extraction=True ) # Extract all tables all_tables = pdf.extract_tables( ocr=ocr, implicit_rows=True, implicit_columns=True, borderless_tables=True, min_confidence=60 ) # Process extracted tables results = [] for page_num, tables in all_tables.items(): for table_idx, table in enumerate(tables): df = table.df results.append({ "page": page_num + 1, "table": table_idx + 1, "title": table.title, "rows": df.shape[0], "columns": df.shape[1], "data": df }) # Save individual table df.to_csv(f"page{page_num + 1}_table{table_idx + 1}.csv", index=False) print(f"Extracted {len(results)} tables from {len(all_tables)} pages") # Export all to single Excel workbook pdf.to_xlsx(dest="all_tables.xlsx", ocr=ocr) ``` -------------------------------- ### docTR Integration Source: https://github.com/xavctn/img2table/blob/main/README.md Integrates docTR for OCR. Requires prior installation. Supports language detection and custom keyword arguments for the OCR predictor. ```APIDOC ## docTR Integration ### Description Integrates docTR for OCR. Requires prior installation. Supports language detection and custom keyword arguments for the OCR predictor. ### Method Instantiation of OCR object ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from img2table.ocr import DocTR ocr = DocTR(detect_language=False, kw={"kwarg": kw_value, ...}) ``` ### Response #### Success Response (200) N/A #### Response Example N/A ### Parameters - **detect_language** (bool, optional, default `False`) - Parameter indicating if language prediction is run on the document - **kw** (dict, optional, default `None`) - Dictionary containing additional keyword arguments passed to the docTR `ocr_predictor` method. ``` -------------------------------- ### Extract Tables with and without Implicit Rows Source: https://github.com/xavctn/img2table/blob/main/examples/Implicit.ipynb Extracts tables from the image using the img2table library. It demonstrates the difference in output when the `implicit_rows` parameter is set to `False` versus `True`. The `implicit_columns` parameter is kept `False` in this example. ```python # Extract tables without implicit rows extracted_tables = img.extract_tables(ocr=ocr, implicit_rows=False, implicit_columns=False) table = extracted_tables.pop() # Extract tables with implicit rows extracted_tables_implicit = img.extract_tables(ocr=ocr, implicit_rows=True, implicit_columns=False) table_implicit_rows = extracted_tables_implicit.pop() ``` -------------------------------- ### Configure EasyOCR Backend Source: https://context7.com/xavctn/img2table/llms.txt Initializes the EasyOCR engine, which supports over 80 languages and provides simple configuration for GPU usage and verbosity. ```python from img2table.ocr import EasyOCR # With custom options ocr = EasyOCR( lang=["en", "ch_sim"], kw={ "gpu": True, "verbose": False } ) ``` -------------------------------- ### Instantiate PDF Document with Python Source: https://github.com/xavctn/img2table/blob/main/README.md Demonstrates how to create a PDF document object from a source file. It allows specifying pages to process, whether to detect rotation, and if text extraction should be performed for native PDFs. The PDF is converted to images at 200 DPI for table identification. ```python from img2table.document import PDF pdf = PDF(src, pages=[0, 2], detect_rotation=False, pdf_text_extraction=True) ``` -------------------------------- ### Load and Process Image Files with Image Class Source: https://context7.com/xavctn/img2table/llms.txt Demonstrates how to initialize the Image class using various sources such as file paths, byte streams, and BytesIO buffers. Includes options for automatic rotation detection to handle skewed documents. ```python from img2table.document import Image import io # Load image from file path image = Image(src="path/to/document.png") # Load image from bytes with open("document.jpg", "rb") as f: image = Image(src=f.read()) # Load with rotation detection enabled image = Image(src="skewed_document.png", detect_rotation=True) # Load from BytesIO buffer buffer = io.BytesIO(image_bytes) image = Image(src=buffer) ``` -------------------------------- ### Configure OCR Backends Source: https://context7.com/xavctn/img2table/llms.txt Initialize various OCR engines including Surya, Google Cloud Vision, AWS Textract, and Azure Cognitive Services. These engines are required to process document text before table extraction. ```python from img2table.ocr import SuryaOCR, VisionOCR, TextractOCR, AzureOCR import os # Surya OCR ocr_surya = SuryaOCR(langs=["en", "fr", "de", "es"]) # Google Vision ocr_vision = VisionOCR(api_key="your-key", timeout=15) # AWS Textract ocr_textract = TextractOCR(aws_access_key_id="key", aws_secret_access_key="secret", region="us-east-1") # Azure OCR ocr_azure = AzureOCR(endpoint="https://...", subscription_key="key") ``` -------------------------------- ### POST /document/initialize Source: https://github.com/xavctn/img2table/blob/main/examples/Basic_usage.ipynb Initializes a document source from a file path, bytes, or file-like object for processing. ```APIDOC ## POST /document/initialize ### Description Creates a document object (Image or PDF) from a source to prepare it for table extraction. ### Method POST ### Endpoint /document/initialize ### Parameters #### Request Body - **type** (string) - Required - The document type ('image' or 'pdf'). - **src** (string/bytes) - Required - The file path, raw bytes, or file-like object. - **pages** (list) - Optional - List of page indices to process (for PDF only). ### Request Example { "type": "pdf", "src": "data/tables.pdf", "pages": [0, 1] } ### Response #### Success Response (200) - **document_id** (string) - Unique identifier for the initialized document object. ``` -------------------------------- ### Configure TesseractOCR Backend Source: https://context7.com/xavctn/img2table/llms.txt Initializes the Tesseract OCR engine with custom configuration parameters such as thread count, language settings, and page segmentation modes. ```python from img2table.ocr import TesseractOCR # Basic initialization ocr = TesseractOCR() # Full configuration ocr = TesseractOCR( n_threads=4, lang="eng+fra", psm=11, tessdata_dir="/usr/share/tesseract-ocr/4.00/tessdata" ) ``` -------------------------------- ### Configure SuryaOCR Backend Source: https://context7.com/xavctn/img2table/llms.txt Initializes the SuryaOCR engine for modern multilingual text recognition. ```python from img2table.ocr import SuryaOCR # English OCR ocr = SuryaOCR(langs=["en"]) ``` -------------------------------- ### Configure DocTR Backend Source: https://context7.com/xavctn/img2table/llms.txt Initializes the DocTR library for document text recognition, allowing for custom detection and recognition architecture selection. ```python from img2table.ocr import DocTR # With custom model options ocr = DocTR( detect_language=False, kw={ "pretrained": True, "det_arch": "db_resnet50", "reco_arch": "crnn_vgg16_bn" } ) ``` -------------------------------- ### Configure PaddleOCR Backend Source: https://context7.com/xavctn/img2table/llms.txt Initializes the PaddleOCR engine for deep learning-based text recognition, including support for GPU acceleration and language selection. ```python from img2table.ocr import PaddleOCR # Basic English OCR ocr = PaddleOCR(lang="en") # With additional PaddleOCR options ocr = PaddleOCR( lang="en", kw={ "use_angle_cls": True, "use_gpu": True, "show_log": False } ) ``` -------------------------------- ### Initialize EasyOCR for img2table Source: https://github.com/xavctn/img2table/blob/main/README.md Initializes the EasyOCR engine. It accepts a list of languages and optional keyword arguments for the Reader constructor. ```python from img2table.ocr import EasyOCR ocr = EasyOCR(lang=["en"], kw={"kwarg": kw_value}) ``` -------------------------------- ### Configure OCR Instances for Table Extraction with img2table Source: https://github.com/xavctn/img2table/blob/main/examples/Basic_usage.ipynb Shows how to initialize and configure various OCR (Optical Character Recognition) tools supported by img2table. These OCR instances are crucial for inferring cell content during table extraction. ```python # Tesseract OCR from img2table.ocr import TesseractOCR tesseract_ocr = TesseractOCR(n_threads=1, lang="eng") # PaddleOCR from img2table.ocr import PaddleOCR paddle_ocr = PaddleOCR(lang="en", kw={"use_dilation": True}) # EasyOCR from img2table.ocr import EasyOCR easyocr = EasyOCR(lang=["en"], kw={"gpu": False}) # docTR from img2table.ocr import DocTR doctr = DocTR(detect_language=True, kw={"detect_orientation": True}) # Google Vision OCR from img2table.ocr import VisionOCR vision_ocr = VisionOCR(api_key="***") # AWS Textract OCR from img2table.ocr import TextractOCR textract_ocr = TextractOCR(aws_access_key_id="***", aws_secret_access_key="***", aws_session_token="***", region="eu-west-1") # Azure Cognitive Services OCR from img2table.ocr import AzureOCR azure_ocr = AzureOCR(endpoint="abc.azure.com", subscription_key="***") ``` -------------------------------- ### Initialize Azure Cognitive Services OCR for img2table Source: https://github.com/xavctn/img2table/blob/main/README.md Initializes the Azure Cognitive Services OCR engine using an endpoint and subscription key. ```python from img2table.ocr import AzureOCR ocr = AzureOCR(endpoint="abc.azure.com", subscription_key="***") ``` -------------------------------- ### Initialize Surya OCR for img2table Source: https://github.com/xavctn/img2table/blob/main/README.md Initializes the Surya OCR engine, which requires Python 3.10 or higher. It automatically downloads models on the first use. ```python from img2table.ocr import SuryaOCR ocr = SuryaOCR(langs=["en"]) ``` -------------------------------- ### PDF Document Initialization Source: https://github.com/xavctn/img2table/blob/main/README.md Instantiates a PDF document object for table extraction, allowing configuration of page selection and text extraction settings. ```APIDOC ## PDF Document Initialization ### Description Initializes a PDF document for processing. Pages are converted to images at 200 DPI for table identification. ### Parameters - **src** (str/Path/bytes) - Required - The PDF source file. - **pages** (list) - Optional - List of page indexes to process. Defaults to all pages. - **detect_rotation** (bool) - Optional - Whether to detect and correct skew/rotation. Defaults to False. - **pdf_text_extraction** (bool) - Optional - Whether to extract text directly from native PDFs. Defaults to True. ### Request Example ```python from img2table.document import PDF pdf = PDF(src='doc.pdf', pages=[0, 2], detect_rotation=False, pdf_text_extraction=True) ``` ``` -------------------------------- ### Initialize AWS Textract for img2table Source: https://github.com/xavctn/img2table/blob/main/README.md Initializes the AWS Textract OCR engine. Credentials can be passed directly or managed via AWS environment variables. ```python from img2table.ocr import TextractOCR ocr = TextractOCR(aws_access_key_id="***", aws_secret_access_key="***", aws_session_token="***", region="eu-west-1") ``` -------------------------------- ### Initialize OCR and Image Objects Source: https://github.com/xavctn/img2table/blob/main/examples/Implicit.ipynb Initializes the Tesseract OCR engine and creates an Image object from a source file. Tesseract OCR is required for text recognition within the image to identify table elements. ```python # Define OCR instance, requires prior installation of Tesseract-OCR ocr = TesseractOCR() # Define image img = Image(src="data/implicit.png") ``` -------------------------------- ### Initialize Google Vision OCR for img2table Source: https://github.com/xavctn/img2table/blob/main/README.md Initializes the Google Vision OCR engine. Authentication is handled via environment variables or an explicit API key. ```python from img2table.ocr import VisionOCR ocr = VisionOCR(api_key="api_key", timeout=15) ``` -------------------------------- ### Load and Display Image Source: https://github.com/xavctn/img2table/blob/main/examples/Implicit.ipynb Loads an image file using Pillow (PIL) and displays it. This step is typically for previewing the image before table extraction. ```python PILImage.open("data/implicit.png") ``` -------------------------------- ### Initialize Image Document in Python Source: https://github.com/xavctn/img2table/blob/main/README.md Initializes an Image document object from a source. The 'src' parameter can be a file path, bytes, or a BytesIO object. The 'detect_rotation' parameter, when set to True, attempts to correct skew and rotation, but may alter image coordinates. ```python from img2table.document import Image image = Image(src, detect_rotation=False) ``` -------------------------------- ### POST /document/image Source: https://github.com/xavctn/img2table/blob/main/README.md Instantiates an image document for table identification and extraction processing. ```APIDOC ## POST /document/image ### Description Instantiates an image object to be used for table detection and extraction. This is the entry point for processing image-based documents. ### Method POST ### Endpoint /document/image ### Parameters #### Request Body - **src** (str, pathlib.Path, bytes, io.BytesIO) - Required - The source of the image file. - **detect_rotation** (bool) - Optional - If True, detects and corrects skew/rotation of the image up to 45 degrees. Defaults to False. ### Request Example { "src": "path/to/image.png", "detect_rotation": true } ### Response #### Success Response (200) - **image_object** (object) - The initialized image document object ready for extraction methods. #### Response Example { "status": "success", "message": "Image instantiated successfully" } ``` -------------------------------- ### Load Documents from Various Sources with img2table Source: https://github.com/xavctn/img2table/blob/main/examples/Basic_usage.ipynb Demonstrates how to load image and PDF documents into img2table from different sources like file paths, byte streams, and file-like objects. This is the first step in processing documents with the library. ```python from img2table.document import Image img_path = "data/tables.png" # Definition of image from path img_from_path = Image(src=img_path) # Definition of image from bytes with open(img_path, 'rb') as f: img_bytes = f.read() img_from_bytes = Image(src=img_bytes) # Definition of image from file-like object from io import BytesIO img_from_file_like = Image(src=BytesIO(img_bytes)) ``` ```python from img2table.document import PDF pdf_path = "data/tables.pdf" # Definition of PDF from path # The optional pages argument enables the extraction of table on specific pages of the PDF pdf_from_path = PDF(src=pdf_path, pages=[0, 1]) # Definition of PDF from bytes with open(pdf_path, 'rb') as f: pdf_bytes = f.read() pdf_from_bytes = PDF(src=pdf_bytes) # Definition of PDF from file-like object from io import BytesIO pdf_from_file_like = PDF(src=BytesIO(pdf_bytes)) ``` -------------------------------- ### Extract Borderless Tables with PaddleOCR Source: https://context7.com/xavctn/img2table/llms.txt Demonstrates how to extract tables without visible borders from an image using img2table and PaddleOCR. This feature relies on text alignment and whitespace analysis and requires at least 3 columns. It processes an image file and returns extracted tables. ```python from img2table.document import Image from img2table.ocr import PaddleOCR ocr = PaddleOCR(lang="en") image = Image("spreadsheet_screenshot.png") # Enable borderless table detection tables = image.extract_tables( ocr=ocr, borderless_tables=True, # Required for borderless detection min_confidence=50 ) # Borderless tables will be included alongside bordered tables for table in tables: print(f"Table with {len(table.content)} rows") print(table.df) ``` -------------------------------- ### Iterate and Display Borderless Tables from Multiple Images Source: https://github.com/xavctn/img2table/blob/main/examples/borderless.ipynb This code iterates through all image files in a specified directory ('data/borderless') and extracts borderless tables from each. It uses the TesseractOCR and a helper function `display_borderless_tables` to visualize the extracted tables as PIL Images, with each table separated by an HTML horizontal rule. ```python for img_path in os.listdir("data/borderless"): img = Image(f"data/borderless/{img_path}") display_img = display_borderless_tables(img=img, ocr=tesseract) display(PILImage.fromarray(display_img)) display_html("
", raw=True) ``` -------------------------------- ### Extract Borderless Tables with TesseractOCR Source: https://github.com/xavctn/img2table/blob/main/examples/borderless.ipynb Demonstrates how to extract borderless tables from an image using the img2table library with TesseractOCR for optical character recognition. It loads an image, initializes TesseractOCR, and then extracts tables, displaying the resulting DataFrame. ```python img = Image("data/borderless.jpg") tesseract = TesseractOCR() # Extract tables with Tesseract and PaddleOCR tables = img.extract_tables(ocr=tesseract, borderless_tables=True) tables[0].df ``` -------------------------------- ### Load and Process PDF Documents with PDF Class Source: https://context7.com/xavctn/img2table/llms.txt Shows how to load PDF files for table extraction, including support for specific page ranges and native text extraction settings. ```python from img2table.document import PDF # Load entire PDF pdf = PDF(src="path/to/document.pdf") # Load specific pages only pdf = PDF(src="document.pdf", pages=[0, 2, 5]) # Load with all options pdf = PDF(src="document.pdf", pages=[0, 1], detect_rotation=True, pdf_text_extraction=True) # Load from bytes with open("document.pdf", "rb") as f: pdf = PDF(src=f.read()) ``` -------------------------------- ### Extract tables from documents using OCR Source: https://github.com/xavctn/img2table/blob/main/README.md Demonstrates how to instantiate an OCR engine and a document object to extract tables from images or PDFs. It utilizes the extract_tables method with various configuration parameters for row, column, and confidence settings. ```python from img2table.ocr import TesseractOCR from img2table.document import Image # Instantiation of OCR ocr = TesseractOCR(n_threads=1, lang="eng") # Instantiation of document, either an image or a PDF doc = Image(src) # Table extraction extracted_tables = doc.extract_tables(ocr=ocr, implicit_rows=False, implicit_columns=False, borderless_tables=False, min_confidence=50) ``` -------------------------------- ### Document extraction output formats Source: https://github.com/xavctn/img2table/blob/main/README.md Shows the expected return structures for table extraction from Image versus PDF documents. ```python # Image output output = [ExtractedTable(...), ExtractedTable(...), ...] # PDF output output = { 0: [ExtractedTable(...), ...], 1: [], ..., last_page: [ExtractedTable(...), ...] } ``` -------------------------------- ### EasyOCR Integration Source: https://github.com/xavctn/img2table/blob/main/README.md Integrates EasyOCR for text extraction. Models are downloaded on first use. Supports language selection and custom keyword arguments. ```APIDOC ## EasyOCR Integration ### Description Integrates EasyOCR for text extraction. Models are downloaded on first use. Supports language selection and custom keyword arguments. ### Method Instantiation of OCR object ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from img2table.ocr import EasyOCR ocr = EasyOCR(lang=["en"], kw={"kwarg": kw_value, ...}) ``` ### Response #### Success Response (200) N/A #### Response Example N/A ### Parameters - **lang** (list, optional, default `["en"]`) - Lang parameter used in EasyOCR for text extraction, check [documentation for available languages](https://www.jaided.ai/easyocr) - **kw** (dict, optional, default `None`) - Dictionary containing additional keyword arguments passed to the EasyOCR `Reader` constructor. ``` -------------------------------- ### Verify XLSX Exported Tables Source: https://github.com/xavctn/img2table/blob/main/examples/Basic_usage.ipynb Loads an XLSX file and iterates through its worksheets to print the number of rows and columns in each. This is a verification step to confirm that the tables were exported correctly to the XLSX file. ```python for ws in load_workbook("data/tables.xlsx"): print(f"Worksheet {ws.title} : {len(tuple(ws.rows))} rows, {len(tuple(ws.rows)[0])} columns") ``` -------------------------------- ### Surya OCR Integration Source: https://github.com/xavctn/img2table/blob/main/README.md Integrates Surya OCR, available for Python 3.10+. Models are downloaded on first use. Supports specifying multiple languages. ```APIDOC ## Surya OCR Integration ### Description Integrates Surya OCR, available for Python 3.10+. Models are downloaded on first use. Supports specifying multiple languages. ### Method Instantiation of OCR object ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from img2table.ocr import SuryaOCR ocr = SuryaOCR(langs=["en"]) ``` ### Response #### Success Response (200) N/A #### Response Example N/A ### Parameters - **langs** (list, optional, default `["en"]`) - Lang parameter used in Surya OCR for text extraction ``` -------------------------------- ### Visualize Detected Table Bounding Boxes with OpenCV Source: https://github.com/xavctn/img2table/blob/main/examples/Basic_usage.ipynb This snippet shows how to use OpenCV to draw bounding boxes around the detected tables and cells in an image. It iterates through the `ExtractedTable` content and uses cell bounding box information for visualization. ```python import cv2 from PIL import Image as PILImage # Assuming extracted_tables is already populated from a previous step # img = Image(src="data/tables.png") # extracted_tables = img.extract_tables() table_img = cv2.imread("data/tables.png") for table in extracted_tables: for row in table.content.values(): for cell in row: cv2.rectangle(table_img, (cell.bbox.x1, cell.bbox.y1), (cell.bbox.x2, cell.bbox.y2), (255, 0, 0), 2) PILImage.fromarray(table_img) ``` -------------------------------- ### AWS Textract OCR Integration Source: https://github.com/xavctn/img2table/blob/main/README.md Integrates AWS Textract using the DetectDocumentText API. Authentication can be handled via `boto3` credentials, environment variables, or configuration files. ```APIDOC ## AWS Textract OCR Integration ### Description Integrates AWS Textract using the DetectDocumentText API. Authentication can be handled via `boto3` credentials, environment variables, or configuration files. ### Method Instantiation of OCR object ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from img2table.ocr import TextractOCR ocr = TextractOCR(aws_access_key_id="***", aws_secret_access_key="***", aws_session_token="***", region="eu-west-1") ``` ### Response #### Success Response (200) N/A #### Response Example N/A ### Parameters - **aws_access_key_id** (str, optional, default `None`) - AWS access key id - **aws_secret_access_key** (str, optional, default `None`) - AWS secret access key - **aws_session_token** (str, optional, default `None`) - AWS temporary session token - **region** (str, optional, default `None`) - AWS server region ``` -------------------------------- ### Table Extraction to XLSX Source: https://github.com/xavctn/img2table/blob/main/README.md This section details how to extract tables from a document and save them into an XLSX file using the `to_xlsx` method. It outlines the various parameters available to customize the extraction process. ```APIDOC ## POST /xavctn/img2table/to_xlsx ### Description Extracts tables from a document and saves them to an XLSX file. This method allows for detailed customization of the table extraction process, including OCR integration and handling of implicit table structures. ### Method POST ### Endpoint /xavctn/img2table/to_xlsx ### Parameters #### Request Body - **dest** (str | pathlib.Path | io.BytesIO) - Required - Destination path or buffer for the XLSX file. - **ocr** (OCRInstance) - Optional - An OCR instance for text extraction. If None, cell content will not be extracted. - **implicit_rows** (bool) - Optional - Defaults to False. Identifies implicit rows in tables. - **implicit_columns** (bool) - Optional - Defaults to False. Identifies implicit columns in tables. - **borderless_tables** (bool) - Optional - Defaults to False. Extracts borderless tables (requires OCR). This feature is in alpha. - **min_confidence** (int) - Optional - Defaults to 50. Minimum OCR confidence level (0-99) for processing text. ### Request Example ```json { "dest": "output.xlsx", "ocr": null, "implicit_rows": false, "implicit_columns": false, "borderless_tables": false, "min_confidence": 50 } ``` ### Response #### Success Response (200) - **xlsx_data** (bytes | None) - The XLSX file content as bytes if `dest` was an `io.BytesIO` object, otherwise None. #### Response Example ```json { "xlsx_data": "" } ``` ``` -------------------------------- ### Perform Table Identification from Image with img2table Source: https://github.com/xavctn/img2table/blob/main/examples/Basic_usage.ipynb Illustrates the process of identifying tables within an image file using the img2table library. The `extract_tables` method is called on an `Image` object to detect table structures. ```python from img2table.document import Image img = Image(src="data/tables.png") # Extract tables extracted_tables = img.extract_tables() ``` -------------------------------- ### OCR Service Configuration Source: https://github.com/xavctn/img2table/blob/main/README.md Configures OCR interfaces for table content parsing using Tesseract or PaddleOCR. ```APIDOC ## OCR Service Configuration ### Description Configures OCR engines to parse table content. If text can be extracted natively from a PDF, these services are bypassed. ### Tesseract Configuration - **n_threads** (int) - Optional - Number of concurrent threads. Default: 1. - **lang** (str) - Optional - Language code. Default: 'eng'. - **psm** (int) - Optional - Page Segmentation Mode. Default: 11. - **tessdata_dir** (str) - Optional - Directory for traineddata files. ### PaddleOCR Configuration - **lang** (str) - Optional - Language code. Default: 'en'. - **kw** (dict) - Optional - Additional keyword arguments for the constructor. ### Usage Example ```python from img2table.ocr import TesseractOCR, PaddleOCR # Tesseract tess = TesseractOCR(n_threads=1, lang='eng', psm=11) # PaddleOCR paddle = PaddleOCR(lang='en') ``` ``` -------------------------------- ### POST /extract_tables Source: https://github.com/xavctn/img2table/blob/main/examples/Implicit.ipynb Extracts tables from an image file using OCR, with options to enable implicit row and column splitting for complex table structures. ```APIDOC ## POST /extract_tables ### Description Extracts structured table data from an image. The endpoint supports implicit row and column detection to handle multi-line cells or large vertical/horizontal spacing. ### Method POST ### Endpoint /extract_tables ### Parameters #### Query Parameters - **implicit_rows** (boolean) - Optional - If true, splits rows containing multi-line cells or large vertical separations. - **implicit_columns** (boolean) - Optional - If true, splits columns based on horizontal separation between elements. #### Request Body - **ocr_instance** (object) - Required - The OCR engine instance (e.g., TesseractOCR). - **image_source** (string) - Required - Path or URL to the source image file. ### Request Example { "ocr": "TesseractOCR", "src": "data/implicit.png", "implicit_rows": true, "implicit_columns": false } ### Response #### Success Response (200) - **tables** (array) - A list of extracted table objects containing cell data and structure. #### Response Example { "tables": [ { "id": "table_1", "content": [[...]] } ] } ``` -------------------------------- ### Extract Table Content with OCR using img2table Source: https://github.com/xavctn/img2table/blob/main/examples/Basic_usage.ipynb Demonstrates how to extract table content, including cell text, by providing an initialized OCR instance to the `extract_tables` method. The extracted tables can be accessed as pandas DataFrames via the `df` attribute. ```python from img2table.document import PDF pdf = PDF(src="data/tables.pdf") # Assuming an OCR instance like tesseract_ocr is initialized # extracted_tables = pdf.extract_tables(ocr=tesseract_ocr) # Accessing the DataFrame representation of the first table # df_table = extracted_tables[0].df ``` -------------------------------- ### Import Libraries for img2table Source: https://github.com/xavctn/img2table/blob/main/examples/borderless.ipynb Imports necessary libraries for image processing, table extraction, and display functionalities within the img2table project. ```python %load_ext autotime import os import cv2 from IPython.display import display_html, display from PIL import Image as PILImage from utils import display_borderless_tables from img2table.document import Image from img2table.ocr import TesseractOCR, PaddleOCR ``` -------------------------------- ### Google Vision OCR Integration Source: https://github.com/xavctn/img2table/blob/main/README.md Integrates Google Vision OCR. Authentication can be done via `GOOGLE_APPLICATION_CREDENTIALS` environment variable or by providing an API key. ```APIDOC ## Google Vision OCR Integration ### Description Integrates Google Vision OCR. Authentication can be done via `GOOGLE_APPLICATION_CREDENTIALS` environment variable or by providing an API key. ### Method Instantiation of OCR object ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from img2table.ocr import VisionOCR ocr = VisionOCR(api_key="api_key", timeout=15) ``` ### Response #### Success Response (200) N/A #### Response Example N/A ### Parameters - **api_key** (str, optional, default `None`) - Google Vision API key - **timeout** (int, optional, default `15`) - API requests timeout, in seconds ``` -------------------------------- ### Display Extracted Tables Source: https://github.com/xavctn/img2table/blob/main/examples/Basic_usage.ipynb Iterates through the extracted tables, page by page, and displays each table's HTML representation. This is useful for visualizing the extracted data and verifying the extraction quality. ```python for page, tables in extracted_tables.items(): for idx, table in enumerate(tables): display_html(table.html_repr(title=f"Page {page + 1} - Extracted table n°{idx + 1}"), raw=True) ``` -------------------------------- ### Display Extracted Tables Source: https://github.com/xavctn/img2table/blob/main/examples/Implicit.ipynb Renders the extracted tables into HTML format for display. It shows both the table extracted with default settings and the one processed with `implicit_rows=True`, allowing for visual comparison. ```python display_html(table.html_repr(title="Regular table"), raw=True) display_html(table_implicit_rows.html_repr(title="Table with implicit rows"), raw=True) ``` -------------------------------- ### Azure Cognitive Services OCR Integration Source: https://github.com/xavctn/img2table/blob/main/README.md Integrates Azure Cognitive Services OCR. Requires an endpoint and subscription key for authentication. ```APIDOC ## Azure Cognitive Services OCR Integration ### Description Integrates Azure Cognitive Services OCR. Requires an endpoint and subscription key for authentication. ### Method Instantiation of OCR object ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from img2table.ocr import AzureOCR ocr = AzureOCR(endpoint="abc.azure.com", subscription_key="***") ``` ### Response #### Success Response (200) N/A #### Response Example N/A ### Parameters - **endpoint** (str, required) - Azure Cognitive Services endpoint - **subscription_key** (str, required) - Azure subscription key ``` -------------------------------- ### POST /extract_tables Source: https://github.com/xavctn/img2table/blob/main/examples/Basic_usage.ipynb Performs table identification and extraction on a provided document object (Image or PDF). ```APIDOC ## POST /extract_tables ### Description Extracts tables from an initialized document object. If an OCR instance is provided, it will infer cell content from the OCR results. ### Method POST ### Endpoint /extract_tables ### Parameters #### Request Body - **ocr** (Instance) - Optional - An instance of an OCR class (e.g., TesseractOCR, PaddleOCR, VisionOCR) used for content inference. - **implicit_rows** (bool) - Optional - Whether to infer implicit rows. ### Request Example { "ocr": "TesseractOCR(lang='eng')", "implicit_rows": true } ### Response #### Success Response (200) - **tables** (List[ExtractedTable]) - A list of extracted table objects containing bounding boxes and cell content. #### Response Example { "tables": [ { "bbox": {"x1": 10, "y1": 10, "x2": 100, "y2": 100}, "content": { "0": ["Header1", "Header2"] } } ] } ``` -------------------------------- ### Extract Tables from PDF Source: https://github.com/xavctn/img2table/blob/main/examples/Basic_usage.ipynb Extracts tables from a PDF document using OCR capabilities. It allows configuration of implicit rows, borderless tables, and minimum confidence levels for extraction. The output is a dictionary mapping page numbers to lists of extracted tables. ```python extracted_tables = pdf.extract_tables(ocr=tesseract_ocr, implicit_rows=False, borderless_tables=False, min_confidence=50) ``` -------------------------------- ### Extract Tables and Save to XLSX Source: https://github.com/xavctn/img2table/blob/main/README.md This function extracts tables from a document and saves them into an XLSX file. It supports OCR for text extraction and offers parameters to control the identification of implicit rows/columns and borderless tables. The minimum OCR confidence level can also be set. ```python doc.to_xlsx(dest=dest, ocr=ocr, implicit_rows=False, implicit_columns=False, borderless_tables=False, min_confidence=50) ``` -------------------------------- ### Export Tables to Excel Source: https://context7.com/xavctn/img2table/llms.txt Export extracted tables directly to an Excel file. This method supports saving to a file path or a BytesIO buffer, preserving table structure and merged cells. ```python from img2table.document import Image from img2table.ocr import TesseractOCR ocr = TesseractOCR() image = Image("document.png") # Export to file image.to_xlsx(dest="output.xlsx", ocr=ocr) ``` -------------------------------- ### Export Tables to XLSX Source: https://github.com/xavctn/img2table/blob/main/examples/Basic_usage.ipynb Exports all extracted tables from a PDF document into a single XLSX file. Each extracted table is saved as a separate worksheet within the XLSX file. This method accepts similar arguments to the `extract_tables` method for fine-grained control over the export process. ```python pdf.to_xlsx('data/tables.xlsx', ocr=tesseract_ocr, implicit_rows=False, borderless_tables=False, min_confidence=50) ``` -------------------------------- ### Access cell-level bounding boxes Source: https://github.com/xavctn/img2table/blob/main/README.md Iterates through the content of an extracted table to retrieve the bounding box coordinates and values for each individual cell. ```python for id_row, row in enumerate(table.content.values()): for id_col, cell in enumerate(row): x1 = cell.bbox.x1 y1 = cell.bbox.y1 x2 = cell.bbox.x2 y2 = cell.bbox.y2 value = cell.value ``` -------------------------------- ### Extract Tables from Documents Source: https://context7.com/xavctn/img2table/llms.txt Use the extract_tables method to parse images or PDFs into structured data. This returns a list of ExtractedTable objects containing bounding boxes and pandas DataFrames. ```python from img2table.document import Image, PDF from img2table.ocr import TesseractOCR ocr = TesseractOCR(lang="eng") # Extract from Image image = Image("document.png") tables = image.extract_tables(ocr=ocr) # Extract from PDF pdf = PDF("document.pdf") tables_by_page = pdf.extract_tables(ocr=ocr) ``` -------------------------------- ### Access Extracted Table Data Source: https://context7.com/xavctn/img2table/llms.txt Interact with the ExtractedTable object to retrieve metadata, pandas DataFrames, HTML representations, and individual cell content with coordinates. ```python for table in tables: print(f"Title: {table.title}") print(table.df.to_string()) # Export to HTML with open("table.html", "w") as f: f.write(table.html) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.