[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-72487":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":17,"stars7d":18,"stars30d":19,"stars90d":16,"forks30d":16,"starsTrendScore":18,"compositeScore":20,"rankGlobal":10,"rankLanguage":10,"license":21,"archived":22,"fork":23,"defaultBranch":24,"hasWiki":22,"hasPages":23,"topics":25,"createdAt":10,"pushedAt":10,"updatedAt":26,"readmeContent":27,"aiSummary":28,"trendingCount":16,"starSnapshotCount":16,"syncStatus":29,"lastSyncTime":30,"discoverSource":31},72487,"agentic-doc","landing-ai\u002Fagentic-doc","landing-ai","Legacy Python library for Agentic Document Extraction (ADE). Use the landingai-ade library for all new projects.","https:\u002F\u002Fva.landing.ai",null,"Python",2401,259,29,14,0,1,3,4,63.14,"Apache License 2.0",true,false,"main",[],"2026-06-12 04:01:06","### DEPRECATION WARNING\n\n⚠️⚠️⚠️ The agentic-doc Python library is now legacy. Please migrate to the new [landingai-ade library](https:\u002F\u002Fgithub.com\u002Flanding-ai\u002Fade-python), which is now the official Python library for Agentic Document Extraction and supports our newer API endpoints.\n\n\u003Cdiv align=\"center\">\n\n# Agentic Document Extraction – Python Library\n\n[![Unit test status](https:\u002F\u002Fgithub.com\u002Flanding-ai\u002Fagentic-doc\u002Factions\u002Fworkflows\u002Fci-unit.yml\u002Fbadge.svg)](https:\u002F\u002Fgithub.com\u002Flanding-ai\u002Fagentic-doc\u002Factions\u002Fworkflows\u002Fci-unit.yml)\n[![Integration test status](https:\u002F\u002Fgithub.com\u002Flanding-ai\u002Fagentic-doc\u002Factions\u002Fworkflows\u002Fci-integ.yml\u002Fbadge.svg)](https:\u002F\u002Fgithub.com\u002Flanding-ai\u002Fagentic-doc\u002Factions\u002Fworkflows\u002Fci-integ.yml)\n[![](https:\u002F\u002Fdcbadge.vercel.app\u002Fapi\u002Fserver\u002FwPdN8RCYew?compact=true&style=flat)](https:\u002F\u002Fdiscord.gg\u002FRVcW3j9RgR)\n[![PyPI version](https:\u002F\u002Fbadge.fury.io\u002Fpy\u002Fagentic-doc.svg)](https:\u002F\u002Fbadge.fury.io\u002Fpy\u002Fagentic-doc)\n\n**[Web App](https:\u002F\u002Fva.landing.ai\u002Fdemo\u002Fdoc-extraction) · [Discord](https:\u002F\u002Fdiscord.com\u002Finvite\u002FRVcW3j9RgR) · [Blog](https:\u002F\u002Flanding.ai\u002Fblog\u002Fgoing-beyond-ocrllm-introducing-agentic-document-extraction) · [Docs](https:\u002F\u002Fsupport.landing.ai\u002Fdocs\u002Fdocument-extraction)**\n\n\u003C\u002Fdiv>\n\n## Overview\n\nThe LandingAI **Agentic Document Extraction** API pulls structured data out of visually complex documents—think tables, pictures, and charts—and returns a hierarchical JSON with exact element locations.\n\nThis Python library wraps that API to provide:\n\n* **Long‑document support** – process 100+ page PDFs in a single call\n* **Auto‑retry \u002F paging** – handles concurrency, time‑outs, and rate limits\n* **Helper utilities** – bounding‑box snippets, visual debuggers, and more\n\n### Features\n\n- 📦 **Batteries‑included install:** `pip install agentic-doc` – nothing else needed → see [Installation](#installation)\n- 🗂️ **All file types:** parse PDFs of *any* length, single images, or URLs → see [Supported Files](#supported-files)\n- 📚 **Long‑doc ready:** auto‑split & parallel‑process 1000+ page PDFs, then stitch results → see [Parse Large PDF Files](#parse-large-pdf-files)\n- 🧩 **Structured output:** returns hierarchical JSON plus ready‑to‑render Markdown → see [Result Schema](#result-schema)\n- 👁️ **Ground‑truth visuals:** optional bounding‑box snippets and full‑page visualizations → see [Save Groundings as Images](#save-groundings-as-images)\n- 🏃 **Batch & parallel:** feed a list; library manages threads & rate limits (`BATCH_SIZE`, `MAX_WORKERS`) → see [Parse Multiple Files in a Batch](#parse-multiple-files-in-a-batch)\n- 🔄 **Resilient:** exponential‑backoff retries for 408\u002F429\u002F502\u002F503\u002F504 and rate‑limit hits → see [Automatically Handle API Errors and Rate Limits with Retries](#automatically-handle-api-errors-and-rate-limits-with-retries)\n- ⚙️ **Config via env \u002F .env:** tweak parallelism, logging style, retry caps—no code changes → see [Configuration Options](#configuration-options)\n- 🌐 **Raw API ready:** advanced users can still hit the REST endpoint directly → see the [API Docs](https:\u002F\u002Fsupport.landing.ai\u002Fdocs\u002Fdocument-extraction)\n\n\n## Quick Start\n\n### Installation\n\n```bash\npip install agentic-doc\n```\n\n### Requirements\n- Python version 3.9, 3.10, 3.11 or 3.12\n- LandingAI agentic AI API key (get the key [here](https:\u002F\u002Fva.landing.ai\u002Fsettings\u002Fapi-key))\n\n### Set the API Key as an Environment Variable\nAfter you get the LandingAI agentic AI API key, set the key as an environment variable (or put it in a `.env` file):\n\n```bash\nexport VISION_AGENT_API_KEY=\u003Cyour-api-key>\n```\n\n### Supported Files\nThe library can extract data from:\n- PDFs (any length)\n- Images that are supported by OpenCV-Python (i.e. the `cv2` library)\n- URLs pointing to PDF or image files\n\n### Basic Usage\n\n#### Extract Data from One Document\nRun the following script to extract data from one document and return the results in both markdown and structured chunks.\n\n```python\nfrom agentic_doc.parse import parse\n\n# Parse a local file\nresult = parse(\"path\u002Fto\u002Fimage.png\")\nprint(result[0].markdown)  # Get the extracted data as markdown\nprint(result[0].chunks)  # Get the extracted data as structured chunks of content\n\n# Parse a document from a URL\nresult = parse(\"https:\u002F\u002Fexample.com\u002Fdocument.pdf\")\nprint(result[0].markdown)\n\n#### Extract Data from Multiple Documents\nRun the following script to extract data from multiple documents.\n\n```python\nfrom agentic_doc.parse import parse\n\n# Parse multiple local files\nfile_paths = [\"path\u002Fto\u002Fyour\u002Fdocument1.pdf\", \"path\u002Fto\u002Fanother\u002Fdocument2.pdf\"]\nresults = parse(file_paths)\nfor result in results:\n    print(result.markdown)\n\n# Parse and save results to a directory\nresults = parse(file_paths, result_save_dir=\"path\u002Fto\u002Fsave\u002Fresults\")\nresult_paths = []\nfor result in results:\n    result_paths.append(result.result_path)\n# result_paths: [\"path\u002Fto\u002Fsave\u002Fresults\u002Fdocument1_20250313_070305.json\", ...]\n```\n\n\n#### Using field extraction\n\n```python\nfrom pydantic import BaseModel, Field\nfrom agentic_doc.parse import parse\n\nclass ExtractedFields(BaseModel):\n    employee_name: str = Field(description=\"the full name of the employee\")\n    employee_ssn: str = Field(description=\"the social security number of the employee\")\n    gross_pay: float = Field(description=\"the gross pay of the employee\")\n    employee_address: str = Field(description=\"the address of the employee\")\n\nresults = parse(\"mydoc.pdf\", extraction_model=ExtractedFields)\nfields = results[0].extraction\nmetadata = results[0].extraction_metadata\nprint(f\"Field value: {fields.employee_name}, confidence: {metadata.employee_name.confidence}\")\n```\n\n\n#### Extract Data Using Connectors\nThe library now supports various connectors to easily access documents from different sources:\n\n##### Google Drive Connector\n\n**Prerequisites: Follow the [Google Drive API Python Quickstart](https:\u002F\u002Fdevelopers.google.com\u002Fworkspace\u002Fdrive\u002Fapi\u002Fquickstart\u002Fpython) tutorial first to set up your credentials.**\n\nThe Google Drive API quickstart will guide you through:\n1. Creating a Google Cloud project\n2. Enabling the Google Drive API\n3. Setting up OAuth 2.0 credentials\n\nAfter completing the quickstart tutorial, you can use the Google Drive connector as follows:\n\n```python\nfrom agentic_doc.parse import parse\nfrom agentic_doc.connectors import GoogleDriveConnectorConfig\n\n# Using OAuth credentials file (from quickstart tutorial)\nconfig = GoogleDriveConnectorConfig(\n    client_secret_file=\"path\u002Fto\u002Fcredentials.json\",\n    folder_id=\"your-google-drive-folder-id\"  # Optional\n)\n\n# Parse all documents in the folder\nresults = parse(config)\n\n# Parse with filtering\nresults = parse(config, connector_pattern=\"*.pdf\")\n```\n\n##### Amazon S3 Connector\n```python\nfrom agentic_doc.parse import parse\nfrom agentic_doc.connectors import S3ConnectorConfig\n\nconfig = S3ConnectorConfig(\n    bucket_name=\"your-bucket-name\",\n    aws_access_key_id=\"your-access-key\",  # Optional if using IAM roles\n    aws_secret_access_key=\"your-secret-key\",  # Optional if using IAM roles\n    region_name=\"us-east-1\"\n)\n\n# Parse all documents in the bucket\nresults = parse(config)\n\n# Parse documents in a specific prefix\u002Ffolder\nresults = parse(config, connector_path=\"documents\u002F\")\n```\n\n##### Local Directory Connector\n```python\nfrom agentic_doc.parse import parse\nfrom agentic_doc.connectors import LocalConnectorConfig\n\nconfig = LocalConnectorConfig()\n\n# Parse all supported documents in a directory\nresults = parse(config, connector_path=\"\u002Fpath\u002Fto\u002Fdocuments\")\n\n# Parse with pattern filtering\nresults = parse(config, connector_path=\"\u002Fpath\u002Fto\u002Fdocuments\", connector_pattern=\"*.pdf\")\n\n# Parse all supported documents in a directory recursively (search subdirectories as well)\nconfig = LocalConnectorConfig(recursive=True)\nresults = parse(config, connector_path=\"\u002Fpath\u002Fto\u002Fdocuments\")\n```\n\n##### URL Connector\n```python\nfrom agentic_doc.parse import parse\nfrom agentic_doc.connectors import URLConnectorConfig\n\nconfig = URLConnectorConfig(\n    headers={\"Authorization\": \"Bearer your-token\"},  # Optional\n    timeout=60  # Optional\n)\n\n# Parse document from URL\nresults = parse(config, connector_path=\"https:\u002F\u002Fexample.com\u002Fdocument.pdf\")\n```\n\n#### Raw Bytes Input\n\n```python\nfrom agentic_doc.parse import parse\n\n# Load a PDF or image file as bytes\nwith open(\"document.pdf\", \"rb\") as f:\n    raw_bytes = f.read()\n\n# Parse the document from bytes\nresults = parse(raw_bytes)\n```\n\nYou can also parse image bytes:\n\n```python\nwith open(\"image.png\", \"rb\") as f:\n    image_bytes = f.read()\n\nresults = parse(image_bytes)\n```\n\nThis is useful when documents are already loaded into memory (e.g., from an API response or uploaded via a web interface). The parser will auto-detect the file type from the bytes.\n\n\n## Why Use It?\n\n- **Simplified Setup:** No need to manage API keys or handle low-level REST calls.\n- **Automatic Large File Processing:** Splits large PDFs into manageable parts and processes them in parallel.\n- **Built-In Error Handling:** Automatically retries requests with exponential backoff and jitter for common HTTP errors.\n- **Parallel Processing:** Efficiently parse multiple documents at once with configurable parallelism.\n\n## Main Features\n\nWith this library, you can do things that are otherwise hard to do with the Agentic Document Extraction API alone.\nThis section describes some of the key features this library offers.\n\n### Parse Large PDF Files\n\n**A single REST API call can only handle up to certain amount of pages at a time** (see [rate limits](https:\u002F\u002Fdocs.landing.ai\u002Fade\u002Fade-rate-limits#maximum-pages-per-document)). This library automatically splits a large PDF into multiple calls, uses a thread pool to process the calls in parallel, and stitches the results back together as a single result.\n\nWe've used this library to successfully parse PDFs that are 1000+ pages long.\n\n### Parse Multiple Files in a Batch\n\nYou can parse multiple files in a single function call with this library. The library processes files in parallel.\n\n> **NOTE:** You can change the parallelism by setting the `batch_size` setting.\n\n### Save Groundings as Images\n\nThe library can extract and save the visual regions (groundings) of the document where each chunk of content was found. This is useful for visualizing exactly what parts of the document were extracted and for debugging extraction issues.\n\nEach grounding represents a bounding box in the original document, and the library can save these regions as individual PNG images. The images are organized by page number and chunk ID.\n\nHere's how to use this feature:\n\n```python\nfrom agentic_doc.parse import parse\n\n# Parse a document from a URL & save groundings\nresults = parse([\"https:\u002F\u002Fwww.rbcroyalbank.com\u002Fbanking-services\u002F_assets-custom\u002Fpdf\u002FeStatement.pdf\"],\n                grounding_save_dir=\".\u002Fgrounding\")\n\n\n# Print the path to each saved grounding\nfor chunk in results[0].chunks:\n    for grounding in chunk.grounding:\n        if grounding.image_path:\n            print(f\"Grounding saved to: {grounding.image_path}\")\n```\n\n\n### Visualize Parsing Results\n\nThe library provides a visualization utility that creates annotated images showing where each chunk of content was extracted from the document. This is useful for:\n- Verifying the accuracy of the extraction\n- Debugging extraction issues\n\nHere's how to use the visualization feature:\n\n```python\nfrom agentic_doc.parse import parse\nfrom agentic_doc.utils import viz_parsed_document\nfrom agentic_doc.config import VisualizationConfig\n\n# Parse a document\nresults = parse(\"path\u002Fto\u002Fdocument.pdf\")\nparsed_doc = results[0]\n\n# Create visualizations with default settings\n# The output images have a PIL.Image.Image type\nimages = viz_parsed_document(\n    \"path\u002Fto\u002Fdocument.pdf\",\n    parsed_doc,\n    output_dir=\"path\u002Fto\u002Fsave\u002Fvisualizations\"\n)\n\n# Or customize the visualization appearance\nviz_config = VisualizationConfig(\n    thickness=2,  # Thicker bounding boxes\n    text_bg_opacity=0.8,  # More opaque text background\n    font_scale=0.7,  # Larger text\n    # Custom colors for different chunk types\n    color_map={\n        ChunkType.TITLE: (0, 0, 255),  # Red for titles\n        ChunkType.TEXT: (255, 0, 0),  # Blue for regular text\n        # ... other chunk types ...\n    }\n)\n\nimages = viz_parsed_document(\n    \"path\u002Fto\u002Fdocument.pdf\",\n    parsed_doc,\n    output_dir=\"path\u002Fto\u002Fsave\u002Fvisualizations\",\n    viz_config=viz_config\n)\n\n# The visualization images will be saved as:\n# path\u002Fto\u002Fsave\u002Fvisualizations\u002Fdocument_viz_page_X.png\n# Where X is the page number\n```\n\nThe visualization shows:\n- Bounding boxes around each extracted chunk\n- Chunk type and index labels\n- Different colors for different types of content (titles, text, tables, etc.)\n- Semi-transparent text backgrounds for better readability\n\n### Automatically Handle API Errors and Rate Limits with Retries\n\nThe REST API endpoint imposes rate limits per API key. This library automatically handles the rate limit error or other intermittent HTTP errors with retries.\n\nFor more information, see [Error Handling](#error-handling) and [Configuration Options](#configuration-options).\n\n### Error Handling\n\nThis library implements a retry mechanism for handling API failures:\n\n- Retries are performed for these HTTP status codes: 408, 429, 502, 503, 504.\n- Exponential backoff with jitter is used for retry wait time.\n- The initial retry wait time is 1 second, which increases exponentially.\n- Retry will stop after `max_retries` attempts. Exceeding the limit raises an exception and results in a failure for this request.\n- Retry wait time is capped at `max_retry_wait_time` seconds.\n- Retries include a random jitter of up to 10 seconds to distribute requests and prevent the thundering herd problem.\n\n### Parsing Errors\n\nIf the REST API request encounters an unrecoverable error during parsing (either from client-side or server-side), the library includes an [errors](.\u002Fagentic_doc\u002Fcommon.py#L75) field in the final result for the affected page(s).\nEach error contains the error message, error_code and corresponding page number.\n\n## Configuration Options\n\nThe library uses a [`Settings`](.\u002Fagentic_doc\u002Fconfig.py) object to manage configuration. You can customize these settings either through environment variables or a `.env` file:\n\nBelow is an example `.env` file that customizes the configurations:\n\n```bash\n# Number of files to process in parallel, defaults to 4\nBATCH_SIZE=4\n# Number of threads used to process parts of each file in parallel, defaults to 5.\nMAX_WORKERS=2\n# Maximum number of retry attempts for failed intermittent requests, defaults to 100\nMAX_RETRIES=80\n# Maximum wait time in seconds for each retry, defaults to 60\nMAX_RETRY_WAIT_TIME=30\n# Logging style for retry, defaults to log_msg\nRETRY_LOGGING_STYLE=log_msg\n```\n\n### Max Parallelism\n\nThe maximum number of parallel requests is determined by multiplying `BATCH_SIZE` × `MAX_WORKERS`.\n\n> **NOTE:** The maximum parallelism allowed by this library is 100.\n\nSpecifically, increasing `MAX_WORKERS` can speed up the processing of large individual files, while increasing `BATCH_SIZE` improves throughput when processing multiple files.\n\n> **NOTE:** Your job's maximum processing throughput may be limited by your API rate limit. If your rate limit isn't high enough, you may encounter rate limit errors, which the library will automatically handle through retries.\n\nThe optimal values for `MAX_WORKERS` and `BATCH_SIZE` depend on your API rate limit and the latency of each REST API call. For example, if your account has a rate limit of 5 requests per minute, and each REST API call takes approximately 60 seconds to complete, and you're processing a single large file, then `MAX_WORKERS` should be set to 5 and `BATCH_SIZE` to 1.\n\nYou can find your REST API latency in the logs. If you want to increase your rate limit, schedule a time to meet with us [here](https:\u002F\u002Fscheduler.zoom.us\u002Fd\u002F56i81uc2\u002Flandingai-document-extraction).\n\n### Set `RETRY_LOGGING_STYLE`\n\nThe `RETRY_LOGGING_STYLE` setting controls how the library logs the retry attempts.\n\n- `log_msg`: Log the retry attempts as a log messages. Each attempt is logged as a separate message. This is the default setting.\n- `inline_block`: Print a yellow progress block ('█') on the same line. Each block represents one retry attempt. Choose this if you don't want to see the verbose retry logging message and still want to track the number of retries that have been made.\n- `none`: Do not log the retry attempts.\n\n\n## Troubleshooting & FAQ\n\n### Common Issues\n- **API Key Errors:**\n  Ensure your API key is correctly set as an environment variable.\n- **Rate Limits:**\n  The library automatically retries requests if you hit the API rate limit. Adjust `BATCH_SIZE` or `MAX_WORKERS` if you encounter frequent rate limit errors.\n- **Parsing Failures:**\n  If a document fails to parse, an error chunk will be included in the result, detailing the error message and page index.\n- **URL Access Issues:**\n  If you're having trouble accessing documents from URLs, check that the URLs are publicly accessible and point to supported file types (PDF or images).\n\n### Note on `include_marginalia` and `include_metadata_in_markdown`\n\n- `include_marginalia`: If True, the parser will attempt to extract and include marginalia (footer notes, page number, etc.) from the document in the output.\n- `include_metadata_in_markdown`: If True, the output markdown will include metadata.\n\nBoth parameters default to True. You can set them to False to exclude these elements from the output.\n\n#### Example: Using the new parameters\n\n```python\nfrom agentic_doc.parse import parse\n\nresults = parse(\n    \"path\u002Fto\u002Fdocument.pdf\",\n    include_marginalia=False,  # Exclude marginalia from output\n    include_metadata_in_markdown=False  # Exclude metadata from markdown\n)\n```\n","Agentic Document Extraction (ADE) 是一个用于从复杂文档中提取结构化数据的Python库。它支持处理包含表格、图片和图表等元素的长文档，并返回带有精确元素位置的层次化JSON。其核心功能包括支持100页以上的PDF文件一次性处理、自动重试与分页处理以应对并发、超时和速率限制，以及提供边界框片段和可视化调试工具等辅助功能。适用于需要从大量或复杂的文档中高效提取信息的场景，如企业级文档管理、数据分析等领域。请注意，此库已不再维护，建议新项目使用landingai-ade库。",2,"2026-06-11 03:42:16","high_star"]