hn-deepocr-client 0.1.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.
@@ -0,0 +1,5 @@
1
+ AK=your_access_key_here
2
+ SK=your_secret_key_here
3
+ PRESIGNED_URL=https://open-sci-datahub.zero2x.org
4
+ LOG_DIR=logs
5
+ LOG_FILE=pdf_parser.log
@@ -0,0 +1,80 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ *.pyo
5
+ *.pyd
6
+ *.so
7
+ *.dll
8
+ *.dylib
9
+ build/
10
+ dist/
11
+ wheels/
12
+ *.egg-info
13
+ *.egg
14
+
15
+ # Virtual environments
16
+ .venv/
17
+ venv/
18
+ ENV/
19
+ env/
20
+ .python-version
21
+
22
+ # UV package manager
23
+ .uv/
24
+
25
+ # IDEs and editors
26
+ .vscode/
27
+ .idea/
28
+ *.swp
29
+ *.swo
30
+ *~
31
+ .DS_Store
32
+
33
+ # Project outputs
34
+ output/
35
+ *.xlsx
36
+ !数据需求*.xlsx
37
+
38
+ # Logs
39
+ logs/
40
+ *.log
41
+
42
+ # Temporary files
43
+ *.tmp
44
+ *.bak
45
+ *.log
46
+ ~$*.xlsx
47
+ ~$*.xls
48
+ ~$*.doc*
49
+
50
+ # Database
51
+ *.db
52
+ *.sqlite
53
+ *.sqlite3
54
+
55
+ # Environment variables
56
+ .env
57
+ .env.local
58
+ .env.*.local
59
+
60
+ # Testing
61
+ .pytest_cache/
62
+ .coverage
63
+ htmlcov/
64
+ *.cover
65
+ .hypothesis/
66
+
67
+ # Jupyter Notebook
68
+ .ipynb_checkpoints/
69
+ *.ipynb
70
+
71
+ # MyPy
72
+ .mypy_cache/
73
+ .dmypy.json
74
+ dmypy.json
75
+
76
+ # Ruff
77
+ .ruff_cache/
78
+
79
+ .claude
80
+ /CLAUDE.md
@@ -0,0 +1,157 @@
1
+ # 项目:OCR 批量处理后台接口
2
+
3
+ ## 项目说明
4
+ 基于 uv 包管理器,调用 PDF 解析 API 完成样例 PDF 解析和结果下载。
5
+
6
+ ## 技术栈
7
+ - **包管理器**: uv
8
+ - **Python 版本**: >= 3.10
9
+ - **核心依赖**: requests, pydantic-settings
10
+
11
+ ## 命令指南
12
+
13
+ ### 依赖安装
14
+ ```bash
15
+ uv sync
16
+ ```
17
+
18
+ ### 运行主程序
19
+ ```bash
20
+ python test_online_openapi.py
21
+ ```
22
+
23
+ ### 运行工具模块
24
+ ```bash
25
+ python utils.py
26
+ ```
27
+
28
+ ### 代码质量检查
29
+ ```bash
30
+ # 代码格式化
31
+ uv run ruff format .
32
+
33
+ # 代码检查
34
+ uv run ruff check .
35
+
36
+ # 自动修复可修复的问题
37
+ uv run ruff check --fix .
38
+
39
+ # 类型检查
40
+ uv run mypy .
41
+ ```
42
+
43
+ ## 代码规范
44
+
45
+ ### 导入组织
46
+ 1. 标准库导入
47
+ 2. 第三方库导入
48
+ 3. 按字母顺序排序
49
+ ```python
50
+ import os
51
+ import json
52
+ import time
53
+ import requests
54
+ import utils
55
+ ```
56
+
57
+ ### 类型注解
58
+ - 新代码建议添加类型注解以提高可读性
59
+ - 现有代码风格:最小化类型注解使用
60
+ - 简单函数可省略,复杂函数和公共接口应添加类型提示
61
+ ```python
62
+ def get_resource_path(resource_name: str) -> str:
63
+ return os.path.join(os.path.dirname(__file__), "resources", resource_name)
64
+ ```
65
+
66
+ ### 命名约定
67
+ - **类名**: PascalCase (如 `ParserPDF`)
68
+ - **函数和变量**: snake_case (如 `get_upload_urls`, `file_path`)
69
+ - **常量**: UPPER_SNAKE_CASE (如 `TIMEOUT`, `API_PATHS`)
70
+ - **私有方法**: 单下划线前缀 `_private_method`
71
+
72
+ ### 注释规范
73
+ - **仅使用文档字符串**: 使用三引号 `"""` 格式
74
+ - **语言**: 英文注释
75
+ - **位置**: 仅在函数和类顶部,严禁代码行内注释
76
+ - **其它**:不用emoji字符,避免无意义的翻译型注释
77
+ ```python
78
+ def load_config(config_path="config.json"):
79
+ """加载配置文件(含AK/SK/接口地址,避免硬编码)"""
80
+ pass
81
+ ```
82
+
83
+ ### 错误处理
84
+ - 使用具体异常类型 (FileNotFoundError, ValueError 等)
85
+ - 使用 `exc_info=True` 记录完整堆栈信息
86
+ - 异常处理后重新抛出
87
+ ```python
88
+ try:
89
+ response = requests.post(url, data, headers=headers, timeout=self.TIMEOUT)
90
+ response.raise_for_status()
91
+ except requests.exceptions.RequestException as e:
92
+ self.logger.error(f"请求异常:{str(e)}", exc_info=True)
93
+ raise
94
+ ```
95
+
96
+ ### 日志记录
97
+ - 初始化同时输出到控制台和文件
98
+ - 使用结构化格式: `%(asctime)s - %(levelname)s - %(message)s`
99
+ - 日志级别: INFO, WARNING, ERROR, CRITICAL
100
+ - 重要操作需记录 INFO 级别日志
101
+ ```python
102
+ def init_logger():
103
+ """初始化日志配置:同时输出到控制台和文件"""
104
+ logger = logging.getLogger("PDFParserLogger")
105
+ logger.setLevel(logging.INFO)
106
+ formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
107
+ # 添加 handlers...
108
+ ```
109
+
110
+ ### 配置管理
111
+ - 使用 Pydantic Settings 管理配置(支持环境变量和 .env 文件)
112
+ - 敏感信息通过 .env 文件管理(已在 .gitignore 中)
113
+ - 自动类型检查和验证
114
+ ```python
115
+ from pydantic_settings import BaseSettings, SettingsConfigDict
116
+
117
+ class Settings(BaseSettings):
118
+ AK: str
119
+ SK: str
120
+ PRESIGNED_URL: str = "https://open-sci-datahub.zero2x.org"
121
+
122
+ model_config = SettingsConfigDict(
123
+ env_file=".env",
124
+ env_file_encoding="utf-8",
125
+ )
126
+ ```
127
+
128
+ ### 类设计
129
+ - 常量定义为类属性 (API_PATHS, TIMEOUT)
130
+ - 配置通过 __init__ 传入
131
+ - 方法职责单一,命名清晰描述行为
132
+ ```python
133
+ class ParserPDF:
134
+ API_PATHS = {
135
+ "GET_UPLOAD_URLS": "/openAPI/deepocr/getUploadUrls",
136
+ }
137
+ TIMEOUT = 300
138
+
139
+ def __init__(self, ak, sk, presigned_url):
140
+ self.ak = ak
141
+ self.sk = sk
142
+ self.presigned_url = presigned_url.rstrip("/")
143
+ self.logger = init_logger()
144
+ ```
145
+
146
+ ## 依赖管理
147
+ - 仅在必要情况下引入新的外部依赖项
148
+ - 引入新依赖前需评估其对项目体积和维护成本的影响
149
+ - 使用 uv 作为包管理器
150
+
151
+ ## 开发工具
152
+ - **代码格式化和检查**: ruff(已配置在 pyproject.toml 中)
153
+ - **类型检查**: mypy(可选,建议复杂函数添加类型提示)
154
+
155
+ ## 测试
156
+ - 当前无正式测试框架配置
157
+ - 测试方式:运行 `test_online_openapi.py` 执行完整工作流
@@ -0,0 +1,27 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.0] - 2026-01-21
9
+
10
+ ### Added
11
+ - Initial release of Haina Deep OCR Client SDK
12
+ - PDF file upload and parsing functionality
13
+ - Authentication token generation and signing
14
+ - Support for chunked file uploads
15
+ - Parsing status polling
16
+ - Multi-format result generation (zip, json, markdown, image, formula, table)
17
+ - Comprehensive error handling with custom exception classes
18
+ - Logging configuration with console and file output
19
+ - Pydantic Settings for configuration management
20
+ - Example code for basic and advanced usage
21
+ - Unit tests for core functionality
22
+ - Full documentation and README
23
+
24
+ ### Changed
25
+ - Migration from JSON configuration to Pydantic Settings + .env
26
+ - Restructured project to follow standard Python SDK layout
27
+ - Improved error messages and logging
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Haina
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,267 @@
1
+ Metadata-Version: 2.4
2
+ Name: hn-deepocr-client
3
+ Version: 0.1.0
4
+ Summary: Haina Deep OCR API Client SDK
5
+ Project-URL: Homepage, https://github.com/yourusername/hn-deepocr-client
6
+ Project-URL: Documentation, https://github.com/yourusername/hn-deepocr-client#readme
7
+ Project-URL: Repository, https://github.com/yourusername/hn-deepocr-client.git
8
+ Project-URL: Issues, https://github.com/yourusername/hn-deepocr-client/issues
9
+ Author-email: Haina <support@haina.com>
10
+ License: MIT
11
+ License-File: LICENSE
12
+ Keywords: api,client,ocr,parser,pdf
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: pydantic-settings>=2.12.0
22
+ Requires-Dist: requests>=2.32.5
23
+ Description-Content-Type: text/markdown
24
+
25
+ # HN Deep OCR Client
26
+
27
+ Python SDK for Haina Deep OCR API - PDF parsing and document processing made easy.
28
+
29
+ [![Python Version](https://img.shields.io/badge/python-3.10%2B-blue)](https://www.python.org/downloads/)
30
+ [![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)
31
+ [![Code Style](https://img.shields.io/badge/code%20style-ruff-000000.svg)](https://github.com/astral-sh/ruff)
32
+
33
+ ## Features
34
+
35
+ - PDF file upload with automatic chunking (configurable chunk size)
36
+ - Parsing status polling with optimized timeouts
37
+ - Multi-format result generation (ZIP, JSON, Markdown, Image, Formula, Table)
38
+ - Comprehensive error handling with custom exception classes
39
+ - Built-in logging configuration
40
+ - Type hints for better IDE support
41
+ - Pydantic Settings for configuration management
42
+ - Connection pooling and HTTP session reuse
43
+ - Intelligent retry mechanism with exponential backoff
44
+ - Granular timeout configuration per operation type
45
+ - Full test coverage
46
+
47
+ ## Installation
48
+
49
+ ```bash
50
+ pip install hn-deepocr-client
51
+ ```
52
+
53
+ Or using uv:
54
+
55
+ ```bash
56
+ uv add hn-deepocr-client
57
+ ```
58
+
59
+ ## Quick Start
60
+
61
+ ### 1. Get API Credentials
62
+
63
+ Apply for Access Key (AK) and Secret Key (SK) from [Haina Platform](https://mkxzg8.yuque.com/hoq002/ilbssv/qmgptn6gltudphik#LoSlF).
64
+
65
+ ### 2. Configure Environment Variables
66
+
67
+ Create a `.env` file in your project root:
68
+
69
+ ```env
70
+ AK=your_access_key_here
71
+ SK=your_secret_key_here
72
+ PRESIGNED_URL=https://open-sci-datahub.zero2x.org
73
+ ```
74
+
75
+ Or use `.env.example` as a template:
76
+
77
+ ```bash
78
+ cp .env.example .env
79
+ # Edit .env with your credentials
80
+ ```
81
+
82
+ ### 3. Basic Usage
83
+
84
+ ```python
85
+ from hn_deepocr_client import ParserPDF, load_config
86
+
87
+ config = load_config()
88
+
89
+ parser = ParserPDF(
90
+ ak=config.AK,
91
+ sk=config.SK,
92
+ presigned_url=config.PRESIGNED_URL,
93
+ )
94
+
95
+ data_id = parser.start(
96
+ file_name="document.pdf",
97
+ file_path="./document.pdf",
98
+ )
99
+
100
+ print(f"Parse completed! DataID: {data_id}")
101
+ ```
102
+
103
+ ## Advanced Usage
104
+
105
+ ### Custom Configuration
106
+
107
+ ```python
108
+ from hn_deepocr_client import ParserPDF, load_config, ConfigurationError
109
+
110
+ try:
111
+ config = load_config()
112
+ parser = ParserPDF(ak=config.AK, sk=config.SK, presigned_url=config.PRESIGNED_URL)
113
+ data_id = parser.start("document.pdf", "./document.pdf")
114
+ except ConfigurationError as e:
115
+ print(f"Configuration error: {e}")
116
+ except UploadError as e:
117
+ print(f"Upload failed: {e}")
118
+ except ParseError as e:
119
+ print(f"Parse failed: {e}")
120
+ ```
121
+
122
+ ### Generate Specific Formats Only
123
+
124
+ ```python
125
+ data_id = parser.start("document.pdf", "./document.pdf", generate_all_formats=False)
126
+
127
+ # Generate only formats you need
128
+ zip_url = parser.generate_zips(data_id, "zip")
129
+ json_url = parser.generate_zips(data_id, "json")
130
+ markdown_url = parser.generate_zips(data_id, "markdown")
131
+ ```
132
+
133
+ ### Direct API Usage
134
+
135
+ ```python
136
+ from hn_deepocr_client import create_token
137
+
138
+ token = create_token(
139
+ ak="your_ak",
140
+ sk="your_sk",
141
+ url="https://api.example.com/upload",
142
+ request_body='{"file":"test.pdf"}',
143
+ )
144
+ ```
145
+
146
+ ## API Reference
147
+
148
+ ### ParserPDF
149
+
150
+ Main class for PDF parsing operations.
151
+
152
+ #### Methods
153
+
154
+ - `__init__(ak: str, sk: str, presigned_url: str)` - Initialize parser
155
+ - `start(file_name: str, file_path: str, generate_all_formats: bool = True) -> str` - Start full parsing workflow
156
+ - `get_parsing_status(data_id: str) -> int` - Query parsing status (1=parsing, 2=success, 3=failed)
157
+ - `generate_zips(data_id: str, file_type: str) -> str` - Generate download link for specific format
158
+
159
+ ### Exception Classes
160
+
161
+ - `HNDeepOCRError` - Base exception class
162
+ - `ConfigurationError` - Configuration related errors
163
+ - `AuthenticationError` - Authentication failures
164
+ - `UploadError` - File upload failures
165
+ - `ParseError` - Parsing failures
166
+
167
+ ### Configuration
168
+
169
+ Configuration is managed via Pydantic Settings. Available options:
170
+
171
+ #### Core Configuration
172
+ | Option | Type | Default | Description |
173
+ |--------|------|---------|-------------|
174
+ | AK | str | (required) | Access Key |
175
+ | SK | str | (required) | Secret Key |
176
+ | PRESIGNED_URL | str | https://open-sci-datahub.zero2x.org | API base URL |
177
+ | LOG_DIR | str | logs | Log directory |
178
+ | LOG_FILE | str | pdf_parser.log | Log filename |
179
+
180
+ #### Network Configuration
181
+ | Option | Type | Default | Description |
182
+ |--------|------|---------|-------------|
183
+ | HN_DEEP_OCR_TIMEOUT_API | int | 30 | API call timeout (seconds) |
184
+ | HN_DEEP_OCR_TIMEOUT_UPLOAD | int | 300 | File upload timeout (seconds) |
185
+ | HN_DEEP_OCR_TIMEOUT_STATUS | int | 10 | Status query timeout (seconds) |
186
+ | HN_DEEP_OCR_TIMEOUT_MERGE | int | 60 | Merge operation timeout (seconds) |
187
+ | HN_DEEP_OCR_MAX_RETRIES_DEFAULT | int | 3 | Default retry count |
188
+ | HN_DEEP_OCR_MAX_RETRIES_UPLOAD | int | 5 | Upload retry count |
189
+ | HN_DEEP_OCR_BASE_DELAY | float | 1.0 | Base delay for retry backoff |
190
+ | HN_DEEP_OCR_CONNECTION_POOL_SIZE | int | 10 | Connection pool size |
191
+ | HN_DEEP_OCR_CONNECTION_MAXSIZE | int | 20 | Maximum connections per pool |
192
+ | HN_DEEP_OCR_PART_SIZE | int | 10485760 | File chunk size in bytes (10MB) |
193
+
194
+ All network configuration options can be set via environment variables with the `HN_DEEP_OCR_` prefix or in your `.env` file.
195
+
196
+ ## Development
197
+
198
+ ### Installation
199
+
200
+ ```bash
201
+ git clone https://github.com/yourusername/hn-deepocr-client.git
202
+ cd hn-deepocr-client
203
+ uv sync
204
+ ```
205
+
206
+ ### Running Tests
207
+
208
+ ```bash
209
+ uv run pytest
210
+ ```
211
+
212
+ With coverage:
213
+
214
+ ```bash
215
+ uv run pytest --cov=hn_deepocr_client
216
+ ```
217
+
218
+ ### Code Quality
219
+
220
+ ```bash
221
+ # Format code
222
+ uv run ruff format .
223
+
224
+ # Lint code
225
+ uv run ruff check .
226
+
227
+ # Fix linting issues
228
+ uv run ruff check --fix .
229
+
230
+ # Type check
231
+ uv run mypy .
232
+ ```
233
+
234
+ ### Examples
235
+
236
+ See the `examples/` directory for usage examples:
237
+
238
+ - `basic_usage.py` - Basic usage example
239
+ - `advanced_usage.py` - Advanced features and error handling
240
+
241
+ ## Documentation
242
+
243
+ For more detailed documentation, see:
244
+
245
+ - [API Reference](docs/api.md)
246
+ - [Examples](docs/examples.md)
247
+ - [Changelog](CHANGELOG.md)
248
+
249
+ ## Contributing
250
+
251
+ Contributions are welcome! Please feel free to submit a Pull Request.
252
+
253
+ ## License
254
+
255
+ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
256
+
257
+ ## Support
258
+
259
+ - Documentation: [https://github.com/yourusername/hn-deepocr-client](https://github.com/yourusername/hn-deepocr-client)
260
+ - Issues: [https://github.com/yourusername/hn-deepocr-client/issues](https://github.com/yourusername/hn-deepocr-client/issues)
261
+ - Email: support@haina.com
262
+
263
+ ## Acknowledgments
264
+
265
+ - Built with [Pydantic](https://pydantic-docs.helpmanual.io/)
266
+ - Code quality powered by [Ruff](https://github.com/astral-sh/ruff)
267
+ - Testing with [pytest](https://docs.pytest.org/)