Skip to content

Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.

refactor: rename server→doclib, register→ingest, document parse-server architecture

jinzhenj0a7bb5c9d7c6
diff --git a/NEW-API.md b/NEXT-API.md
similarity index 100%
rename from NEW-API.md
rename to NEXT-API.md
diff --git a/NEXT-CLI.md b/NEXT-CLI.md
index 64ecda8c..05667b0a 100644
--- a/NEXT-CLI.md
+++ b/NEXT-CLI.md
@@ -77,7 +77,7 @@ mineru parse <file> [flags]
| Flag | 类型 | 默认 | 说明 |
|------|------|------|------|
| `--remote` | url (可选) | — | 切换为远端模式。不带参数时使用默认地址 mineru.net;带参数时使用指定地址 |
-| `--api-key` | string | — | API Key(也从配置文件和环境变量 `MINERU_API_KEY` 读取)。仅远端模式有效 |
+| `--api-key` | string | — | API Key(也从配置文件 `parse_server.remote.api_key` 和环境变量 `MINERU_API_KEY` 读取)|
### 解析配置
@@ -131,6 +131,7 @@ mineru parse <file> [flags]
**CLI ↔ API 对齐**:
- `--remote` 模式下,`--tier` 参数直接映射到 API 的 `tier` 字段(值相同:`standard` / `pro`)
- 远端模式下,CLI 统一请求 JSON 格式产物,markdown/text/html 由 CLI 本地从 JSON 生成
+- local parse-server 提供与 mineru.net 完全相同的 API(Files/Uploads/Jobs),ParseWorker 根据 `--remote` 选择 base URL
> **团队讨论项**:是否为 `standard` 提供 `core` 作为短别名。
@@ -140,10 +141,12 @@ mineru 是一款强调用户隐私的工具。显式调用 `mineru parse` 时,
```
1. 用户是否指定了 --remote?
- ├─ 是 → 使用远端解析,正常执行
+ ├─ 是 → 优先使用远程解析(--remote 不带参数时默认 mineru.net,带参数时使用指定地址)
+ │ 远程不可用时 fallback 到本地 parse-server(如果可用)
+ │ 本地也不可用 → 报错
└─ 否 →
- 2. 本地是否有 standard 或 pro 引擎可用?
- ├─ 有 → 使用本地引擎解析,正常执行
+ 2. 是否有本地 parse-server 可用(managed 或 self-hosted 模式探活成功)?
+ ├─ 是 → 使用本地 parse-server 解析,正常执行
└─ 没有 →
3. 用户是否指定了 --tier flash?
├─ 是 → 使用本地 flash 引擎(仅 CPU),正常执行
@@ -158,12 +161,13 @@ Error: 本地未检测到 standard/pro 解析引擎。
可选方案:
1. mineru parse doc.pdf --remote 使用远端解析(文件将上传至 mineru.net)
2. mineru parse doc.pdf --tier flash 使用本地轻量解析(仅 CPU,质量较低)
- 3. 启动本地解析服务后重试 参考: mineru-kit vlm-server --help
+ 3. 配置并启动本地解析服务后重试 参考: mineru-kit api-server --help
```
**设计要点**:
-- 不会在用户不知情的情况下把文件发到远端
-- 不会在用户不知情的情况下降级到 flash
+- 不会在用户不知情的情况下把文件发到远端。必须显式 `--remote` 才会触发上传
+- 不会在用户不知情的情况下降级到 flash。`auto` tier 不可用时报错而非静默降级
+- `--remote` 远程不可用时 fallback 到本地 parse-server——用户已接受上传,远程偶尔不可用本地兜底
- agent 收到此报错后可自行判断文件敏感性,决定选 `--remote` 还是 `--tier flash`
## 输出格式说明
@@ -372,14 +376,14 @@ mineru server status # 运行状态 + 索引统计 + 队列长度
Server 启动时:
- 清空所有未释放的锁(`*_locked_at` 字段)
- 重置处于 `parsing` 状态的任务为 `error`(可重试)
-- 对已注册文件进行活性验证(检测已删除文件)
+- 对已入库文件进行活性验证(检测已删除文件)
# Watch 与 Parsing-Rules
## Watch 机制
-用户配置 mineru 监控哪些目录,系统自动发现并注册文件:
+用户配置 mineru 监控哪些目录,系统自动发现并入库:
```bash
mineru config watch add ~/Documents
@@ -389,8 +393,8 @@ mineru config watch rm ~/Documents
```
**Watch 行为**:
-- 发现文件 → 注册(计算 SHA-256、记录 path/size/mtime、文件名进 FTS)
-- 注册后默认使用 **flash** tier 解析首尾各 5 页
+- 发现文件 → 入库(计算 SHA-256、记录 path/size/mtime、文件名进 FTS)
+- 入库后默认使用 **flash** tier 解析首尾各 5 页
- 文件类型决定解析方式:office 文档直接本地全量解析(成本低),PDF/image 用 flash
**文件类型白名单**(Watch 自动发现的范围):
@@ -465,7 +469,7 @@ mineru config parsing-rules rm <id>
## mineru search
-搜索已注册/已解析的文档内容:
+搜索已入库/已解析的文档内容:
```bash
mineru search "关键词" # 搜索文档内容
@@ -480,7 +484,7 @@ mineru search "关键词" --json # JSON 输出(给 agent)
## mineru find
-仅搜索文件名(覆盖所有已注册文件,不论是否解析过):
+仅搜索文件名(覆盖所有已入库文件,不论是否解析过):
```bash
mineru find "report"
@@ -506,8 +510,24 @@ mineru config show # 查看全部配置
mineru config watch add/list/rm # Watch 目录管理
mineru config exclude add/list/rm # 排除规则(glob pattern)
mineru config parsing-rules add/list/rm # 解析规则
+mineru config parse-server local.mode <mode> # 本地 parse-server 模式: disabled | managed | self_hosted
+mineru config parse-server local.managed-tier <tier> # managed 模式 tier: standard | pro
+mineru config parse-server local.self_hosted_url <url> # self_hosted 模式的 parse-server 地址
+mineru config parse-server remote.url <url> # 远程 parse-server 地址(默认 mineru.net)
+mineru config parse-server remote.api-key <key> # 远程 API Key
```
+**parse-server 配置说明**:
+
+| 配置项 | 默认值 | 说明 |
+|------|------|------|
+| `parse_server.local.mode` | `disabled` | `disabled` — 无本地 parse-server;`managed` — doclib 自动拉起;`self_hosted` — 用户管理 |
+| `parse_server.local.managed_tier` | `standard` | managed 模式启动的 tier |
+| `parse_server.local.self_hosted_url` | — | self_hosted 模式的 parse-server HTTP 地址 |
+| `parse_server.local.self_hosted_api_key` | — | self_hosted 模式的 API Key(可选) |
+| `parse_server.remote.url` | `https://mineru.net/api` | 远程 parse-server 地址 |
+| `parse_server.remote.api_key` | — | 远程 API Key(环境变量 `MINERU_API_KEY` 也可设置)|
+
# mineru 数据库设计概要
@@ -543,8 +563,7 @@ config KV 全局配置
子命令:
- mineru-kit parse(单个文件、文件夹的解析)
-- mineru-kit api-server(本地启动的端到端解析服务,与MinerU-SaaS的API格式兼容)
-- mineru-kit vlm-server(启动本地VLM服务,提供Layout和OCR能力,与OpenAI的API格式兼容)
+- mineru-kit api-server(本地启动的端到端解析服务,实现 NEXT-API.md 规范,提供 standard / pro tier 的解析能力)
mineru-kit parse 替换:
- mineru -p xxx.pdf -o xxx.md
@@ -559,6 +578,38 @@ mineru-kit vlm-server 替换:
- mineru-lmdeploy-server
- mineru-openai-server
+## mineru-kit api-server
+
+`api-server` 是本地部署的 HTTP 解析服务,实现 NEXT-API.md 定义的 Files/Uploads/Jobs 端点。它在功能上与 mineru.net 等价,区别仅在于 base URL 不同(`http://127.0.0.1:15981` vs `https://mineru.net/api`)。
+
+### 与 mineru doclib 的协作
+
+```
+mineru doclib(纯 CPU 进程)
+ │
+ ├─ flash tier → 直接调用 mineru.parser.parse()
+ │
+ └─ standard / pro tier → HTTP 调用
+ ├─ 未指定 --remote → mineru-kit api-server (127.0.0.1:15981)
+ └─ 指定 --remote → mineru.net/api (或 --remote 指定的地址)
+```
+
+- **managed 模式**:doclib 启动时自动拉起 api-server,停止时一起关闭
+- **self_hosted 模式**:用户独立启动 api-server,通过 config 告知 doclib 地址
+- **API 格式完全一致**:local parse-server 和 mineru.net 使用同一套 API,ParseWorker 仅切换 base URL
+
+### Usage
+
+```bash
+mineru-kit api-server --tier standard --port 15981
+mineru-kit api-server --tier pro --port 15981
+```
+
+| Flag | 默认 | 说明 |
+|------|------|------|
+| `--tier` | `standard` | 服务提供的解析档位:`standard` / `pro` |
+| `--port` | `15981` | 监听端口(仅 127.0.0.1) |
+
# mineru-kit parse
diff --git a/NEXT-DESIGN.md b/NEXT-DESIGN.md
index 18cbc8a3..484274a0 100644
--- a/NEXT-DESIGN.md
+++ b/NEXT-DESIGN.md
@@ -10,44 +10,55 @@
```
┌──────────────┐ Unix Domain Socket ┌───────────────────────────────────┐
-│ mineru CLI │ ──── HTTP + JSON ────→ │ mineru server │
+│ mineru CLI │ ──── HTTP + JSON ────→ │ mineru doclib │
│ (typer) │ ←─── HTTP + JSON ──── │ (FastAPI + uvicorn) │
└──────────────┘ │ │
│ ┌─ Routes ── Services ── Core │
┌──────────────┐ │ │ │
│ MCP Server │ ──── HTTP + JSON ────→ │ └─ Background │
│ (P1) │ │ ├─ WatchLoop │
-└──────────────┘ │ ├─ RegistrationWorker │
+└──────────────┘ │ ├─ IngestWorker │
│ ├─ ParseWorker │
-┌──────────────┐ │ └─ DeviceMonitor │
-│ MinerU.app │ ──── HTTP + JSON ────→ │ │
-│ (P1) │ └────────────┬──────────────────────┘
-└──────────────┘ │
+┌──────────────┐ │ │ (routes per tier) │
+│ MinerU.app │ ──── HTTP + JSON ────→ │ ├─ ParseServerHealthCheck │
+│ (P1) │ │ ├─ DeviceMonitor │
+└──────────────┘ │ └─ Compaction │
+ │ │
+ └────────────┬──────────────────────┘
+ │
┌────┴────┐
│ SQLite │
│ + FTS5 │
└─────────┘
+
+┌──────────────────────────┐
+│ local parse-server │ ← 独立进程(可选,仅供 standard / pro tier)
+│ (mineru-kit api-server) │ 实现 NEXT-API.md 的 Files/Uploads/Jobs 端点
+│ FastAPI + GPU 模型 │ 由 doclib 探活,ParseWorker 通过 HTTP 调用
+└──────────────────────────┘
```
### 1.1 核心设计决策
| 决策 | 选择 | 理由 |
|------|------|------|
-| 进程模型 | 单进程 asyncio | 简单可靠,避免 IPC 复杂度 |
-| CLI ↔ Server 通信 | HTTP + JSON over Unix Domain Socket | 安全(权限 0600)、低延迟、无端口冲突 |
+| 进程模型 | doclib (单进程 asyncio) + local parse-server (独立进程) | doclib 纯 CPU,local parse-server 加载 GPU 模型;crash 隔离,不互相影响 |
+| CLI ↔ doclib 通信 | HTTP + JSON over Unix Domain Socket | 安全(权限 0600)、低延迟、无端口冲突 |
+| doclib ↔ parse-server 通信 | HTTP + JSON over TCP | parse-server 为独立进程,通过 TCP 环回地址通信 |
| 数据库 | SQLite (WAL) + FTS5 | 零运维、单文件、全文搜索内置 |
| 任务队列 | DB rows + 时间戳锁 | 无外部依赖,崩溃恢复简单 |
-| CPU-bound offload | `asyncio.to_thread()` | SHA-256 计算、文件解析等交给线程池 |
+| CPU-bound offload | `asyncio.to_thread()` | SHA-256 计算、flash 解析等交给线程池 |
| 文件监控 | watchfiles (FSEvents/inotify) | 跨平台、高性能 |
### 1.2 Socket 与端口
| 通道 | 路径 / 地址 | 权限 | 用途 |
|------|-----------|------|------|
-| UDS | `/tmp/mineru.sock` | `0600` | CLI / MCP / 桌面端通信 |
-| TCP | `127.0.0.1:<随机端口>` | loopback only | 可选,供浏览器访问 Web UI (P1) |
+| UDS | `/tmp/mineru.sock` | `0600` | CLI / MCP / 桌面端与 doclib 通信 |
+| TCP (parse-server) | `127.0.0.1:15981` | loopback only | doclib ParseWorker 调用 local parse-server API |
+| TCP (doclib Web UI) | `127.0.0.1:<随机端口>` | loopback only | 可选,供浏览器访问 Web UI (P1) |
-Server 启动后 UDS sock 文件位于 `/tmp/mineru.sock`(权限 0600)。CLI 通过 sock 连接检测 server 状态。TCP 端口按 config 中 `http.enabled` 决定是否启动。
+doclib 启动后 UDS sock 文件位于 `/tmp/mineru.sock`(权限 0600)。CLI 通过 sock 连接检测 server 状态。TCP 端口按 config 中 `http.enabled` 决定是否启动。parse-server 端口固定为 `127.0.0.1:15981`,仅环回地址可访问。managed 模式下 parse-server 由 doclib 自动拉起,self-hosted 模式下用户自行管理。
---
@@ -82,7 +93,7 @@ Core(数据层:DB、FTS、文件 IO)
| Service | 依赖 | 职责 |
|---------|------|------|
-| `ParseService` | DB, FTS, ConfigService | 接收解析请求、文件注册(SHA-256 + metadata)、分配任务、管理 per-tier 解析状态 |
+| `ParseService` | DB, FTS, ConfigService | 接收解析请求、文件入库(SHA-256 + metadata)、分配任务、管理 per-tier 解析状态 |
| `SearchService` | DB, FTS | 内容搜索 (fts_contents)、文件名搜索 (fts_filenames) |
| `ConfigService` | DB | KV 配置读写、Watch 目录 CRUD、Parsing-Rules CRUD、路径排除判断 |
| `CleanupService` | DB | 孤儿文档清理、已删除文件清理、解析缓存清理 |
@@ -143,14 +154,14 @@ CREATE TABLE docs (
keywords TEXT,
is_encrypted INTEGER NOT NULL DEFAULT 0,
is_scanned INTEGER NOT NULL DEFAULT 0,
- meta_tier TEXT, -- 当前 metadata 的来源 tier,NULL 表示注册阶段
+ meta_tier TEXT, -- 当前 metadata 的来源 tier,NULL 表示尚未解析
first_seen_at INTEGER NOT NULL, -- Unix epoch ms
updated_at INTEGER NOT NULL -- Unix epoch ms
);
```
> **docs 元数据填充策略**:
-> - **注册阶段**(register_file):SHA-256 已全量读文件,顺手通过 pypdfium2 / python-docx 提取 metadata,成本可忽略。page_count 准确(pypdfium2 仅读 Catalog),title/author/subject/keywords 取自文件 metadata(可能不准,做保护性截断:title≤500、author≤200、subject≤1000、keywords≤1000)。`meta_tier=NULL`
+> - **Ingest 阶段**(ingest_file):SHA-256 已全量读文件,顺手通过 pypdfium2 / python-docx 提取 metadata,成本可忽略。page_count 准确(pypdfium2 仅读 Catalog),title/author/subject/keywords 取自文件 metadata(可能不准,做保护性截断:title≤500、author≤200、subject≤1000、keywords≤1000)。`meta_tier=NULL`
> - **解析完成后**(ParseWorker):引擎产出的 metadata 仅在 `tier ≥ meta_tier`(或 meta_tier 为 NULL)时 UPDATE docs 覆盖,同时更新 `meta_tier`。同一 tier 的多次批次不会重复更新
> - 解析状态全部在 `parses` 表中按 tier 独立管理
@@ -167,6 +178,9 @@ CREATE TABLE parses (
locked_at INTEGER, -- Unix epoch ms
error_code TEXT, -- 错误码,e.g. "parse_timeout"
error_msg TEXT, -- 人类可读错误描述
+ privacy TEXT NOT NULL DEFAULT 'local', -- local / remote
+ remote_url TEXT, -- 用户指定的远程 URL,null = 使用默认 mineru.net
+ via TEXT, -- 实际执行的隐私路径: local / remote(fallback 后可能与 privacy 不同)
output_path TEXT, -- 解析产物存储路径
done_at INTEGER, -- Unix epoch ms
created_at INTEGER NOT NULL, -- Unix epoch ms
@@ -177,6 +191,16 @@ CREATE INDEX idx_parses_status ON parses(status, priority DESC, created_at ASC);
CREATE INDEX idx_parses_doc ON parses(sha256, tier);
```
+**privacy / remote_url / via 说明**:
+
+| 列 | 含义 |
+|------|------|
+| `privacy` | 用户请求时的隐私偏好。`local` 默认(文档不出本地),`remote` 即 `--remote`(文档上传到远程) |
+| `remote_url` | 用户指定的远程地址。`privacy=remote` 时必带,默认 `mineru.net` |
+| `via` | 实际执行路径。`privacy=remote` 但远程不可用时 fallback 到 `local`,此列记录实际走的路径。缓存键为 `(sha256, tier)`,与 `privacy`/`via` 无关——同一 tier 不同来源产出解析结果一致 |
+
+**缓存命中**:按 `(sha256, tier)` 去重,不区分 `privacy`。同一份文档用 `privacy=local` 和 `privacy=remote` 走同一 tier,只有一条 done 记录命中缓存。
+
**pages 字段**:
- 用 range 字符串描述,如 `"1~5"`、`"1~5,46~50"`、`"1~1000"`
- 仅存正值——用户输入的负索引(如 `-5~-1`)和 `all` 在插入前根据 `docs.page_count` 展开为正值
@@ -358,7 +382,7 @@ INSERT INTO config (key, value) VALUES
('data_dir', '~/MinerU'),
('default_tier', 'flash'),
('scan_interval_sec', '300'),
- ('reg_lock_timeout_sec', '60'),
+ ('ingest_lock_timeout_sec', '60'),
('parse_lock_timeout_sec', '1800'),
('device_check_interval_sec', '5');
```
@@ -372,9 +396,11 @@ INSERT INTO config (key, value) VALUES
| 组件 | 职责 | 并发数 |
|------|------|--------|
| WatchLoop | 文件系统事件监控(watchfiles),发现文件变更 | 1 |
-| RegistrationWorker | 计算 SHA-256、提取 metadata、写入 files/docs、FTS 索引文件名、触发默认 flash 解析 | 2 |
-| ParseWorker | 执行解析任务(调用 `mineru.parser`),写入 FTS | 2 |
+| IngestWorker | 计算 SHA-256、提取 metadata、写入 files/docs、FTS 索引文件名、触发默认 flash 解析 | 2 |
+| ParseWorker | 执行解析任务。按 tier 路由:flash → 直接调用 `mineru.parser`;standard/pro → HTTP 调用 parse-server(本地或 remote,取决于 `privacy`) | 2 |
+| ParseServerHealthCheck | 定期探查 parse-server 健康状态(`GET /tiers`,60s 间隔),结果存内存供 ParseWorker 消费 | 1 |
| DeviceMonitor | 定期检测 removable watch 路径的可达性 | 1 |
+| Compaction | 合并同一 (sha256, tier) 的 done 批次,减少 parses 表记录数 | 1 |
所有组件均为 asyncio task,在 server 启动时创建,关闭时 graceful stop。
@@ -383,7 +409,7 @@ INSERT INTO config (key, value) VALUES
无外部消息队列。Worker 通过原子 SQL 获取任务:
```sql
--- RegistrationWorker 获取任务
+-- IngestWorker 获取任务
UPDATE files
SET locked_at = ?
WHERE id = (
@@ -422,60 +448,126 @@ RETURNING *;
### 5.1 两阶段模型
```
-阶段 1: 注册(RegistrationWorker)
+阶段 1: 入库(IngestWorker)
- 计算 SHA-256
- 提取 metadata (mime_type, page_count, title, author)
- FTS 索引文件名
- - 触发默认 flash 解析(INSERT INTO parses (sha256, tier, pages, status='pending', priority=0))
+ - 触发默认 flash 解析(INSERT INTO parses (sha256, tier, pages, status='pending', privacy='local', priority=0))
阶段 2: 解析(ParseWorker)
- flash tier:提取首尾各 5 页文本,写入 fts_contents
- - standard/pro tier:完整解析,写入 fts_contents(覆盖 flash 的)
+ - standard/pro tier:按 tier 路由选择执行路径(见 §5.3),完整解析,写入 fts_contents(覆盖 flash 的)
```
-> **设计简化**:everydoc 的 L1 Index(注册 + 预览文本提取)在 MinerU 中被拆为:注册(仅 SHA-256 + metadata)+ flash 解析(首尾页文本)。用户无需理解"索引"和"解析"两个概念——所有内容提取都是 parse,只是 tier 不同。
+> **设计简化**:everydoc 的 L1 Index(入库 + 预览文本提取)在 MinerU 中被拆为:入库(仅 SHA-256 + metadata)+ flash 解析(首尾页文本)。用户无需理解"索引"和"解析"两个概念——所有内容提取都是 parse,只是 tier 不同。
-### 5.2 文件发现 → 注册
+### 5.2 文件发现 → 入库
```
Watch 检测到文件事件
→ 过滤(ext 白名单 + exclude 规则)
→ INSERT OR IGNORE INTO files (path, filename, ext, size_bytes, mtime_ms, sha256=NULL)
- → RegistrationWorker.acquire_task(): UPDATE files SET locked_at WHERE sha256 IS NULL
+ → IngestWorker.acquire_task(): UPDATE files SET locked_at WHERE sha256 IS NULL
→ process_file():
1. compute SHA-256 (asyncio.to_thread)
2. INSERT OR IGNORE INTO docs (sha256, size_bytes, page_count, title, author, subject, keywords, is_encrypted)
3. FTS insert fts_filenames
4. UPDATE files SET sha256=?, locked_at=NULL
5. check parsing-rules
- 6. INSERT INTO parses (sha256, tier, pages, status='pending', priority=0)
+ 6. INSERT INTO parses (sha256, tier, pages, status='pending', privacy='local', priority=0)
→ 失败时: UPDATE files SET sha256=NULL, error_code=?, error_msg=?(可重试)
```
-### 5.3 解析请求
+### 5.3 解析请求与 ParseWorker 路由
+
+#### 5.3.1 解析请求入队
```
-用户请求: mineru parse doc.pdf --tier standard --pages 1~10
+用户请求: mineru parse doc.pdf --tier standard --pages 1~10 [--remote [url]]
→ CLI → Product SDK (client.py) → Server POST /parse
→ ParseService.request_parse():
- 1. 查 files 表获取 sha256(如果文件未注册,先同步注册)
+ 1. 查 files 表获取 sha256(如果文件未入库,先同步 ingest)
2. 查 parses WHERE sha256=? AND tier=? AND status='done'
3. 已有 done 批次的 pages 覆盖请求范围 → 直接返回缓存
- 4. 否则 → INSERT INTO parses (sha256, tier, pages, priority=1)
+ 4. 否则 → INSERT INTO parses (sha256, tier, pages, privacy=?, remote_url=?, priority=1)
5. --force 时 → DELETE FROM parses WHERE sha256=? AND tier=?,再 INSERT
→ ParseWorker.acquire_task()
- → process_doc():
- 1. 从 parses 读取 sha256、tier、pages
- 2. resolve_engine(tier) 确定 backend
- 3. 调用 mineru.parser.parse(path, tier=..., pages=...)
- 4. 写入解析产物到 ~/MinerU/parsed/{sha256[:2]}/{sha256}/{tier}/
- 5. INSERT OR REPLACE fts_contents(仅当新 tier ≥ 当前 tier;截断到 30K head+tail)
- 6. UPDATE parses SET status='done', done_at=?
- 7. UPDATE docs(引擎能拿到更好的 title/author/subject/keywords/lang/is_scanned 时覆盖)
- → 失败时: UPDATE parses SET status='failed', error_code=?, error_msg=?
```
-### 5.4 解析产物存储
+#### 5.3.2 ParseWorker 路由决策
+
+ParseWorker 取到 task 后,按 tier 和 privacy 决定执行路径:
+
+```
+ParseWorker.acquire_task()
+ → 从 parses 读取 sha256, tier, pages, privacy, remote_url
+ → route_parse(tier, privacy, remote_url):
+
+ ┌─ flash tier ──────────────────────────────────────────────┐
+ │ 直接调用 mineru.parser.parse(path, backend="flash", ...) │
+ │ → via = 'local' │
+ └────────────────────────────────────────────────────────────┘
+
+ ┌─ standard / pro tier ─────────────────────────────────────┐
+ │ │
+ │ privacy = 'remote' ? │
+ │ ├─ 是 → 目标: remote_url(默认 mineru.net) │
+ │ │ ParseServerHealthCheck 探活通过? │
+ │ │ ├─ 是 → POST {remote_url}/v1/parse/jobs │
+ │ │ │ via = 'remote' │
+ │ │ └─ 否 → fallback 到 local(见下) │
+ │ │ │
+ │ └─ 否 (privacy = 'local') → │
+ │ parse-server 配置? │
+ │ ├─ mode = disabled → 报错 no_engine │
+ │ ├─ mode = managed / self-hosted → │
+ │ │ ParseServerHealthCheck 探活通过? │
+ │ │ ├─ 是 → POST {parse-server-url}/v1/parse/jobs │
+ │ │ │ via = 'local' │
+ │ │ └─ 否 → 探活不可用,返回 engine_unavailable │
+ │ │ (可重试 error code,等待 server 就绪) │
+ └────────────────────────────────────────────────────────────┘
+
+ → 解析完成:
+ 1. 写入解析产物到 ~/MinerU/parsed/{sha256[:2]}/{sha256}/{tier}/
+ 2. INSERT OR REPLACE fts_contents(tier 门控)
+ 3. UPDATE parses SET status='done', done_at=?, via=?
+ 4. UPDATE docs(更高 tier 的 metadata 覆盖)
+ → 失败时:
+ - 可重试 error code → re-enqueue(保持 privacy,下次再走同一条路由)
+ - 不可重试 → UPDATE parses SET status='failed', error_code=?, error_msg=?
+```
+
+**关键设计点**:
+
+- **`--remote` 优先**:用户一旦指定 `--remote`,即优先使用远程,节省本地算力。远程不可用时 fallback 到本地
+- **privacy 不可变**:解析失败后 re-enqueue,保持原始 `privacy` 值不变。用户选择 remote 意味着接受文档上传,不会因重试改变立场
+- **`auto` tier 不可用时报错**:不静默降级,让用户做决定选择 flash 或 --remote
+- **缓存键**:`(sha256, tier)`,与 privacy/via 无关——同一 tier 不同来源产出解析结果一致
+- **remote 产物同样入库**:remote 解析完成后,middle_json 和 markdown 和本地解析一样写入 `~/MinerU/parsed/` 并更新 fts_contents
+
+### 5.4 parse-server 健康检查
+
+```
+ParseServerHealthCheck(asyncio task,每 60s 执行一次)
+ → 根据 config parse-server.* 决定检查哪些 server
+ → local parse-server(managed 或 self-hosted 模式):
+ GET {url}/v1/tiers
+ 成功 → 更新内存状态: local_healthy = true, supported_tiers = [...]
+ 失败 → 更新内存状态: local_healthy = false
+ → remote parse-server:
+ GET {remote_url}/v1/tiers(默认 mineru.net)
+ 成功 → 更新内存状态: remote_healthy = true, supported_tiers = [...]
+ 失败 → 更新内存状态: remote_healthy = false
+ → 状态通过 AppState 暴露给 ParseWorker 消费
+
+健康状态与 ParseWorker 路由联动:
+ - ParseWorker 取 task 时同步读内存健康状态
+ - 探活不可用 → 返回可重试 error code(parse_server_unavailable)
+ - 探活失败不关闭 server,不影响已 running 的解析
+```
+
+### 5.5 解析产物存储
```
~/MinerU/
@@ -499,7 +591,7 @@ Watch 检测到文件事件
每个 tier 独立目录,互不覆盖。
-### 5.5 搜索
+### 5.7 搜索
```
用户请求: mineru search "关键词"
→ SearchService.search():
@@ -510,7 +602,7 @@ Watch 检测到文件事件
5. 结果标注解析状态(flash / standard / pro)
```
-### 5.6 可插拔设备
+### 5.8 可插拔设备
```
DeviceMonitor 每 5 秒检测:
@@ -548,14 +640,24 @@ async def startup():
parse_svc = ParseService(db, fts, config_svc)
search_svc = SearchService(db, fts)
- # 5. 启动后台任务
+ # 5. 启动 parse-server(仅 managed 模式)
+ if config.parse_server.local.mode == "managed":
+ subprocess.Popen([
+ sys.executable, "-m", "mineru.parser.api_server",
+ "--tier", config.parse_server.local.managed_tier,
+ "--port", "15981",
+ ])
+
+ # 6. 启动后台任务
asyncio.create_task(watch_loop.run())
+ asyncio.create_task(parse_server_health_check.run())
for _ in range(2):
- asyncio.create_task(registration_worker.run())
+ asyncio.create_task(ingest_worker.run())
asyncio.create_task(parse_worker.run())
asyncio.create_task(device_monitor.run())
+ asyncio.create_task(compaction.run())
- # 6. 启动 uvicorn(UDS + 可选 TCP)
+ # 7. 启动 uvicorn(UDS + 可选 TCP)
await uvicorn_server.serve()
```
@@ -565,11 +667,18 @@ async def startup():
async def shutdown():
# 1. 停止所有后台任务(设置 stop event,等待当前任务完成)
await watch_loop.stop()
- await registration_worker_pool.stop()
+ await parse_server_health_check.stop()
+ await ingest_worker_pool.stop()
await parse_worker_pool.stop()
await device_monitor.stop()
+ await compaction.stop()
+
+ # 2. 停止 parse-server(仅 managed 模式)
+ if config.parse_server.local.mode == "managed" and parse_server_proc:
+ parse_server_proc.terminate()
+ parse_server_proc.wait(timeout=10)
- # 2. 关闭数据库连接
+ # 3. 关闭数据库连接
await db.close()
# 3. 删除 socket 文件
@@ -582,9 +691,9 @@ Server 启动时执行以下恢复操作:
| 操作 | 目的 |
|------|------|
-| `UPDATE files SET locked_at=NULL` | 释放因崩溃而未释放的注册锁 |
+| `UPDATE files SET locked_at=NULL` | 释放因崩溃而未释放的 ingest 锁 |
| `UPDATE parses SET locked_at=NULL, status='failed' WHERE status='parsing'` | 释放解析锁,标记为可重试 |
-| 检查已注册文件的活性(`os.path.exists`) | 标记已删除的文件 |
+| 检查已入库文件的活性(`os.path.exists`) | 标记已删除的文件 |
---
@@ -594,17 +703,53 @@ Server 启动时执行以下恢复操作:
所有配置存储在 SQLite `config` 表中(KV store),不使用外部配置文件。CLI 通过 `mineru config` 命令管理。
-### 7.2 配置项
+### 7.2 本地配置项
+
+这些配置项存储在 SQLite `config` 表中,由 `mineru config` 命令管理。
| key | 默认值 | 说明 |
|-----|--------|------|
| `data_dir` | `~/MinerU` | 数据目录根路径 |
| `default_tier` | `flash` | Watch 自动解析的默认 tier |
| `scan_interval_sec` | `300` | Watch 全量扫描间隔(秒) |
-| `reg_lock_timeout_sec` | `60` | 注册锁超时 |
+| `ingest_lock_timeout_sec` | `60` | ingest 锁超时 |
| `parse_lock_timeout_sec` | `1800` | 解析锁超时(30 分钟) |
-### 7.3 Watch 目录
+### 7.3 parse-server 配置
+
+parse-server 是独立的 HTTP 服务进程(`mineru-kit api-server`),提供 standard / pro tier 的解析能力。doclib 通过 HTTP 调用 parse-server 执行解析。
+
+config 表中的 parse-server 配置前缀为 `parse_server.*`:
+
+| key | 默认值 | 说明 |
+|-----|--------|------|
+| `parse_server.local.mode` | `disabled` | 本地 parse-server 模式:`disabled` / `managed` / `self_hosted` |
+| `parse_server.local.managed_tier` | `standard` | managed 模式下启动的 tier:`standard` / `pro` |
+| `parse_server.local.self_hosted_url` | — | self_hosted 模式下 parse-server 的 HTTP 地址 |
+| `parse_server.local.self_hosted_api_key` | — | self_hosted 模式下的 API Key(可选) |
+| `parse_server.remote.url` | `https://mineru.net/api` | 远程 parse-server 地址 |
+| `parse_server.remote.api_key` | — | 远程 API Key(从环境变量 `MINERU_API_KEY` 也可读取) |
+
+**`local.mode` 行为**:
+
+| mode | 行为 |
+|------|------|
+| `disabled` | 不使用本地 parse-server。`privacy=local` + standard/pro tier 请求直接报错 `no_engine` |
+| `managed` | doclib 启动时自动拉起 parse-server 进程,停止时一并关闭。生命周期由 doclib 管理 |
+| `self_hosted` | 用户自行启动和管理 parse-server。doclib 启动时不自动拉起,仅通过配置的 URL 连接探活 |
+
+**API Key 读取优先级**:环境变量 `MINERU_API_KEY` > config 中的 `remote.api_key` / `self_hosted_api_key`。
+
+CLI 命令:
+
+```bash
+mineru config parse-server local.mode managed
+mineru config parse-server local.managed-tier pro
+mineru config parse-server local.self_hosted_url http://10.0.1.5:8080
+mineru config parse-server remote.api-key sk-xxx
+```
+
+### 7.4 Watch 目录
通过 `watch_targets` 表管理,CLI 操作:
@@ -617,7 +762,7 @@ mineru config watch rm ~/Documents
约束:不允许嵌套、必须绝对路径。
-### 7.4 Parsing-Rules
+### 7.5 Parsing-Rules
通过 `rules` 表管理,使用 `fnmatch` glob 匹配:
@@ -630,7 +775,7 @@ mineru config parsing-rules rm <id>
规则命中时,系统检查是否具备对应 tier 的能力(本地引擎可用 或 规则包含 `--remote`)。不会因规则配置而静默上传文件到远端。
-### 7.5 排除规则
+### 7.6 排除规则
```bash
mineru config exclude add "*.tmp"
@@ -714,6 +859,16 @@ flash 的首尾各 5 页文本通常在 30K 限制内,不会触发截断。sta
| File 级 | 路径不存在、权限不足 | `files.error_code` | 清除 sha256,可重试 |
| Doc 级 | 文件损坏、加密 | `files.error_code` | 不自动重试 |
| Parse 级 | 引擎崩溃、超时、OOM | `parses.error_code` | 标记 `status='failed'`,可重试 |
+| Parse-server 级 | parse-server 不可用、探活失败 | `parses.error_code` = `parse_server_unavailable` | 可重试(等待 server 就绪或用户启动),保留 `privacy` 不变 |
+
+**parse-server 相关错误码**:
+
+| code | 触发场景 | 可重试 |
+|------|---------|:--:|
+| `no_engine` | `privacy=local` + parse-server `disabled` + tier 非 flash | 否 |
+| `engine_unavailable` | parse-server 已配置但探活不可用 | 是 |
+| `parse_server_unavailable` | `privacy=remote` 远程不可用,且 local fallback 也不可用 | 是 |
+| `parse_failed` | parse-server 返回解析失败 | 否 |
---
diff --git a/NEXT-SDK.md b/NEXT-SDK.md
index c74ae761..33ff4295 100644
--- a/NEXT-SDK.md
+++ b/NEXT-SDK.md
@@ -36,10 +36,10 @@ mineru/
│ ├── types.py # PageInfo, Block, Line, Span
│ └── api_server.py # mineru-kit api-server(无状态 HTTP 解析服务,兼容 SaaS API 格式)
│
-├── server/ # [填充现有空目录] 本地 Server
+├── doclib/ # 本地文档库(原 server/)
│ ├── __init__.py
-│ ├── app.py # FastAPI app factory, lifecycle
-│ ├── config.py # Server 配置(UDS 路径、端口、SQLite 路径等)
+│ ├── server.py # FastAPI app factory, lifecycle
+│ ├── config.py # doclib 配置(UDS 路径、端口、SQLite 路径等)
│ ├── routes/ # HTTP 路由
│ │ ├── parse.py
│ │ ├── search.py
@@ -89,14 +89,19 @@ mineru/
## 3. 依赖方向
```
-cli_next/mineru_cmd → client → server/ → parser/ → backend/
+cli_next/mineru_cmd → client → doclib/ → parser/ → backend/
+ │
+ ├── flash tier: 直接调用
+ └── standard/pro tier: HTTP 调用
+ ├─ mineru-kit api-server (本地)
+ └─ mineru.net/api (远程)
cli_next/kit_cmd → parser/ → backend/
mineru-kit api-server → parser/api_server.py → parser/ → backend/
```
-- `mineru-kit` 只依赖 `parser/`,不碰 `client` 和 `server/`
-- `mineru` 通过 `client` 与 server 通信,server 内部调用 `parser/` 做实际解析
-- `parser/api_server.py` 是无状态 HTTP 解析服务(`mineru-kit api-server`),与 `server/` 完全独立
+- `mineru-kit` 只依赖 `parser/`,不碰 `client` 和 `doclib/`
+- `mineru` 通过 `client` 与 doclib 通信,doclib 内部调用 `parser/` 做 flash 解析,或通过 HTTP 调用 parse-server 做 standard/pro 解析
+- `parser/api_server.py` 是无状态 HTTP 解析服务(`mineru-kit api-server`),与 `doclib/` 完全独立。它实现 NEXT-API.md 的 Files/Uploads/Jobs 端点,被 doclib 的 ParseWorker 通过 HTTP 调用
- `errors.py`、`constants.py`、`types.py` 是共享基础模块,被各层引用
---
@@ -108,10 +113,10 @@ mineru-kit api-server → parser/api_server.py → parser/ → backend/
| `mineru/api/` | `mineru/parser/` | 重构接口签名(加入 tier),保留解析逻辑 |
| `mineru/api/api_parser.py` | `mineru/parser/remote.py` | MinerUApiParser 移入,改用新 API 格式 |
| `mineru/cli/` (click) | `mineru/cli_next/` (typer) | 新写,迁移完成后 cli/ 删除、cli_next/ 改名 cli/ |
-| `mineru/cli/fast_api.py` | 删除 | 被 `server/` 替代 |
+| `mineru/cli/fast_api.py` | 删除 | 被 `doclib/` 替代 |
| `mineru/parse_server.py` | `mineru/parser/api_server.py` | 移入 parser 包,属于 mineru-kit api-server |
-| `mineru/server/` (空) | 填充实现 | — |
-| `mineru/config.py` | `mineru/server/config.py` | 移入 server |
+| `mineru/doclib/` (原 server/) | 已实现 | — |
+| `mineru/config.py` | `mineru/doclib/config.py` | 移入 doclib |
---
diff --git a/mineru/cli_next/commands/cleanup.py b/mineru/cli_next/commands/cleanup.py
index a2af54b4..698b24bb 100644
--- a/mineru/cli_next/commands/cleanup.py
+++ b/mineru/cli_next/commands/cleanup.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import typer
-from mineru.server.client import MineruClient
+from mineru.doclib.client import MineruClient
from mineru.cli_next.output import print_error, print_success, print_info
diff --git a/mineru/cli_next/commands/config.py b/mineru/cli_next/commands/config.py
index 71ac06ad..4dfc536e 100644
--- a/mineru/cli_next/commands/config.py
+++ b/mineru/cli_next/commands/config.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import typer
-from mineru.server.client import MineruClient
+from mineru.doclib.client import MineruClient
from mineru.cli_next.output import print_error, print_success, print_info, print_json
app = typer.Typer(help="Configuration management", no_args_is_help=True)
diff --git a/mineru/cli_next/commands/parse.py b/mineru/cli_next/commands/parse.py
index a058a055..63e6694c 100644
--- a/mineru/cli_next/commands/parse.py
+++ b/mineru/cli_next/commands/parse.py
@@ -8,7 +8,7 @@ from pathlib import Path
import typer
-from mineru.server.client import MineruClient
+from mineru.doclib.client import MineruClient
from mineru.cli_next.output import format_parse_result, print_error, print_success, print_info
diff --git a/mineru/cli_next/commands/search.py b/mineru/cli_next/commands/search.py
index 24299b16..5e85e621 100644
--- a/mineru/cli_next/commands/search.py
+++ b/mineru/cli_next/commands/search.py
@@ -4,7 +4,7 @@ from __future__ import annotations
import typer
-from mineru.server.client import MineruClient
+from mineru.doclib.client import MineruClient
from mineru.cli_next.output import format_search_results, format_info, print_error
diff --git a/mineru/cli_next/commands/server.py b/mineru/cli_next/commands/server.py
index d59580d8..157f1ddb 100644
--- a/mineru/cli_next/commands/server.py
+++ b/mineru/cli_next/commands/server.py
@@ -19,7 +19,7 @@ def _server_running() -> bool:
if not os.path.exists(SOCKET_PATH):
return False
try:
- from mineru.server.client import MineruClient
+ from mineru.doclib.client import MineruClient
c = MineruClient(timeout=3)
c.server_status()
return True
@@ -52,7 +52,7 @@ def start() -> None:
pass
proc = subprocess.Popen(
- [sys.executable, "-m", "mineru.server.app"],
+ [sys.executable, "-m", "mineru.doclib.server"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
@@ -73,7 +73,7 @@ def stop() -> None:
return
try:
- from mineru.server.client import MineruClient
+ from mineru.doclib.client import MineruClient
c = MineruClient(timeout=5)
c.shutdown()
except Exception:
@@ -105,7 +105,7 @@ def status() -> None:
return
try:
- from mineru.server.client import MineruClient
+ from mineru.doclib.client import MineruClient
c = MineruClient(timeout=5)
data = c.server_status()
format_server_status(data)
diff --git a/mineru/cli_next/output.py b/mineru/cli_next/output.py
index 400fb759..b53d8d10 100644
--- a/mineru/cli_next/output.py
+++ b/mineru/cli_next/output.py
@@ -118,7 +118,7 @@ def format_server_status(data: dict, json_mode: bool = False) -> None:
table.add_row("Files tracked", str(data.get("files_total", 0)))
table.add_row("Docs indexed", str(data.get("docs_total", 0)))
table.add_row("Parse queue", str(data.get("parse_queue_length", 0)))
- table.add_row("Reg queue", str(data.get("reg_queue_length", 0)))
+ table.add_row("Ingest queue", str(data.get("ingest_queue_length", 0)))
table.add_row("Watches", str(data.get("watch_count", 0)))
console.print(table)
else:
diff --git a/mineru/doclib/__init__.py b/mineru/doclib/__init__.py
new file mode 100644
index 00000000..72084c98
--- /dev/null
+++ b/mineru/doclib/__init__.py
@@ -0,0 +1 @@
+# The local mineru document library.
diff --git a/mineru/server/background/compaction.py b/mineru/doclib/background/compaction.py
similarity index 91%
rename from mineru/server/background/compaction.py
rename to mineru/doclib/background/compaction.py
index 12d28edf..a9af008e 100644
--- a/mineru/server/background/compaction.py
+++ b/mineru/doclib/background/compaction.py
@@ -9,13 +9,14 @@ import os
import time
from mineru.constants import DATA_DIR
+from ..core.db import DatabaseManager
from ..services.parse_svc import parse_range_set
logger = logging.getLogger("mineru.compaction")
class Compaction:
- def __init__(self, db, interval_sec: int = 600) -> None:
+ def __init__(self, db: DatabaseManager, interval_sec: int = 600) -> None:
self.db = db
self.interval_sec = interval_sec
self.running = False
@@ -101,7 +102,9 @@ class Compaction:
return len(rows) - len(merged_ranges)
- async def _compact_json(self, sha256: str, tier: str, merged_ranges: list[str]) -> None:
+ async def _compact_json(
+ self, sha256: str, tier: str, merged_ranges: list[str]
+ ) -> None:
"""Merge per-batch middle_*.json files to match compacted parses rows."""
data_dir = os.path.expanduser(DATA_DIR)
tier_dir = os.path.join(data_dir, "parsed", sha256[:2], sha256, tier)
@@ -134,13 +137,17 @@ class Compaction:
# write one compacted JSON per merged range
for pages_str in merged_ranges:
page_set = parse_range_set(pages_str)
- json_pages = [pages_by_idx[i] for i in sorted(page_set) if i in pages_by_idx]
+ json_pages = [
+ pages_by_idx[i] for i in sorted(page_set) if i in pages_by_idx
+ ]
if not json_pages:
continue
json_path = os.path.join(tier_dir, f"{_safe_filename(pages_str)}.json")
try:
with open(json_path, "w", encoding="utf-8") as f:
- _json.dump({"pdf_info": json_pages}, f, ensure_ascii=False, indent=2)
+ _json.dump(
+ {"pdf_info": json_pages}, f, ensure_ascii=False, indent=2
+ )
except Exception:
pass
diff --git a/mineru/server/background/device_monitor.py b/mineru/doclib/background/device_monitor.py
similarity index 90%
rename from mineru/server/background/device_monitor.py
rename to mineru/doclib/background/device_monitor.py
index 5ffb8bef..886dd4c4 100644
--- a/mineru/server/background/device_monitor.py
+++ b/mineru/doclib/background/device_monitor.py
@@ -4,11 +4,13 @@ from __future__ import annotations
import asyncio
import os
-import time
+
+from ..core.db import DatabaseManager
+from ..services.config_svc import ConfigService
class DeviceMonitor:
- def __init__(self, db, config_svc) -> None:
+ def __init__(self, db: DatabaseManager, config_svc: ConfigService) -> None:
self.db = db
self.config_svc = config_svc
self.running = False
@@ -23,7 +25,6 @@ class DeviceMonitor:
try:
os.stat(w["path"])
except (FileNotFoundError, OSError):
- now = int(time.time() * 1000)
await self.config_svc.update_watch_status(w["id"], "unreachable")
await self.db.execute(
"UPDATE files SET scan_status='unreachable' "
diff --git a/mineru/server/background/reg_worker.py b/mineru/doclib/background/ingest.py
similarity index 64%
rename from mineru/server/background/reg_worker.py
rename to mineru/doclib/background/ingest.py
index d412661b..928f0792 100644
--- a/mineru/server/background/reg_worker.py
+++ b/mineru/doclib/background/ingest.py
@@ -1,4 +1,4 @@
-"""Registration worker pool — picks up unregistered files and runs register_file()."""
+"""Ingest worker pool — picks up files not yet ingested and runs ingest_file()."""
from __future__ import annotations
@@ -6,11 +6,13 @@ import asyncio
import logging
import time
-logger = logging.getLogger("mineru.reg_worker")
+from ..services.parse_svc import ParseService
+logger = logging.getLogger("mineru.ingest")
-class RegistrationWorkerPool:
- def __init__(self, parse_svc, num_workers: int = 2) -> None:
+
+class IngestWorkerPool:
+ def __init__(self, parse_svc: ParseService, num_workers: int = 2) -> None:
self.parse_svc = parse_svc
self.num_workers = num_workers
self.running = False
@@ -18,10 +20,12 @@ class RegistrationWorkerPool:
async def run(self) -> None:
self.running = True
- self._tasks = [asyncio.create_task(self._worker(i)) for i in range(self.num_workers)]
+ self._tasks = [
+ asyncio.create_task(self._worker(i)) for i in range(self.num_workers)
+ ]
async def _worker(self, worker_id: int) -> None:
- logger.info(f"Reg worker {worker_id} started")
+ logger.info(f"Ingest worker {worker_id} started")
processed = 0
no_task_count = 0
@@ -33,33 +37,37 @@ class RegistrationWorkerPool:
q = await self.parse_svc.db.fetchone(
"SELECT COUNT(*) as cnt FROM files WHERE sha256 IS NULL AND scan_status='active'"
)
- logger.info(f"Reg worker {worker_id}: queue={q['cnt'] if q else 0}")
+ logger.info(f"Ingest worker {worker_id}: queue={q['cnt'] if q else 0}")
await asyncio.sleep(0.5)
continue
no_task_count = 0
try:
- await self.parse_svc.register_file(task["path"], watch_id=task.get("watch_id"))
+ await self.parse_svc.ingest_file(
+ task["path"], watch_id=task.get("watch_id")
+ )
processed += 1
if processed % 100 == 0:
- logger.info(f"Reg worker {worker_id} registered {processed} files")
+ logger.info(f"Ingest worker {worker_id} ingested {processed} files")
except Exception as exc:
- logger.error(f"Reg worker {worker_id} error on {task.get('path')}: {exc}")
+ logger.error(
+ f"Ingest worker {worker_id} error on {task.get('path')}: {exc}"
+ )
try:
now = int(time.time() * 1000)
await self.parse_svc.db.execute(
"UPDATE files SET sha256=NULL, locked_at=NULL, error_code=?, error_msg=?, "
"updated_at=? WHERE id=?",
- ("reg_failed", str(exc)[:500], now, task["id"]),
+ ("ingest_failed", str(exc)[:500], now, task["id"]),
)
except Exception:
pass
- logger.info(f"Reg worker {worker_id} stopped, processed {processed} total")
+ logger.info(f"Ingest worker {worker_id} stopped, processed {processed} total")
async def _acquire_task(self) -> dict | None:
now = int(time.time() * 1000)
- timeout = now - 60 * 1000 # 60s reg lock timeout
+ timeout = now - 60 * 1000 # 60s ingest lock timeout
return await self.parse_svc.db.fetchone(
"UPDATE files SET locked_at=? "
"WHERE id = ("
diff --git a/mineru/server/background/parse_worker.py b/mineru/doclib/background/parse_worker.py
similarity index 79%
rename from mineru/server/background/parse_worker.py
rename to mineru/doclib/background/parse_worker.py
index 08c892ca..334be9a6 100644
--- a/mineru/server/background/parse_worker.py
+++ b/mineru/doclib/background/parse_worker.py
@@ -6,11 +6,13 @@ import asyncio
import logging
import time
+from ..services.parse_svc import ParseService
+
logger = logging.getLogger("mineru.parse_worker")
class ParseWorkerPool:
- def __init__(self, parse_svc, num_workers: int = 2) -> None:
+ def __init__(self, parse_svc: ParseService, num_workers: int = 2) -> None:
self.parse_svc = parse_svc
self.num_workers = num_workers
self.running = False
@@ -18,7 +20,9 @@ class ParseWorkerPool:
async def run(self) -> None:
self.running = True
- self._tasks = [asyncio.create_task(self._worker(i)) for i in range(self.num_workers)]
+ self._tasks = [
+ asyncio.create_task(self._worker(i)) for i in range(self.num_workers)
+ ]
async def _worker(self, worker_id: int) -> None:
logger.info(f"Parse worker {worker_id} started")
@@ -41,9 +45,13 @@ class ParseWorkerPool:
if success:
processed += 1
if processed % 50 == 0:
- logger.info(f"Parse worker {worker_id} processed {processed} batches")
+ logger.info(
+ f"Parse worker {worker_id} processed {processed} batches"
+ )
except Exception as exc:
- logger.error(f"Parse worker {worker_id} error on {task.get('sha256')}: {exc}")
+ logger.error(
+ f"Parse worker {worker_id} error on {task.get('sha256')}: {exc}"
+ )
try:
now = int(time.time() * 1000)
await self.parse_svc.db.execute(
diff --git a/mineru/server/background/watch.py b/mineru/doclib/background/watch.py
similarity index 93%
rename from mineru/server/background/watch.py
rename to mineru/doclib/background/watch.py
index 132bb6a6..602b4757 100644
--- a/mineru/server/background/watch.py
+++ b/mineru/doclib/background/watch.py
@@ -11,9 +11,15 @@ from watchfiles import awatch
from mineru.constants import ALLOWED_EXTENSIONS
+from ..core.db import DatabaseManager
+from ..services.config_svc import ConfigService
+from ..services.parse_svc import ParseService
+
class WatchLoop:
- def __init__(self, db, config_svc, parse_svc) -> None:
+ def __init__(
+ self, db: DatabaseManager, config_svc: ConfigService, parse_svc: ParseService
+ ) -> None:
self.db = db
self.config_svc = config_svc
self.parse_svc = parse_svc
diff --git a/mineru/server/client.py b/mineru/doclib/client.py
similarity index 69%
rename from mineru/server/client.py
rename to mineru/doclib/client.py
index 1aec9993..fdfaa600 100644
--- a/mineru/server/client.py
+++ b/mineru/doclib/client.py
@@ -1,26 +1,30 @@
-"""Product SDK — communicates with the local mineru server over UDS."""
+"""Product SDK — communicates with the local mineru doclib over UDS."""
from __future__ import annotations
+from typing import Any
+
import httpx
from mineru.constants import SOCKET_PATH
-from mineru.errors import MineruError, ServerNotRunningError, error_type_for
+from mineru.errors import MineruError, ServerNotRunningError
class MineruClient:
- """httpx-based client for the local mineru server."""
+ """httpx-based client for the local mineru doclib."""
def __init__(self, socket_path: str = SOCKET_PATH, timeout: int = 60) -> None:
transport = httpx.HTTPTransport(uds=socket_path)
- self._client = httpx.Client(transport=transport, base_url="http://mineru", timeout=timeout)
+ self._client = httpx.Client(
+ transport=transport, base_url="http://mineru", timeout=timeout
+ )
def close(self) -> None:
self._client.close()
# ── helpers ────────────────────────────────────────────────
- def _get(self, url_path: str, **params) -> dict:
+ def _get(self, url_path: str, **params: Any) -> dict:
data = self._request("GET", url_path, query_params=params or None)
return data
@@ -28,13 +32,17 @@ class MineruClient:
data = self._request("POST", url_path, json_data=json_data)
return data
- def _delete(self, url_path: str, **params) -> dict:
+ def _delete(self, url_path: str, **params: Any) -> dict:
data = self._request("DELETE", url_path, query_params=params or None)
return data
- def _request(self, method: str, url_path: str,
- query_params: dict | None = None,
- json_data: dict | None = None) -> dict:
+ def _request(
+ self,
+ method: str,
+ url_path: str,
+ query_params: dict | None = None,
+ json_data: dict | None = None,
+ ) -> dict:
try:
if method == "GET":
resp = self._client.get(url_path, params=query_params or {})
@@ -64,11 +72,23 @@ class MineruClient:
# ── parse ──────────────────────────────────────────────────
- def parse(self, path: str, *, tier: str | None = None,
- pages: str | None = None, force: bool = False) -> dict:
- return self._post("/parse", {
- "path": path, "tier": tier, "pages": pages, "force": force,
- })
+ def parse(
+ self,
+ path: str,
+ *,
+ tier: str | None = None,
+ pages: str | None = None,
+ force: bool = False,
+ ) -> dict:
+ return self._post(
+ "/parse",
+ {
+ "path": path,
+ "tier": tier,
+ "pages": pages,
+ "force": force,
+ },
+ )
def parse_status(self, sha256: str, tier: str) -> dict:
return self._get("/parse/status", sha256=sha256, tier=tier)
@@ -81,8 +101,9 @@ class MineruClient:
# ── search ─────────────────────────────────────────────────
- def search(self, query: str, file_type: str | None = None,
- limit: int = 20, offset: int = 0) -> dict:
+ def search(
+ self, query: str, file_type: str | None = None, limit: int = 20, offset: int = 0
+ ) -> dict:
return self._get("/search", q=query, type=file_type, limit=limit, offset=offset)
def find(self, query: str, limit: int = 50) -> dict:
@@ -98,9 +119,12 @@ class MineruClient:
def config_show(self) -> dict:
return self._get("/config")
- def config_watch_add(self, path: str, *, removable: bool = False,
- label: str | None = None) -> dict:
- return self._post("/config/watch", {"path": path, "removable": removable, "label": label})
+ def config_watch_add(
+ self, path: str, *, removable: bool = False, label: str | None = None
+ ) -> dict:
+ return self._post(
+ "/config/watch", {"path": path, "removable": removable, "label": label}
+ )
def config_watch_list(self) -> dict:
return self._get("/config/watch")
@@ -117,12 +141,25 @@ class MineruClient:
def config_exclude_rm(self, rule_id: int) -> dict:
return self._delete(f"/config/exclude/{rule_id}")
- def config_parsing_rules_add(self, pattern: str, *, tier: str | None = None,
- pages: str | None = None, remote: bool = False,
- name: str | None = None) -> dict:
- return self._post("/config/parsing-rules", {
- "pattern": pattern, "tier": tier, "pages": pages, "remote": remote, "name": name,
- })
+ def config_parsing_rules_add(
+ self,
+ pattern: str,
+ *,
+ tier: str | None = None,
+ pages: str | None = None,
+ remote: bool = False,
+ name: str | None = None,
+ ) -> dict:
+ return self._post(
+ "/config/parsing-rules",
+ {
+ "pattern": pattern,
+ "tier": tier,
+ "pages": pages,
+ "remote": remote,
+ "name": name,
+ },
+ )
def config_parsing_rules_list(self) -> dict:
return self._get("/config/parsing-rules")
diff --git a/mineru/server/config.py b/mineru/doclib/config.py
similarity index 98%
rename from mineru/server/config.py
rename to mineru/doclib/config.py
index d45b5304..6c157d4a 100644
--- a/mineru/server/config.py
+++ b/mineru/doclib/config.py
@@ -65,7 +65,7 @@ class ServerConfig(BaseModel):
http: HTTPConfig = HTTPConfig()
log: LogConfig = LogConfig()
data_dir: str = _default_data_path()
- reg_workers: int = 2
+ ingest_workers: int = 2
parse_workers: int = 2
compaction_interval_sec: int = 3600
diff --git a/mineru/server/core/db.py b/mineru/doclib/core/db.py
similarity index 98%
rename from mineru/server/core/db.py
rename to mineru/doclib/core/db.py
index fc9955a1..63e5ff6b 100644
--- a/mineru/server/core/db.py
+++ b/mineru/doclib/core/db.py
@@ -5,6 +5,8 @@ import time
import aiosqlite
+from ..config import SQLiteConfig
+
SCHEMA_VERSION = 1
CREATE_TABLES_SQL = [
@@ -32,7 +34,6 @@ CREATE_TABLES_SQL = [
"CREATE INDEX IF NOT EXISTS idx_files_sha256 ON files(sha256);",
"CREATE INDEX IF NOT EXISTS idx_files_watch_id ON files(watch_id);",
"CREATE INDEX IF NOT EXISTS idx_files_scan_status ON files(scan_status);",
-
# ── docs ───────────────────────────────────────────────────────
"""
CREATE TABLE IF NOT EXISTS docs (
@@ -52,7 +53,6 @@ CREATE_TABLES_SQL = [
updated_at INTEGER NOT NULL
);
""",
-
# ── parses ─────────────────────────────────────────────────────
"""
CREATE TABLE IF NOT EXISTS parses (
@@ -73,7 +73,6 @@ CREATE_TABLES_SQL = [
""",
"CREATE INDEX IF NOT EXISTS idx_parses_status ON parses(status, priority DESC, created_at ASC);",
"CREATE INDEX IF NOT EXISTS idx_parses_doc ON parses(sha256, tier);",
-
# ── fts_contents ───────────────────────────────────────────────
"""
CREATE VIRTUAL TABLE IF NOT EXISTS fts_contents USING fts5(
@@ -86,7 +85,6 @@ CREATE_TABLES_SQL = [
tokenize='unicode61'
);
""",
-
# ── fts_filenames ──────────────────────────────────────────────
"""
CREATE VIRTUAL TABLE IF NOT EXISTS fts_filenames USING fts5(
@@ -96,7 +94,6 @@ CREATE_TABLES_SQL = [
tokenize='unicode61'
);
""",
-
# ── watch_targets ──────────────────────────────────────────────
"""
CREATE TABLE IF NOT EXISTS watch_targets (
@@ -112,7 +109,6 @@ CREATE_TABLES_SQL = [
last_scan_files INTEGER DEFAULT 0
);
""",
-
# ── rules ──────────────────────────────────────────────────────
"""
CREATE TABLE IF NOT EXISTS rules (
@@ -128,7 +124,6 @@ CREATE_TABLES_SQL = [
hit_count INTEGER NOT NULL DEFAULT 0
);
""",
-
# ── config ─────────────────────────────────────────────────────
"""
CREATE TABLE IF NOT EXISTS config (
@@ -136,7 +131,6 @@ CREATE_TABLES_SQL = [
value TEXT NOT NULL
);
""",
-
# ── _migrations ────────────────────────────────────────────────
"""
CREATE TABLE IF NOT EXISTS _migrations (
@@ -151,7 +145,7 @@ DEFAULT_CONFIG = {
"data_dir": "~/MinerU",
"default_tier": "flash",
"scan_interval_sec": "300",
- "reg_lock_timeout_sec": "60",
+ "ingest_lock_timeout_sec": "60",
"parse_lock_timeout_sec": "1800",
"device_check_interval_sec": "5",
}
@@ -176,7 +170,7 @@ DEFAULT_EXCLUDE_RULES = [
class DatabaseManager:
"""Per-operation connection manager — no pooling, no shared state."""
- def __init__(self, db_path: str, sqlite_cfg=None) -> None:
+ def __init__(self, db_path: str, sqlite_cfg: SQLiteConfig | None = None) -> None:
self.db_path = db_path
self.sqlite_cfg = sqlite_cfg # SQLiteConfig or None
@@ -305,6 +299,7 @@ class DatabaseManager:
# ── helpers ────────────────────────────────────────────────────────
+
def _now_ms() -> int:
return int(time.time() * 1000)
diff --git a/mineru/server/core/file_io.py b/mineru/doclib/core/file_io.py
similarity index 97%
rename from mineru/server/core/file_io.py
rename to mineru/doclib/core/file_io.py
index 40df5f99..41cbc244 100644
--- a/mineru/server/core/file_io.py
+++ b/mineru/doclib/core/file_io.py
@@ -32,6 +32,7 @@ TRUNC_KEYWORDS = 1000
# ── SHA-256 ────────────────────────────────────────────────────────
+
def _sha256_sync(filepath: str) -> str:
h = hashlib.sha256()
with open(filepath, "rb") as f:
@@ -46,13 +47,16 @@ async def compute_sha256(filepath: str) -> str:
# ── file stat ──────────────────────────────────────────────────────
+
async def get_file_stat(filepath: str) -> dict:
def _stat() -> dict:
st = os.stat(filepath)
return {
"size_bytes": st.st_size,
"mtime_ms": int(st.st_mtime * 1000),
- "birthtime_ms": int(st.st_birthtime * 1000) if hasattr(st, "st_birthtime") else int(st.st_ctime * 1000),
+ "birthtime_ms": int(st.st_birthtime * 1000)
+ if hasattr(st, "st_birthtime")
+ else int(st.st_ctime * 1000),
}
return await asyncio.to_thread(_stat)
@@ -60,6 +64,7 @@ async def get_file_stat(filepath: str) -> dict:
# ── metadata extraction ────────────────────────────────────────────
+
async def extract_metadata(filepath: str) -> dict:
"""Extract metadata from file. Returns dict with keys matching docs table columns.
All string fields are protectively truncated."""
@@ -98,6 +103,7 @@ async def extract_metadata(filepath: str) -> dict:
# ── PDF metadata ───────────────────────────────────────────────────
+
async def _extract_pdf_meta(filepath: str, result: dict) -> None:
def _extract() -> None:
pdf = pypdfium2.PdfDocument(filepath)
@@ -120,6 +126,7 @@ async def _extract_pdf_meta(filepath: str, result: dict) -> None:
# ── Office metadata ────────────────────────────────────────────────
+
async def _extract_office_meta(filepath: str, ext: str, result: dict) -> None:
def _extract() -> None:
if ext == "docx":
diff --git a/mineru/server/core/fts.py b/mineru/doclib/core/fts.py
similarity index 79%
rename from mineru/server/core/fts.py
rename to mineru/doclib/core/fts.py
index 0c337f8e..0a5b3030 100644
--- a/mineru/server/core/fts.py
+++ b/mineru/doclib/core/fts.py
@@ -7,6 +7,8 @@ try:
except ImportError:
jieba = None # type: ignore[assignment]
+from .db import DatabaseManager
+
FTS_SEP = ""
@@ -36,24 +38,34 @@ def strip_sep(text: str) -> str:
class FTSManager:
- def __init__(self, db) -> None:
+ def __init__(self, db: DatabaseManager) -> None:
self.db = db
# ── fts_contents ────────────────────────────────────────────
- async def replace(self, *, sha256: str, tier: str, text: str,
- title: str, author: str, filename: str) -> None:
+ async def replace(
+ self,
+ *,
+ sha256: str,
+ tier: str,
+ text: str,
+ title: str,
+ author: str,
+ filename: str,
+ ) -> None:
"""Insert or replace content for a doc. Caller is responsible
for tier-gating (only call if new tier >= current)."""
tokenized = tokenize_for_index(text)
- await self.db.execute_atomic([
- ("DELETE FROM fts_contents WHERE sha256=?", (sha256,)),
- (
- "INSERT INTO fts_contents (sha256, tier, text, title, author, filename) "
- "VALUES (?, ?, ?, ?, ?, ?)",
- (sha256, tier, tokenized, title or "", author or "", filename),
- ),
- ])
+ await self.db.execute_atomic(
+ [
+ ("DELETE FROM fts_contents WHERE sha256=?", (sha256,)),
+ (
+ "INSERT INTO fts_contents (sha256, tier, text, title, author, filename) "
+ "VALUES (?, ?, ?, ?, ?, ?)",
+ (sha256, tier, tokenized, title or "", author or "", filename),
+ ),
+ ]
+ )
async def search(self, query: str, limit: int = 200) -> list[dict]:
tokens = _sanitize_query_tokens(tokenize_for_query(query))
@@ -83,13 +95,15 @@ class FTSManager:
# ── fts_filenames ────────────────────────────────────────────
async def upsert_filename(self, file_id: int, filename: str, ext: str) -> None:
- await self.db.execute_atomic([
- ("DELETE FROM fts_filenames WHERE file_id=?", (file_id,)),
- (
- "INSERT INTO fts_filenames (file_id, filename, ext) VALUES (?, ?, ?)",
- (file_id, tokenize_for_index(filename), ext),
- ),
- ])
+ await self.db.execute_atomic(
+ [
+ ("DELETE FROM fts_filenames WHERE file_id=?", (file_id,)),
+ (
+ "INSERT INTO fts_filenames (file_id, filename, ext) VALUES (?, ?, ?)",
+ (file_id, tokenize_for_index(filename), ext),
+ ),
+ ]
+ )
async def search_filenames(self, query: str, limit: int = 50) -> list[dict]:
tokens = _sanitize_query_tokens(tokenize_for_query(query))
@@ -113,6 +127,7 @@ class FTSManager:
# ── helpers ────────────────────────────────────────────────────────
+
def _sanitize_query_tokens(tokenized: str) -> list[str]:
"""Remove special characters and FTS5 operators from query tokens."""
safe: list[str] = []
diff --git a/mineru/server/routes/cleanup.py b/mineru/doclib/routes/cleanup.py
similarity index 90%
rename from mineru/server/routes/cleanup.py
rename to mineru/doclib/routes/cleanup.py
index de0d5a0d..03c585a6 100644
--- a/mineru/server/routes/cleanup.py
+++ b/mineru/doclib/routes/cleanup.py
@@ -12,10 +12,11 @@ async def cleanup_deleted(
request: Request,
older_than_days: int = Query(30, ge=1),
dry_run: bool = Query(True),
-):
+) -> dict:
state = request.state.app
count = await state.cleanup_svc.cleanup_deleted(
- older_than_days=older_than_days, dry_run=dry_run,
+ older_than_days=older_than_days,
+ dry_run=dry_run,
)
return {"deleted_files": count, "dry_run": dry_run}
@@ -24,7 +25,7 @@ async def cleanup_deleted(
async def cleanup_orphans(
request: Request,
dry_run: bool = Query(True),
-):
+) -> dict:
state = request.state.app
count = await state.cleanup_svc.cleanup_orphans(dry_run=dry_run)
return {"orphan_docs": count, "dry_run": dry_run}
@@ -34,7 +35,7 @@ async def cleanup_orphans(
async def cleanup_temp(
request: Request,
older_than_days: int = Query(7, ge=1),
-):
+) -> dict:
state = request.state.app
count = await state.cleanup_svc.cleanup_temp_files(older_than_days=older_than_days)
return {"temp_files_removed": count}
diff --git a/mineru/server/routes/config.py b/mineru/doclib/routes/config.py
similarity index 75%
rename from mineru/server/routes/config.py
rename to mineru/doclib/routes/config.py
index 7ba29f5d..28480af8 100644
--- a/mineru/server/routes/config.py
+++ b/mineru/doclib/routes/config.py
@@ -26,8 +26,9 @@ router = APIRouter(tags=["config"])
# ── global config ────────────────────────────────────────────────
+
@router.get("/config")
-async def get_config(request: Request):
+async def get_config(request: Request) -> dict:
state = request.state.app
cfg = await state.config_svc.get_all()
watches = await state.config_svc.list_watches()
@@ -37,24 +38,27 @@ async def get_config(request: Request):
# ── watch ────────────────────────────────────────────────────────
+
@router.get("/config/watch")
-async def list_watches(request: Request):
+async def list_watches(request: Request) -> dict:
state = request.state.app
watches = await state.config_svc.list_watches()
return {"watches": watches}
@router.post("/config/watch")
-async def add_watch(req: WatchRequest, request: Request):
+async def add_watch(req: WatchRequest, request: Request) -> dict:
state = request.state.app
w = await state.config_svc.add_watch(
- req.path, removable=req.removable, label=req.label,
+ req.path,
+ removable=req.removable,
+ label=req.label,
)
return w
@router.delete("/config/watch")
-async def remove_watch(request: Request, path: str = Query(...)):
+async def remove_watch(request: Request, path: str = Query(...)) -> dict:
state = request.state.app
await state.config_svc.remove_watch(path)
return {"message": f"Watch removed: {path}"}
@@ -62,24 +66,28 @@ async def remove_watch(request: Request, path: str = Query(...)):
# ── exclude ──────────────────────────────────────────────────────
+
@router.get("/config/exclude")
-async def list_excludes(request: Request):
+async def list_excludes(request: Request) -> dict:
state = request.state.app
rules = await state.config_svc.list_rules("exclude")
return {"rules": rules}
@router.post("/config/exclude")
-async def add_exclude(req: RuleRequest, request: Request):
+async def add_exclude(req: RuleRequest, request: Request) -> dict:
state = request.state.app
rid = await state.config_svc.add_rule(
- req.name or "用户规则", "exclude", req.pattern, priority=req.priority,
+ req.name or "用户规则",
+ "exclude",
+ req.pattern,
+ priority=req.priority,
)
return {"id": rid}
@router.delete("/config/exclude/{rule_id}")
-async def remove_exclude(rule_id: int, request: Request):
+async def remove_exclude(rule_id: int, request: Request) -> dict:
state = request.state.app
await state.config_svc.remove_rule(rule_id)
return {"message": f"Exclude rule {rule_id} removed"}
@@ -87,25 +95,31 @@ async def remove_exclude(rule_id: int, request: Request):
# ── parsing-rules ────────────────────────────────────────────────
+
@router.get("/config/parsing-rules")
-async def list_parsing_rules(request: Request):
+async def list_parsing_rules(request: Request) -> dict:
state = request.state.app
rules = await state.config_svc.list_rules("parsing_rule")
return {"rules": rules}
@router.post("/config/parsing-rules")
-async def add_parsing_rule(req: RuleRequest, request: Request):
+async def add_parsing_rule(req: RuleRequest, request: Request) -> dict:
state = request.state.app
rid = await state.config_svc.add_rule(
- req.name or "规则", "parsing_rule", req.pattern,
- tier=req.tier, pages=req.pages, remote=req.remote, priority=req.priority,
+ req.name or "规则",
+ "parsing_rule",
+ req.pattern,
+ tier=req.tier,
+ pages=req.pages,
+ remote=req.remote,
+ priority=req.priority,
)
return {"id": rid}
@router.delete("/config/parsing-rules/{rule_id}")
-async def remove_parsing_rule(rule_id: int, request: Request):
+async def remove_parsing_rule(rule_id: int, request: Request) -> dict:
state = request.state.app
await state.config_svc.remove_rule(rule_id)
return {"message": f"Parsing rule {rule_id} removed"}
diff --git a/mineru/server/routes/info.py b/mineru/doclib/routes/info.py
similarity index 64%
rename from mineru/server/routes/info.py
rename to mineru/doclib/routes/info.py
index 1a318318..030e49da 100644
--- a/mineru/server/routes/info.py
+++ b/mineru/doclib/routes/info.py
@@ -8,7 +8,7 @@ router = APIRouter(tags=["info"])
@router.get("/info")
-async def info(request: Request, path: str = Query(...)):
+async def info(request: Request, path: str = Query(...)) -> dict:
state = request.state.app
file_row = await state.db.fetchone(
@@ -18,21 +18,31 @@ async def info(request: Request, path: str = Query(...)):
return {"path": path, "found": False}
sha = file_row["sha256"]
- doc = await state.db.fetchone("SELECT * FROM docs WHERE sha256=?", (sha,)) if sha else None
+ doc = (
+ await state.db.fetchone("SELECT * FROM docs WHERE sha256=?", (sha,))
+ if sha
+ else None
+ )
# aggregate parse batches
- parse_rows = await state.db.fetchall(
- "SELECT * FROM parses WHERE sha256=? ORDER BY tier, created_at DESC", (sha,)
- ) if sha else []
+ parse_rows = (
+ await state.db.fetchall(
+ "SELECT * FROM parses WHERE sha256=? ORDER BY tier, created_at DESC", (sha,)
+ )
+ if sha
+ else []
+ )
tiers: list[dict] = []
for pr in parse_rows:
- tiers.append({
- "tier": pr["tier"],
- "status": pr["status"],
- "pages": pr["pages"],
- "done_at": pr["done_at"],
- })
+ tiers.append(
+ {
+ "tier": pr["tier"],
+ "status": pr["status"],
+ "pages": pr["pages"],
+ "done_at": pr["done_at"],
+ }
+ )
return {
"path": file_row["path"],
diff --git a/mineru/server/routes/parse.py b/mineru/doclib/routes/parse.py
similarity index 83%
rename from mineru/server/routes/parse.py
rename to mineru/doclib/routes/parse.py
index 95a7458f..8b9056c4 100644
--- a/mineru/server/routes/parse.py
+++ b/mineru/doclib/routes/parse.py
@@ -12,10 +12,13 @@ router = APIRouter(tags=["parse"])
@router.post("/parse")
-async def parse(req: ParseRequest, request: Request):
+async def parse(req: ParseRequest, request: Request) -> dict:
state = request.state.app
result = await state.parse_svc.request_parse(
- req.path, tier=req.tier, pages=req.pages, force=req.force,
+ req.path,
+ tier=req.tier,
+ pages=req.pages,
+ force=req.force,
)
return result
@@ -25,7 +28,7 @@ async def parse_status(
request: Request,
sha256: str = Query(...),
tier: str = Query(...),
-):
+) -> dict:
state = request.state.app
result = await state.parse_svc.get_parse_status(sha256, tier)
if result is None:
@@ -39,14 +42,19 @@ async def parse_content(
sha256: str = Query(...),
tier: str = Query(...),
output: str | None = Query(None),
-):
+) -> dict:
"""Read parsed markdown content from per-batch JSON files."""
state = request.state.app
data_dir = getattr(state, "data_dir", os.path.expanduser("~/MinerU"))
tier_dir = os.path.join(data_dir, "parsed", sha256[:2], sha256, tier)
if not os.path.isdir(tier_dir):
- return {"sha256": sha256, "tier": tier, "content": None, "error": "Content not found"}
+ return {
+ "sha256": sha256,
+ "tier": tier,
+ "content": None,
+ "error": "Content not found",
+ }
import json as _json
@@ -64,7 +72,12 @@ async def parse_content(
pass
if not pages_by_idx:
- return {"sha256": sha256, "tier": tier, "content": None, "error": "Content not found"}
+ return {
+ "sha256": sha256,
+ "tier": tier,
+ "content": None,
+ "error": "Content not found",
+ }
sorted_pages = [pages_by_idx[i] for i in sorted(pages_by_idx)]
content = _markdown_from_pages(sorted_pages)
diff --git a/mineru/server/routes/search.py b/mineru/doclib/routes/search.py
similarity index 88%
rename from mineru/server/routes/search.py
rename to mineru/doclib/routes/search.py
index 3954a38a..a39e6c6e 100644
--- a/mineru/server/routes/search.py
+++ b/mineru/doclib/routes/search.py
@@ -14,10 +14,13 @@ async def search(
type: str | None = Query(None),
limit: int = Query(20, ge=1, le=200),
offset: int = Query(0, ge=0),
-):
+) -> dict:
state = request.state.app
results, total = await state.search_svc.search(
- query=q, file_type=type, limit=limit, offset=offset,
+ query=q,
+ file_type=type,
+ limit=limit,
+ offset=offset,
)
return {"results": results, "total": total, "query": q}
@@ -27,7 +30,7 @@ async def find(
request: Request,
q: str = Query(..., description="Filename search query"),
limit: int = Query(50, ge=1, le=500),
-):
+) -> dict:
state = request.state.app
results, total = await state.search_svc.search_filenames(query=q, limit=limit)
return {"results": results, "total": total, "query": q}
diff --git a/mineru/server/routes/server.py b/mineru/doclib/routes/server.py
similarity index 87%
rename from mineru/server/routes/server.py
rename to mineru/doclib/routes/server.py
index ed565ec5..303db18f 100644
--- a/mineru/server/routes/server.py
+++ b/mineru/doclib/routes/server.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import asyncio
import os
import signal
import time
@@ -13,7 +12,7 @@ router = APIRouter(tags=["server"])
@router.get("/server/status")
-async def server_status(request: Request):
+async def server_status(request: Request) -> dict:
state = request.state.app
files_total = await state.db.fetchone(
@@ -21,7 +20,7 @@ async def server_status(request: Request):
)
docs_total = await state.db.fetchone("SELECT COUNT(*) as cnt FROM docs")
parse_q = await state.parse_svc.get_queue_length()
- reg_q = await state.db.fetchone(
+ ingest_q = await state.db.fetchone(
"SELECT COUNT(*) as cnt FROM files WHERE sha256 IS NULL AND scan_status='active'"
)
watches = await state.config_svc.list_watches()
@@ -36,7 +35,7 @@ async def server_status(request: Request):
"files_total": files_total["cnt"] if files_total else 0,
"docs_total": docs_total["cnt"] if docs_total else 0,
"parse_queue_length": parse_q,
- "reg_queue_length": reg_q["cnt"] if reg_q else 0,
+ "ingest_queue_length": ingest_q["cnt"] if ingest_q else 0,
"watch_count": len(watches),
"watches": [
{
@@ -51,12 +50,12 @@ async def server_status(request: Request):
@router.post("/shutdown")
-async def shutdown(request: Request):
+async def shutdown(request: Request) -> dict:
"""Gracefully shut down the server."""
# Signal shutdown in a background task so we can return a response first
import asyncio
- async def _shutdown():
+ async def _shutdown() -> None:
await asyncio.sleep(0.1)
os.kill(os.getpid(), signal.SIGTERM)
diff --git a/mineru/server/app.py b/mineru/doclib/server.py
similarity index 83%
rename from mineru/server/app.py
rename to mineru/doclib/server.py
index dc05b559..fe0026e2 100644
--- a/mineru/server/app.py
+++ b/mineru/doclib/server.py
@@ -1,4 +1,4 @@
-"""mineru server — FastAPI app factory, lifecycle, UDS + optional TCP."""
+"""mineru doclib — FastAPI app factory, lifecycle, UDS + optional TCP."""
from __future__ import annotations
@@ -8,21 +8,23 @@ import logging
import os
import socket
import time
+from collections.abc import Callable
from logging.handlers import RotatingFileHandler
+from typing import Any
import uvicorn
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from mineru.errors import MineruError, error_response
-from .config import Config
+from .config import Config, LogConfig
def create_app(cfg: Config | None = None) -> FastAPI:
"""Create the FastAPI app. Accepts an optional Config for testing."""
if cfg is None:
cfg = Config()
- app = FastAPI(title="MinerU Server", version="1.0.0")
+ app = FastAPI(title="MinerU DocLib", version="1.0.0")
state = AppState()
# ── startup ──────────────────────────────────────────────────
@@ -36,7 +38,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:
from .services.config_svc import ConfigService
from .services.cleanup_svc import CleanupService
from .background.watch import WatchLoop
- from .background.reg_worker import RegistrationWorkerPool
+ from .background.ingest import IngestWorkerPool
from .background.parse_worker import ParseWorkerPool
from .background.device_monitor import DeviceMonitor
from .background.compaction import Compaction
@@ -58,20 +60,28 @@ def create_app(cfg: Config | None = None) -> FastAPI:
state.cleanup_svc = CleanupService(state.db, data_dir)
# crash recovery
- await state.db.execute("UPDATE files SET locked_at = NULL WHERE locked_at IS NOT NULL")
+ await state.db.execute(
+ "UPDATE files SET locked_at = NULL WHERE locked_at IS NOT NULL"
+ )
await state.db.execute(
"UPDATE parses SET locked_at = NULL, status = 'failed' WHERE status = 'parsing'"
)
# background tasks
state.watch = WatchLoop(state.db, state.config_svc, state.parse_svc)
- state.reg_workers = RegistrationWorkerPool(state.parse_svc, num_workers=cfg.server.reg_workers)
- state.parse_workers = ParseWorkerPool(state.parse_svc, num_workers=cfg.server.parse_workers)
+ state.ingest_workers = IngestWorkerPool(
+ state.parse_svc, num_workers=cfg.server.ingest_workers
+ )
+ state.parse_workers = ParseWorkerPool(
+ state.parse_svc, num_workers=cfg.server.parse_workers
+ )
state.device_monitor = DeviceMonitor(state.db, state.config_svc)
- state.compaction = Compaction(state.db, interval_sec=cfg.server.compaction_interval_sec)
+ state.compaction = Compaction(
+ state.db, interval_sec=cfg.server.compaction_interval_sec
+ )
asyncio.create_task(state.watch.run())
- asyncio.create_task(state.reg_workers.run())
+ asyncio.create_task(state.ingest_workers.run())
asyncio.create_task(state.parse_workers.run())
asyncio.create_task(state.device_monitor.run())
asyncio.create_task(state.compaction.run())
@@ -85,7 +95,13 @@ def create_app(cfg: Config | None = None) -> FastAPI:
@app.on_event("shutdown")
async def shutdown() -> None:
- for comp in ["watch", "reg_workers", "parse_workers", "device_monitor", "compaction"]:
+ for comp in [
+ "watch",
+ "ingest_workers",
+ "parse_workers",
+ "device_monitor",
+ "compaction",
+ ]:
c = getattr(state, comp, None)
if c and hasattr(c, "stop"):
await c.stop()
@@ -96,7 +112,7 @@ def create_app(cfg: Config | None = None) -> FastAPI:
# ── middleware ────────────────────────────────────────────────
@app.middleware("http")
- async def attach_state(request: Request, call_next):
+ async def attach_state(request: Request, call_next: Callable) -> Any:
request.state.app = state
return await call_next(request)
@@ -147,7 +163,7 @@ class AppState:
def main() -> None:
- """Entry point: python -m mineru.server.app"""
+ """Entry point: python -m mineru.doclib.server"""
cfg = Config()
uds_path = cfg.server.uds.path
@@ -188,7 +204,9 @@ def main() -> None:
port = cfg.server.http.port
tcp_sock.listen(cfg.server.http.backlog)
sockets.append(tcp_sock)
- print(f"MinerU server listening on UDS {uds_path} and TCP {cfg.server.http.host}:{port}")
+ print(
+ f"MinerU server listening on UDS {uds_path} and TCP {cfg.server.http.host}:{port}"
+ )
else:
print(f"MinerU server listening on UDS {uds_path}")
@@ -209,7 +227,7 @@ def main() -> None:
loop.close()
-def _setup_logging(log_cfg) -> None:
+def _setup_logging(log_cfg: LogConfig) -> None:
logger = logging.getLogger("mineru")
level = getattr(logging, log_cfg.level.upper(), logging.INFO)
logger.setLevel(level)
@@ -218,7 +236,9 @@ def _setup_logging(log_cfg) -> None:
# console
ch = logging.StreamHandler()
ch.setLevel(level)
- ch.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))
+ ch.setFormatter(
+ logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
+ )
logger.addHandler(ch)
# file
@@ -226,7 +246,9 @@ def _setup_logging(log_cfg) -> None:
os.makedirs(os.path.dirname(log_path), exist_ok=True)
fh = RotatingFileHandler(log_path, maxBytes=5 * 1024 * 1024, backupCount=3)
fh.setLevel(level)
- fh.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))
+ fh.setFormatter(
+ logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s")
+ )
logger.addHandler(fh)
diff --git a/mineru/server/services/cleanup_svc.py b/mineru/doclib/services/cleanup_svc.py
similarity index 93%
rename from mineru/server/services/cleanup_svc.py
rename to mineru/doclib/services/cleanup_svc.py
index 1b98a08d..77c288a2 100644
--- a/mineru/server/services/cleanup_svc.py
+++ b/mineru/doclib/services/cleanup_svc.py
@@ -6,9 +6,11 @@ import os
import shutil
import time
+from ..core.db import DatabaseManager
+
class CleanupService:
- def __init__(self, db, data_dir: str = "~/MinerU") -> None:
+ def __init__(self, db: DatabaseManager, data_dir: str = "~/MinerU") -> None:
self.db = db
self.data_dir = os.path.expanduser(data_dir)
@@ -42,8 +44,9 @@ class CleanupService:
# ── deleted files ───────────────────────────────────────────
- async def cleanup_deleted(self, older_than_days: int = 30,
- dry_run: bool = True) -> int:
+ async def cleanup_deleted(
+ self, older_than_days: int = 30, dry_run: bool = True
+ ) -> int:
row = await self.db.fetchone(
"SELECT COUNT(*) as cnt FROM files WHERE scan_status='deleted' "
"AND deleted_at < ?",
diff --git a/mineru/server/services/config_svc.py b/mineru/doclib/services/config_svc.py
similarity index 90%
rename from mineru/server/services/config_svc.py
rename to mineru/doclib/services/config_svc.py
index 6e2619e6..60403ed8 100644
--- a/mineru/server/services/config_svc.py
+++ b/mineru/doclib/services/config_svc.py
@@ -8,9 +8,11 @@ import time
import fnvhash
+from ..core.db import DatabaseManager
+
class ConfigService:
- def __init__(self, db) -> None:
+ def __init__(self, db: DatabaseManager) -> None:
self.db = db
# ── KV config ───────────────────────────────────────────────
@@ -30,8 +32,9 @@ class ConfigService:
# ── watch targets ───────────────────────────────────────────
- async def add_watch(self, path: str, removable: bool = False,
- label: str | None = None) -> dict:
+ async def add_watch(
+ self, path: str, removable: bool = False, label: str | None = None
+ ) -> dict:
if not os.path.isabs(path):
raise ValueError(f"Path must be absolute: {path}")
if os.path.normpath(path) != path:
@@ -76,9 +79,16 @@ class ConfigService:
# ── rules ───────────────────────────────────────────────────
- async def add_rule(self, name: str, rule_type: str, pattern: str,
- tier: str | None = None, pages: str | None = None,
- remote: bool = False, priority: int = 0) -> int:
+ async def add_rule(
+ self,
+ name: str,
+ rule_type: str,
+ pattern: str,
+ tier: str | None = None,
+ pages: str | None = None,
+ remote: bool = False,
+ priority: int = 0,
+ ) -> int:
return await self.db.execute_insert(
"INSERT INTO rules (name, rule_type, pattern, tier, pages, remote, priority) "
"VALUES (?, ?, ?, ?, ?, ?, ?)",
diff --git a/mineru/server/services/parse_svc.py b/mineru/doclib/services/parse_svc.py
similarity index 86%
rename from mineru/server/services/parse_svc.py
rename to mineru/doclib/services/parse_svc.py
index 51f517d7..6bb79f39 100644
--- a/mineru/server/services/parse_svc.py
+++ b/mineru/doclib/services/parse_svc.py
@@ -1,4 +1,4 @@
-"""Parse service: file registration, parse request/acquire/process."""
+"""Parse service: file ingestion, parse request/acquire/process."""
from __future__ import annotations
@@ -9,7 +9,10 @@ from pathlib import Path
from mineru.constants import TIER_ORDER, ParseStatus, Tier
+from ..core.db import DatabaseManager
from ..core.file_io import compute_sha256, extract_metadata, get_file_stat
+from ..core.fts import FTSManager
+from .config_svc import ConfigService
def _now_ms() -> int:
@@ -110,7 +113,9 @@ def expand_pages(pages: str | None, page_count: int) -> str:
# ── text truncation ────────────────────────────────────────────────
-def truncate_head_tail(text: str, max_chars: int = MAX_FTS_CHARS, half: int = FTS_HEAD_HALF) -> str:
+def truncate_head_tail(
+ text: str, max_chars: int = MAX_FTS_CHARS, half: int = FTS_HEAD_HALF
+) -> str:
if len(text) <= max_chars:
return text
return text[:half] + "\n...\n" + text[-half:]
@@ -120,27 +125,39 @@ def truncate_head_tail(text: str, max_chars: int = MAX_FTS_CHARS, half: int = FT
class ParseService:
- def __init__(self, db, fts, config_svc, data_dir: str = "~/MinerU") -> None:
+ def __init__(
+ self,
+ db: DatabaseManager,
+ fts: FTSManager,
+ config_svc: ConfigService,
+ data_dir: str = "~/MinerU",
+ ) -> None:
self.db = db
self.fts = fts
self.config_svc = config_svc
self.data_dir = os.path.expanduser(data_dir)
- # ── registration (shared) ──────────────────────────────────
+ # ── ingestion (shared) ──────────────────────────────────
- async def register_file(self, path: str, watch_id: int | None = None) -> dict | None:
- """Register a file: SHA-256 + metadata + trigger default parse."""
+ async def ingest_file(
+ self, path: str, watch_id: int | None = None
+ ) -> dict | None:
+ """Ingest a file: SHA-256 + metadata + trigger default parse."""
stat = await get_file_stat(path)
sha256 = await compute_sha256(path)
now = _now_ms()
- # check if this path is already registered
- existing_path = await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,))
+ # check if this path is already ingested
+ existing_path = await self.db.fetchone(
+ "SELECT * FROM files WHERE path=?", (path,)
+ )
if existing_path and existing_path["sha256"]:
return existing_path
# check if same content (sha256) is already tracked by another path
- existing_sha = await self.db.fetchone("SELECT * FROM files WHERE sha256=?", (sha256,))
+ existing_sha = await self.db.fetchone(
+ "SELECT * FROM files WHERE sha256=?", (sha256,)
+ )
if existing_sha:
# same file, different path — just add this path pointing to the same doc
await self.db.execute("DELETE FROM files WHERE path=?", (path,))
@@ -255,17 +272,33 @@ class ParseService:
# ── parse request ───────────────────────────────────────────
- async def request_parse(self, path: str, *, tier: str | None = None, pages: str | None = None, force: bool = False) -> dict:
+ async def request_parse(
+ self,
+ path: str,
+ *,
+ tier: str | None = None,
+ pages: str | None = None,
+ force: bool = False,
+ ) -> dict:
"""Handle a parse request from CLI. Returns info for status polling."""
- # ensure file is registered
- file_row = await self.db.fetchone("SELECT * FROM files WHERE path=? AND scan_status='active'", (path,))
+ # ensure file is ingested
+ file_row = await self.db.fetchone(
+ "SELECT * FROM files WHERE path=? AND scan_status='active'", (path,)
+ )
if file_row is None or file_row["sha256"] is None:
- file_row = await self.register_file(path)
+ file_row = await self.ingest_file(path)
if file_row is None:
- return {"sha256": "", "tier": tier or "", "status": "error", "tip": "File could not be registered."}
+ return {
+ "sha256": "",
+ "tier": tier or "",
+ "status": "error",
+ "tip": "File could not be ingested.",
+ }
sha256 = file_row["sha256"]
- doc = await self.db.fetchone("SELECT page_count FROM docs WHERE sha256=?", (sha256,))
+ doc = await self.db.fetchone(
+ "SELECT page_count FROM docs WHERE sha256=?", (sha256,)
+ )
page_count = doc["page_count"] if doc else 1
requested_tier = tier or Tier.FLASH
@@ -276,7 +309,9 @@ class ParseService:
requested_tier = Tier.FLASH
# expand pages
- default_pages = f"1~5,-5~-1" if page_count and page_count > 10 else f"1~{page_count}"
+ default_pages = (
+ "1~5,-5~-1" if page_count and page_count > 10 else f"1~{page_count}"
+ )
raw_pages = pages or default_pages
pages_str = expand_pages(raw_pages, page_count or 1)
@@ -366,7 +401,9 @@ class ParseService:
pages = task["pages"]
# guard
- current = await self.db.fetchone("SELECT status FROM parses WHERE id=?", (task["id"],))
+ current = await self.db.fetchone(
+ "SELECT status FROM parses WHERE id=?", (task["id"],)
+ )
if current is None or current["status"] != ParseStatus.PARSING:
return False
@@ -378,7 +415,12 @@ class ParseService:
if file_row is None:
await self.db.execute(
"UPDATE parses SET status=?, error_code=?, error_msg=?, locked_at=NULL WHERE id=?",
- (ParseStatus.FAILED, "no_accessible_file", "No active file found for this document", task["id"]),
+ (
+ ParseStatus.FAILED,
+ "no_accessible_file",
+ "No active file found for this document",
+ task["id"],
+ ),
)
return False
@@ -391,7 +433,12 @@ class ParseService:
except ImportError:
await self.db.execute(
"UPDATE parses SET status=?, error_code=?, error_msg=?, locked_at=NULL WHERE id=?",
- (ParseStatus.FAILED, "no_engine", "mineru.parser module not available", task["id"]),
+ (
+ ParseStatus.FAILED,
+ "no_engine",
+ "mineru.parser module not available",
+ task["id"],
+ ),
)
return False
@@ -468,7 +515,12 @@ class ParseService:
(sha256, tier),
)
if active:
- return {"sha256": sha256, "tier": tier, "status": active["status"], "pages": active["pages"]}
+ return {
+ "sha256": sha256,
+ "tier": tier,
+ "status": active["status"],
+ "pages": active["pages"],
+ }
failed = await self.db.fetchone(
"SELECT * FROM parses WHERE sha256=? AND tier=? AND status='failed' ORDER BY created_at DESC LIMIT 1",
@@ -486,9 +538,13 @@ class ParseService:
# ── internal helpers ────────────────────────────────────────
- async def _maybe_update_fts(self, sha256: str, tier: str, text: str, file_row: dict) -> None:
+ async def _maybe_update_fts(
+ self, sha256: str, tier: str, text: str, file_row: dict
+ ) -> None:
existing_tier = await self.fts.get_tier(sha256)
- if existing_tier and TIER_ORDER.get(existing_tier, -1) >= TIER_ORDER.get(tier, -1):
+ if existing_tier and TIER_ORDER.get(existing_tier, -1) >= TIER_ORDER.get(
+ tier, -1
+ ):
return # current FTS data is from a higher or equal tier
text = truncate_head_tail(text)
@@ -502,11 +558,15 @@ class ParseService:
)
async def _maybe_update_docs_meta(self, sha256: str, tier: str) -> None:
- doc = await self.db.fetchone("SELECT meta_tier FROM docs WHERE sha256=?", (sha256,))
+ doc = await self.db.fetchone(
+ "SELECT meta_tier FROM docs WHERE sha256=?", (sha256,)
+ )
if doc is None:
return
existing_tier = doc.get("meta_tier")
- if existing_tier and TIER_ORDER.get(existing_tier, -1) >= TIER_ORDER.get(tier, -1):
+ if existing_tier and TIER_ORDER.get(existing_tier, -1) >= TIER_ORDER.get(
+ tier, -1
+ ):
return
# for now just update meta_tier; full metadata update comes when
@@ -530,7 +590,9 @@ def _tier_to_backend(tier: str) -> str:
return mapping.get(tier, "pipeline")
-def _split_ranges(pages: str, file_row: dict, sha256: str) -> list[tuple[int, int | None]]:
+def _split_ranges(
+ pages: str, file_row: dict, sha256: str
+) -> list[tuple[int, int | None]]:
"""Split a pages range string into contiguous (start, end) tuples
suitable for the current parse() API. start is 0-based, end is inclusive."""
page_set = parse_range_set(pages)
diff --git a/mineru/server/services/search_svc.py b/mineru/doclib/services/search_svc.py
similarity index 67%
rename from mineru/server/services/search_svc.py
rename to mineru/doclib/services/search_svc.py
index 3dba8e77..ef290d53 100644
--- a/mineru/server/services/search_svc.py
+++ b/mineru/doclib/services/search_svc.py
@@ -2,11 +2,12 @@
from __future__ import annotations
-from ..core.fts import tokenize_for_query, strip_sep
+from ..core.db import DatabaseManager
+from ..core.fts import FTSManager, strip_sep
class SearchService:
- def __init__(self, db, fts) -> None:
+ def __init__(self, db: DatabaseManager, fts: FTSManager) -> None:
self.db = db
self.fts = fts
@@ -62,24 +63,28 @@ class SearchService:
snippet = strip_sep(row.get("snippet", ""))
tier = row.get("tier") or ""
- results.append({
- "sha256": sha,
- "title": row.get("title") or fts_file.get("title"),
- "author": row.get("author") or fts_file.get("author"),
- "filename": row.get("filename") or fts_file.get("filename"),
- "ext": fts_file.get("ext", ""),
- "size_bytes": fts_file.get("size_bytes", 0),
- "tier": tier,
- "snippet": snippet,
- "paths": [f["path"] for f in files],
- })
+ results.append(
+ {
+ "sha256": sha,
+ "title": row.get("title") or fts_file.get("title"),
+ "author": row.get("author") or fts_file.get("author"),
+ "filename": row.get("filename") or fts_file.get("filename"),
+ "ext": fts_file.get("ext", ""),
+ "size_bytes": fts_file.get("size_bytes", 0),
+ "tier": tier,
+ "snippet": snippet,
+ "paths": [f["path"] for f in files],
+ }
+ )
total = len(results)
- return results[offset:offset + limit], total
+ return results[offset : offset + limit], total
# ── filename search ─────────────────────────────────────────
- async def search_filenames(self, query: str, limit: int = 50) -> tuple[list[dict], int]:
+ async def search_filenames(
+ self, query: str, limit: int = 50
+ ) -> tuple[list[dict], int]:
"""Search filenames only. Returns (results, total_count)."""
rows = await self.fts.search_filenames(query, limit=limit)
if not rows:
@@ -101,16 +106,18 @@ class SearchService:
fr = files_by_id.get(row["file_id"])
if not fr:
continue
- results.append({
- "sha256": fr.get("sha256", ""),
- "title": fr.get("title"),
- "filename": fr["filename"],
- "ext": fr.get("ext", ""),
- "size_bytes": fr.get("size_bytes", 0),
- "tier": "",
- "snippet": strip_sep(row.get("snippet", "")),
- "paths": [fr["path"]],
- })
+ results.append(
+ {
+ "sha256": fr.get("sha256", ""),
+ "title": fr.get("title"),
+ "filename": fr["filename"],
+ "ext": fr.get("ext", ""),
+ "size_bytes": fr.get("size_bytes", 0),
+ "tier": "",
+ "snippet": strip_sep(row.get("snippet", "")),
+ "paths": [fr["path"]],
+ }
+ )
total = len(results)
return results, total
diff --git a/mineru/server/types.py b/mineru/doclib/types.py
similarity index 98%
rename from mineru/server/types.py
rename to mineru/doclib/types.py
index d70790da..3d8bcf98 100644
--- a/mineru/server/types.py
+++ b/mineru/doclib/types.py
@@ -112,6 +112,6 @@ class ServerStatus(BaseModel):
files_total: int = 0
docs_total: int = 0
parse_queue_length: int = 0
- reg_queue_length: int = 0
+ ingest_queue_length: int = 0
watch_count: int = 0
watches: list[dict] = []
diff --git a/mineru/server/__init__.py b/mineru/server/__init__.py
deleted file mode 100644
index c5091562..00000000
--- a/mineru/server/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-# The local mineru server.