Transforms complex documents like PDFs and Office docs into LLM-ready markdown/JSON for your Agentic workflows.
Python ai4sciencedocument-analysisdocxextract-datalayout-analysisocrparserpdfpdf-converterpdf-extractor-llmpdf-extractor-pretrainpdf-extractor-ragpdf-parserpptxpythonxlsx
feat: implement minueru server, CLI, and flash backend
jinzhenj2c6893bdd670
diff --git a/NEXT-DESIGN.md b/NEXT-DESIGN.mdindex 731f97ad..18cbc8a3 100644--- a/NEXT-DESIGN.md+++ b/NEXT-DESIGN.md@@ -47,7 +47,7 @@| UDS | `/tmp/mineru.sock` | `0600` | CLI / MCP / 桌面端通信 || TCP | `127.0.0.1:<随机端口>` | loopback only | 可选,供浏览器访问 Web UI (P1) |-Server 启动后写入 lock 文件 `~/MinerU/server.lock`,内容为 PID 和 TCP 端口。CLI 通过此文件发现 server 状态。+Server 启动后 UDS sock 文件位于 `/tmp/mineru.sock`(权限 0600)。CLI 通过 sock 连接检测 server 状态。TCP 端口按 config 中 `http.enabled` 决定是否启动。---@@ -83,7 +83,7 @@ Core(数据层:DB、FTS、文件 IO)| Service | 依赖 | 职责 ||---------|------|------|| `ParseService` | DB, FTS, ConfigService | 接收解析请求、文件注册(SHA-256 + metadata)、分配任务、管理 per-tier 解析状态 |-| `SearchService` | DB, FTS | 内容搜索 (fts_index)、文件名搜索 (fts_filenames) |+| `SearchService` | DB, FTS | 内容搜索 (fts_contents)、文件名搜索 (fts_filenames) || `ConfigService` | DB | KV 配置读写、Watch 目录 CRUD、Parsing-Rules CRUD、路径排除判断 || `CleanupService` | DB | 孤儿文档清理、已删除文件清理、解析缓存清理 |@@ -111,11 +111,14 @@ CREATE TABLE files (ext TEXT NOT NULL,size_bytes INTEGER NOT NULL,mtime_ms INTEGER NOT NULL,+ birthtime_ms INTEGER, -- 文件创建时间,Unix epoch mssha256 TEXT REFERENCES docs(sha256),watch_id INTEGER REFERENCES watch_targets(id),scan_status TEXT NOT NULL DEFAULT 'active', -- active / deleted / unreachable- reg_locked_at INTEGER, -- 注册锁,Unix epoch ms- reg_error TEXT,+ locked_at INTEGER, -- Unix epoch ms+ error_code TEXT, -- 错误码,e.g. "permission_denied"+ error_msg TEXT, -- 人类可读错误描述+ deleted_at INTEGER, -- 标记删除时间,Unix epoch msfirst_seen_at INTEGER NOT NULL, -- Unix epoch msupdated_at INTEGER NOT NULL -- Unix epoch ms);@@ -136,57 +139,113 @@ CREATE TABLE docs (lang TEXT,title TEXT,author TEXT,+ subject TEXT,+ keywords TEXT,is_encrypted INTEGER NOT NULL DEFAULT 0,+ is_scanned INTEGER NOT NULL DEFAULT 0,+ meta_tier TEXT, -- 当前 metadata 的来源 tier,NULL 表示注册阶段first_seen_at INTEGER NOT NULL, -- Unix epoch msupdated_at INTEGER NOT NULL -- Unix epoch ms);```-> **注意**:`docs` 表不含解析状态字段(无 `parse_status`、`preview_text` 等),解析状态全部在 `doc_parses` 表中按 tier 独立管理。注册阶段仅填充 metadata(SHA-256、page_count、mime_type 等),不提取预览文本——预览文本由 flash tier 的解析产出。+> **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`+> - **解析完成后**(ParseWorker):引擎产出的 metadata 仅在 `tier ≥ meta_tier`(或 meta_tier 为 NULL)时 UPDATE docs 覆盖,同时更新 `meta_tier`。同一 tier 的多次批次不会重复更新+> - 解析状态全部在 `parses` 表中按 tier 独立管理-#### doc_parses — 每个 tier 独立的解析记录+#### parses — 解析记录(每次解析请求为一行)```sql-CREATE TABLE doc_parses (- id INTEGER PRIMARY KEY AUTOINCREMENT,- sha256 TEXT NOT NULL REFERENCES docs(sha256),- tier TEXT NOT NULL, -- flash / standard / pro- parse_status TEXT NOT NULL DEFAULT 'pending', -- pending / parsing / done / error- parsed_pages TEXT, -- JSON array, e.g. [1,2,3,4,5]- total_pages INTEGER,- parse_locked_at INTEGER, -- Unix epoch ms- parse_error TEXT,- parse_path TEXT, -- 解析产物存储路径- parsed_at INTEGER, -- Unix epoch ms- created_at INTEGER NOT NULL, -- Unix epoch ms- updated_at INTEGER NOT NULL, -- Unix epoch ms- UNIQUE(sha256, tier)+CREATE TABLE parses (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ sha256 TEXT NOT NULL REFERENCES docs(sha256),+ tier TEXT NOT NULL, -- flash / standard / pro+ pages TEXT NOT NULL, -- 页码范围,正值已展开,e.g. "1~5,46~50"+ status TEXT NOT NULL DEFAULT 'pending', -- pending / parsing / done / failed+ priority INTEGER NOT NULL DEFAULT 0,+ locked_at INTEGER, -- Unix epoch ms+ error_code TEXT, -- 错误码,e.g. "parse_timeout"+ error_msg TEXT, -- 人类可读错误描述+ output_path TEXT, -- 解析产物存储路径+ done_at INTEGER, -- Unix epoch ms+ created_at INTEGER NOT NULL, -- Unix epoch ms+ updated_at INTEGER NOT NULL -- Unix epoch ms);-CREATE INDEX idx_doc_parses_status ON doc_parses(parse_status);+CREATE INDEX idx_parses_status ON parses(status, priority DESC, created_at ASC);+CREATE INDEX idx_parses_doc ON parses(sha256, tier);```-> **设计要点**:每个 tier 的解析记录独立存储在 `doc_parses` 表中,同一文档可同时拥有 flash、standard、pro 三份解析结果。`parsed_pages` 记录已解析的页码列表,支持增量解析。`--force` 时删除对应 tier 的记录后重建。--#### fts_index — 全文搜索索引(flash 解析文本)+**pages 字段**:+- 用 range 字符串描述,如 `"1~5"`、`"1~5,46~50"`、`"1~1000"`+- 仅存正值——用户输入的负索引(如 `-5~-1`)和 `all` 在插入前根据 `docs.page_count` 展开为正值+- 不存储为逐页展开的数组(1000 页全解析存 `"1~1000"`,不是 `"1,2,3,...,1000"`)+**并发**:Worker 获取单条 batch:```sql-CREATE VIRTUAL TABLE fts_index USING fts5(- doc_sha256 UNINDEXED,- indexed_text,- title,- author,- filename,- tokenize='unicode61'-);+UPDATE parses+SET locked_at=?, status='parsing'+WHERE id = (+ SELECT id FROM parses+ WHERE status='pending' AND (locked_at IS NULL OR locked_at<?)+ ORDER BY priority DESC, created_at ASC LIMIT 1+)+RETURNING *;+```++**增量解析**:同一 sha256+tier 可有多行(如 1~5 和 6~10 是两个 batch),各自独立执行。Agent 等待时 `priority=1`,Watch 后台 `priority=0`。++**Force 重解析**:直接 `INSERT` 新行即可(允许与已有行 pages 重叠):++```python+# --force --pages 4~7+await db.execute(+ "INSERT INTO parses (sha256, tier, pages, status, priority, created_at, updated_at) "+ "VALUES (?, ?, ?, 'pending', 1, ?, ?)",+ (sha256, tier, "4~7", now_ms(), now_ms())+)+```++**缓存命中**(`request_parse()` 时):查该 (sha256, tier) 所有 done 行,按 `done_at DESC` 排序取最新覆盖:++```python+def pages_covered(request_pages: str, done_rows: list[dict]) -> bool:+ """检查请求的 pages 是否已被 done 批次完全覆盖。+ 按 done_at 倒序,取最新 batch 的覆盖范围。"""+ needed = parse_range_set(request_pages) # → {1,2,3,4,5}+ covered = set()+ for r in sorted(done_rows, key=lambda r: r["done_at"], reverse=True):+ covered |= parse_range_set(r["pages"])+ if needed <= covered:+ return True+ return False```-#### fts_parsed — 全文搜索索引(standard/pro 完整解析文本)+**Compaction**(后台定时任务):合并同一 (sha256, tier) 的 done 行,消除重叠和邻接区间,减少 parses 表记录数:++```+合并前 合并后+"1~5" + "6~10" → "1~10"+"1~5" + "4~7" → "1~7"+"1~5" + "6~10" + "12~15" → "1~10" + "12~15"++算法:+1. 取出所有 done 行,展开 pages 为整数集合+2. 排序后合并邻接区间(e.g. [1..5]+[6..10] → "1~10")+3. DELETE 旧 done 行 + INSERT 合并后的新行+4. done_at 取被合并行中的最大值+```++Compaction 不在解析 critical path,作为低优先级后台周期性任务运行。++#### fts_contents — 全文搜索索引```sql-CREATE VIRTUAL TABLE fts_parsed USING fts5(- doc_sha256 UNINDEXED,- full_text,+CREATE VIRTUAL TABLE fts_contents USING fts5(+ sha256 UNINDEXED,+ tier UNINDEXED, -- 当前内容的来源 tier+ text,title,author,filename,@@ -194,12 +253,35 @@ CREATE VIRTUAL TABLE fts_parsed USING fts5();```+**FTS 更新策略**:保留最高 tier 的内容。++```python+TIER_ORDER = {"flash": 0, "standard": 1, "pro": 2}+MAX_FTS_CHARS = 30_000 # 超出则 head+tail 截断(前 15K + 后 15K)++async def update_fts(sha256, text, title, author, filename, tier):+ existing = await db.fetchone(+ "SELECT tier FROM fts_contents WHERE sha256=?", (sha256,))+ if existing and TIER_ORDER[existing["tier"]] >= TIER_ORDER[tier]:+ return # 跳过——当前已有更高或同 tier 的内容++ text = truncate_head_tail(text, MAX_FTS_CHARS)+ await db.execute(+ "INSERT OR REPLACE INTO fts_contents (sha256, text, title, author, filename, tier) "+ "VALUES (?, ?, ?, ?, ?, ?)",+ (sha256, text, title or "", author or "", filename, tier))+```++- flash 先完成 → 写入;standard 后完成 → 覆盖;pro 后完成 → 再覆盖+- pro 先完成 → 写入;flash 后完成 → 跳过(pro > flash)+- 搜索只查这一张表,完整内容从解析产物文件读取+#### fts_filenames — 文件名搜索```sqlCREATE VIRTUAL TABLE fts_filenames USING fts5(file_id UNINDEXED,- filename_text,+ filename,ext,tokenize='unicode61');@@ -303,25 +385,25 @@ INSERT INTO config (key, value) VALUES```sql-- RegistrationWorker 获取任务UPDATE files-SET reg_locked_at = ?+SET locked_at = ?WHERE id = (SELECT id FROM filesWHERE sha256 IS NULLAND scan_status = 'active'- AND (reg_locked_at IS NULL OR reg_locked_at < ?)+ AND (locked_at IS NULL OR locked_at < ?)ORDER BY first_seen_at ASCLIMIT 1)RETURNING *;-- ParseWorker 获取任务-UPDATE doc_parses-SET parse_locked_at = ?, parse_status = 'parsing'+UPDATE parses+SET locked_at = ?, status = 'parsing'WHERE id = (- SELECT id FROM doc_parses- WHERE parse_status = 'pending'- AND (parse_locked_at IS NULL OR parse_locked_at < ?)- ORDER BY created_at ASC+ SELECT id FROM parses+ WHERE status = 'pending'+ AND (locked_at IS NULL OR locked_at < ?)+ ORDER BY priority DESC, created_at ASCLIMIT 1)RETURNING *;@@ -344,11 +426,11 @@ RETURNING *;- 计算 SHA-256- 提取 metadata (mime_type, page_count, title, author)- FTS 索引文件名- - 触发默认 flash 解析(INSERT INTO doc_parses, tier='flash', parse_status='pending')+ - 触发默认 flash 解析(INSERT INTO parses (sha256, tier, pages, status='pending', priority=0))阶段 2: 解析(ParseWorker)- - flash tier:提取首尾各 5 页文本,写入 fts_index- - standard/pro tier:完整解析,写入 fts_parsed+ - flash tier:提取首尾各 5 页文本,写入 fts_contents+ - standard/pro tier:完整解析,写入 fts_contents(覆盖 flash 的)```> **设计简化**:everydoc 的 L1 Index(注册 + 预览文本提取)在 MinerU 中被拆为:注册(仅 SHA-256 + metadata)+ flash 解析(首尾页文本)。用户无需理解"索引"和"解析"两个概念——所有内容提取都是 parse,只是 tier 不同。@@ -359,16 +441,15 @@ RETURNING *;Watch 检测到文件事件→ 过滤(ext 白名单 + exclude 规则)→ INSERT OR IGNORE INTO files (path, filename, ext, size_bytes, mtime_ms, sha256=NULL)- → RegistrationWorker.acquire_task(): UPDATE files SET reg_locked_at WHERE sha256 IS NULL+ → RegistrationWorker.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)- 3. extract metadata (title, author, page_count, mime_type)- 4. FTS insert fts_filenames- 5. UPDATE files SET sha256=?, reg_locked_at=NULL- 6. check parsing-rules → 命中时用规则指定的 tier,否则用 default_tier (flash)- 7. INSERT INTO doc_parses (sha256, tier, parse_status='pending')- → 失败时: UPDATE files SET sha256=NULL, reg_error=?(可重试)+ 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)+ → 失败时: UPDATE files SET sha256=NULL, error_code=?, error_msg=?(可重试)```### 5.3 解析请求@@ -378,22 +459,23 @@ Watch 检测到文件事件→ CLI → Product SDK (client.py) → Server POST /parse→ ParseService.request_parse():1. 查 files 表获取 sha256(如果文件未注册,先同步注册)- 2. 查 doc_parses WHERE sha256=? AND tier='standard'- 3. 已有记录且 parsed_pages 覆盖请求范围 → 直接返回缓存- 4. 否则 → INSERT OR UPDATE doc_parses (parse_status='pending', parsed_pages 合并)- 5. --force 时 → DELETE + INSERT+ 2. 查 parses WHERE sha256=? AND tier=? AND status='done'+ 3. 已有 done 批次的 pages 覆盖请求范围 → 直接返回缓存+ 4. 否则 → INSERT INTO parses (sha256, tier, pages, priority=1)+ 5. --force 时 → DELETE FROM parses WHERE sha256=? AND tier=?,再 INSERT→ ParseWorker.acquire_task()→ process_doc():- 1. 从 doc_parses 读取 tier、待解析页码+ 1. 从 parses 读取 sha256、tier、pages2. resolve_engine(tier) 确定 backend3. 调用 mineru.parser.parse(path, tier=..., pages=...)4. 写入解析产物到 ~/MinerU/parsed/{sha256[:2]}/{sha256}/{tier}/- 5. flash → UPDATE fts_index;standard/pro → UPDATE fts_parsed- 6. UPDATE doc_parses SET parse_status='done', parsed_pages=?, parsed_at=?- → 失败时: UPDATE doc_parses SET parse_status='error', parse_error=?+ 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.3 解析产物存储+### 5.4 解析产物存储```~/MinerU/@@ -417,19 +499,18 @@ Watch 检测到文件事件每个 tier 独立目录,互不覆盖。-### 5.4 搜索-+### 5.5 搜索```用户请求: mineru search "关键词"→ SearchService.search():1. 分词(jieba / unicode61)- 2. FTS5 MATCH on fts_parsed(优先)+ fts_index(补充)+ 2. FTS5 MATCH on fts_contents3. JOIN files/docs 获取元数据- 4. 按 doc_sha256 去重(同一文档可能有多个路径)+ 4. 按 sha256 去重(同一文档可能有多个路径)5. 结果标注解析状态(flash / standard / pro)```-### 5.5 可插拔设备+### 5.6 可插拔设备```DeviceMonitor 每 5 秒检测:@@ -459,8 +540,8 @@ async def startup():await db.initialize()# 3. 崩溃恢复:清理 stale 锁- await db.execute("UPDATE files SET reg_locked_at = NULL WHERE reg_locked_at IS NOT NULL")- await db.execute("UPDATE doc_parses SET parse_locked_at = NULL, parse_status = 'error' WHERE parse_status = 'parsing'")+ await db.execute("UPDATE files SET locked_at = NULL WHERE locked_at IS NOT NULL")+ await db.execute("UPDATE parses SET locked_at = NULL, status = 'failed' WHERE status = 'parsing'")# 4. 创建 servicesconfig_svc = ConfigService(db)@@ -474,8 +555,8 @@ async def startup():asyncio.create_task(parse_worker.run())asyncio.create_task(device_monitor.run())- # 6. 写入 lock 文件- write_lock_file(pid=os.getpid(), port=tcp_port)+ # 6. 启动 uvicorn(UDS + 可选 TCP)+ await uvicorn_server.serve()```### 6.2 关闭@@ -491,8 +572,7 @@ async def shutdown():# 2. 关闭数据库连接await db.close()- # 3. 删除 lock 文件和 socket 文件- remove_lock_file()+ # 3. 删除 socket 文件remove_socket()```@@ -502,8 +582,8 @@ Server 启动时执行以下恢复操作:| 操作 | 目的 ||------|------|-| 清除所有 `reg_locked_at` | 释放因崩溃而未释放的注册锁 |-| 清除所有 `parse_locked_at`,将 `parsing` 状态改为 `error` | 释放解析锁,标记为可重试 |+| `UPDATE files SET locked_at=NULL` | 释放因崩溃而未释放的注册锁 |+| `UPDATE parses SET locked_at=NULL, status='failed' WHERE status='parsing'` | 释放解析锁,标记为可重试 || 检查已注册文件的活性(`os.path.exists`) | 标记已删除的文件 |---@@ -521,9 +601,8 @@ Server 启动时执行以下恢复操作:| `data_dir` | `~/MinerU` | 数据目录根路径 || `default_tier` | `flash` | Watch 自动解析的默认 tier || `scan_interval_sec` | `300` | Watch 全量扫描间隔(秒) |-| `index_lock_timeout_sec` | `60` | 注册锁超时 |+| `reg_lock_timeout_sec` | `60` | 注册锁超时 || `parse_lock_timeout_sec` | `1800` | 解析锁超时(30 分钟) |-| `fts_preview_kb` | `30` | 预览文本截取大小(KB) |### 7.3 Watch 目录@@ -614,14 +693,15 @@ Watch 自动发现以下类型的文件:- **查询阶段**:jieba 切词后用空格连接- **展示阶段**:`strip_sep()` 去除分隔符-### 9.2 两张 FTS 表+### 9.2 FTS 截断策略++| 表 | 数据来源 | 截断规则 |+|---|---------|---------|+| `fts_contents` | 解析产出的文本 | ≤30K 字符存全文;>30K 取前 15K + 后 15K(对齐段落边界) |-| 表 | 数据来源 | 时机 |-|---|---------|------|-| `fts_index` | flash tier 解析的首尾页文本 | flash 解析完成时 |-| `fts_parsed` | standard/pro tier 的完整解析文本 | standard/pro 解析完成时 |+flash 的首尾各 5 页文本通常在 30K 限制内,不会触发截断。standard/pro 的完整解析文档若超出限制,用 head+tail 保留首尾搜索能力。-搜索时优先查 `fts_parsed`(覆盖更全),`fts_index` 作为补充(仅 flash 解析的文件也能搜到首尾页内容)。+同一文档永远只有一行 FTS 记录,无需跨表合并。完整内容从解析产物 markdown 文件中读取。---@@ -631,9 +711,9 @@ Watch 自动发现以下类型的文件:| 层级 | 示例 | 存储位置 | 恢复策略 ||------|------|---------|---------|-| File 级 | 路径不存在、权限不足 | `files.reg_error` | 清除 sha256,可重试 |-| Doc 级 | 文件损坏、加密 | `files.reg_error` | 不自动重试,需用户介入 |-| Parse 级 | 引擎崩溃、超时、OOM | `doc_parses.parse_error` | 标记 `parse_status='error'`,可通过 `--force` 重试 |+| File 级 | 路径不存在、权限不足 | `files.error_code` | 清除 sha256,可重试 |+| Doc 级 | 文件损坏、加密 | `files.error_code` | 不自动重试 |+| Parse 级 | 引擎崩溃、超时、OOM | `parses.error_code` | 标记 `status='failed'`,可重试 |---@@ -650,6 +730,7 @@ Watch 自动发现以下类型的文件:| `aiosqlite` | 异步 SQLite || `watchfiles` | 文件系统监控(FSEvents / inotify) || `jieba` | 中文分词(FTS 索引) |+| `pypdfium2` | PDF page_count / metadata 读取 + flash 引擎文本提取 |### 11.2 现有依赖(保持不变)diff --git a/mineru/backend/flash/__init__.py b/mineru/backend/flash/__init__.pynew file mode 100644index 00000000..ac2ac734--- /dev/null+++ b/mineru/backend/flash/__init__.py@@ -0,0 +1 @@+# Flash tier: CPU-only lightweight PDF text extraction.\ No newline at end of filediff --git a/mineru/backend/flash/pdf_extractor.py b/mineru/backend/flash/pdf_extractor.pynew file mode 100644index 00000000..00adfda9--- /dev/null+++ b/mineru/backend/flash/pdf_extractor.py@@ -0,0 +1,34 @@+"""Flash tier PDF extractor — CPU-only text extraction via pypdfium2."""++from __future__ import annotations+++def extract_text(filepath: str, start_page: int = 0, end_page: int | None = None) -> str:+ """Extract plain text from a PDF file using pypdfium2.++ Args:+ filepath: Path to the PDF file.+ start_page: 0-based start page (inclusive).+ end_page: 0-based end page (exclusive). None means all pages.++ Returns:+ Extracted text as a string, one page per `\\n\\n`.+ """+ import pypdfium2++ pdf = pypdfium2.PdfDocument(filepath)+ try:+ total = len(pdf)+ end = total if end_page is None else min(end_page, total)++ parts: list[str] = []+ for i in range(start_page, end):+ page = pdf[i]+ tp = page.get_textpage()+ text = tp.get_text_range()+ if text:+ parts.append(text)++ return "\n\n".join(parts)+ finally:+ pdf.close()diff --git a/mineru/cli_next/commands/cleanup.py b/mineru/cli_next/commands/cleanup.pynew file mode 100644index 00000000..a2af54b4--- /dev/null+++ b/mineru/cli_next/commands/cleanup.py@@ -0,0 +1,65 @@+"""mineru cleanup — clean up orphan docs, deleted records, temp files."""++from __future__ import annotations++import typer++from mineru.server.client import MineruClient+from mineru.cli_next.output import print_error, print_success, print_info+++def cleanup_cmd(+ orphans: bool = typer.Option(False, "--orphans", help="Clean orphan docs"),+ deleted: bool = typer.Option(False, "--deleted", help="Clean deleted file records"),+ temp: bool = typer.Option(False, "--temp", help="Clean temporary files"),+ older_than: int = typer.Option(30, "--older-than", help="Days threshold for deleted cleanup"),+ dry_run: bool = typer.Option(True, "--dry-run", help="Preview only — don't actually delete"),+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),+) -> None:+ """Clean up database records and temp files.++ Examples:+ mineru cleanup --orphans --dry-run+ mineru cleanup --deleted --older-than 60+ mineru cleanup --temp+ """+ try:+ client = MineruClient(timeout=30)+ except Exception:+ print_error("Cannot connect to mineru server. Run 'mineru server start' first.")+ raise typer.Exit(1) from None++ if orphans:+ try:+ data = client._post("/cleanup/orphans", json_data={"dry_run": dry_run})+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+ count = data.get("orphan_docs", 0)+ if dry_run:+ print_info(f"Would remove {count} orphan doc(s). Use --no-dry-run to proceed.")+ else:+ print_success(f"Removed {count} orphan doc(s).")+ elif deleted:+ try:+ data = client._post("/cleanup/deleted", json_data={+ "dry_run": dry_run, "older_than_days": older_than,+ })+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+ count = data.get("deleted_files", 0)+ if dry_run:+ print_info(f"Would remove {count} deleted file record(s). Use --no-dry-run to proceed.")+ else:+ print_success(f"Removed {count} deleted file record(s).")+ elif temp:+ try:+ data = client._post("/cleanup/temp", json_data={"older_than_days": older_than})+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+ count = data.get("temp_files_removed", 0)+ print_success(f"Removed {count} temp file(s).")+ else:+ print_info("Specify --orphans, --deleted, or --temp.")diff --git a/mineru/cli_next/commands/config.py b/mineru/cli_next/commands/config.pynew file mode 100644index 00000000..71ac06ad--- /dev/null+++ b/mineru/cli_next/commands/config.py@@ -0,0 +1,225 @@+"""mineru config — configuration management."""++from __future__ import annotations++import typer++from mineru.server.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)++# sub-command groups+watch_app = typer.Typer(help="Watch directory management", no_args_is_help=True)+exclude_app = typer.Typer(help="Exclusion rule management", no_args_is_help=True)+parsing_rules_app = typer.Typer(help="Parsing rule management", no_args_is_help=True)++app.add_typer(watch_app, name="watch")+app.add_typer(exclude_app, name="exclude")+app.add_typer(parsing_rules_app, name="parsing-rules")+++# ── config show ─────────────────────────────────────────────────+++def show(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:+ """Show all configuration."""+ try:+ client = MineruClient(timeout=10)+ data = client.config_show()+ if json_mode:+ print_json(data)+ else:+ _print_config(data)+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+++# ── watch ────────────────────────────────────────────────────────+++@watch_app.command("add")+def watch_add(+ path: str = typer.Argument(..., help="Directory path to watch"),+ removable: bool = typer.Option(False, "--removable", help="Removable device"),+ label: str = typer.Option(None, "--label", help="Label for this watch"),+) -> None:+ """Add a directory to watch."""+ try:+ client = MineruClient(timeout=10)+ data = client.config_watch_add(path, removable=removable, label=label)+ print_success(f"Watch added: {data.get('path')} (id={data.get('id')})")+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+++@watch_app.command("list")+def watch_list(json_mode: bool = typer.Option(False, "--json", help="JSON output")) -> None:+ """List all watched directories."""+ try:+ client = MineruClient(timeout=10)+ data = client.config_watch_list()+ if json_mode:+ print_json(data)+ else:+ watches = data.get("watches", [])+ if not watches:+ print_info("No watches configured.")+ for w in watches:+ status = w.get("watch_status", "?")+ icon = "✓" if status == "active" else "✗"+ extra = " [removable]" if w.get("removable") else ""+ print(f" {icon} {w['path']}{extra} [{status}]")+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+++@watch_app.command("rm")+def watch_rm(path: str = typer.Argument(..., help="Watch directory path to remove")) -> None:+ """Remove a watched directory."""+ try:+ client = MineruClient(timeout=10)+ client.config_watch_rm(path)+ print_success(f"Watch removed: {path}")+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+++# ── exclude ──────────────────────────────────────────────────────+++@exclude_app.command("add")+def exclude_add(+ pattern: str = typer.Argument(..., help="Glob pattern to exclude"),+ priority: int = typer.Option(0, "--priority", help="Rule priority"),+) -> None:+ """Add an exclusion pattern."""+ try:+ client = MineruClient(timeout=10)+ data = client.config_exclude_add(pattern, priority=priority)+ print_success(f"Exclude rule added: id={data.get('id')}")+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+++@exclude_app.command("list")+def exclude_list(+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),+) -> None:+ """List all exclusion rules."""+ try:+ client = MineruClient(timeout=10)+ data = client.config_exclude_list()+ if json_mode:+ print_json(data)+ else:+ rules = data.get("rules", [])+ if not rules:+ print_info("No exclude rules configured.")+ for r in rules:+ print(f" [{r['id']}] {r['pattern']} priority={r.get('priority', 0)}")+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+++@exclude_app.command("rm")+def exclude_rm(rule_id: int = typer.Argument(..., help="Rule ID to remove")) -> None:+ """Remove an exclusion rule."""+ try:+ client = MineruClient(timeout=10)+ client.config_exclude_rm(rule_id)+ print_success(f"Exclude rule {rule_id} removed.")+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+++# ── parsing-rules ────────────────────────────────────────────────+++@parsing_rules_app.command("add")+def parsing_rules_add(+ pattern: str = typer.Argument(..., help="Glob pattern to match"),+ tier: str = typer.Option(None, "--tier", help="Parse tier: flash, standard, pro"),+ pages: str = typer.Option(None, "--pages", help="Page range, e.g. 'all' or '1~10'"),+ remote: bool = typer.Option(False, "--remote", help="Allow remote parsing"),+ name: str = typer.Option(None, "--name", help="Rule name"),+) -> None:+ """Add a parsing rule."""+ try:+ client = MineruClient(timeout=10)+ data = client.config_parsing_rules_add(+ pattern, tier=tier, pages=pages, remote=remote, name=name,+ )+ print_success(f"Parsing rule added: id={data.get('id')}")+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+++@parsing_rules_app.command("list")+def parsing_rules_list(+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),+) -> None:+ """List all parsing rules."""+ try:+ client = MineruClient(timeout=10)+ data = client.config_parsing_rules_list()+ if json_mode:+ print_json(data)+ else:+ rules = data.get("rules", [])+ if not rules:+ print_info("No parsing rules configured.")+ for r in rules:+ flags = []+ if r.get("tier"):+ flags.append(f"tier={r['tier']}")+ if r.get("pages"):+ flags.append(f"pages={r['pages']}")+ if r.get("remote"):+ flags.append("remote")+ print(f" [{r['id']}] {r['pattern']} {', '.join(flags)}")+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+++@parsing_rules_app.command("rm")+def parsing_rules_rm(rule_id: int = typer.Argument(..., help="Rule ID to remove")) -> None:+ """Remove a parsing rule."""+ try:+ client = MineruClient(timeout=10)+ client.config_parsing_rules_rm(rule_id)+ print_success(f"Parsing rule {rule_id} removed.")+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+++# ── helpers ──────────────────────────────────────────────────────+++def _print_config(data: dict) -> None:+ cfg = data.get("config", {})+ watches = data.get("watches", [])+ rules = data.get("rules", [])++ print("\n[Global Config]")+ for k, v in cfg.items():+ print(f" {k} = {v}")++ print(f"\n[Watches] ({len(watches)})")+ for w in watches:+ print(f" {w['path']} [{w.get('watch_status','?')}]")++ print(f"\n[Rules] ({len(rules)})")+ for r in rules:+ print(f" [{r['rule_type']}] {r['pattern']}")diff --git a/mineru/cli_next/commands/parse.py b/mineru/cli_next/commands/parse.pynew file mode 100644index 00000000..a058a055--- /dev/null+++ b/mineru/cli_next/commands/parse.py@@ -0,0 +1,137 @@+"""mineru parse — document parsing command."""++from __future__ import annotations++import sys+import time+from pathlib import Path++import typer++from mineru.server.client import MineruClient+from mineru.cli_next.output import format_parse_result, print_error, print_success, print_info+++def parse_cmd(+ path: str = typer.Argument(..., help="Path to the document file"),+ tier: str = typer.Option(None, "--tier", help="Parse tier: flash, standard, pro"),+ pages: str = typer.Option(+ None, "-p", "--pages", help="Page range, e.g. '1~5' or 'all'"+ ),+ force: bool = typer.Option(False, "--force", help="Force re-parse, ignore cache"),+ wait: int = typer.Option(+ 60, "--wait", help="Max seconds to wait for parse to complete"+ ),+ no_wait: bool = typer.Option(+ False, "--no-wait", help="Don't wait — return immediately"+ ),+ output: str = typer.Option(+ None, "-o", "--output", help="Output file path (default: STDOUT)"+ ),+ no_marker: bool = typer.Option(+ False, "--no-marker", help="Omit document structure markers from output"+ ),+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),+ verbose: bool = typer.Option(False, "-v", "--verbose", help="Verbose output"),+) -> None:+ """Parse a document file."""+ file_path = str(Path(path).resolve())++ if not Path(file_path).exists():+ print_error(f"File not found: {file_path}")+ raise typer.Exit(1)++ try:+ client = MineruClient(timeout=wait + 30)+ except Exception:+ print_error("Cannot connect to mineru server. Run 'mineru server start' first.")+ raise typer.Exit(1) from None++ # send parse request+ try:+ result = client.parse(file_path, tier=tier, pages=pages, force=force)+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None++ sha256 = result.get("sha256", "")+ req_tier = result.get("tier", tier or "flash")+ status = result.get("status", "?")++ # cached+ if status == "done":+ if verbose:+ print_info("Cache hit — returning cached result.")+ _output_content(client, sha256, req_tier, json_mode, output)+ return++ # no-wait+ if no_wait or status not in ("pending", "parsing"):+ format_parse_result(result, json_mode=json_mode)+ return++ # poll until done or timeout+ if verbose:+ print_info(f"Parse queued (tier={req_tier}). Waiting up to {wait}s...")++ deadline = time.time() + wait+ interval = 0.5+ while time.time() < deadline:+ time.sleep(interval)+ interval = min(interval * 1.2, 3.0)+ try:+ s = client.parse_status(sha256, req_tier)+ except Exception:+ continue++ st = s.get("status", "?")+ if verbose or st in ("done", "failed"):+ print_info(f" Parse status: {st}")++ if st == "done":+ if not json_mode:+ _output_content(client, sha256, req_tier, json_mode, output)+ else:+ format_parse_result(s, json_mode=json_mode)+ return+ elif st == "failed":+ err = s.get("error", {})+ print_error(f"Parse failed: {err.get('code','?')} — {err.get('message','')}")+ raise typer.Exit(1)++ print_info(+ f"Parse still in progress (tier={req_tier}). "+ f"Check status with: mineru info {file_path}"+ )+ if json_mode:+ print_info('{"status":"parsing","tip":"Re-run the same command to continue waiting."}')+++if __name__ != "__main__":+ def _register(app: typer.Typer) -> None:+ app.command()(parse_cmd)+++def _output_content(client, sha256: str, tier: str, json_mode: bool,+ output: str | None = None) -> None:+ """Fetch and output parsed content. If --output is specified, server writes to file."""+ try:+ content = client.parse_content(sha256, tier, output=output)+ if output and output != "-":+ if content.get("output"):+ print_success(f"Written to {content['output']}")+ else:+ print_error("Failed to write output file.")+ return++ text = content.get("content", "")+ if text:+ if json_mode:+ import json+ print(json.dumps({"sha256": sha256, "tier": tier, "content": text}, ensure_ascii=False))+ else:+ print(text)+ else:+ print_error("No content returned from parse.")+ except Exception as exc:+ print_error(f"Failed to read content: {exc}")diff --git a/mineru/cli_next/commands/search.py b/mineru/cli_next/commands/search.pynew file mode 100644index 00000000..24299b16--- /dev/null+++ b/mineru/cli_next/commands/search.py@@ -0,0 +1,57 @@+"""mineru search / find / info commands."""++from __future__ import annotations++import typer++from mineru.server.client import MineruClient+from mineru.cli_next.output import format_search_results, format_info, print_error+++def search_cmd(+ query: str = typer.Argument(..., help="Search query"),+ file_type: str = typer.Option(None, "--type", help="File type filter (pdf, docx, ...)"),+ limit: int = typer.Option(20, "--limit", "-n", help="Max results"),+ offset: int = typer.Option(0, "--offset", help="Result offset"),+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),+) -> None:+ """Search parsed document content."""+ try:+ client = MineruClient(timeout=10)+ result = client.search(query, file_type=file_type, limit=limit, offset=offset)+ format_search_results(result, json_mode=json_mode)+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+++def find_cmd(+ query: str = typer.Argument(..., help="Filename search query"),+ limit: int = typer.Option(50, "--limit", "-n", help="Max results"),+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),+) -> None:+ """Search filenames only (not document content)."""+ try:+ client = MineruClient(timeout=10)+ result = client.find(query, limit=limit)+ format_search_results(result, json_mode=json_mode)+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from None+++def info_cmd(+ path: str = typer.Argument(..., help="File path"),+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),+) -> None:+ """Show file/document details."""+ from pathlib import Path++ file_path = str(Path(path).resolve())+ try:+ client = MineruClient(timeout=10)+ result = client.info(file_path)+ format_info(result, json_mode=json_mode)+ except Exception as exc:+ print_error(str(exc))+ raise typer.Exit(1) from Nonediff --git a/mineru/cli_next/commands/server.py b/mineru/cli_next/commands/server.pynew file mode 100644index 00000000..d59580d8--- /dev/null+++ b/mineru/cli_next/commands/server.py@@ -0,0 +1,113 @@+"""mineru server — server lifecycle management."""++from __future__ import annotations++import os+import subprocess+import sys+import time++import typer++from mineru.constants import SOCKET_PATH+from mineru.cli_next.output import format_server_status, print_error, print_success, print_info++app = typer.Typer(help="Server lifecycle management", no_args_is_help=True)+++def _server_running() -> bool:+ if not os.path.exists(SOCKET_PATH):+ return False+ try:+ from mineru.server.client import MineruClient+ c = MineruClient(timeout=3)+ c.server_status()+ return True+ except Exception:+ return False+++def _wait_for_sock(timeout: float = 15.0) -> bool:+ deadline = time.time() + timeout+ while time.time() < deadline:+ if os.path.exists(SOCKET_PATH):+ time.sleep(0.3)+ if _server_running():+ return True+ time.sleep(0.3)+ return False+++def start() -> None:+ """Start the mineru server in the background."""+ if _server_running():+ print_info("Server is already running.")+ return++ # Clean stale socket+ try:+ os.unlink(SOCKET_PATH)+ except OSError:+ pass++ proc = subprocess.Popen(+ [sys.executable, "-m", "mineru.server.app"],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )++ if not _wait_for_sock():+ proc.kill()+ print_error("Server failed to start within 15 seconds.")+ raise typer.Exit(1)++ print_success(f"Server started (PID {proc.pid}). Socket: {SOCKET_PATH}")+++def stop() -> None:+ """Stop the mineru server gracefully."""+ if not _server_running():+ print_info("Server is not running.")+ return++ try:+ from mineru.server.client import MineruClient+ c = MineruClient(timeout=5)+ c.shutdown()+ except Exception:+ pass++ time.sleep(0.5)+ try:+ os.unlink(SOCKET_PATH)+ except OSError:+ pass++ print_success("Server stopped.")+++def restart() -> None:+ """Restart the mineru server."""+ if _server_running():+ stop()+ time.sleep(1)+ start()+++def status() -> None:+ """Show server status."""+ if not _server_running():+ print_info("Server is not running.")+ return++ try:+ from mineru.server.client import MineruClient+ c = MineruClient(timeout=5)+ data = c.server_status()+ format_server_status(data)+ except Exception as exc:+ print_error(str(exc))diff --git a/mineru/cli_next/main.py b/mineru/cli_next/main.pynew file mode 100644index 00000000..eea36dfb--- /dev/null+++ b/mineru/cli_next/main.py@@ -0,0 +1,110 @@+"""mineru CLI — local document center."""++from __future__ import annotations++import typer++app = typer.Typer(+ name="mineru",+ help="MinerU — 本地文档中心",+ no_args_is_help=True,+)++# sub-command groups+from .commands import server, config++app.add_typer(server.app, name="server")+app.add_typer(config.app, name="config")+++# top-level commands+def parse(+ path: str = typer.Argument(..., help="Path to the document file"),+ tier: str = typer.Option(None, "--tier", help="Parse tier: flash, standard, pro"),+ pages: str = typer.Option(+ None, "-p", "--pages", help="Page range, e.g. '1~5' or 'all'"+ ),+ force: bool = typer.Option(False, "--force", help="Force re-parse, ignore cache"),+ wait: int = typer.Option(+ 60, "--wait", help="Max seconds to wait for parse to complete"+ ),+ no_wait: bool = typer.Option(False, "--no-wait", help="Don't wait — return immediately"),+ output: str = typer.Option(None, "-o", "--output", help="Output file path (default: STDOUT)"),+ no_marker: bool = typer.Option(+ False, "--no-marker", help="Omit document structure markers from output"+ ),+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),+ verbose: bool = typer.Option(False, "-v", "--verbose", help="Verbose output"),+) -> None:+ """Parse a document file."""+ from .commands.parse import parse_cmd++ parse_cmd(+ path=path, tier=tier, pages=pages, force=force,+ wait=wait, no_wait=no_wait, output=output,+ no_marker=no_marker, json_mode=json_mode, verbose=verbose,+ )+++def search(+ query: str = typer.Argument(..., help="Search query"),+ file_type: str = typer.Option(None, "--type", help="File type filter"),+ limit: int = typer.Option(20, "--limit", "-n", help="Max results"),+ offset: int = typer.Option(0, "--offset", help="Result offset"),+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),+) -> None:+ """Search parsed document content."""+ from .commands.search import search_cmd++ search_cmd(query=query, file_type=file_type, limit=limit, offset=offset, json_mode=json_mode)+++def find(+ query: str = typer.Argument(..., help="Filename search query"),+ limit: int = typer.Option(50, "--limit", "-n", help="Max results"),+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),+) -> None:+ """Search filenames only (not document content)."""+ from .commands.search import find_cmd++ find_cmd(query=query, limit=limit, json_mode=json_mode)+++def info(+ path: str = typer.Argument(..., help="File path"),+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),+) -> None:+ """Show file/document details and parse status."""+ from .commands.search import info_cmd++ info_cmd(path=path, json_mode=json_mode)+++def cleanup(+ orphans: bool = typer.Option(False, "--orphans", help="Clean orphan docs"),+ deleted: bool = typer.Option(False, "--deleted", help="Clean deleted file records"),+ temp: bool = typer.Option(False, "--temp", help="Clean temporary files"),+ older_than: int = typer.Option(30, "--older-than", help="Days threshold for deleted cleanup"),+ dry_run: bool = typer.Option(True, "--dry-run", help="Preview only"),+ json_mode: bool = typer.Option(False, "--json", help="JSON output"),+) -> None:+ """Clean up database records and temp files."""+ from .commands.cleanup import cleanup_cmd++ cleanup_cmd(+ orphans=orphans, deleted=deleted, temp=temp,+ older_than=older_than, dry_run=dry_run, json_mode=json_mode,+ )+++def main() -> None:+ app()+++if __name__ == "__main__":+ main()diff --git a/mineru/cli_next/output.py b/mineru/cli_next/output.pynew file mode 100644index 00000000..400fb759--- /dev/null+++ b/mineru/cli_next/output.py@@ -0,0 +1,172 @@+"""Rich-based output formatting for mineru CLI."""++from __future__ import annotations++import json+import sys++try:+ from rich.console import Console+ from rich.table import Table+ from rich.panel import Panel+ console = Console()+except ImportError:+ console = None+++def print_error(msg: str) -> None:+ if console:+ console.print(f"[red]Error:[/red] {msg}")+ else:+ print(f"Error: {msg}", file=sys.stderr)+++def print_success(msg: str) -> None:+ if console:+ console.print(f"[green]{msg}[/green]")+ else:+ print(msg)+++def print_info(msg: str) -> None:+ if console:+ console.print(f"[dim]{msg}[/dim]")+ else:+ print(msg)+++def print_json(data: dict) -> None:+ print(json.dumps(data, ensure_ascii=False, indent=2))+++# ── parse ──────────────────────────────────────────────────────+++def format_parse_result(data: dict, json_mode: bool = False) -> None:+ if json_mode:+ print_json(data)+ return++ status = data.get("status", "?")+ tip = data.get("tip", "")++ if status == "pending" or status == "parsing":+ print_info(f"Parse {status}... {tip}")+ elif status == "failed":+ err = data.get("error", {})+ print_error(f"Parse failed: {err.get('code','?')} — {err.get('message','')}")+ else:+ print_success(f"Parse complete (tier={data.get('tier','?')}) {tip}")+++# ── search ─────────────────────────────────────────────────────+++def format_search_results(data: dict, json_mode: bool = False) -> None:+ results = data.get("results", [])+ total = data.get("total", 0)++ if json_mode:+ print_json(data)+ return++ if not results:+ print_info("No results found.")+ return++ table = Table(title=f"Search results ({total} total)")+ table.add_column("File", style="cyan", no_wrap=True)+ table.add_column("Tier", style="green", width=10)+ table.add_column("Snippet", style="dim")+ table.add_column("Paths", style="dim")++ for r in results:+ table.add_row(+ r.get("title") or r.get("filename", "?"),+ r.get("tier", ""),+ (r.get("snippet") or "")[:80],+ ", ".join(r.get("paths", [])[:3]),+ )++ if console:+ console.print(table)+ else:+ for r in results:+ print(f"{r.get('title')} [{r.get('tier')}] — {', '.join(r.get('paths', []))}")+++# ── server status ──────────────────────────────────────────────+++def format_server_status(data: dict, json_mode: bool = False) -> None:+ if json_mode:+ print_json(data)+ return++ if not data.get("running"):+ print_info("Server is not running.")+ return++ if console:+ table = Table(title="MinerU Server")+ table.add_column("Metric", style="cyan")+ table.add_column("Value", style="green")+ table.add_row("PID", str(data.get("pid", "?")))+ table.add_row("Uptime", f"{data.get('uptime_seconds', 0):.0f}s")+ table.add_row("Socket", data.get("socket_path", ""))+ table.add_row("Data dir", data.get("data_dir", ""))+ 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("Watches", str(data.get("watch_count", 0)))+ console.print(table)+ else:+ print(f"Server running (PID {data.get('pid')}), {data.get('files_total')} files")+++# ── info ───────────────────────────────────────────────────────+++def format_info(data: dict, json_mode: bool = False) -> None:+ if json_mode:+ print_json(data)+ return++ if not data.get("found"):+ print_info("File not found in database.")+ return++ if console:+ table = Table(title=f"File Info: {data.get('filename','?')}")+ table.add_column("Field", style="cyan")+ table.add_column("Value", style="green")+ table.add_row("Path", data.get("path", "?"))+ table.add_row("Type", data.get("ext", "?"))+ table.add_row("Size", _format_bytes(data.get("size_bytes")))+ table.add_row("SHA-256", (data.get("sha256") or "")[:16] + "...")+ table.add_row("Page count", str(data.get("page_count", "?")))+ table.add_row("Title", data.get("title") or "—")+ table.add_row("Author", data.get("author") or "—")++ tiers = data.get("tiers", [])+ if tiers:+ tier_str = ", ".join(f"{t['tier']}={t['status']}" for t in tiers)+ table.add_row("Tiers", tier_str)++ console.print(table)+ else:+ print(f"{data.get('filename')} — {data.get('title') or 'No title'}")+++# ── helpers ────────────────────────────────────────────────────+++def _format_bytes(n: int | None) -> str:+ if n is None:+ return "?"+ for unit in ("B", "KB", "MB", "GB"):+ if n < 1024:+ return f"{n} {unit}"+ n //= 1024+ return f"{n} TB"diff --git a/mineru/constants.py b/mineru/constants.pyindex 115b2472..92a0fb27 100644--- a/mineru/constants.py+++ b/mineru/constants.py@@ -1 +1,75 @@-# Shared enums, file type whitelists, and constants.+"""Shared enums, file type whitelists, and constants."""++from __future__ import annotations++from enum import StrEnum++# ── paths ──────────────────────────────────────────────────────────++SOCKET_PATH = "/tmp/mineru.sock"+DATA_DIR = "~/MinerU"++# ── file types ─────────────────────────────────────────────────────++ALLOWED_EXTENSIONS: set[str] = {+ "pdf", "doc", "docx", "xls", "xlsx", "ppt", "pptx", "csv", "rtf", "odt", "ods",+ "epub", "mobi",+ "pages", "key", "numbers",+ "txt", "md", "markdown", "rst", "tex",+ "html", "htm",+ "eml", "mbox",+}++DEFAULT_EXCLUDE_PATTERNS: list[str] = [+ "*/Library/*",+ "*/.git/*",+ "*/node_modules/*",+ "*/vendor/*",+ "*/go/pkg/*",+ "*/__pycache__/*",+ "*/.venv/*",+ "*/miniconda3/*",+ "*/.nvm/*",+ "*/.docker/*",+ "*/target/*",+ "*/dist/*",+ "*/build/*",+]++# ── enums ──────────────────────────────────────────────────────────+++class Tier(StrEnum):+ FLASH = "flash"+ STANDARD = "standard"+ PRO = "pro"+++TIER_ORDER: dict[str, int] = {+ Tier.FLASH: 0,+ Tier.STANDARD: 1,+ Tier.PRO: 2,+}+++class ScanStatus(StrEnum):+ ACTIVE = "active"+ DELETED = "deleted"+ UNREACHABLE = "unreachable"+++class ParseStatus(StrEnum):+ PENDING = "pending"+ PARSING = "parsing"+ DONE = "done"+ FAILED = "failed"+++class RuleType(StrEnum):+ EXCLUDE = "exclude"+ PARSING_RULE = "parsing_rule"+++class WatchStatus(StrEnum):+ ACTIVE = "active"+ UNREACHABLE = "unreachable"diff --git a/mineru/errors.py b/mineru/errors.pyindex 7330fc25..92431107 100644--- a/mineru/errors.py+++ b/mineru/errors.py@@ -1,2 +1,109 @@-# Error code definitions for MinerU API and CLI.-# See NEXT-ERROR.md for the full error code specification.+"""Error definitions for MinerU server and CLI. Aligned with NEXT-ERROR.md."""++from __future__ import annotations++# ── error_code → type mapping ──────────────────────────────────────++_ERROR_TYPE_MAP: dict[str, str] = {+ # invalid_request_error+ "invalid_request": "invalid_request_error",+ "page_range_invalid": "invalid_request_error",+ "file_type_unsupported": "invalid_request_error",+ "file_encrypted": "invalid_request_error",+ "file_corrupted": "invalid_request_error",+ "file_too_large": "invalid_request_error",+ "file_not_found": "invalid_request_error",+ "file_permission_denied": "invalid_request_error",+ "file_hash_mismatch": "invalid_request_error",+ "bytes_mismatch": "invalid_request_error",+ "upload_not_found": "invalid_request_error",+ "upload_not_ready": "invalid_request_error",+ "upload_expired": "invalid_request_error",+ "job_not_found": "invalid_request_error",+ "job_already_terminal": "invalid_request_error",+ "model_not_found": "invalid_request_error",+ "not_cached": "invalid_request_error",+ # authentication_error+ "invalid_api_key": "authentication_error",+ # permission_error+ "feature_requires_api_key": "permission_error",+ "list_requires_api_key": "permission_error",+ "quota_exceeded": "permission_error",+ # rate_limit_error+ "rate_limit_exceeded": "rate_limit_error",+ # engine_error+ "no_engine": "engine_error",+ "engine_unavailable": "engine_error",+ "parse_failed": "engine_error",+ "parse_timeout": "engine_error",+ # api_error+ "internal_error": "api_error",+ "service_unavailable": "api_error",+ "server_not_running": "api_error",+ "server_busy": "api_error",+ "remote_timeout": "api_error",+ "remote_unreachable": "api_error",+}+++def error_type_for(code: str) -> str:+ return _ERROR_TYPE_MAP.get(code, "api_error")+++# ── exception hierarchy ────────────────────────────────────────────+++class MineruError(Exception):+ """Base error with OpenAI-compatible fields."""++ def __init__(self, code: str, message: str = "", param: str | None = None) -> None:+ self.code = code+ self.message = message+ self.param = param+ self.type = error_type_for(code)+++class InvalidRequestError(MineruError):+ def __init__(self, code: str = "invalid_request", message: str = "", param: str | None = None) -> None:+ super().__init__(code, message, param)+++class NotFoundError(MineruError):+ def __init__(self, code: str = "file_not_found", message: str = "", param: str | None = None) -> None:+ super().__init__(code, message, param)+++class PermissionError_(MineruError):+ """Renamed to avoid shadowing builtin PermissionError."""++ def __init__(self, code: str = "file_permission_denied", message: str = "", param: str | None = None) -> None:+ super().__init__(code, message, param)+++class ConflictError(MineruError):+ def __init__(self, code: str = "job_already_terminal", message: str = "", param: str | None = None) -> None:+ super().__init__(code, message, param)+++class EngineError(MineruError):+ def __init__(self, code: str = "parse_failed", message: str = "", param: str | None = None) -> None:+ super().__init__(code, message, param)+++class ServerNotRunningError(MineruError):+ def __init__(self) -> None:+ super().__init__("server_not_running", "Local mineru server is not running. Run 'mineru server start'.")+++# ── FastAPI error response builder ─────────────────────────────────+++def error_response(exc: MineruError) -> dict:+ return {+ "error": {+ "type": exc.type,+ "code": exc.code,+ "message": exc.message,+ "param": exc.param,+ }+ }diff --git a/mineru/parser/__init__.py b/mineru/parser/__init__.pyindex 815ae684..959ca39e 100644--- a/mineru/parser/__init__.py+++ b/mineru/parser/__init__.py@@ -95,7 +95,48 @@ def parse(start_page_id=start_page_id,end_page_id=end_page_id,)+ elif backend == "flash":+ return _parse_flash(path, start_page_id, end_page_id, output_dir)else:raise ValueError(f"Unknown backend: {backend}")- return parser.parse(path)\ No newline at end of file+ return parser.parse(path)+++def _parse_flash(path: str | Path, start_page_id: int, end_page_id: int | None,+ output_dir: str = "./output") -> ParseResult:+ """Flash parse — extract text via pypdfium2 and build proper ParseResult."""+ from pathlib import Path as P++ from ..backend.flash.pdf_extractor import extract_text+ from .. import version+ from .types import Block, Line, PageInfo, Span++ path = P(path)+ text = extract_text(str(path), start_page=start_page_id, end_page=end_page_id)+ pages_text = text.split("\n\n") # each page separated by double newline++ page_count = len(pages_text)+ current_page = start_page_id++ pages: list[PageInfo] = []+ for pt in pages_text:+ if not pt.strip():+ continue+ block = Block(+ type="text",+ lines=[Line(spans=[Span(type="text", content=pt.strip())])],+ )+ page = PageInfo(+ page_idx=current_page,+ para_blocks=[block],+ )+ pages.append(page)+ current_page += 1++ return ParseResult(+ pages=pages,+ _backend="flash",+ _version_name=version.__version__,+ _file_name=path.stem,+ )\ No newline at end of filediff --git a/mineru/parser/engines.py b/mineru/parser/engines.pynew file mode 100644index 00000000..472f87b2--- /dev/null+++ b/mineru/parser/engines.py@@ -0,0 +1,18 @@+"""Tier → backend mapping and engine resolution."""++from __future__ import annotations++from mineru.constants import Tier++TIER_BACKEND_MAP: dict[str, str] = {+ Tier.FLASH: "flash",+ Tier.STANDARD: "pipeline",+ Tier.PRO: "hybrid-auto-engine",+}+++def resolve_backend(tier: str, backend: str | None = None) -> str:+ """Resolve tier to a concrete backend. Explicit backend overrides tier."""+ if backend:+ return backend+ return TIER_BACKEND_MAP.get(tier, "pipeline")diff --git a/mineru/parser/parse_result.py b/mineru/parser/parse_result.pyindex 931766e5..ce65d8c4 100644--- a/mineru/parser/parse_result.py+++ b/mineru/parser/parse_result.py@@ -24,11 +24,29 @@ def _load_union_make(backend: str):from ..backend.vlm.vlm_middle_json_mkcontent import union_makereturn union_make+ if backend == "flash":+ return _flash_union_makefrom ..backend.office.office_middle_json_mkcontent import union_makereturn union_make+def _flash_union_make(pages: list, mode) -> str | list:+ """Minimal union_make for flash: just concatenate text from spans."""+ from ..utils.enum_class import MakeMode++ if mode == MakeMode.MM_MD:+ parts: list[str] = []+ for p in pages:+ for block in getattr(p, "para_blocks", []):+ for line in getattr(block, "lines", []):+ for span in getattr(line, "spans", []):+ if getattr(span, "content", ""):+ parts.append(span.content)+ return "\n\n".join(parts)+ return []++@dataclassclass ParseResult:"""The parsed result of a document.@@ -57,6 +75,22 @@ class ParseResult:assert isinstance(markdown, str)return markdown+ def markdown_with_markers(self, *, page_count: int | None = None) -> str:+ """Generate markdown with page boundary markers (<!-- page N of M -->)."""+ total = page_count or len(self.pages)+ union_make = _load_union_make(self._backend)+ parts: list[str] = []+ for p in self.pages:+ page_num = p.page_idx + 1 # 1-based+ parts.append(f"<!-- page {page_num} of {total} -->")+ try:+ page_md = union_make([p], MakeMode.MM_MD)+ if isinstance(page_md, str) and page_md.strip():+ parts.append(page_md)+ except Exception:+ pass+ return "\n\n".join(parts)+def content_list(self) -> list[dict[str, Any]]:union_make = _load_union_make(self._backend)return union_make(self.pages, MakeMode.CONTENT_LIST) # type: ignore[return-value]diff --git a/mineru/server/app.py b/mineru/server/app.pynew file mode 100644index 00000000..dc05b559--- /dev/null+++ b/mineru/server/app.py@@ -0,0 +1,234 @@+"""mineru server — FastAPI app factory, lifecycle, UDS + optional TCP."""++from __future__ import annotations++import asyncio+import errno+import logging+import os+import socket+import time+from logging.handlers import RotatingFileHandler++import uvicorn+from fastapi import FastAPI, Request+from fastapi.responses import JSONResponse++from mineru.errors import MineruError, error_response+from .config import Config+++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")+ state = AppState()++ # ── startup ──────────────────────────────────────────────────++ @app.on_event("startup")+ async def startup() -> None:+ from .core.db import DatabaseManager+ from .core.fts import FTSManager+ from .services.parse_svc import ParseService+ from .services.search_svc import SearchService+ 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.parse_worker import ParseWorkerPool+ from .background.device_monitor import DeviceMonitor+ from .background.compaction import Compaction++ data_dir = os.path.expanduser(cfg.server.data_dir)+ os.makedirs(data_dir, exist_ok=True)++ _setup_logging(cfg.server.log)++ db_path = os.path.expanduser(cfg.sqlite.path)+ os.makedirs(os.path.dirname(db_path), exist_ok=True)+ state.db = DatabaseManager(db_path, cfg.sqlite)+ await state.db.initialize()++ state.fts = FTSManager(state.db)+ state.config_svc = ConfigService(state.db)+ state.parse_svc = ParseService(state.db, state.fts, state.config_svc, data_dir)+ state.search_svc = SearchService(state.db, state.fts)+ 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 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.device_monitor = DeviceMonitor(state.db, state.config_svc)+ 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.parse_workers.run())+ asyncio.create_task(state.device_monitor.run())+ asyncio.create_task(state.compaction.run())++ state.start_time = time.time()+ state.pid = os.getpid()+ state.data_dir = data_dir+ state.config = cfg++ # ── shutdown ─────────────────────────────────────────────────++ @app.on_event("shutdown")+ async def shutdown() -> None:+ for comp in ["watch", "reg_workers", "parse_workers", "device_monitor", "compaction"]:+ c = getattr(state, comp, None)+ if c and hasattr(c, "stop"):+ await c.stop()++ if state.db:+ await state.db.close()++ # ── middleware ────────────────────────────────────────────────++ @app.middleware("http")+ async def attach_state(request: Request, call_next):+ request.state.app = state+ return await call_next(request)++ # ── error handler ────────────────────────────────────────────++ @app.exception_handler(MineruError)+ async def mineru_error_handler(_request: Request, exc: MineruError) -> JSONResponse:+ status_map = {+ "invalid_request_error": 400,+ "authentication_error": 401,+ "permission_error": 403,+ "rate_limit_error": 429,+ "engine_error": 500,+ "api_error": 500,+ }+ return JSONResponse(+ status_code=status_map.get(exc.type, 500),+ content=error_response(exc),+ )++ # ── routes ───────────────────────────────────────────────────++ from .routes.parse import router as parse_router+ from .routes.search import router as search_router+ from .routes.info import router as info_router+ from .routes.config import router as config_router+ from .routes.cleanup import router as cleanup_router+ from .routes.server import router as server_router++ app.include_router(parse_router)+ app.include_router(search_router)+ app.include_router(info_router)+ app.include_router(config_router)+ app.include_router(cleanup_router)+ app.include_router(server_router)++ return app+++# ── AppState ────────────────────────────────────────────────────────+++class AppState:+ pass+++# ── server entry point ─────────────────────────────────────────────+++def main() -> None:+ """Entry point: python -m mineru.server.app"""+ cfg = Config()+ uds_path = cfg.server.uds.path++ # remove stale socket+ try:+ os.unlink(uds_path)+ except OSError:+ pass++ app = create_app(cfg)+ uv_config = uvicorn.Config(+ app,+ lifespan="on",+ timeout_keep_alive=cfg.server.http.timeout,+ )+ server = uvicorn.Server(uv_config)++ # UDS+ uds_sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)+ uds_sock.bind(uds_path)+ os.chmod(uds_path, cfg.server.uds.permission)+ uds_sock.listen(cfg.server.http.backlog)+ sockets = [uds_sock]++ if cfg.server.http.enabled:+ tcp_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)+ tcp_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ try:+ tcp_sock.bind((cfg.server.http.host, cfg.server.http.port))+ except OSError as exc:+ if exc.errno == errno.EADDRINUSE and not cfg.server.http.strict_port:+ tcp_sock.bind((cfg.server.http.host, 0))+ port = tcp_sock.getsockname()[1]+ print(f"Port {cfg.server.http.port} in use, using {port}")+ else:+ raise+ else:+ 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}")+ else:+ print(f"MinerU server listening on UDS {uds_path}")++ loop = asyncio.new_event_loop()++ async def serve() -> None:+ await server.serve(sockets=sockets)++ try:+ loop.run_until_complete(serve())+ except KeyboardInterrupt:+ pass+ finally:+ try:+ os.unlink(uds_path)+ except OSError:+ pass+ loop.close()+++def _setup_logging(log_cfg) -> None:+ logger = logging.getLogger("mineru")+ level = getattr(logging, log_cfg.level.upper(), logging.INFO)+ logger.setLevel(level)++ if not logger.handlers:+ # console+ ch = logging.StreamHandler()+ ch.setLevel(level)+ ch.setFormatter(logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s"))+ logger.addHandler(ch)++ # file+ log_path = os.path.expanduser(log_cfg.path)+ 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"))+ logger.addHandler(fh)+++if __name__ == "__main__":+ main()diff --git a/mineru/server/background/compaction.py b/mineru/server/background/compaction.pynew file mode 100644index 00000000..12d28edf--- /dev/null+++ b/mineru/server/background/compaction.py@@ -0,0 +1,149 @@+"""Compaction — merges overlapping / adjacent done parse batches to keep the parses table lean."""++from __future__ import annotations++import asyncio+import json as _json+import logging+import os+import time++from mineru.constants import DATA_DIR+from ..services.parse_svc import parse_range_set++logger = logging.getLogger("mineru.compaction")+++class Compaction:+ def __init__(self, db, interval_sec: int = 600) -> None:+ self.db = db+ self.interval_sec = interval_sec+ self.running = False++ async def run(self) -> None:+ self.running = True+ while self.running:+ await asyncio.sleep(self.interval_sec)+ if not self.running:+ break+ try:+ merged = await self._compact()+ if merged > 0:+ logger.info(f"Compaction merged {merged} parse batches")+ except Exception as exc:+ logger.error(f"Compaction error: {exc}")++ async def stop(self) -> None:+ self.running = False++ async def _compact(self) -> int:+ """Scan all (sha256, tier) pairs with multiple done batches and merge them."""+ rows = await self.db.fetchall(+ "SELECT sha256, tier FROM parses WHERE status='done' "+ "GROUP BY sha256, tier HAVING COUNT(*) > 1"+ )+ total_merged = 0+ for r in rows:+ merged = await self._compact_doc_tier(r["sha256"], r["tier"])+ total_merged += merged+ return total_merged++ async def _compact_doc_tier(self, sha256: str, tier: str) -> int:+ rows = await self.db.fetchall(+ "SELECT * FROM parses WHERE sha256=? AND tier=? AND status='done' "+ "ORDER BY done_at DESC",+ (sha256, tier),+ )+ if len(rows) <= 1:+ return 0++ # collect all done pages+ all_pages: set[int] = set()+ max_done_at = 0+ for r in rows:+ all_pages |= parse_range_set(r["pages"])+ if r["done_at"] and r["done_at"] > max_done_at:+ max_done_at = r["done_at"]++ # merge contiguous ranges+ sorted_pages = sorted(all_pages)+ merged_ranges: list[str] = []+ start = sorted_pages[0]+ end = start+ for p in sorted_pages[1:]:+ if p == end + 1:+ end = p+ else:+ merged_ranges.append(f"{start}~{end}" if start != end else str(start))+ start = p+ end = p+ merged_ranges.append(f"{start}~{end}" if start != end else str(start))++ # check if merge actually reduced row count+ if len(merged_ranges) >= len(rows):+ return 0 # no benefit++ # atomic replace+ now = int(time.time() * 1000)+ await self.db.execute(+ "DELETE FROM parses WHERE sha256=? AND tier=? AND status='done'",+ (sha256, tier),+ )+ for pages_str in merged_ranges:+ await self.db.execute(+ "INSERT INTO parses (sha256, tier, pages, status, done_at, priority, "+ "created_at, updated_at) VALUES (?, ?, ?, 'done', ?, 0, ?, ?)",+ (sha256, tier, pages_str, max_done_at, now, now),+ )++ # compact JSON files+ await self._compact_json(sha256, tier, merged_ranges)++ return len(rows) - len(merged_ranges)++ 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)+ if not os.path.isdir(tier_dir):+ return++ # collect all pages from existing JSON files+ pages_by_idx: dict[int, dict] = {}+ for fname in os.listdir(tier_dir):+ if not fname.endswith(".json"):+ continue+ try:+ with open(os.path.join(tier_dir, fname), encoding="utf-8") as f:+ for p in _json.load(f).get("pdf_info", []):+ pages_by_idx[p["page_idx"]] = p+ except Exception:+ pass++ if not pages_by_idx:+ return++ # delete old JSON files+ for fname in os.listdir(tier_dir):+ if fname.endswith(".json"):+ try:+ os.unlink(os.path.join(tier_dir, fname))+ except OSError:+ pass++ # 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]+ 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)+ except Exception:+ pass+++def _safe_filename(s: str) -> str:+ return s # pages string is already safe: "1~5,43~47"diff --git a/mineru/server/background/device_monitor.py b/mineru/server/background/device_monitor.pynew file mode 100644index 00000000..5ffb8bef--- /dev/null+++ b/mineru/server/background/device_monitor.py@@ -0,0 +1,50 @@+"""Device monitor — polls removable watch paths for plug/unplug events."""++from __future__ import annotations++import asyncio+import os+import time+++class DeviceMonitor:+ def __init__(self, db, config_svc) -> None:+ self.db = db+ self.config_svc = config_svc+ self.running = False++ async def run(self) -> None:+ self.running = True+ while self.running:+ watches = await self.config_svc.get_watches_by_status("active")+ for w in watches:+ if not w["removable"]:+ continue+ 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' "+ "WHERE watch_id=? AND scan_status='active'",+ (w["id"],),+ )++ unreachable = await self.config_svc.get_watches_by_status("unreachable")+ for w in unreachable:+ try:+ os.stat(w["path"])+ await self.config_svc.update_watch_status(w["id"], "active")+ await self.db.execute(+ "UPDATE files SET scan_status='active' "+ "WHERE watch_id=? AND scan_status='unreachable'",+ (w["id"],),+ )+ except (FileNotFoundError, OSError):+ pass++ await asyncio.sleep(5)++ async def stop(self) -> None:+ self.running = Falsediff --git a/mineru/server/background/parse_worker.py b/mineru/server/background/parse_worker.pynew file mode 100644index 00000000..08c892ca--- /dev/null+++ b/mineru/server/background/parse_worker.py@@ -0,0 +1,64 @@+"""Parse worker pool — picks up pending parse batches and executes engine."""++from __future__ import annotations++import asyncio+import logging+import time++logger = logging.getLogger("mineru.parse_worker")+++class ParseWorkerPool:+ def __init__(self, parse_svc, num_workers: int = 2) -> None:+ self.parse_svc = parse_svc+ self.num_workers = num_workers+ self.running = False+ self._tasks: list[asyncio.Task] = []++ async def run(self) -> None:+ self.running = True+ 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")+ processed = 0+ no_task_count = 0++ while self.running:+ task = await self.parse_svc.acquire_task()+ if task is None:+ no_task_count += 1+ if no_task_count == 1 or no_task_count % 20 == 0:+ q = await self.parse_svc.get_queue_length()+ logger.info(f"Parse worker {worker_id}: queue={q}")+ await asyncio.sleep(0.5)+ continue++ no_task_count = 0+ try:+ success = await self.parse_svc.process_doc(task)+ if success:+ processed += 1+ if processed % 50 == 0:+ 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}")+ try:+ now = int(time.time() * 1000)+ await self.parse_svc.db.execute(+ "UPDATE parses SET status='failed', error_code=?, error_msg=?, "+ "locked_at=NULL, updated_at=? WHERE id=?",+ ("parse_failed", str(exc)[:500], now, task["id"]),+ )+ except Exception:+ pass++ logger.info(f"Parse worker {worker_id} stopped, processed {processed} total")++ async def stop(self) -> None:+ self.running = False+ for t in self._tasks:+ t.cancel()+ if self._tasks:+ await asyncio.gather(*self._tasks, return_exceptions=True)diff --git a/mineru/server/background/reg_worker.py b/mineru/server/background/reg_worker.pynew file mode 100644index 00000000..d412661b--- /dev/null+++ b/mineru/server/background/reg_worker.py@@ -0,0 +1,79 @@+"""Registration worker pool — picks up unregistered files and runs register_file()."""++from __future__ import annotations++import asyncio+import logging+import time++logger = logging.getLogger("mineru.reg_worker")+++class RegistrationWorkerPool:+ def __init__(self, parse_svc, num_workers: int = 2) -> None:+ self.parse_svc = parse_svc+ self.num_workers = num_workers+ self.running = False+ self._tasks: list[asyncio.Task] = []++ async def run(self) -> None:+ self.running = True+ 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")+ processed = 0+ no_task_count = 0++ while self.running:+ task = await self._acquire_task()+ if task is None:+ no_task_count += 1+ if no_task_count == 1 or no_task_count % 20 == 0:+ 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}")+ 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"))+ processed += 1+ if processed % 100 == 0:+ logger.info(f"Reg worker {worker_id} registered {processed} files")+ except Exception as exc:+ logger.error(f"Reg 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"]),+ )+ except Exception:+ pass++ logger.info(f"Reg 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+ return await self.parse_svc.db.fetchone(+ "UPDATE files SET locked_at=? "+ "WHERE id = ("+ " SELECT id FROM files "+ " WHERE sha256 IS NULL AND scan_status='active' "+ " AND (locked_at IS NULL OR locked_at < ?) "+ " ORDER BY first_seen_at ASC LIMIT 1"+ ") RETURNING *",+ (now, timeout),+ )++ async def stop(self) -> None:+ self.running = False+ for t in self._tasks:+ t.cancel()+ if self._tasks:+ await asyncio.gather(*self._tasks, return_exceptions=True)diff --git a/mineru/server/background/watch.py b/mineru/server/background/watch.pynew file mode 100644index 00000000..132bb6a6--- /dev/null+++ b/mineru/server/background/watch.py@@ -0,0 +1,103 @@+"""Filesystem watch loop — monitors configured directories for new/changed files."""++from __future__ import annotations++import asyncio+import os+import time+from pathlib import Path++from watchfiles import awatch++from mineru.constants import ALLOWED_EXTENSIONS+++class WatchLoop:+ def __init__(self, db, config_svc, parse_svc) -> None:+ self.db = db+ self.config_svc = config_svc+ self.parse_svc = parse_svc+ self.running = False+ self._active_watchers: dict[int, asyncio.Task] = {}++ async def run(self) -> None:+ self.running = True+ while self.running:+ watches = await self.config_svc.list_watches()+ active_ids: set[int] = set()++ for w in watches:+ if w["watch_status"] != "active":+ continue+ active_ids.add(w["id"])++ if w["id"] not in self._active_watchers:+ await self._initial_scan(w["path"], w["id"])+ task = asyncio.create_task(self._watch_one(w["path"], w["id"]))+ self._active_watchers[w["id"]] = task++ # cancel watchers for removed watches+ for wid in list(self._active_watchers):+ if wid not in active_ids:+ self._active_watchers[wid].cancel()+ del self._active_watchers[wid]++ await asyncio.sleep(30)++ async def _initial_scan(self, path: str, watch_id: int) -> None:+ """Walk directory tree and discover all existing files."""+ try:+ file_count = 0+ for root, dirs, files in os.walk(path):+ dirs[:] = [d for d in dirs if not d.startswith(".")]+ for fname in files:+ filepath = os.path.join(root, fname)+ ext = Path(filepath).suffix.lstrip(".").lower()+ if ext not in ALLOWED_EXTENSIONS:+ continue+ if await self.config_svc.is_path_excluded(filepath):+ continue+ await self._discover_file(filepath, watch_id)+ file_count += 1+ await self.config_svc.update_watch_scan_stats(watch_id, file_count)+ except Exception:+ pass++ async def _watch_one(self, path: str, watch_id: int) -> None:+ try:+ async for changes in awatch(path, recursive=True, debounce=500):+ if not self.running:+ break+ for _change_type, filepath in changes:+ await self._handle_event(filepath, watch_id)+ except Exception:+ pass++ async def _handle_event(self, filepath: str, watch_id: int) -> None:+ ext = Path(filepath).suffix.lstrip(".").lower()+ if ext not in ALLOWED_EXTENSIONS:+ return+ if await self.config_svc.is_path_excluded(filepath):+ return+ await self._discover_file(filepath, watch_id)++ async def _discover_file(self, filepath: str, watch_id: int) -> None:+ now = int(time.time() * 1000)++ await self.db.execute(+ "INSERT OR IGNORE INTO files (path, filename, ext, size_bytes, mtime_ms, "+ "watch_id, first_seen_at, updated_at) VALUES (?, ?, ?, 0, 0, ?, ?, ?)",+ (+ filepath,+ Path(filepath).name,+ Path(filepath).suffix.lstrip(".").lower(),+ watch_id,+ now,+ now,+ ),+ )++ async def stop(self) -> None:+ self.running = False+ for t in self._active_watchers.values():+ t.cancel()diff --git a/mineru/server/client.py b/mineru/server/client.pynew file mode 100644index 00000000..1aec9993--- /dev/null+++ b/mineru/server/client.py@@ -0,0 +1,138 @@+"""Product SDK — communicates with the local mineru server over UDS."""++from __future__ import annotations++import httpx++from mineru.constants import SOCKET_PATH+from mineru.errors import MineruError, ServerNotRunningError, error_type_for+++class MineruClient:+ """httpx-based client for the local mineru server."""++ 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)++ def close(self) -> None:+ self._client.close()++ # ── helpers ────────────────────────────────────────────────++ def _get(self, url_path: str, **params) -> dict:+ data = self._request("GET", url_path, query_params=params or None)+ return data++ def _post(self, url_path: str, json_data: dict | None = None) -> dict:+ data = self._request("POST", url_path, json_data=json_data)+ return data++ def _delete(self, url_path: str, **params) -> 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:+ try:+ if method == "GET":+ resp = self._client.get(url_path, params=query_params or {})+ elif method == "POST":+ resp = self._client.post(url_path, json=json_data or {})+ else:+ resp = self._client.delete(url_path, params=query_params or {})+ resp.raise_for_status()+ except httpx.ConnectError:+ raise ServerNotRunningError() from None+ data = resp.json()+ if not isinstance(data, dict):+ return {}+ if "error" in data:+ err = data["error"]+ if isinstance(err, dict):+ raise _error_from_response(err)+ return data++ # ── server ─────────────────────────────────────────────────++ def server_status(self) -> dict:+ return self._get("/server/status")++ def shutdown(self) -> dict:+ return self._post("/shutdown")++ # ── 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_status(self, sha256: str, tier: str) -> dict:+ return self._get("/parse/status", sha256=sha256, tier=tier)++ def parse_content(self, sha256: str, tier: str, output: str | None = None) -> dict:+ params = {"sha256": sha256, "tier": tier}+ if output:+ params["output"] = output+ return self._get("/parse/content", **params)++ # ── search ─────────────────────────────────────────────────++ 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:+ return self._get("/find", q=query, limit=limit)++ # ── info ───────────────────────────────────────────────────++ def info(self, file_path: str) -> dict:+ return self._get("/info", path=file_path)++ # ── config ─────────────────────────────────────────────────++ 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_list(self) -> dict:+ return self._get("/config/watch")++ def config_watch_rm(self, path: str) -> dict:+ return self._delete("/config/watch", path=path)++ def config_exclude_add(self, pattern: str, priority: int = 0) -> dict:+ return self._post("/config/exclude", {"pattern": pattern, "priority": priority})++ def config_exclude_list(self) -> dict:+ return self._get("/config/exclude")++ 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_list(self) -> dict:+ return self._get("/config/parsing-rules")++ def config_parsing_rules_rm(self, rule_id: int) -> dict:+ return self._delete(f"/config/parsing-rules/{rule_id}")+++def _error_from_response(error: dict) -> MineruError:+ code = error.get("code", "internal_error")+ message = error.get("message", "")+ param = error.get("param")+ return MineruError(code, message, param)diff --git a/mineru/server/config.py b/mineru/server/config.pynew file mode 100644index 00000000..d45b5304--- /dev/null+++ b/mineru/server/config.py@@ -0,0 +1,87 @@+import os+import platform+import socket+import tempfile++from pydantic import BaseModel+++def _uds_available() -> bool:+ try:+ socket.socket(socket.AF_UNIX, socket.SOCK_STREAM).close()+ return True+ except Exception:+ return False+++def _default_uds_path() -> str:+ system = platform.system().lower()+ if system not in ("windows", "darwin", "linux"):+ raise RuntimeError(f"System [{system}] is not supported.")+ if not _uds_available():+ raise RuntimeError("Unix domain socket is not available.")+ TEMP = tempfile.gettempdir() if system == "windows" else "/tmp"+ return os.path.join(TEMP, "mineru.sock")+++def _default_data_path() -> str:+ HOME = os.path.expanduser("~")+ return os.path.join(HOME, "MinerU")+++def _default_log_path() -> str:+ HOME = os.path.expanduser("~")+ return os.path.join(HOME, "MinerU", "mineru.log")+++def _default_db_path() -> str:+ HOME = os.path.expanduser("~")+ return os.path.join(HOME, "MinerU", "mineru.db")+++class UDSConfig(BaseModel):+ path: str = _default_uds_path()+ permission: int = 0o600+++class HTTPConfig(BaseModel):+ enabled: bool = False+ host: str = "127.0.0.1"+ port: int = 15980+ strict_port: bool = False+ backlog: int = 128+ timeout: int = 600+++class LogConfig(BaseModel):+ path: str = _default_log_path()+ level: str = "info"+ # max_bytes: 5242880 # 5MB 轮转+ # backup_count: 3+++class ServerConfig(BaseModel):+ uds: UDSConfig = UDSConfig()+ http: HTTPConfig = HTTPConfig()+ log: LogConfig = LogConfig()+ data_dir: str = _default_data_path()+ reg_workers: int = 2+ parse_workers: int = 2+ compaction_interval_sec: int = 3600+++class SQLiteConfig(BaseModel):+ path: str = _default_db_path()+ mmap_size: int = 268435456 # 256 MB+ cache_size: int = -20000 # 20 MB (negative = KB)+ wal_autocheckpoint: int = 1000+ journal_size_limit: int = 33_554_432 # 32 MB+ temp_store: str = "memory"+ synchronous: str = "NORMAL"+++class Config(BaseModel):+ """Configurations mainly needed before server was started."""++ server: ServerConfig = ServerConfig()+ sqlite: SQLiteConfig = SQLiteConfig()diff --git a/mineru/server/core/db.py b/mineru/server/core/db.pynew file mode 100644index 00000000..fc9955a1--- /dev/null+++ b/mineru/server/core/db.py@@ -0,0 +1,315 @@+from __future__ import annotations++import os+import time++import aiosqlite++SCHEMA_VERSION = 1++CREATE_TABLES_SQL = [+ # ── files ──────────────────────────────────────────────────────+ """+ CREATE TABLE IF NOT EXISTS files (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ path TEXT NOT NULL UNIQUE,+ filename TEXT NOT NULL,+ ext TEXT NOT NULL,+ size_bytes INTEGER NOT NULL,+ mtime_ms INTEGER NOT NULL,+ birthtime_ms INTEGER,+ sha256 TEXT REFERENCES docs(sha256),+ watch_id INTEGER REFERENCES watch_targets(id),+ scan_status TEXT NOT NULL DEFAULT 'active',+ locked_at INTEGER,+ error_code TEXT,+ error_msg TEXT,+ deleted_at INTEGER,+ first_seen_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ """,+ "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 (+ sha256 TEXT PRIMARY KEY,+ size_bytes INTEGER NOT NULL,+ mime_type TEXT,+ page_count INTEGER,+ lang TEXT,+ title TEXT,+ author TEXT,+ subject TEXT,+ keywords TEXT,+ is_encrypted INTEGER NOT NULL DEFAULT 0,+ is_scanned INTEGER NOT NULL DEFAULT 0,+ meta_tier TEXT,+ first_seen_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ """,++ # ── parses ─────────────────────────────────────────────────────+ """+ CREATE TABLE IF NOT EXISTS parses (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ sha256 TEXT NOT NULL REFERENCES docs(sha256),+ tier TEXT NOT NULL,+ pages TEXT NOT NULL,+ status TEXT NOT NULL DEFAULT 'pending',+ priority INTEGER NOT NULL DEFAULT 0,+ locked_at INTEGER,+ error_code TEXT,+ error_msg TEXT,+ output_path TEXT,+ done_at INTEGER,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ """,+ "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(+ sha256 UNINDEXED,+ tier UNINDEXED,+ text,+ title,+ author,+ filename,+ tokenize='unicode61'+ );+ """,++ # ── fts_filenames ──────────────────────────────────────────────+ """+ CREATE VIRTUAL TABLE IF NOT EXISTS fts_filenames USING fts5(+ file_id UNINDEXED,+ filename,+ ext,+ tokenize='unicode61'+ );+ """,++ # ── watch_targets ──────────────────────────────────────────────+ """+ CREATE TABLE IF NOT EXISTS watch_targets (+ id INTEGER PRIMARY KEY,+ path TEXT NOT NULL UNIQUE,+ label TEXT,+ removable INTEGER NOT NULL DEFAULT 0,+ enabled INTEGER NOT NULL DEFAULT 1,+ recursive INTEGER NOT NULL DEFAULT 0,+ watch_status TEXT NOT NULL DEFAULT 'active',+ unreachable_at INTEGER,+ last_scan_at INTEGER,+ last_scan_files INTEGER DEFAULT 0+ );+ """,++ # ── rules ──────────────────────────────────────────────────────+ """+ CREATE TABLE IF NOT EXISTS rules (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ name TEXT,+ rule_type TEXT NOT NULL,+ pattern TEXT NOT NULL,+ tier TEXT,+ pages TEXT,+ remote INTEGER NOT NULL DEFAULT 0,+ enabled INTEGER NOT NULL DEFAULT 1,+ priority INTEGER NOT NULL DEFAULT 0,+ hit_count INTEGER NOT NULL DEFAULT 0+ );+ """,++ # ── config ─────────────────────────────────────────────────────+ """+ CREATE TABLE IF NOT EXISTS config (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL+ );+ """,++ # ── _migrations ────────────────────────────────────────────────+ """+ CREATE TABLE IF NOT EXISTS _migrations (+ version INTEGER PRIMARY KEY,+ applied_at INTEGER NOT NULL,+ description TEXT+ );+ """,+]++DEFAULT_CONFIG = {+ "data_dir": "~/MinerU",+ "default_tier": "flash",+ "scan_interval_sec": "300",+ "reg_lock_timeout_sec": "60",+ "parse_lock_timeout_sec": "1800",+ "device_check_interval_sec": "5",+}++DEFAULT_EXCLUDE_RULES = [+ ("系统-*/Library/*", "*/Library/*"),+ ("系统-*/.git/*", "*/.git/*"),+ ("系统-*/node_modules/*", "*/node_modules/*"),+ ("系统-*/vendor/*", "*/vendor/*"),+ ("系统-*/go/pkg/*", "*/go/pkg/*"),+ ("系统-*/__pycache__/*", "*/__pycache__/*"),+ ("系统-*/.venv/*", "*/.venv/*"),+ ("系统-*/miniconda3/*", "*/miniconda3/*"),+ ("系统-*/.nvm/*", "*/.nvm/*"),+ ("系统-*/.docker/*", "*/.docker/*"),+ ("系统-*/target/*", "*/target/*"),+ ("系统-*/dist/*", "*/dist/*"),+ ("系统-*/build/*", "*/build/*"),+]+++class DatabaseManager:+ """Per-operation connection manager — no pooling, no shared state."""++ def __init__(self, db_path: str, sqlite_cfg=None) -> None:+ self.db_path = db_path+ self.sqlite_cfg = sqlite_cfg # SQLiteConfig or None++ # ── lifecycle ──────────────────────────────────────────────────++ async def initialize(self) -> None:+ """Create tables, apply migrations, seed default data. Idempotent."""+ os.makedirs(os.path.dirname(self.db_path), exist_ok=True)+ conn = await aiosqlite.connect(self.db_path)+ await conn.execute("PRAGMA journal_mode=WAL")+ await conn.execute("PRAGMA foreign_keys=ON")++ if self.sqlite_cfg:+ await conn.execute(f"PRAGMA synchronous={self.sqlite_cfg.synchronous}")+ await conn.execute(f"PRAGMA mmap_size={self.sqlite_cfg.mmap_size}")+ await conn.execute(f"PRAGMA cache_size={self.sqlite_cfg.cache_size}")+ await conn.execute(f"PRAGMA temp_store={self.sqlite_cfg.temp_store}")+ await conn.execute(+ f"PRAGMA wal_autocheckpoint={self.sqlite_cfg.wal_autocheckpoint}"+ )+ await conn.execute(+ f"PRAGMA journal_size_limit={self.sqlite_cfg.journal_size_limit}"+ )+ else:+ await conn.execute("PRAGMA synchronous=NORMAL")+ await conn.execute("PRAGMA mmap_size=268435456")+ await conn.execute("PRAGMA cache_size=-20000")+ await conn.execute("PRAGMA temp_store=MEMORY")+ await conn.execute("PRAGMA wal_autocheckpoint=1000")+ await conn.execute("PRAGMA journal_size_limit=33554432")++ for sql in CREATE_TABLES_SQL:+ await conn.execute(sql)++ # ── migrations ──────────────────────────────────────────+ for version in range(1, SCHEMA_VERSION + 1):+ cursor = await conn.execute(+ "SELECT 1 FROM _migrations WHERE version=?", (version,)+ )+ if await cursor.fetchone() is None:+ await _apply_migration(conn, version)+ await conn.execute(+ "INSERT INTO _migrations (version, applied_at) VALUES (?, ?)",+ (version, _now_ms()),+ )++ # ── seed data ───────────────────────────────────────────+ for key, value in DEFAULT_CONFIG.items():+ await conn.execute(+ "INSERT OR IGNORE INTO config (key, value) VALUES (?, ?)", (key, value)+ )++ for name, pattern in DEFAULT_EXCLUDE_RULES:+ await conn.execute(+ "INSERT OR IGNORE INTO rules (name, rule_type, pattern, priority) "+ "SELECT ?, 'exclude', ?, 0 "+ "WHERE NOT EXISTS (SELECT 1 FROM rules WHERE rule_type='exclude' AND pattern=?)",+ (name, pattern, pattern),+ )++ await conn.commit()+ await conn.close()++ async def _connect(self) -> aiosqlite.Connection:+ conn = await aiosqlite.connect(self.db_path)+ await conn.execute("PRAGMA journal_mode=WAL")+ await conn.execute("PRAGMA foreign_keys=ON")+ conn.row_factory = aiosqlite.Row+ return conn++ async def close(self) -> None:+ pass # no cached connection++ # ── query helpers ──────────────────────────────────────────────++ async def execute(self, sql: str, params: tuple | None = None) -> aiosqlite.Cursor:+ conn = await self._connect()+ cursor = await conn.execute(sql, params or ())+ await conn.commit()+ await conn.close()+ return cursor++ async def execute_insert(self, sql: str, params: tuple | None = None) -> int:+ conn = await self._connect()+ cursor = await conn.execute(sql, params or ())+ await conn.commit()+ lastid = cursor.lastrowid+ await conn.close()+ return lastid++ async def fetchone(self, sql: str, params: tuple | None = None) -> dict | None:+ conn = await self._connect()+ cursor = await conn.execute(sql, params or ())+ row = await cursor.fetchone()+ result = dict(row) if row else None+ await conn.commit()+ await conn.close()+ return result++ async def fetchall(self, sql: str, params: tuple | None = None) -> list[dict]:+ conn = await self._connect()+ cursor = await conn.execute(sql, params or ())+ rows = await cursor.fetchall()+ result = [dict(row) for row in rows]+ await conn.commit()+ await conn.close()+ return result++ async def commit(self) -> None:+ pass++ async def execute_atomic(self, statements: list[tuple[str, tuple]]) -> int:+ """Execute multiple statements in a single transaction."""+ conn = await self._connect()+ try:+ for sql, params in statements:+ await conn.execute(sql, params)+ await conn.commit()+ except Exception:+ await conn.rollback()+ raise+ finally:+ await conn.close()+ return len(statements)+++# ── helpers ────────────────────────────────────────────────────────++def _now_ms() -> int:+ return int(time.time() * 1000)+++async def _apply_migration(conn: aiosqlite.Connection, version: int) -> None:+ """Apply a single schema migration. Extend here as schema evolves."""+ # version 1: initial schema — already created by CREATE_TABLES_SQL+ passdiff --git a/mineru/server/core/file_io.py b/mineru/server/core/file_io.pynew file mode 100644index 00000000..40df5f99--- /dev/null+++ b/mineru/server/core/file_io.py@@ -0,0 +1,159 @@+"""File I/O utilities: SHA-256, stat, metadata extraction."""++from __future__ import annotations++import asyncio+import hashlib+import os+from pathlib import Path++import pypdfium2++# Optional office doc support+try:+ from docx import Document+except ImportError:+ Document = None # type: ignore[assignment]+try:+ from pptx import Presentation+except ImportError:+ Presentation = None # type: ignore[assignment]+try:+ from openpyxl import load_workbook+except ImportError:+ load_workbook = None # type: ignore[assignment]++# Metadata truncation limits+TRUNC_TITLE = 500+TRUNC_AUTHOR = 200+TRUNC_SUBJECT = 1000+TRUNC_KEYWORDS = 1000+++# ── SHA-256 ────────────────────────────────────────────────────────++def _sha256_sync(filepath: str) -> str:+ h = hashlib.sha256()+ with open(filepath, "rb") as f:+ while chunk := f.read(65536):+ h.update(chunk)+ return h.hexdigest()+++async def compute_sha256(filepath: str) -> str:+ return await asyncio.to_thread(_sha256_sync, filepath)+++# ── 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),+ }++ return await asyncio.to_thread(_stat)+++# ── 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."""+ ext = Path(filepath).suffix.lower().lstrip(".")++ result = {+ "mime_type": None,+ "page_count": None,+ "title": None,+ "author": None,+ "subject": None,+ "keywords": None,+ "is_encrypted": 0,+ "is_scanned": 0,+ }++ if ext == "pdf":+ await _extract_pdf_meta(filepath, result)++ elif ext in ("docx", "pptx", "xlsx"):+ await _extract_office_meta(filepath, ext, result)++ # truncate all string fields+ for field, limit in [+ ("title", TRUNC_TITLE),+ ("author", TRUNC_AUTHOR),+ ("subject", TRUNC_SUBJECT),+ ("keywords", TRUNC_KEYWORDS),+ ]:+ val = result.get(field)+ if val and len(val) > limit:+ result[field] = val[:limit]++ return result+++# ── PDF metadata ───────────────────────────────────────────────────++async def _extract_pdf_meta(filepath: str, result: dict) -> None:+ def _extract() -> None:+ pdf = pypdfium2.PdfDocument(filepath)+ try:+ result["page_count"] = len(pdf)++ meta = pdf.get_metadata_dict() or {}+ result["title"] = meta.get("Title") or None+ result["author"] = meta.get("Author") or None+ result["subject"] = meta.get("Subject") or None+ result["keywords"] = meta.get("Keywords") or None++ # pypdfium2 doesn't expose is_encrypted directly;+ # trying to access pages on an encrypted doc raises.+ finally:+ pdf.close()++ await asyncio.to_thread(_extract)+++# ── Office metadata ────────────────────────────────────────────────++async def _extract_office_meta(filepath: str, ext: str, result: dict) -> None:+ def _extract() -> None:+ if ext == "docx":+ if Document is None:+ return+ doc = Document(filepath)+ cp = doc.core_properties+ result["title"] = cp.title or None+ result["author"] = cp.author or None+ result["subject"] = cp.subject or None+ result["keywords"] = cp.keywords or None+ # DOCX has no fixed page count; leave as None (will be set to 1 later by caller)++ elif ext == "pptx":+ if Presentation is None:+ return+ prs = Presentation(filepath)+ cp = prs.core_properties+ result["title"] = cp.title or None+ result["author"] = cp.author or None+ result["subject"] = cp.subject or None+ result["keywords"] = cp.keywords or None+ result["page_count"] = len(prs.slides)++ elif ext == "xlsx":+ if load_workbook is None:+ return+ wb = load_workbook(filepath, read_only=True)+ cp = wb.properties+ result["title"] = cp.title or None+ result["author"] = cp.creator or None+ result["subject"] = cp.subject or None+ result["keywords"] = cp.keywords or None+ result["page_count"] = len(wb.sheetnames)+ wb.close()++ await asyncio.to_thread(_extract)diff --git a/mineru/server/core/fts.py b/mineru/server/core/fts.pynew file mode 100644index 00000000..0c337f8e--- /dev/null+++ b/mineru/server/core/fts.py@@ -0,0 +1,123 @@+"""FTS5 manager and CJK tokenization."""++from __future__ import annotations++try:+ import jieba+except ImportError:+ jieba = None # type: ignore[assignment]++FTS_SEP = ""+++# ── tokenization ───────────────────────────────────────────────────+++def tokenize_for_index(text: str) -> str:+ """Tokenize text for FTS storage. Uses jieba + Unit Separator."""+ if not text or jieba is None:+ return text+ return FTS_SEP.join(jieba.cut(text))+++def tokenize_for_query(text: str) -> str:+ """Tokenize query for FTS search. Uses jieba + space."""+ if not text or jieba is None:+ return text+ return " ".join(jieba.cut(text))+++def strip_sep(text: str) -> str:+ """Remove FTS separator from snippet output."""+ return text.replace(FTS_SEP, "")+++# ── FTS manager ────────────────────────────────────────────────────+++class FTSManager:+ def __init__(self, db) -> None:+ self.db = db++ # ── fts_contents ────────────────────────────────────────────++ 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),+ ),+ ])++ async def search(self, query: str, limit: int = 200) -> list[dict]:+ tokens = _sanitize_query_tokens(tokenize_for_query(query))+ if not tokens:+ return []+ fts_query = " ".join(tokens)+ try:+ return await self.db.fetchall(+ "SELECT sha256, title, author, filename, tier, "+ "snippet(fts_contents, 2, '<mark>', '</mark>', '...', 40) AS snippet, rank "+ "FROM fts_contents WHERE fts_contents MATCH ? "+ "ORDER BY rank LIMIT ?",+ (fts_query, limit),+ )+ except Exception:+ return []++ async def get_tier(self, sha256: str) -> str | None:+ row = await self.db.fetchone(+ "SELECT tier FROM fts_contents WHERE sha256=?", (sha256,)+ )+ return row["tier"] if row else None++ async def delete(self, sha256: str) -> None:+ await self.db.execute("DELETE FROM fts_contents WHERE sha256=?", (sha256,))++ # ── 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),+ ),+ ])++ async def search_filenames(self, query: str, limit: int = 50) -> list[dict]:+ tokens = _sanitize_query_tokens(tokenize_for_query(query))+ if not tokens:+ return []+ fts_query = " ".join(tokens)+ try:+ return await self.db.fetchall(+ "SELECT file_id, ext, "+ "snippet(fts_filenames, 1, '<mark>', '</mark>', '...', 40) AS snippet "+ "FROM fts_filenames WHERE fts_filenames MATCH ? "+ "ORDER BY rank LIMIT ?",+ (fts_query, limit),+ )+ except Exception:+ return []++ async def delete_filename(self, file_id: int) -> None:+ await self.db.execute("DELETE FROM fts_filenames WHERE file_id=?", (file_id,))+++# ── helpers ────────────────────────────────────────────────────────++def _sanitize_query_tokens(tokenized: str) -> list[str]:+ """Remove special characters and FTS5 operators from query tokens."""+ safe: list[str] = []+ for t in tokenized.split():+ t = t.strip().replace('"', "").replace(".", "").replace("-", "")+ if t and t.upper() not in ("AND", "OR", "NOT", "NEAR"):+ safe.append(t)+ return safediff --git a/mineru/server/routes/cleanup.py b/mineru/server/routes/cleanup.pynew file mode 100644index 00000000..de0d5a0d--- /dev/null+++ b/mineru/server/routes/cleanup.py@@ -0,0 +1,40 @@+"""Cleanup routes."""++from __future__ import annotations++from fastapi import APIRouter, Query, Request++router = APIRouter(tags=["cleanup"])++[email protected]("/cleanup/deleted")+async def cleanup_deleted(+ request: Request,+ older_than_days: int = Query(30, ge=1),+ dry_run: bool = Query(True),+):+ state = request.state.app+ count = await state.cleanup_svc.cleanup_deleted(+ older_than_days=older_than_days, dry_run=dry_run,+ )+ return {"deleted_files": count, "dry_run": dry_run}++[email protected]("/cleanup/orphans")+async def cleanup_orphans(+ request: Request,+ dry_run: bool = Query(True),+):+ state = request.state.app+ count = await state.cleanup_svc.cleanup_orphans(dry_run=dry_run)+ return {"orphan_docs": count, "dry_run": dry_run}++[email protected]("/cleanup/temp")+async def cleanup_temp(+ request: Request,+ older_than_days: int = Query(7, ge=1),+):+ 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/server/routes/config.pynew file mode 100644index 00000000..7ba29f5d--- /dev/null+++ b/mineru/server/routes/config.py@@ -0,0 +1,111 @@+"""Config routes: watch, exclude, parsing-rules, global config."""++from __future__ import annotations++from fastapi import APIRouter, Query, Request+from pydantic import BaseModel+++class WatchRequest(BaseModel):+ path: str+ removable: bool = False+ label: str | None = None+++class RuleRequest(BaseModel):+ pattern: str+ name: str | None = None+ tier: str | None = None+ pages: str | None = None+ remote: bool = False+ priority: int = 0+++router = APIRouter(tags=["config"])+++# ── global config ────────────────────────────────────────────────+[email protected]("/config")+async def get_config(request: Request):+ state = request.state.app+ cfg = await state.config_svc.get_all()+ watches = await state.config_svc.list_watches()+ rules = await state.config_svc.list_rules()+ return {"config": cfg, "watches": watches, "rules": rules}+++# ── watch ────────────────────────────────────────────────────────+[email protected]("/config/watch")+async def list_watches(request: Request):+ state = request.state.app+ watches = await state.config_svc.list_watches()+ return {"watches": watches}++[email protected]("/config/watch")+async def add_watch(req: WatchRequest, request: Request):+ state = request.state.app+ w = await state.config_svc.add_watch(+ req.path, removable=req.removable, label=req.label,+ )+ return w++[email protected]("/config/watch")+async def remove_watch(request: Request, path: str = Query(...)):+ state = request.state.app+ await state.config_svc.remove_watch(path)+ return {"message": f"Watch removed: {path}"}+++# ── exclude ──────────────────────────────────────────────────────+[email protected]("/config/exclude")+async def list_excludes(request: Request):+ state = request.state.app+ rules = await state.config_svc.list_rules("exclude")+ return {"rules": rules}++[email protected]("/config/exclude")+async def add_exclude(req: RuleRequest, request: Request):+ state = request.state.app+ rid = await state.config_svc.add_rule(+ req.name or "用户规则", "exclude", req.pattern, priority=req.priority,+ )+ return {"id": rid}++[email protected]("/config/exclude/{rule_id}")+async def remove_exclude(rule_id: int, request: Request):+ state = request.state.app+ await state.config_svc.remove_rule(rule_id)+ return {"message": f"Exclude rule {rule_id} removed"}+++# ── parsing-rules ────────────────────────────────────────────────+[email protected]("/config/parsing-rules")+async def list_parsing_rules(request: Request):+ state = request.state.app+ rules = await state.config_svc.list_rules("parsing_rule")+ return {"rules": rules}++[email protected]("/config/parsing-rules")+async def add_parsing_rule(req: RuleRequest, request: Request):+ 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,+ )+ return {"id": rid}++[email protected]("/config/parsing-rules/{rule_id}")+async def remove_parsing_rule(rule_id: int, request: Request):+ 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/server/routes/info.pynew file mode 100644index 00000000..1a318318--- /dev/null+++ b/mineru/server/routes/info.py@@ -0,0 +1,52 @@+"""Info route."""++from __future__ import annotations++from fastapi import APIRouter, Query, Request++router = APIRouter(tags=["info"])++[email protected]("/info")+async def info(request: Request, path: str = Query(...)):+ state = request.state.app++ file_row = await state.db.fetchone(+ "SELECT * FROM files WHERE path=? AND scan_status='active'", (path,)+ )+ if file_row is None:+ return {"path": path, "found": False}++ sha = file_row["sha256"]+ 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 []++ tiers: list[dict] = []+ for pr in parse_rows:+ tiers.append({+ "tier": pr["tier"],+ "status": pr["status"],+ "pages": pr["pages"],+ "done_at": pr["done_at"],+ })++ return {+ "path": file_row["path"],+ "filename": file_row["filename"],+ "ext": file_row["ext"],+ "size_bytes": file_row["size_bytes"],+ "mtime_ms": file_row["mtime_ms"],+ "sha256": sha,+ "scan_status": file_row["scan_status"],+ "title": doc["title"] if doc else None,+ "author": doc["author"] if doc else None,+ "page_count": doc["page_count"] if doc else None,+ "lang": doc["lang"] if doc else None,+ "is_encrypted": doc["is_encrypted"] if doc else 0,+ "tiers": tiers,+ "found": True,+ }diff --git a/mineru/server/routes/parse.py b/mineru/server/routes/parse.pynew file mode 100644index 00000000..95a7458f--- /dev/null+++ b/mineru/server/routes/parse.py@@ -0,0 +1,90 @@+"""Parse routes."""++from __future__ import annotations++import os++from fastapi import APIRouter, Query, Request++from ..types import ParseRequest++router = APIRouter(tags=["parse"])++[email protected]("/parse")+async def parse(req: ParseRequest, request: Request):+ state = request.state.app+ result = await state.parse_svc.request_parse(+ req.path, tier=req.tier, pages=req.pages, force=req.force,+ )+ return result++[email protected]("/parse/status")+async def parse_status(+ request: Request,+ sha256: str = Query(...),+ tier: str = Query(...),+):+ state = request.state.app+ result = await state.parse_svc.get_parse_status(sha256, tier)+ if result is None:+ return {"sha256": sha256, "tier": tier, "status": "not_found"}+ return result++[email protected]("/parse/content")+async def parse_content(+ request: Request,+ sha256: str = Query(...),+ tier: str = Query(...),+ output: str | None = Query(None),+):+ """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"}++ import json as _json++ # merge all JSON files by page_idx+ pages_by_idx: dict[int, dict] = {}+ for fname in sorted(os.listdir(tier_dir)):+ if not fname.endswith(".json"):+ continue+ try:+ with open(os.path.join(tier_dir, fname), encoding="utf-8") as f:+ data = _json.load(f)+ for p in data.get("pdf_info", []):+ pages_by_idx[p["page_idx"]] = p+ except Exception:+ pass++ if not pages_by_idx:+ 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)++ if output and output != "-":+ os.makedirs(os.path.dirname(os.path.abspath(output)), exist_ok=True)+ with open(output, "w", encoding="utf-8") as f:+ f.write(content)+ return {"sha256": sha256, "tier": tier, "output": os.path.abspath(output)}++ return {"sha256": sha256, "tier": tier, "content": content}+++def _markdown_from_pages(pages: list[dict]) -> str:+ """Generate markdown from page dicts — iterate blocks/lines/spans."""+ parts: list[str] = []+ for page in pages:+ for block in page.get("para_blocks", []):+ for line in block.get("lines", []):+ for span in line.get("spans", []):+ if span.get("content"):+ parts.append(span["content"])+ return "\n\n".join(parts)diff --git a/mineru/server/routes/search.py b/mineru/server/routes/search.pynew file mode 100644index 00000000..3954a38a--- /dev/null+++ b/mineru/server/routes/search.py@@ -0,0 +1,33 @@+"""Search routes."""++from __future__ import annotations++from fastapi import APIRouter, Query, Request++router = APIRouter(tags=["search"])++[email protected]("/search")+async def search(+ request: Request,+ q: str = Query(..., description="Search query"),+ type: str | None = Query(None),+ limit: int = Query(20, ge=1, le=200),+ offset: int = Query(0, ge=0),+):+ state = request.state.app+ results, total = await state.search_svc.search(+ query=q, file_type=type, limit=limit, offset=offset,+ )+ return {"results": results, "total": total, "query": q}++[email protected]("/find")+async def find(+ request: Request,+ q: str = Query(..., description="Filename search query"),+ limit: int = Query(50, ge=1, le=500),+):+ 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/server/routes/server.pynew file mode 100644index 00000000..ed565ec5--- /dev/null+++ b/mineru/server/routes/server.py@@ -0,0 +1,64 @@+"""Server routes: status and shutdown."""++from __future__ import annotations++import asyncio+import os+import signal+import time++from fastapi import APIRouter, Request++router = APIRouter(tags=["server"])++[email protected]("/server/status")+async def server_status(request: Request):+ state = request.state.app++ files_total = await state.db.fetchone(+ "SELECT COUNT(*) as cnt FROM files WHERE scan_status='active'"+ )+ 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(+ "SELECT COUNT(*) as cnt FROM files WHERE sha256 IS NULL AND scan_status='active'"+ )+ watches = await state.config_svc.list_watches()+ uptime = time.time() - state.start_time if hasattr(state, "start_time") else 0++ return {+ "running": True,+ "pid": state.pid,+ "uptime_seconds": uptime,+ "socket_path": getattr(state, "socket_path", ""),+ "data_dir": getattr(state, "data_dir", ""),+ "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,+ "watch_count": len(watches),+ "watches": [+ {+ "id": w["id"],+ "path": w["path"],+ "removable": bool(w["removable"]),+ "watch_status": w["watch_status"],+ }+ for w in watches+ ],+ }++[email protected]("/shutdown")+async def shutdown(request: Request):+ """Gracefully shut down the server."""+ # Signal shutdown in a background task so we can return a response first+ import asyncio++ async def _shutdown():+ await asyncio.sleep(0.1)+ os.kill(os.getpid(), signal.SIGTERM)++ asyncio.create_task(_shutdown())+ return {"message": "Server shutting down..."}diff --git a/mineru/server/services/cleanup_svc.py b/mineru/server/services/cleanup_svc.pynew file mode 100644index 00000000..1b98a08d--- /dev/null+++ b/mineru/server/services/cleanup_svc.py@@ -0,0 +1,94 @@+"""Cleanup service: orphan docs, deleted files, temp files."""++from __future__ import annotations++import os+import shutil+import time+++class CleanupService:+ def __init__(self, db, data_dir: str = "~/MinerU") -> None:+ self.db = db+ self.data_dir = os.path.expanduser(data_dir)++ # ── orphan docs ─────────────────────────────────────────────++ async def find_orphan_docs(self) -> list[dict]:+ return await self.db.fetchall(+ "SELECT d.* FROM docs d WHERE NOT EXISTS ("+ " SELECT 1 FROM files f WHERE f.sha256 = d.sha256 AND f.scan_status = 'active'"+ ")"+ )++ async def cleanup_orphans(self, dry_run: bool = True) -> int:+ orphans = await self.find_orphan_docs()+ if dry_run:+ return len(orphans)++ count = 0+ for doc in orphans:+ sha256 = doc["sha256"]+ await self.db.execute("DELETE FROM fts_contents WHERE sha256=?", (sha256,))+ await self.db.execute("DELETE FROM parses WHERE sha256=?", (sha256,))+ await self.db.execute("DELETE FROM docs WHERE sha256=?", (sha256,))+ # remove parsed output dir+ parsed_dir = os.path.join(self.data_dir, "parsed", sha256[:2], sha256)+ if os.path.isdir(parsed_dir):+ shutil.rmtree(parsed_dir, ignore_errors=True)+ count += 1+ await self.db.commit()+ return count++ # ── deleted files ───────────────────────────────────────────++ 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 < ?",+ (_days_ago_ms(older_than_days),),+ )+ count = row["cnt"] if row else 0++ if not dry_run and count > 0:+ await self.db.execute(+ "DELETE FROM files WHERE scan_status='deleted' AND deleted_at < ?",+ (_days_ago_ms(older_than_days),),+ )+ await self.db.commit()+ await self.cleanup_orphans(dry_run=False)++ return count++ # ── temp files ──────────────────────────────────────────────++ async def cleanup_temp_files(self, older_than_days: int = 7) -> int:+ """Remove process temp files (e.g. incomplete parse artifacts)."""+ temp_dir = os.path.join(self.data_dir, "temp")+ if not os.path.isdir(temp_dir):+ return 0++ threshold = _days_ago_ms(older_than_days) / 1000.0+ count = 0+ for root, dirs, files in os.walk(temp_dir, topdown=False):+ for name in files:+ fp = os.path.join(root, name)+ try:+ if os.path.getmtime(fp) < threshold:+ os.remove(fp)+ count += 1+ except OSError:+ pass+ for name in dirs:+ dp = os.path.join(root, name)+ try:+ if not os.listdir(dp):+ os.rmdir(dp)+ except OSError:+ pass+ return count+++def _days_ago_ms(days: int) -> int:+ return int((time.time() - days * 86400) * 1000)diff --git a/mineru/server/services/config_svc.py b/mineru/server/services/config_svc.pynew file mode 100644index 00000000..6e2619e6--- /dev/null+++ b/mineru/server/services/config_svc.py@@ -0,0 +1,119 @@+"""Configuration service: KV config, watch targets, rules."""++from __future__ import annotations++import fnmatch+import os+import time++import fnvhash+++class ConfigService:+ def __init__(self, db) -> None:+ self.db = db++ # ── KV config ───────────────────────────────────────────────++ async def get(self, key: str, default: str | None = None) -> str | None:+ row = await self.db.fetchone("SELECT value FROM config WHERE key=?", (key,))+ return row["value"] if row else default++ async def set(self, key: str, value: str) -> None:+ await self.db.execute(+ "INSERT OR REPLACE INTO config (key, value) VALUES (?, ?)", (key, value)+ )++ async def get_all(self) -> dict[str, str]:+ rows = await self.db.fetchall("SELECT key, value FROM config")+ return {r["key"]: r["value"] for r in rows}++ # ── watch targets ───────────────────────────────────────────++ 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:+ raise ValueError(f"Path must be normalized: {path}")++ wid = fnvhash.fnv1a_64(path.encode())+ if wid >= 2**63:+ wid -= 2**64++ await self.db.execute(+ "INSERT OR REPLACE INTO watch_targets (id, path, label, removable) "+ "VALUES (?, ?, ?, ?)",+ (wid, path, label, int(removable)),+ )+ return await self.db.fetchone("SELECT * FROM watch_targets WHERE id=?", (wid,))++ async def list_watches(self) -> list[dict]:+ return await self.db.fetchall(+ "SELECT * FROM watch_targets WHERE enabled=1 ORDER BY path"+ )++ async def remove_watch(self, path: str) -> None:+ await self.db.execute("DELETE FROM watch_targets WHERE path=?", (path,))++ async def get_watches_by_status(self, watch_status: str) -> list[dict]:+ return await self.db.fetchall(+ "SELECT * FROM watch_targets WHERE watch_status=? AND enabled=1",+ (watch_status,),+ )++ async def update_watch_status(self, watch_id: int, status: str) -> None:+ await self.db.execute(+ "UPDATE watch_targets SET watch_status=? WHERE id=?", (status, watch_id)+ )++ async def update_watch_scan_stats(self, watch_id: int, file_count: int) -> None:+ now = int(time.time() * 1000)+ await self.db.execute(+ "UPDATE watch_targets SET last_scan_at=?, last_scan_files=? WHERE id=?",+ (now, file_count, watch_id),+ )++ # ── 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:+ return await self.db.execute_insert(+ "INSERT INTO rules (name, rule_type, pattern, tier, pages, remote, priority) "+ "VALUES (?, ?, ?, ?, ?, ?, ?)",+ (name, rule_type, pattern, tier, pages, int(remote), priority),+ )++ async def list_rules(self, rule_type: str | None = None) -> list[dict]:+ if rule_type:+ return await self.db.fetchall(+ "SELECT * FROM rules WHERE rule_type=? AND enabled=1 ORDER BY priority DESC",+ (rule_type,),+ )+ return await self.db.fetchall(+ "SELECT * FROM rules WHERE enabled=1 ORDER BY rule_type, priority DESC"+ )++ async def remove_rule(self, rule_id: int) -> None:+ await self.db.execute("DELETE FROM rules WHERE id=?", (rule_id,))++ async def match_rules(self, file_path: str, rule_type: str) -> list[dict]:+ rules = await self.db.fetchall(+ "SELECT * FROM rules WHERE rule_type=? AND enabled=1 ORDER BY priority DESC",+ (rule_type,),+ )+ matched: list[dict] = []+ for rule in rules:+ if fnmatch.fnmatch(file_path, rule["pattern"]):+ matched.append(rule)+ await self.db.execute(+ "UPDATE rules SET hit_count=hit_count+1 WHERE id=?", (rule["id"],)+ )+ if matched:+ await self.db.commit()+ return matched++ async def is_path_excluded(self, file_path: str) -> bool:+ matched = await self.match_rules(file_path, "exclude")+ return len(matched) > 0diff --git a/mineru/server/services/parse_svc.py b/mineru/server/services/parse_svc.pynew file mode 100644index 00000000..410b27f9--- /dev/null+++ b/mineru/server/services/parse_svc.py@@ -0,0 +1,561 @@+"""Parse service: file registration, parse request/acquire/process."""++from __future__ import annotations++import asyncio+import os+import time+from pathlib import Path++from mineru.constants import ParseStatus, TIER_ORDER, Tier+from ..core.file_io import compute_sha256, extract_metadata, get_file_stat+++def _now_ms() -> int:+ return int(time.time() * 1000)+++MAX_FTS_CHARS = 30_000+FTS_HEAD_HALF = 15_000+++# ── range helpers ──────────────────────────────────────────────────+++def parse_range_set(s: str) -> set[int]:+ """Parse a pages range string like '1~5,10~15' into a set of integers."""+ pages: set[int] = set()+ for part in s.split(","):+ part = part.strip()+ if not part:+ continue+ if "~" in part:+ a, b = part.split("~", 1)+ pages.update(range(int(a.strip()), int(b.strip()) + 1))+ else:+ pages.add(int(part))+ return pages+++def pages_covered(request_pages: str, done_batches: list[dict]) -> bool:+ """Check whether request_pages is fully covered by done batches.+ Batches are sorted by done_at DESC so newer batches take precedence."""+ needed = parse_range_set(request_pages)+ covered: set[int] = set()+ for b in sorted(done_batches, key=lambda r: r.get("done_at") or 0, reverse=True):+ covered |= parse_range_set(b["pages"])+ if needed <= covered:+ return True+ return False+++def pages_uncovered(request_pages: str, done_batches: list[dict]) -> set[int]:+ """Return the subset of request_pages NOT covered by any done batch."""+ needed = parse_range_set(request_pages)+ covered: set[int] = set()+ for b in done_batches:+ covered |= parse_range_set(b["pages"])+ return needed - covered+++def _pages_set_to_str(pages: set[int]) -> str:+ """Convert a set of page numbers (1-based) to a compact range string."""+ if not pages:+ return ""+ sorted_pages = sorted(pages)+ ranges: list[str] = []+ start = sorted_pages[0]+ end = start+ for p in sorted_pages[1:]:+ if p == end + 1:+ end = p+ else:+ ranges.append(f"{start}~{end}" if start != end else str(start))+ start = p+ end = p+ ranges.append(f"{start}~{end}" if start != end else str(start))+ return ",".join(ranges)+++def expand_pages(pages: str | None, page_count: int) -> str:+ """Expand shorthand pages like 'all' or negative ranges like '-5~-1'+ into positive page ranges. Returns '1~{page_count}' for None/empty."""+ if not pages or pages.strip() == "all":+ return f"1~{page_count}"+ result: list[str] = []+ for part in pages.split(","):+ part = part.strip()+ if not part:+ continue+ if "~" in part:+ a, b = part.split("~", 1)+ a, b = a.strip(), b.strip()+ start = int(a)+ end = int(b)+ # negative index: -5 means page_count-5+1+ if start < 0:+ start = page_count + start + 1+ if end < 0:+ end = page_count + end + 1+ result.append(f"{start}~{end}")+ else:+ p = int(part.strip())+ if p < 0:+ p = page_count + p + 1+ result.append(str(p))+ return ",".join(result)+++# ── text truncation ────────────────────────────────────────────────+++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:]+++# ── ParseService ───────────────────────────────────────────────────+++class ParseService:+ def __init__(self, db, fts, config_svc, 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) ──────────────────────────────────++ async def register_file(self, path: str, watch_id: int | None = None) -> dict | None:+ """Register 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,))+ 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,))+ 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,))+ await self.db.execute(+ "INSERT INTO files (path, filename, ext, size_bytes, mtime_ms, "+ "birthtime_ms, sha256, watch_id, first_seen_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",+ (+ path, Path(path).name, Path(path).suffix.lstrip(".").lower(),+ stat["size_bytes"], stat["mtime_ms"], stat["birthtime_ms"],+ sha256, watch_id, now, now,+ ),+ )+ return await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,))++ # brand new document+ metadata = await extract_metadata(path)++ # Office: no page_count → default to 1+ page_count = metadata["page_count"]+ if page_count is None:+ ext = Path(path).suffix.lower().lstrip(".")+ if ext in ("docx",):+ page_count = 1 # reflow docs+ elif ext in ("pptx", "xlsx"):+ page_count = 1 # will be updated by metadata extraction++ now = _now_ms()+ await self.db.execute(+ "INSERT OR IGNORE INTO files (path, filename, ext, size_bytes, mtime_ms, "+ "birthtime_ms, watch_id, first_seen_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",+ (+ path,+ Path(path).name,+ Path(path).suffix.lstrip(".").lower(),+ stat["size_bytes"],+ stat["mtime_ms"],+ stat["birthtime_ms"],+ watch_id,+ now,+ now,+ ),+ )++ await self.db.execute(+ "INSERT OR IGNORE INTO docs (sha256, size_bytes, mime_type, page_count, "+ "title, author, subject, keywords, is_encrypted, first_seen_at, updated_at) "+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",+ (+ sha256,+ stat["size_bytes"],+ metadata["mime_type"],+ page_count,+ metadata["title"],+ metadata["author"],+ metadata["subject"],+ metadata["keywords"],+ metadata["is_encrypted"],+ now,+ now,+ ),+ )++ # FTS filename index+ file_row = await self.db.fetchone("SELECT id FROM files WHERE path=?", (path,))+ if file_row:+ await self.fts.upsert_filename(+ file_row["id"],+ Path(path).stem,+ Path(path).suffix.lstrip(".").lower(),+ )++ # determine tier and pages for initial parse+ tier = Tier.FLASH+ if page_count and page_count > 10:+ initial_pages = "1~5,-5~-1"+ elif page_count:+ initial_pages = f"1~{page_count}"+ else:+ initial_pages = "1~5"++ # check parsing-rules+ matched = await self.config_svc.match_rules(path, "parsing_rule")+ if matched:+ rule = matched[0]+ tier = rule.get("tier") or tier+ rule_pages = rule.get("pages")+ if rule_pages:+ initial_pages = expand_pages(rule_pages, page_count or 1)++ # insert parse batch+ pages_str = expand_pages(initial_pages, page_count or 1)+ await self.db.execute(+ "INSERT INTO parses (sha256, tier, pages, status, priority, created_at, updated_at) "+ "VALUES (?, ?, ?, ?, 0, ?, ?)",+ (sha256, tier, pages_str, ParseStatus.PENDING, now, now),+ )++ await self.db.execute(+ "UPDATE files SET sha256=?, locked_at=NULL, updated_at=? WHERE path=?",+ (sha256, now, path),+ )++ return await self.db.fetchone("SELECT * FROM files WHERE path=?", (path,))++ # ── parse request ───────────────────────────────────────────++ 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,)+ )+ if file_row is None or file_row["sha256"] is None:+ file_row = await self.register_file(path)+ if file_row is None:+ return {"sha256": "", "tier": tier or "", "status": "error",+ "tip": "File could not be registered."}++ sha256 = file_row["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++ # Office documents: always flash, ignore requested tier+ ext = file_row["ext"]+ if ext in ("docx", "pptx", "xlsx", "doc", "xls", "ppt"):+ 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}"+ raw_pages = pages or default_pages+ pages_str = expand_pages(raw_pages, page_count or 1)++ # check cache+ if not force:+ done_batches = await self.db.fetchall(+ "SELECT * FROM parses WHERE sha256=? AND tier=? AND status='done'",+ (sha256, requested_tier),+ )+ if done_batches:+ if pages_covered(pages_str, done_batches):+ return {+ "sha256": sha256,+ "tier": requested_tier,+ "pages": pages_str,+ "status": "done",+ "tip": "Cached. Use --force to re-parse.",+ }+ # only parse pages not yet covered+ uncovered = pages_uncovered(pages_str, done_batches)+ if not uncovered:+ return {+ "sha256": sha256,+ "tier": requested_tier,+ "pages": pages_str,+ "status": "done",+ "tip": "Cached.",+ }+ pages_str = _pages_set_to_str(uncovered)++ # check if there's already a pending/parsing batch with overlapping pages+ active = await self.db.fetchone(+ "SELECT * FROM parses WHERE sha256=? AND tier=? AND status IN ('pending', 'parsing') "+ "ORDER BY created_at DESC LIMIT 1",+ (sha256, requested_tier),+ )+ if active:+ return {+ "sha256": sha256,+ "tier": requested_tier,+ "pages": pages_str,+ "status": active["status"],+ "tip": "Parse already in progress. Check status with: mineru info <path>",+ }++ # insert new batch+ now = _now_ms()+ await self.db.execute(+ "INSERT INTO parses (sha256, tier, pages, status, priority, created_at, updated_at) "+ "VALUES (?, ?, ?, ?, 1, ?, ?)",+ (sha256, requested_tier, pages_str, ParseStatus.PENDING, now, now),+ )++ return {+ "sha256": sha256,+ "tier": requested_tier,+ "pages": pages_str,+ "status": ParseStatus.PENDING,+ }++ # ── worker ──────────────────────────────────────────────────++ async def get_queue_length(self) -> int:+ timeout_ms = _now_ms() - 30 * 60 * 1000 # 30min lock timeout+ row = await self.db.fetchone(+ "SELECT COUNT(*) as cnt FROM parses WHERE status=? "+ "AND (locked_at IS NULL OR locked_at < ?)",+ (ParseStatus.PENDING, timeout_ms),+ )+ return row["cnt"] if row else 0++ async def acquire_task(self) -> dict | None:+ now = _now_ms()+ timeout = now - 30 * 60 * 1000 # 30min lock timeout+ return await self.db.fetchone(+ "UPDATE parses SET locked_at=?, status=? "+ "WHERE id = ("+ " SELECT id FROM parses WHERE status=? "+ " AND (locked_at IS NULL OR locked_at < ?) "+ " ORDER BY priority DESC, created_at ASC LIMIT 1"+ ") RETURNING *",+ (now, ParseStatus.PARSING, ParseStatus.PENDING, timeout),+ )++ async def process_doc(self, task: dict) -> bool:+ """Execute parse for a batch. Returns True on success."""+ sha256 = task["sha256"]+ tier = task["tier"]+ pages = task["pages"]++ # guard+ current = await self.db.fetchone(+ "SELECT status FROM parses WHERE id=?", (task["id"],)+ )+ if current is None or current["status"] != ParseStatus.PARSING:+ return False++ # find the file+ file_row = await self.db.fetchone(+ "SELECT * FROM files WHERE sha256=? AND scan_status='active' LIMIT 1",+ (sha256,),+ )+ 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"]),+ )+ return False++ output_dir = os.path.join(self.data_dir, "parsed", sha256[:2], sha256, tier)+ os.makedirs(output_dir, exist_ok=True)++ # call mineru.parser+ try:+ from mineru.parser import parse+ 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"]),+ )+ return False++ try:+ # parse each contiguous range sequentially, collect results+ results: list = []+ ranges = _split_ranges(pages, file_row, sha256)+ for start, end in ranges:+ result = await asyncio.to_thread(+ parse,+ file_row["path"],+ backend=_tier_to_backend(tier),+ start_page_id=start,+ end_page_id=end,+ output_dir=output_dir,+ )+ results.append(result)+ except Exception as exc:+ await self.db.execute(+ "UPDATE parses SET status=?, error_code=?, error_msg=?, locked_at=NULL WHERE id=?",+ (ParseStatus.FAILED, "parse_failed", str(exc)[:500], task["id"]),+ )+ return False++ # save per-batch JSON (each parses row → one JSON file)+ md_text = ""+ for result in results:+ md = result.markdown() if hasattr(result, "markdown") else ""+ md_text += md + "\n"++ if results:+ import json as _json++ pages_key = _safe_filename(task["pages"])+ json_path = os.path.join(output_dir, f"{pages_key}.json")+ new_pages: list[dict] = []+ for r in results:+ if hasattr(r, "as_dict"):+ new_pages.extend(r.as_dict().get("pdf_info", []))++ os.makedirs(output_dir, exist_ok=True)+ try:+ with open(json_path, "w", encoding="utf-8") as f:+ _json.dump({"pdf_info": new_pages}, f, ensure_ascii=False, indent=2)+ except Exception:+ pass++ # update fts_contents (tier-gated)+ await self._maybe_update_fts(sha256, tier, md_text, file_row)++ # update docs metadata (tier-gated)+ await self._maybe_update_docs_meta(sha256, tier)++ # mark done+ now = _now_ms()+ await self.db.execute(+ "UPDATE parses SET status=?, done_at=?, locked_at=NULL, output_path=?, updated_at=? WHERE id=?",+ (ParseStatus.DONE, now, output_dir, now, task["id"]),+ )+ return True++ async def get_parse_status(self, sha256: str, tier: str) -> dict | None:+ """Get aggregate status for a doc+tier. Returns latest batch info."""+ done = await self.db.fetchone(+ "SELECT * FROM parses WHERE sha256=? AND tier=? AND status='done' "+ "ORDER BY done_at DESC LIMIT 1",+ (sha256, tier),+ )+ if done:+ return {"sha256": sha256, "tier": tier, "status": "done", "pages": "TBD"}++ active = await self.db.fetchone(+ "SELECT * FROM parses WHERE sha256=? AND tier=? AND status IN ('pending', 'parsing') "+ "ORDER BY created_at DESC LIMIT 1",+ (sha256, tier),+ )+ if active:+ 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",+ (sha256, tier),+ )+ if failed:+ return {+ "sha256": sha256,+ "tier": tier,+ "status": "failed",+ "error": {"code": failed["error_code"], "message": failed["error_msg"]},+ }++ return None++ # ── internal helpers ────────────────────────────────────────++ 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):+ return # current FTS data is from a higher or equal tier++ text = truncate_head_tail(text)+ await self.fts.replace(+ sha256=sha256,+ tier=tier,+ text=text,+ title=file_row.get("title") or "",+ author=file_row.get("author") or "",+ filename=file_row["filename"],+ )++ 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,))+ 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):+ return++ # for now just update meta_tier; full metadata update comes when+ # engine provides richer output+ now = _now_ms()+ await self.db.execute(+ "UPDATE docs SET meta_tier=?, updated_at=? WHERE sha256=?",+ (tier, now, sha256),+ )+++# ── tier → backend mapping ─────────────────────────────────────────+++def _tier_to_backend(tier: str) -> str:+ mapping = {+ Tier.FLASH: "flash",+ Tier.STANDARD: "pipeline",+ Tier.PRO: "hybrid-auto-engine",+ }+ return mapping.get(tier, "pipeline")+++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)+ if not page_set:+ return [(0, None)]++ sorted_pages = sorted(page_set)+ ranges: list[tuple[int, int | None]] = []+ start = sorted_pages[0]+ end = start++ for p in sorted_pages[1:]:+ if p == end + 1:+ end = p+ else:+ ranges.append((start - 1, end - 1)) # convert to 0-based+ start = p+ end = p+ ranges.append((start - 1, end - 1))+ return ranges+++def _safe_filename(s: str) -> str:+ """Convert a pages range string to a safe filename — keep ~ and , as-is."""+ return s # pages string is already safe: "1~5,43~47"diff --git a/mineru/server/services/search_svc.py b/mineru/server/services/search_svc.pynew file mode 100644index 00000000..3dba8e77--- /dev/null+++ b/mineru/server/services/search_svc.py@@ -0,0 +1,116 @@+"""Search service: content search and filename search."""++from __future__ import annotations++from ..core.fts import tokenize_for_query, strip_sep+++class SearchService:+ def __init__(self, db, fts) -> None:+ self.db = db+ self.fts = fts++ # ── content search ──────────────────────────────────────────++ async def search(+ self,+ query: str,+ file_type: str | None = None,+ limit: int = 20,+ offset: int = 0,+ ) -> tuple[list[dict], int]:+ """Full-text search. Returns (results, total_count)."""+ rows = await self.fts.search(query, limit=200)+ if not rows:+ return [], 0++ # dedup by sha256+ sha256s = list({r["sha256"] for r in rows})++ # join with docs + files+ placeholders = ",".join("?" * len(sha256s))+ sql = (+ "SELECT f.*, d.title, d.author, d.page_count "+ "FROM files f JOIN docs d ON f.sha256 = d.sha256 "+ f"WHERE f.sha256 IN ({placeholders}) AND f.scan_status = 'active'"+ )+ params = list(sha256s)++ if file_type:+ sql += " AND f.ext = ?"+ params.append(file_type.lower())++ file_rows = await self.db.fetchall(sql, params)++ # group files by sha256+ files_by_doc: dict[str, list[dict]] = {}+ for fr in file_rows:+ sha = fr["sha256"]+ if sha not in files_by_doc:+ files_by_doc[sha] = []+ files_by_doc[sha].append(fr)++ # build results+ results: list[dict] = []+ for row in rows:+ sha = row["sha256"]+ files = files_by_doc.get(sha, [])+ if not files:+ continue++ fts_file = files[0]+ 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],+ })++ total = len(results)+ return results[offset:offset + limit], total++ # ── filename search ─────────────────────────────────────────++ 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:+ return [], 0++ file_ids = [r["file_id"] for r in rows]+ placeholders = ",".join("?" * len(file_ids))+ file_rows = await self.db.fetchall(+ f"SELECT f.*, d.title "+ f"FROM files f LEFT JOIN docs d ON f.sha256 = d.sha256 "+ f"WHERE f.id IN ({placeholders}) AND f.scan_status = 'active'",+ file_ids,+ )++ files_by_id = {fr["id"]: fr for fr in file_rows}++ results: list[dict] = []+ for row in rows:+ 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"]],+ })++ total = len(results)+ return results, totaldiff --git a/mineru/server/types.py b/mineru/server/types.pynew file mode 100644index 00000000..d70790da--- /dev/null+++ b/mineru/server/types.py@@ -0,0 +1,117 @@+"""Shared Pydantic models for request/response contracts between client and server."""++from __future__ import annotations++from pydantic import BaseModel+++# ── parse ──────────────────────────────────────────────────────────+++class ParseRequest(BaseModel):+ path: str+ tier: str | None = None+ pages: str | None = None+ force: bool = False+++class ParseResponse(BaseModel):+ sha256: str+ tier: str+ pages: str+ status: str # pending / parsing / done / failed+ markdown: str | None = None+ tip: str | None = None # hint for user when status is not 'done'+++class ParseStatusResponse(BaseModel):+ sha256: str+ tier: str+ status: str+ pages: str+ markdown: str | None = None+ error: dict | None = None+++# ── search ─────────────────────────────────────────────────────────+++class SearchResult(BaseModel):+ sha256: str+ title: str | None = None+ author: str | None = None+ filename: str | None = None+ ext: str | None = None+ size_bytes: int | None = None+ tier: str | None = None+ snippet: str | None = None+ paths: list[str] = []+++class SearchResponse(BaseModel):+ results: list[SearchResult]+ total: int+ query: str+++# ── info ───────────────────────────────────────────────────────────+++class FileInfo(BaseModel):+ path: str+ filename: str+ ext: str+ size_bytes: int+ mtime_ms: int+ sha256: str | None = None+ scan_status: str+ # from docs+ title: str | None = None+ author: str | None = None+ page_count: int | None = None+ lang: str | None = None+ is_encrypted: int = 0+ # from parses (aggregated)+ tiers: list[dict] = [] # [{tier, status, pages, done_at}, ...]+ watch_label: str | None = None+++# ── config ─────────────────────────────────────────────────────────+++class WatchTargetInfo(BaseModel):+ id: int+ path: str+ label: str | None = None+ removable: bool = False+ enabled: bool = True+ watch_status: str+++class RuleInfo(BaseModel):+ id: int+ name: str | None = None+ rule_type: str+ pattern: str+ tier: str | None = None+ pages: str | None = None+ remote: bool = False+ enabled: bool = True+ priority: int = 0+++# ── server ─────────────────────────────────────────────────────────+++class ServerStatus(BaseModel):+ running: bool+ pid: int | None = None+ uptime_seconds: float | None = None+ socket_path: str+ data_dir: str+ files_total: int = 0+ docs_total: int = 0+ parse_queue_length: int = 0+ reg_queue_length: int = 0+ watch_count: int = 0+ watches: list[dict] = []