pdf-to-markdown-cli 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pdf_to_markdown_cli-0.2.0/LICENSE +21 -0
- pdf_to_markdown_cli-0.2.0/MANIFEST.in +24 -0
- pdf_to_markdown_cli-0.2.0/PKG-INFO +179 -0
- pdf_to_markdown_cli-0.2.0/README.md +137 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/__init__.py +0 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/__main__.py +5 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/api/__init__.py +0 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/api/client.py +218 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/api/models.py +66 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/config/__init__.py +0 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/config/cli.py +86 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/config/settings.py +108 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/core/__init__.py +0 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/core/processor.py +229 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/core/result_handler.py +496 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/main.py +55 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/pdf/__init__.py +0 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/pdf/splitter.py +199 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/storage/__init__.py +0 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/storage/cache.py +125 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/storage/models.py +85 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/utils/__init__.py +0 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/utils/exceptions.py +33 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/utils/file_utils.py +189 -0
- pdf_to_markdown_cli-0.2.0/docs_to_md/utils/logging.py +134 -0
- pdf_to_markdown_cli-0.2.0/pdf_to_markdown_cli.egg-info/PKG-INFO +179 -0
- pdf_to_markdown_cli-0.2.0/pdf_to_markdown_cli.egg-info/SOURCES.txt +31 -0
- pdf_to_markdown_cli-0.2.0/pdf_to_markdown_cli.egg-info/dependency_links.txt +1 -0
- pdf_to_markdown_cli-0.2.0/pdf_to_markdown_cli.egg-info/entry_points.txt +2 -0
- pdf_to_markdown_cli-0.2.0/pdf_to_markdown_cli.egg-info/requires.txt +8 -0
- pdf_to_markdown_cli-0.2.0/pdf_to_markdown_cli.egg-info/top_level.txt +1 -0
- pdf_to_markdown_cli-0.2.0/setup.cfg +4 -0
- pdf_to_markdown_cli-0.2.0/setup.py +67 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 SokolskyNikita
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
# Include the README and LICENSE
|
|
2
|
+
include README.md
|
|
3
|
+
include LICENSE
|
|
4
|
+
|
|
5
|
+
# Include the package source directory
|
|
6
|
+
recursive-include docs_to_md *
|
|
7
|
+
|
|
8
|
+
# Exclude development/cache/temporary files and directories
|
|
9
|
+
global-exclude *.py[cod]
|
|
10
|
+
global-exclude __pycache__
|
|
11
|
+
global-exclude .DS_Store
|
|
12
|
+
prune .git
|
|
13
|
+
prune .vscode
|
|
14
|
+
prune .marker_cache
|
|
15
|
+
prune pdfs
|
|
16
|
+
prune converted
|
|
17
|
+
prune examples
|
|
18
|
+
prune chunks
|
|
19
|
+
prune __pycache__
|
|
20
|
+
|
|
21
|
+
# Exclude files not needed for the installed package
|
|
22
|
+
exclude marker_api_docs.md
|
|
23
|
+
exclude requirements.txt
|
|
24
|
+
# exclude setup.py # This MUST be included in the sdist for building
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pdf-to-markdown-cli
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: CLI tool to convert PDF files (and other documents) to markdown using the Marker API.
|
|
5
|
+
Home-page: https://github.com/SokolskyNikita/pdf-to-markdown-cli
|
|
6
|
+
Author: Nikita Sokolsky
|
|
7
|
+
Project-URL: Bug Tracker, https://github.com/SokolskyNikita/pdf-to-markdown-cli/issues
|
|
8
|
+
Keywords: pdf,markdown,converter,cli,document,marker,md
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Intended Audience :: End Users/Desktop
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Operating System :: OS Independent
|
|
18
|
+
Classifier: Topic :: Text Processing
|
|
19
|
+
Classifier: Topic :: Utilities
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: backoff>=2.0
|
|
24
|
+
Requires-Dist: diskcache>=5.0
|
|
25
|
+
Requires-Dist: filetype>=1.0
|
|
26
|
+
Requires-Dist: pikepdf>=8.0
|
|
27
|
+
Requires-Dist: pydantic>=2.0
|
|
28
|
+
Requires-Dist: ratelimit>=2.0
|
|
29
|
+
Requires-Dist: requests>=2.0
|
|
30
|
+
Requires-Dist: tqdm>=4.0
|
|
31
|
+
Dynamic: author
|
|
32
|
+
Dynamic: classifier
|
|
33
|
+
Dynamic: description
|
|
34
|
+
Dynamic: description-content-type
|
|
35
|
+
Dynamic: home-page
|
|
36
|
+
Dynamic: keywords
|
|
37
|
+
Dynamic: license-file
|
|
38
|
+
Dynamic: project-url
|
|
39
|
+
Dynamic: requires-dist
|
|
40
|
+
Dynamic: requires-python
|
|
41
|
+
Dynamic: summary
|
|
42
|
+
|
|
43
|
+
# PDF to Markdown CLI (using Marker API)
|
|
44
|
+
|
|
45
|
+
Convert PDF files (and other documents) to markdown using the [Marker API](https://www.marker.io/) via a command-line tool.
|
|
46
|
+
|
|
47
|
+
## Overview
|
|
48
|
+
|
|
49
|
+
This package provides a convenient command-line interface (`pdf-to-md`) for converting PDF files (and other document formats like Word, EPUB, images, etc.) to markdown. It leverages the Marker API for high-quality PDF conversion and handles chunking, parallel processing, and result combination.
|
|
50
|
+
|
|
51
|
+
## Features
|
|
52
|
+
|
|
53
|
+
- Convert PDFs, Word documents, PowerPoint files, spreadsheets, epub, HTML, and images to markdown
|
|
54
|
+
- Optionally use the Marker API for enhanced PDF conversion
|
|
55
|
+
- Handle large documents by splitting them into chunks
|
|
56
|
+
- Progress tracking for long-running operations
|
|
57
|
+
- Customizable OCR options
|
|
58
|
+
- Local caching of results
|
|
59
|
+
- Output in markdown, JSON, or HTML format
|
|
60
|
+
|
|
61
|
+
## Installation
|
|
62
|
+
|
|
63
|
+
### From PyPI
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
pip install pdf-to-markdown-cli
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### From source
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
git clone https://github.com/SokolskyNikita/pdf-to-markdown-cli.git
|
|
73
|
+
cd pdf-to-markdown-cli
|
|
74
|
+
pip install -e .
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## Usage
|
|
78
|
+
|
|
79
|
+
### Command-line interface
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
# Set your Marker API key
|
|
83
|
+
export MARKER_PDF_KEY=your_api_key_here
|
|
84
|
+
|
|
85
|
+
# Basic usage
|
|
86
|
+
pdf-to-md /path/to/file.pdf
|
|
87
|
+
|
|
88
|
+
# Process all files in a directory
|
|
89
|
+
pdf-to-md /path/to/directory
|
|
90
|
+
|
|
91
|
+
# Output in JSON format
|
|
92
|
+
pdf-to-md /path/to/file.pdf --json
|
|
93
|
+
|
|
94
|
+
# Use additional languages for OCR
|
|
95
|
+
pdf-to-md /path/to/file.pdf --langs "English,French,German"
|
|
96
|
+
|
|
97
|
+
# Use all Marker OCR enhancements
|
|
98
|
+
pdf-to-md /path/to/file.pdf --max
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
### API
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
# Internal module paths remain the same
|
|
105
|
+
from docs_to_md.config.settings import Config
|
|
106
|
+
from docs_to_md.core.processor import MarkerProcessor
|
|
107
|
+
|
|
108
|
+
# Create configuration
|
|
109
|
+
config = Config(
|
|
110
|
+
api_key="your_api_key_here",
|
|
111
|
+
input_path="/path/to/file.pdf",
|
|
112
|
+
output_format="markdown",
|
|
113
|
+
use_llm=True
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
# Create processor and run
|
|
117
|
+
processor = MarkerProcessor(config)
|
|
118
|
+
processor.process()
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
## Command-line Options
|
|
122
|
+
|
|
123
|
+
- `input`: Input file or directory path
|
|
124
|
+
- `--json`: Output in JSON format (default is markdown)
|
|
125
|
+
- `--langs`: Comma-separated OCR languages (default: "English")
|
|
126
|
+
- `--llm`: Use LLM for enhanced processing
|
|
127
|
+
- `--strip`: Redo OCR processing
|
|
128
|
+
- `--noimg`: Disable image extraction
|
|
129
|
+
- `--force`: Force OCR on all pages
|
|
130
|
+
- `--pages`: Add page delimiters
|
|
131
|
+
- `--max`: Enable all OCR enhancements (equivalent to --llm --strip --force)
|
|
132
|
+
- `--max-pages`: Maximum number of pages to process from the start of the file
|
|
133
|
+
- `--no-chunk`: Disable PDF chunking
|
|
134
|
+
- `--chunk-size`: Set PDF chunk size in pages (default: 25)
|
|
135
|
+
- `--output-dir`: Output directory (default: "converted")
|
|
136
|
+
- `--cache-dir`: Cache directory (default: ".marker_cache")
|
|
137
|
+
|
|
138
|
+
## Project Structure
|
|
139
|
+
|
|
140
|
+
The package is organized as follows:
|
|
141
|
+
|
|
142
|
+
```
|
|
143
|
+
pdf-to-markdown-cli/ (Project Root)
|
|
144
|
+
├── docs_to_md/ (Python Package Source)
|
|
145
|
+
│ ├── api/
|
|
146
|
+
│ ├── config/
|
|
147
|
+
│ ├── core/
|
|
148
|
+
│ ├── pdf/
|
|
149
|
+
│ ├── storage/
|
|
150
|
+
│ └── utils/
|
|
151
|
+
├── setup.py
|
|
152
|
+
├── README.md
|
|
153
|
+
└── ... (other config files)
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## Requirements
|
|
157
|
+
|
|
158
|
+
- Python 3.10 or higher
|
|
159
|
+
- Runtime dependencies are listed in `setup.py` and automatically installed via pip.
|
|
160
|
+
- The `requirements.txt` file lists exact versions used for development and testing, and can be used to set up a development environment: `pip install -r requirements.txt`
|
|
161
|
+
|
|
162
|
+
## Development
|
|
163
|
+
|
|
164
|
+
To run the code directly from the source tree without installation:
|
|
165
|
+
|
|
166
|
+
```bash
|
|
167
|
+
# Using the installed entry point (requires editable install):
|
|
168
|
+
# pip install -e .
|
|
169
|
+
# pdf-to-md /path/to/file.pdf
|
|
170
|
+
|
|
171
|
+
# Or running the module directly:
|
|
172
|
+
python -m docs_to_md /path/to/file.pdf
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
For regular use after installation, use the `pdf-to-md` command.
|
|
176
|
+
|
|
177
|
+
## License
|
|
178
|
+
|
|
179
|
+
This project is licensed under the MIT License - see the LICENSE file for details.
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# PDF to Markdown CLI (using Marker API)
|
|
2
|
+
|
|
3
|
+
Convert PDF files (and other documents) to markdown using the [Marker API](https://www.marker.io/) via a command-line tool.
|
|
4
|
+
|
|
5
|
+
## Overview
|
|
6
|
+
|
|
7
|
+
This package provides a convenient command-line interface (`pdf-to-md`) for converting PDF files (and other document formats like Word, EPUB, images, etc.) to markdown. It leverages the Marker API for high-quality PDF conversion and handles chunking, parallel processing, and result combination.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
- Convert PDFs, Word documents, PowerPoint files, spreadsheets, epub, HTML, and images to markdown
|
|
12
|
+
- Optionally use the Marker API for enhanced PDF conversion
|
|
13
|
+
- Handle large documents by splitting them into chunks
|
|
14
|
+
- Progress tracking for long-running operations
|
|
15
|
+
- Customizable OCR options
|
|
16
|
+
- Local caching of results
|
|
17
|
+
- Output in markdown, JSON, or HTML format
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
### From PyPI
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install pdf-to-markdown-cli
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### From source
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
git clone https://github.com/SokolskyNikita/pdf-to-markdown-cli.git
|
|
31
|
+
cd pdf-to-markdown-cli
|
|
32
|
+
pip install -e .
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
### Command-line interface
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
# Set your Marker API key
|
|
41
|
+
export MARKER_PDF_KEY=your_api_key_here
|
|
42
|
+
|
|
43
|
+
# Basic usage
|
|
44
|
+
pdf-to-md /path/to/file.pdf
|
|
45
|
+
|
|
46
|
+
# Process all files in a directory
|
|
47
|
+
pdf-to-md /path/to/directory
|
|
48
|
+
|
|
49
|
+
# Output in JSON format
|
|
50
|
+
pdf-to-md /path/to/file.pdf --json
|
|
51
|
+
|
|
52
|
+
# Use additional languages for OCR
|
|
53
|
+
pdf-to-md /path/to/file.pdf --langs "English,French,German"
|
|
54
|
+
|
|
55
|
+
# Use all Marker OCR enhancements
|
|
56
|
+
pdf-to-md /path/to/file.pdf --max
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### API
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
# Internal module paths remain the same
|
|
63
|
+
from docs_to_md.config.settings import Config
|
|
64
|
+
from docs_to_md.core.processor import MarkerProcessor
|
|
65
|
+
|
|
66
|
+
# Create configuration
|
|
67
|
+
config = Config(
|
|
68
|
+
api_key="your_api_key_here",
|
|
69
|
+
input_path="/path/to/file.pdf",
|
|
70
|
+
output_format="markdown",
|
|
71
|
+
use_llm=True
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
# Create processor and run
|
|
75
|
+
processor = MarkerProcessor(config)
|
|
76
|
+
processor.process()
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Command-line Options
|
|
80
|
+
|
|
81
|
+
- `input`: Input file or directory path
|
|
82
|
+
- `--json`: Output in JSON format (default is markdown)
|
|
83
|
+
- `--langs`: Comma-separated OCR languages (default: "English")
|
|
84
|
+
- `--llm`: Use LLM for enhanced processing
|
|
85
|
+
- `--strip`: Redo OCR processing
|
|
86
|
+
- `--noimg`: Disable image extraction
|
|
87
|
+
- `--force`: Force OCR on all pages
|
|
88
|
+
- `--pages`: Add page delimiters
|
|
89
|
+
- `--max`: Enable all OCR enhancements (equivalent to --llm --strip --force)
|
|
90
|
+
- `--max-pages`: Maximum number of pages to process from the start of the file
|
|
91
|
+
- `--no-chunk`: Disable PDF chunking
|
|
92
|
+
- `--chunk-size`: Set PDF chunk size in pages (default: 25)
|
|
93
|
+
- `--output-dir`: Output directory (default: "converted")
|
|
94
|
+
- `--cache-dir`: Cache directory (default: ".marker_cache")
|
|
95
|
+
|
|
96
|
+
## Project Structure
|
|
97
|
+
|
|
98
|
+
The package is organized as follows:
|
|
99
|
+
|
|
100
|
+
```
|
|
101
|
+
pdf-to-markdown-cli/ (Project Root)
|
|
102
|
+
├── docs_to_md/ (Python Package Source)
|
|
103
|
+
│ ├── api/
|
|
104
|
+
│ ├── config/
|
|
105
|
+
│ ├── core/
|
|
106
|
+
│ ├── pdf/
|
|
107
|
+
│ ├── storage/
|
|
108
|
+
│ └── utils/
|
|
109
|
+
├── setup.py
|
|
110
|
+
├── README.md
|
|
111
|
+
└── ... (other config files)
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
## Requirements
|
|
115
|
+
|
|
116
|
+
- Python 3.10 or higher
|
|
117
|
+
- Runtime dependencies are listed in `setup.py` and automatically installed via pip.
|
|
118
|
+
- The `requirements.txt` file lists exact versions used for development and testing, and can be used to set up a development environment: `pip install -r requirements.txt`
|
|
119
|
+
|
|
120
|
+
## Development
|
|
121
|
+
|
|
122
|
+
To run the code directly from the source tree without installation:
|
|
123
|
+
|
|
124
|
+
```bash
|
|
125
|
+
# Using the installed entry point (requires editable install):
|
|
126
|
+
# pip install -e .
|
|
127
|
+
# pdf-to-md /path/to/file.pdf
|
|
128
|
+
|
|
129
|
+
# Or running the module directly:
|
|
130
|
+
python -m docs_to_md /path/to/file.pdf
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
For regular use after installation, use the `pdf-to-md` command.
|
|
134
|
+
|
|
135
|
+
## License
|
|
136
|
+
|
|
137
|
+
This project is licensed under the MIT License - see the LICENSE file for details.
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from typing import Dict, Optional, Any
|
|
5
|
+
|
|
6
|
+
import backoff
|
|
7
|
+
import filetype
|
|
8
|
+
import requests
|
|
9
|
+
from ratelimit import limits, sleep_and_retry
|
|
10
|
+
|
|
11
|
+
from docs_to_md.api.models import MarkerStatus, StatusEnum, SubmitResponse, SUPPORTED_MIME_TYPES
|
|
12
|
+
from docs_to_md.utils.exceptions import APIError
|
|
13
|
+
from docs_to_md.utils.file_utils import FileIO
|
|
14
|
+
|
|
15
|
+
# Constants
|
|
16
|
+
MAX_REQUESTS_PER_MINUTE = 150
|
|
17
|
+
REQUEST_TIMEOUT = 30 # seconds
|
|
18
|
+
MAX_RETRIES = 3
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class MarkerClient:
|
|
24
|
+
"""Client for interacting with the Marker API."""
|
|
25
|
+
|
|
26
|
+
BASE_URL = "https://www.datalab.to/api/v1/marker"
|
|
27
|
+
|
|
28
|
+
def __init__(self, api_key: str):
|
|
29
|
+
"""
|
|
30
|
+
Initialize the API client.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
api_key: API key for authentication
|
|
34
|
+
|
|
35
|
+
Raises:
|
|
36
|
+
APIError: If API key is not provided or invalid
|
|
37
|
+
"""
|
|
38
|
+
# Check for empty API key
|
|
39
|
+
if not api_key:
|
|
40
|
+
raise APIError("API key is required")
|
|
41
|
+
|
|
42
|
+
# Basic validation - API keys should typically be alphanumeric
|
|
43
|
+
# and have a reasonable length. The exact format depends on Marker's specs.
|
|
44
|
+
api_key = api_key.strip() # Remove accidental whitespace
|
|
45
|
+
if len(api_key) < 8: # Assuming a minimum sensible length
|
|
46
|
+
raise APIError("API key appears to be too short")
|
|
47
|
+
|
|
48
|
+
self.headers = {"X-Api-Key": api_key}
|
|
49
|
+
|
|
50
|
+
@sleep_and_retry
|
|
51
|
+
@limits(calls=MAX_REQUESTS_PER_MINUTE, period=60)
|
|
52
|
+
@backoff.on_exception(
|
|
53
|
+
backoff.expo,
|
|
54
|
+
(requests.exceptions.RequestException, json.JSONDecodeError),
|
|
55
|
+
max_tries=MAX_RETRIES
|
|
56
|
+
)
|
|
57
|
+
def submit_file(
|
|
58
|
+
self,
|
|
59
|
+
file_path: Path,
|
|
60
|
+
output_format: str = "markdown",
|
|
61
|
+
langs: str = "English",
|
|
62
|
+
use_llm: bool = False,
|
|
63
|
+
strip_existing_ocr: bool = False,
|
|
64
|
+
disable_image_extraction: bool = False,
|
|
65
|
+
force_ocr: bool = False,
|
|
66
|
+
paginate: bool = False,
|
|
67
|
+
max_pages: Optional[int] = None,
|
|
68
|
+
) -> Optional[str]:
|
|
69
|
+
"""
|
|
70
|
+
Submit a file for conversion.
|
|
71
|
+
|
|
72
|
+
Args:
|
|
73
|
+
file_path: Path to the file to submit
|
|
74
|
+
output_format: Desired output format (markdown, json, html)
|
|
75
|
+
langs: Comma-separated OCR languages
|
|
76
|
+
use_llm: Whether to use LLM for enhanced processing
|
|
77
|
+
strip_existing_ocr: Whether to redo OCR processing
|
|
78
|
+
disable_image_extraction: Whether to disable image extraction
|
|
79
|
+
force_ocr: Whether to force OCR on all pages
|
|
80
|
+
paginate: Whether to add page delimiters
|
|
81
|
+
max_pages: Maximum pages to process
|
|
82
|
+
|
|
83
|
+
Returns:
|
|
84
|
+
Request ID if successful, None otherwise
|
|
85
|
+
|
|
86
|
+
Raises:
|
|
87
|
+
APIError: If file is invalid or API request fails
|
|
88
|
+
"""
|
|
89
|
+
try:
|
|
90
|
+
# Validate file exists
|
|
91
|
+
if not file_path.exists():
|
|
92
|
+
raise APIError(f"File not found: {file_path}")
|
|
93
|
+
|
|
94
|
+
# Read file and check type
|
|
95
|
+
file_data = FileIO.read_file(file_path)
|
|
96
|
+
kind = filetype.guess(file_data)
|
|
97
|
+
if not kind or kind.mime not in SUPPORTED_MIME_TYPES:
|
|
98
|
+
raise APIError(f"Unsupported file type: {kind.mime if kind else 'unknown'}")
|
|
99
|
+
|
|
100
|
+
# Build form data
|
|
101
|
+
files = {
|
|
102
|
+
'file': (file_path.name, file_data, kind.mime),
|
|
103
|
+
'langs': (None, langs),
|
|
104
|
+
'force_ocr': (None, force_ocr),
|
|
105
|
+
'paginate': (None, paginate),
|
|
106
|
+
'strip_existing_ocr': (None, strip_existing_ocr),
|
|
107
|
+
'disable_image_extraction': (None, disable_image_extraction),
|
|
108
|
+
'use_llm': (None, use_llm),
|
|
109
|
+
'output_format': (None, output_format),
|
|
110
|
+
}
|
|
111
|
+
# Add max_pages only if it's provided
|
|
112
|
+
if max_pages is not None:
|
|
113
|
+
files['max_pages'] = (None, max_pages)
|
|
114
|
+
|
|
115
|
+
# Send request
|
|
116
|
+
response = requests.post(
|
|
117
|
+
self.BASE_URL,
|
|
118
|
+
files=files,
|
|
119
|
+
headers=self.headers,
|
|
120
|
+
timeout=REQUEST_TIMEOUT
|
|
121
|
+
)
|
|
122
|
+
response.raise_for_status()
|
|
123
|
+
|
|
124
|
+
# Parse response
|
|
125
|
+
data = response.json()
|
|
126
|
+
submit_response = SubmitResponse.model_validate(data)
|
|
127
|
+
|
|
128
|
+
if not submit_response.success:
|
|
129
|
+
logger.error(f"API request failed: {submit_response.error or 'Unknown error'}")
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
logger.info(f"Successfully submitted file. Request ID: {submit_response.request_id}")
|
|
133
|
+
return submit_response.request_id
|
|
134
|
+
|
|
135
|
+
except Exception as e:
|
|
136
|
+
logger.error(f"Error submitting file {file_path}: {e}")
|
|
137
|
+
return None
|
|
138
|
+
|
|
139
|
+
@sleep_and_retry
|
|
140
|
+
@limits(calls=MAX_REQUESTS_PER_MINUTE, period=60)
|
|
141
|
+
@backoff.on_exception(
|
|
142
|
+
backoff.expo,
|
|
143
|
+
(requests.exceptions.RequestException, json.JSONDecodeError),
|
|
144
|
+
max_tries=MAX_RETRIES
|
|
145
|
+
)
|
|
146
|
+
def check_status(self, request_id: str) -> Optional[MarkerStatus]:
|
|
147
|
+
"""
|
|
148
|
+
Check the status of a conversion request.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
request_id: Request ID to check
|
|
152
|
+
|
|
153
|
+
Returns:
|
|
154
|
+
MarkerStatus object with current status, or None if request fails
|
|
155
|
+
"""
|
|
156
|
+
if not request_id:
|
|
157
|
+
logger.error("Cannot check status: empty request_id provided")
|
|
158
|
+
return None
|
|
159
|
+
|
|
160
|
+
try:
|
|
161
|
+
# Make API request with timeout
|
|
162
|
+
response = requests.get(
|
|
163
|
+
f"{self.BASE_URL}/{request_id}",
|
|
164
|
+
headers=self.headers,
|
|
165
|
+
timeout=REQUEST_TIMEOUT
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
# Handle non-200 responses properly
|
|
169
|
+
if response.status_code != 200:
|
|
170
|
+
logger.error(f"API returned status code {response.status_code} for request {request_id}")
|
|
171
|
+
if response.status_code == 404:
|
|
172
|
+
return MarkerStatus(status=StatusEnum.PROCESSING, error="Request not found")
|
|
173
|
+
elif response.status_code == 401:
|
|
174
|
+
return MarkerStatus(status=StatusEnum.FAILED, error="Authentication failed")
|
|
175
|
+
elif response.status_code == 429:
|
|
176
|
+
return MarkerStatus(status=StatusEnum.PROCESSING, error="Rate limit exceeded")
|
|
177
|
+
return None
|
|
178
|
+
|
|
179
|
+
# Parse response JSON
|
|
180
|
+
try:
|
|
181
|
+
data = response.json()
|
|
182
|
+
except json.JSONDecodeError as e:
|
|
183
|
+
logger.error(f"Invalid JSON response for request {request_id}: {e}")
|
|
184
|
+
return None
|
|
185
|
+
|
|
186
|
+
# Handle empty response
|
|
187
|
+
if not data:
|
|
188
|
+
logger.error(f"Empty response for request {request_id}")
|
|
189
|
+
return None
|
|
190
|
+
|
|
191
|
+
# Validate and create status object
|
|
192
|
+
try:
|
|
193
|
+
status = MarkerStatus.model_validate(data)
|
|
194
|
+
return status
|
|
195
|
+
except Exception as e:
|
|
196
|
+
logger.error(f"Failed to parse status response for {request_id}: {e}")
|
|
197
|
+
return None
|
|
198
|
+
|
|
199
|
+
except requests.exceptions.Timeout:
|
|
200
|
+
logger.error(f"Timeout checking status for {request_id}")
|
|
201
|
+
return None
|
|
202
|
+
except requests.exceptions.ConnectionError:
|
|
203
|
+
logger.error(f"Connection error checking status for {request_id}")
|
|
204
|
+
return None
|
|
205
|
+
except requests.exceptions.RequestException as e:
|
|
206
|
+
logger.error(f"Request error checking status for {request_id}: {e}")
|
|
207
|
+
return None
|
|
208
|
+
except Exception as e:
|
|
209
|
+
logger.error(f"Unexpected error checking status for {request_id}: {e}")
|
|
210
|
+
return None
|
|
211
|
+
|
|
212
|
+
def __enter__(self):
|
|
213
|
+
"""Support for context manager."""
|
|
214
|
+
return self
|
|
215
|
+
|
|
216
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
|
217
|
+
"""Clean up resources if needed."""
|
|
218
|
+
pass # No cleanup needed for API client
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
from enum import Enum
|
|
2
|
+
from typing import Any, Dict, Optional, Set
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class StatusEnum(str, Enum):
|
|
9
|
+
"""Enum for API status values."""
|
|
10
|
+
COMPLETE = "complete"
|
|
11
|
+
PROCESSING = "processing"
|
|
12
|
+
FAILED = "failed"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MarkerStatus(BaseModel):
|
|
16
|
+
"""Model for API status response."""
|
|
17
|
+
status: StatusEnum # Indicates the status of the request (`complete`, or `processing`).
|
|
18
|
+
output_format: Optional[str] = None # The requested output format, `json`, `html`, or `markdown`.
|
|
19
|
+
success: Optional[bool] = None # Indicates if the request completed successfully. `True` or `False`.
|
|
20
|
+
error: Optional[str] = None # If there was an error, this contains the error message.
|
|
21
|
+
markdown: Optional[str] = None # The output from the file if `output_format` is `markdown`.
|
|
22
|
+
json_data: Optional[Dict[str, Any]] = None # The output from the file if `output_format` is `json`.
|
|
23
|
+
images: Optional[Dict[str, str]] = None # Dictionary of image filenames (keys) and base64 encoded images (values).
|
|
24
|
+
meta: Optional[Dict[str, Any]] = None # Metadata about the markdown conversion.
|
|
25
|
+
page_count: Optional[int] = None # Number of pages that were converted.
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class SubmitResponse(BaseModel):
|
|
29
|
+
"""Model for API submit response."""
|
|
30
|
+
success: bool
|
|
31
|
+
error: Optional[str] = None
|
|
32
|
+
request_id: str
|
|
33
|
+
request_check_url: Optional[str] = None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class ApiParams:
|
|
38
|
+
"""Parameters for the Marker API submit call."""
|
|
39
|
+
output_format: str = "markdown"
|
|
40
|
+
langs: str = "English"
|
|
41
|
+
use_llm: bool = False
|
|
42
|
+
strip_existing_ocr: bool = False
|
|
43
|
+
disable_image_extraction: bool = False
|
|
44
|
+
force_ocr: bool = False
|
|
45
|
+
paginate: bool = False
|
|
46
|
+
max_pages: Optional[int] = None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
# Supported mime types according to API docs
|
|
50
|
+
SUPPORTED_MIME_TYPES: Set[str] = {
|
|
51
|
+
# PDF
|
|
52
|
+
'application/pdf',
|
|
53
|
+
# Word documents
|
|
54
|
+
'application/msword',
|
|
55
|
+
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
56
|
+
# Powerpoint
|
|
57
|
+
'application/vnd.ms-powerpoint',
|
|
58
|
+
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
59
|
+
# Images
|
|
60
|
+
'image/png',
|
|
61
|
+
'image/jpeg',
|
|
62
|
+
'image/webp',
|
|
63
|
+
'image/gif',
|
|
64
|
+
'image/tiff',
|
|
65
|
+
'image/jpg'
|
|
66
|
+
}
|
|
File without changes
|