xdoc-tools 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- xdoc/__init__.py +12 -0
- xdoc/__main__.py +6 -0
- xdoc/api.py +121 -0
- xdoc/assets.py +63 -0
- xdoc/cli.py +206 -0
- xdoc/converters/__init__.py +84 -0
- xdoc/converters/csv.py +31 -0
- xdoc/converters/docx.py +123 -0
- xdoc/converters/epub.py +68 -0
- xdoc/converters/html.py +86 -0
- xdoc/converters/image.py +72 -0
- xdoc/converters/legacy.py +81 -0
- xdoc/converters/media.py +247 -0
- xdoc/converters/pdf.py +321 -0
- xdoc/converters/pptx.py +86 -0
- xdoc/converters/text.py +69 -0
- xdoc/converters/xlsx.py +106 -0
- xdoc/detect.py +144 -0
- xdoc/errors.py +11 -0
- xdoc/ir.py +84 -0
- xdoc/mcp_server.py +87 -0
- xdoc/options.py +218 -0
- xdoc/plugins.py +290 -0
- xdoc/render.py +202 -0
- xdoc/workers/asr_worker.py +187 -0
- xdoc/workers/ocr_worker.py +93 -0
- xdoc_tools-0.1.0.dist-info/METADATA +218 -0
- xdoc_tools-0.1.0.dist-info/RECORD +31 -0
- xdoc_tools-0.1.0.dist-info/WHEEL +4 -0
- xdoc_tools-0.1.0.dist-info/entry_points.txt +2 -0
- xdoc_tools-0.1.0.dist-info/licenses/LICENSE +21 -0
xdoc/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""xdoc —— 本地、离线、忠实的文档转文本层。
|
|
2
|
+
|
|
3
|
+
设计原则(用户需求,见 docs/PLAN.md):
|
|
4
|
+
- 只转换,不摘要、不改写:金额/日期/编号/代码原样保留。
|
|
5
|
+
- 可追溯:PDF 页码、PPT 幻灯片号、Excel 工作表名与区域、音视频时间戳。
|
|
6
|
+
- 一个入口(MCP 单工具 read / 同源 CLI)、一个出口(markdown | text | json)。
|
|
7
|
+
- 运行期完全离线;可选引擎(OCR/ASR/媒体)按需下载安装,可随时卸载。
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
__version__ = "0.1.0"
|
|
11
|
+
|
|
12
|
+
__all__ = ["__version__"]
|
xdoc/__main__.py
ADDED
xdoc/api.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""对外主入口:read()。
|
|
2
|
+
|
|
3
|
+
流程:识别类型 → 转换 →(需要时)OCR 补页 → 预算/续读 → 渲染。
|
|
4
|
+
CLI 与 MCP 都调这里,保证两种入口结果一致。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import subprocess
|
|
11
|
+
import tempfile
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from .assets import AssetStore
|
|
15
|
+
from .converters import convert
|
|
16
|
+
from .errors import XdocError
|
|
17
|
+
from .ir import Block, Document
|
|
18
|
+
from .options import ReadOptions, apply_budget
|
|
19
|
+
from .plugins import PluginManager
|
|
20
|
+
from .render import render
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def file_sha256(path: Path) -> str:
|
|
24
|
+
digest = hashlib.sha256()
|
|
25
|
+
with path.open("rb") as fh:
|
|
26
|
+
for chunk in iter(lambda: fh.read(1 << 20), b""):
|
|
27
|
+
digest.update(chunk)
|
|
28
|
+
return digest.hexdigest()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _ocr_pdf_pages(doc: Document, path: Path, options: ReadOptions, assets: AssetStore) -> None:
|
|
32
|
+
"""给没有文本层的 PDF 页补 OCR 文字。"""
|
|
33
|
+
manager = PluginManager(Path(options.plugin_dir) if options.plugin_dir else None)
|
|
34
|
+
if not manager.is_installed("ocr"):
|
|
35
|
+
return
|
|
36
|
+
needs = doc.meta.get("needs_ocr") or []
|
|
37
|
+
if not needs:
|
|
38
|
+
return
|
|
39
|
+
try:
|
|
40
|
+
import pymupdf
|
|
41
|
+
except ImportError: # pragma: no cover
|
|
42
|
+
return
|
|
43
|
+
|
|
44
|
+
tmpdir = Path(tempfile.mkdtemp(prefix="xdoc-ocr-"))
|
|
45
|
+
try:
|
|
46
|
+
pdf = pymupdf.open(str(path))
|
|
47
|
+
image_paths: list[str] = []
|
|
48
|
+
for page_number in needs:
|
|
49
|
+
page = pdf[page_number - 1]
|
|
50
|
+
pix = page.get_pixmap(dpi=200)
|
|
51
|
+
target = tmpdir / f"p{page_number}.png"
|
|
52
|
+
pix.save(str(target))
|
|
53
|
+
image_paths.append(str(target))
|
|
54
|
+
|
|
55
|
+
result = manager.run_worker("ocr", {"images": image_paths})
|
|
56
|
+
if result.get("error"):
|
|
57
|
+
raise XdocError(f"OCR 失败: {result['error']}")
|
|
58
|
+
by_index = {item.get("index"): item for item in result.get("results") or []}
|
|
59
|
+
|
|
60
|
+
for page_number in needs:
|
|
61
|
+
item = by_index.get(page_number - 1) or {}
|
|
62
|
+
text = (item.get("text") or "").strip()
|
|
63
|
+
section = next((s for s in doc.sections if s.anchor == f"page:{page_number}"), None)
|
|
64
|
+
if section is None:
|
|
65
|
+
continue
|
|
66
|
+
# 去掉"无文本层"的提示块,替换成 OCR 结果
|
|
67
|
+
section.blocks = [b for b in section.blocks if not (b.kind == "note" and "没有文本层" in b.text)]
|
|
68
|
+
if text:
|
|
69
|
+
section.add(Block(kind="text", text=text, meta={"ocr": True, "page": page_number}))
|
|
70
|
+
pdf.close()
|
|
71
|
+
doc.meta["ocr_pages"] = list(needs)
|
|
72
|
+
finally:
|
|
73
|
+
import shutil
|
|
74
|
+
|
|
75
|
+
shutil.rmtree(tmpdir, ignore_errors=True)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def read_document(path: str | Path, options: ReadOptions | None = None) -> Document:
|
|
79
|
+
"""把文件读成 Document(未截断)。"""
|
|
80
|
+
options = options or ReadOptions()
|
|
81
|
+
p = Path(path).expanduser()
|
|
82
|
+
if not p.exists():
|
|
83
|
+
raise XdocError(f"文件不存在: {p}")
|
|
84
|
+
if p.is_dir():
|
|
85
|
+
raise XdocError(f"暂不支持目录: {p}(请逐个文件读取)")
|
|
86
|
+
|
|
87
|
+
assets = AssetStore(Path(options.assets_dir) if options.assets_dir else None,
|
|
88
|
+
enabled=options.images != "none")
|
|
89
|
+
doc = convert(p, options, assets)
|
|
90
|
+
doc.source = str(p.resolve())
|
|
91
|
+
doc.meta.setdefault("sha256", file_sha256(p))
|
|
92
|
+
doc.meta.setdefault("bytes", p.stat().st_size)
|
|
93
|
+
doc.meta.setdefault("assets_root", str(assets.root))
|
|
94
|
+
|
|
95
|
+
if doc.kind == "pdf" and doc.meta.get("needs_ocr") and options.ocr != "off":
|
|
96
|
+
_ocr_pdf_pages(doc, p, options, assets)
|
|
97
|
+
|
|
98
|
+
return doc
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def read(path: str | Path, options: ReadOptions | None = None) -> str:
|
|
102
|
+
"""主入口:返回渲染后的文本。"""
|
|
103
|
+
options = options or ReadOptions()
|
|
104
|
+
doc = read_document(path, options)
|
|
105
|
+
doc, cursor = apply_budget(doc, options.max_tokens, options.cursor)
|
|
106
|
+
if cursor:
|
|
107
|
+
doc.meta["next_cursor"] = cursor
|
|
108
|
+
else:
|
|
109
|
+
doc.meta.pop("next_cursor", None)
|
|
110
|
+
return render(doc, options.format, front_matter=options.front_matter)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def read_with_meta(path: str | Path, options: ReadOptions | None = None) -> tuple[str, Document]:
|
|
114
|
+
options = options or ReadOptions()
|
|
115
|
+
doc = read_document(path, options)
|
|
116
|
+
doc, cursor = apply_budget(doc, options.max_tokens, options.cursor)
|
|
117
|
+
if cursor:
|
|
118
|
+
doc.meta["next_cursor"] = cursor
|
|
119
|
+
else:
|
|
120
|
+
doc.meta.pop("next_cursor", None)
|
|
121
|
+
return render(doc, options.format, front_matter=options.front_matter), doc
|
xdoc/assets.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""附件(图片等)落盘管理。
|
|
2
|
+
|
|
3
|
+
提取出来的图片要能被 Agent 真正读到(模型能看图),所以必须落成真实文件,
|
|
4
|
+
并给出稳定、可预测的路径。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import hashlib
|
|
10
|
+
import shutil
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def default_assets_root() -> Path:
|
|
15
|
+
base = Path.home() / ".local" / "share" / "xdoc" / "assets"
|
|
16
|
+
base.mkdir(parents=True, exist_ok=True)
|
|
17
|
+
return base
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class AssetStore:
|
|
21
|
+
"""把提取出的二进制资源写入磁盘,返回相对路径。"""
|
|
22
|
+
|
|
23
|
+
def __init__(self, root: Path | None = None, *, enabled: bool = True) -> None:
|
|
24
|
+
self.root = Path(root) if root else default_assets_root()
|
|
25
|
+
self.enabled = enabled
|
|
26
|
+
self._rel_dir = ""
|
|
27
|
+
|
|
28
|
+
def bind(self, source: Path) -> None:
|
|
29
|
+
"""按源文件绑定一个子目录,避免不同文件的同名图片互相覆盖。"""
|
|
30
|
+
digest = hashlib.sha1(str(source.resolve()).encode()).hexdigest()[:10]
|
|
31
|
+
stem = source.stem.replace(" ", "_")[:40]
|
|
32
|
+
self._rel_dir = f"{stem}-{digest}"
|
|
33
|
+
if self.enabled:
|
|
34
|
+
(self.root / self._rel_dir).mkdir(parents=True, exist_ok=True)
|
|
35
|
+
|
|
36
|
+
@staticmethod
|
|
37
|
+
def _rel(path: str) -> str:
|
|
38
|
+
"""统一用 / 分隔的相对路径,且不带前导斜杠(否则会被当成绝对路径)。"""
|
|
39
|
+
return path.replace("\\", "/").lstrip("/")
|
|
40
|
+
|
|
41
|
+
def save(self, data: bytes, filename: str) -> str | None:
|
|
42
|
+
if not self.enabled:
|
|
43
|
+
return None
|
|
44
|
+
self.root.mkdir(parents=True, exist_ok=True)
|
|
45
|
+
target = self.root / self._rel_dir / filename
|
|
46
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
47
|
+
target.write_bytes(data)
|
|
48
|
+
return self._rel(f"{self._rel_dir}/{filename}")
|
|
49
|
+
|
|
50
|
+
def save_file(self, src: Path, filename: str | None = None) -> str | None:
|
|
51
|
+
if not self.enabled:
|
|
52
|
+
return None
|
|
53
|
+
name = filename or src.name
|
|
54
|
+
return self.save(src.read_bytes(), name)
|
|
55
|
+
|
|
56
|
+
def copy_dir(self, src: Path) -> str | None:
|
|
57
|
+
if not self.enabled:
|
|
58
|
+
return None
|
|
59
|
+
dest = self.root / self._rel_dir / src.name
|
|
60
|
+
if dest.exists():
|
|
61
|
+
shutil.rmtree(dest)
|
|
62
|
+
shutil.copytree(src, dest)
|
|
63
|
+
return self._rel(f"{self._rel_dir}/{src.name}")
|
xdoc/cli.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""命令行入口:xdoc read / xdoc plugin / xdoc doctor / xdoc serve。
|
|
2
|
+
|
|
3
|
+
CLI 与 MCP 共用同一套实现,输出结果一致。
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import argparse
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
import sys
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
from . import __version__
|
|
15
|
+
from .api import read_with_meta
|
|
16
|
+
from .errors import XdocError
|
|
17
|
+
from .options import ReadOptions
|
|
18
|
+
from .plugins import PLUGINS, PluginManager
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
22
|
+
parser = argparse.ArgumentParser(
|
|
23
|
+
prog="xdoc",
|
|
24
|
+
description="把 PDF/图片/音频/视频/Office/富文本 转成忠实文本,供 Agent 阅读。",
|
|
25
|
+
)
|
|
26
|
+
parser.add_argument("--version", action="version", version=f"xdoc {__version__}")
|
|
27
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
28
|
+
|
|
29
|
+
read_cmd = sub.add_parser("read", help="读取单个文件")
|
|
30
|
+
read_cmd.add_argument("path", help="文件路径")
|
|
31
|
+
read_cmd.add_argument("--format", default="markdown", choices=["markdown", "text", "json"],
|
|
32
|
+
help="输出格式(默认 markdown)")
|
|
33
|
+
read_cmd.add_argument("--max-tokens", type=int, default=None, help="token 预算,超出即截断并给续读游标")
|
|
34
|
+
read_cmd.add_argument("--cursor", default=None, help="续读游标(配合 --max-tokens 使用)")
|
|
35
|
+
read_cmd.add_argument("--pages", default=None, help="页/幻灯片/表范围,例如 1-5,8")
|
|
36
|
+
read_cmd.add_argument("--ocr", default="auto", choices=["auto", "on", "off", "vlm"],
|
|
37
|
+
help="OCR 开关(需安装 ocr 插件)")
|
|
38
|
+
read_cmd.add_argument("--asr", default="auto",
|
|
39
|
+
choices=["auto", "on", "off", "zh", "whisper"],
|
|
40
|
+
help="语音转写:auto(自动挑引擎)/ zh(中文 FunASR)/ whisper(通用 faster-whisper)/ off")
|
|
41
|
+
read_cmd.add_argument("--asr-model", default=None, help="ASR 模型名,如 small / large-v3")
|
|
42
|
+
read_cmd.add_argument("--tables", default="auto", choices=["auto", "on", "off"],
|
|
43
|
+
help="PDF 表格识别:auto(页面有画线才识别,快)/ on(每页都按画线识别)/ off(不识别)")
|
|
44
|
+
read_cmd.add_argument("--no-images", action="store_true", help="不提取内嵌图片")
|
|
45
|
+
read_cmd.add_argument("--no-front-matter", action="store_true", help="不输出元数据头")
|
|
46
|
+
read_cmd.add_argument("-o", "--output", default=None, help="输出到文件而不是标准输出")
|
|
47
|
+
|
|
48
|
+
plugin_cmd = sub.add_parser("plugin", help="可选引擎插件管理(安装/卸载/查看)")
|
|
49
|
+
plugin_sub = plugin_cmd.add_subparsers(dest="plugin_command", required=True)
|
|
50
|
+
plugin_sub.add_parser("list", help="列出插件及安装状态")
|
|
51
|
+
add_cmd = plugin_sub.add_parser("add", help="安装插件(按需下载)")
|
|
52
|
+
add_cmd.add_argument("name", choices=sorted(PLUGINS))
|
|
53
|
+
rm_cmd = plugin_sub.add_parser("remove", help="卸载插件")
|
|
54
|
+
rm_cmd.add_argument("name", choices=sorted(PLUGINS))
|
|
55
|
+
# 同义词:install/download ≈ add,uninstall ≈ remove
|
|
56
|
+
for alias, help_text in (("install", "安装插件(add 的同义词)"),
|
|
57
|
+
("download", "下载并安装插件(add 的同义词)"),
|
|
58
|
+
("uninstall", "卸载插件(remove 的同义词)")):
|
|
59
|
+
alias_cmd = plugin_sub.add_parser(alias, help=help_text)
|
|
60
|
+
alias_cmd.add_argument("name", choices=sorted(PLUGINS))
|
|
61
|
+
|
|
62
|
+
sub.add_parser("doctor", help="检查环境与依赖")
|
|
63
|
+
sub.add_parser("serve", help="以 stdio 方式启动 MCP 服务")
|
|
64
|
+
return parser
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _cmd_read(args) -> int:
|
|
68
|
+
options = ReadOptions(
|
|
69
|
+
format=args.format,
|
|
70
|
+
max_tokens=args.max_tokens,
|
|
71
|
+
cursor=args.cursor,
|
|
72
|
+
pages=args.pages,
|
|
73
|
+
ocr=args.ocr,
|
|
74
|
+
asr=args.asr,
|
|
75
|
+
asr_model=args.asr_model,
|
|
76
|
+
tables=args.tables,
|
|
77
|
+
images="none" if args.no_images else "refs",
|
|
78
|
+
front_matter=not args.no_front_matter,
|
|
79
|
+
)
|
|
80
|
+
text, doc = read_with_meta(args.path, options)
|
|
81
|
+
if args.output:
|
|
82
|
+
Path(args.output).write_text(text, encoding="utf-8")
|
|
83
|
+
print(f"written: {args.output} ({doc.chars} chars, {len(doc.sections)} sections)")
|
|
84
|
+
else:
|
|
85
|
+
sys.stdout.write(text)
|
|
86
|
+
return 0
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _cmd_plugin(args) -> int:
|
|
90
|
+
manager = PluginManager()
|
|
91
|
+
if args.plugin_command == "list":
|
|
92
|
+
items = manager.list()
|
|
93
|
+
if args.json:
|
|
94
|
+
print(json.dumps(items, ensure_ascii=False, indent=2))
|
|
95
|
+
return 0
|
|
96
|
+
print("插件状态:")
|
|
97
|
+
for item in items:
|
|
98
|
+
mark = "已安装" if item["installed"] else "未安装"
|
|
99
|
+
print(f" [{mark:4s}] {item['name']:6s} {item['title']} ({item['approx_size']})")
|
|
100
|
+
print("\n安装: xdoc plugin add|install <name> 卸载: xdoc plugin remove|uninstall <name>")
|
|
101
|
+
return 0
|
|
102
|
+
if args.plugin_command in ("add", "install", "download"):
|
|
103
|
+
result = manager.install(args.name)
|
|
104
|
+
print(f"{args.name}: {result['status']}")
|
|
105
|
+
return 0
|
|
106
|
+
if args.plugin_command in ("remove", "uninstall"):
|
|
107
|
+
result = manager.uninstall(args.name)
|
|
108
|
+
print(f"{args.name}: {result['status']}")
|
|
109
|
+
return 0
|
|
110
|
+
return 1
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _cmd_doctor() -> int:
|
|
114
|
+
import importlib
|
|
115
|
+
|
|
116
|
+
print(f"xdoc {__version__}")
|
|
117
|
+
print(f"python: {sys.executable}")
|
|
118
|
+
print("\n核心依赖:")
|
|
119
|
+
missing: list[str] = []
|
|
120
|
+
for module, label in [
|
|
121
|
+
("pymupdf", "PDF"),
|
|
122
|
+
("docx", "DOCX"),
|
|
123
|
+
("pptx", "PPTX"),
|
|
124
|
+
("openpyxl", "XLSX"),
|
|
125
|
+
("bs4", "HTML"),
|
|
126
|
+
("markdownify", "HTML->Markdown"),
|
|
127
|
+
("mcp", "MCP 服务"),
|
|
128
|
+
]:
|
|
129
|
+
try:
|
|
130
|
+
importlib.import_module(module)
|
|
131
|
+
print(f" [ok] {module:14s} {label}")
|
|
132
|
+
except ImportError:
|
|
133
|
+
missing.append(module)
|
|
134
|
+
print(f" [缺失] {module:14s} {label}")
|
|
135
|
+
|
|
136
|
+
print("\n外部工具(可选,缺失不影响基础能力):")
|
|
137
|
+
from .converters.legacy import find_soffice
|
|
138
|
+
soffice = find_soffice()
|
|
139
|
+
print(f" [{'ok' if soffice else '缺失'}] LibreOffice {soffice or '(旧版 .doc/.ppt/.xls 转换需要)'}")
|
|
140
|
+
manager = PluginManager()
|
|
141
|
+
print(f" [{'ok' if manager.ffmpeg_path() else '缺失'}] ffmpeg {manager.ffmpeg_path() or '(视频抽帧需要)'}")
|
|
142
|
+
|
|
143
|
+
print("\n插件(可选,按需安装):")
|
|
144
|
+
for item in manager.list():
|
|
145
|
+
print(f" [{'已装' if item['installed'] else '未装'}] {item['name']:6s} {item['title']}")
|
|
146
|
+
|
|
147
|
+
if missing:
|
|
148
|
+
print(f"\n核心依赖缺失: {', '.join(missing)};重新安装 xdoc 即可。")
|
|
149
|
+
return 1
|
|
150
|
+
print("\n核心依赖齐全,基础能力可用。")
|
|
151
|
+
return 0
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _setup_console() -> None:
|
|
155
|
+
"""Windows 控制台默认代码页可能是 cp936/cp1252,直接写中文会抛 UnicodeEncodeError。
|
|
156
|
+
|
|
157
|
+
统一改成 UTF-8 输出、无法编码的字符降级为替换符——宁可显示成 ?,也不能因为编码崩掉。
|
|
158
|
+
MCP 的 serve 模式走 stdio 协议,不碰标准流。
|
|
159
|
+
"""
|
|
160
|
+
if os.name == "nt":
|
|
161
|
+
try:
|
|
162
|
+
import ctypes
|
|
163
|
+
|
|
164
|
+
ctypes.windll.kernel32.SetConsoleOutputCP(65001)
|
|
165
|
+
ctypes.windll.kernel32.SetConsoleCP(65001)
|
|
166
|
+
except Exception: # pragma: no cover - 老终端不支持就算了
|
|
167
|
+
pass
|
|
168
|
+
for stream in (sys.stdout, sys.stderr):
|
|
169
|
+
try:
|
|
170
|
+
stream.reconfigure(encoding="utf-8", errors="replace")
|
|
171
|
+
except (AttributeError, ValueError): # pragma: no cover - 已被替换的流
|
|
172
|
+
pass
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def main(argv: list[str] | None = None) -> int:
|
|
176
|
+
parser = build_parser()
|
|
177
|
+
args = parser.parse_args(argv)
|
|
178
|
+
|
|
179
|
+
# --json 是 plugin list 的可选输出
|
|
180
|
+
if args.command == "plugin" and args.plugin_command == "list":
|
|
181
|
+
args.json = False
|
|
182
|
+
|
|
183
|
+
if args.command != "serve":
|
|
184
|
+
_setup_console()
|
|
185
|
+
|
|
186
|
+
try:
|
|
187
|
+
if args.command == "read":
|
|
188
|
+
return _cmd_read(args)
|
|
189
|
+
if args.command == "plugin":
|
|
190
|
+
return _cmd_plugin(args)
|
|
191
|
+
if args.command == "doctor":
|
|
192
|
+
return _cmd_doctor()
|
|
193
|
+
if args.command == "serve":
|
|
194
|
+
from .mcp_server import main as serve_main
|
|
195
|
+
|
|
196
|
+
return serve_main()
|
|
197
|
+
except XdocError as exc:
|
|
198
|
+
print(f"错误: {exc}", file=sys.stderr)
|
|
199
|
+
return 2
|
|
200
|
+
except KeyboardInterrupt: # pragma: no cover
|
|
201
|
+
return 130
|
|
202
|
+
return 1
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
if __name__ == "__main__": # pragma: no cover
|
|
206
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""格式转换器:每个格式负责把源文件变成统一的 IR(Section -> Block)。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from ..assets import AssetStore
|
|
8
|
+
from ..errors import XdocError
|
|
9
|
+
from ..options import ReadOptions
|
|
10
|
+
|
|
11
|
+
__all__ = ["convert", "filter_pages"]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def convert(path: str | Path, options: ReadOptions, assets: AssetStore):
|
|
15
|
+
"""把任意支持的文件转换成 Document。"""
|
|
16
|
+
from ..detect import detect_kind
|
|
17
|
+
|
|
18
|
+
p = Path(path)
|
|
19
|
+
kind = detect_kind(p)
|
|
20
|
+
handler = _handlers().get(kind)
|
|
21
|
+
if handler is None:
|
|
22
|
+
raise XdocError(f"暂不支持的文件类型: {kind}({p.suffix or '无扩展名'})")
|
|
23
|
+
# 统一绑定资源子目录,避免各转换器漏调导致图片落到工作目录或路径为空
|
|
24
|
+
assets.bind(p)
|
|
25
|
+
doc = handler(p, options, assets)
|
|
26
|
+
doc.meta.setdefault("engine", kind)
|
|
27
|
+
if options.pages:
|
|
28
|
+
filter_pages(doc, options.pages)
|
|
29
|
+
return doc
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def filter_pages(doc, spec: str) -> None:
|
|
33
|
+
"""按 "1-5,8" 之类的规格筛选章节(页/幻灯片/表)。"""
|
|
34
|
+
wanted: set[int] = set()
|
|
35
|
+
for part in spec.split(","):
|
|
36
|
+
part = part.strip()
|
|
37
|
+
if not part:
|
|
38
|
+
continue
|
|
39
|
+
if "-" in part:
|
|
40
|
+
start, _, end = part.partition("-")
|
|
41
|
+
try:
|
|
42
|
+
wanted.update(range(int(start), int(end) + 1))
|
|
43
|
+
except ValueError:
|
|
44
|
+
continue
|
|
45
|
+
else:
|
|
46
|
+
try:
|
|
47
|
+
wanted.add(int(part))
|
|
48
|
+
except ValueError:
|
|
49
|
+
continue
|
|
50
|
+
if not wanted:
|
|
51
|
+
return
|
|
52
|
+
doc.sections = [s for i, s in enumerate(doc.sections, start=1) if i in wanted]
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _handlers():
|
|
56
|
+
from . import csv as csv_mod
|
|
57
|
+
from . import docx as docx_mod
|
|
58
|
+
from . import epub as epub_mod
|
|
59
|
+
from . import html as html_mod
|
|
60
|
+
from . import image as image_mod
|
|
61
|
+
from . import legacy as legacy_mod
|
|
62
|
+
from . import media as media_mod
|
|
63
|
+
from . import pdf as pdf_mod
|
|
64
|
+
from . import pptx as pptx_mod
|
|
65
|
+
from . import text as text_mod
|
|
66
|
+
from . import xlsx as xlsx_mod
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
"pdf": pdf_mod.convert,
|
|
70
|
+
"docx": docx_mod.convert,
|
|
71
|
+
"pptx": pptx_mod.convert,
|
|
72
|
+
"xlsx": xlsx_mod.convert,
|
|
73
|
+
"html": html_mod.convert,
|
|
74
|
+
"markdown": text_mod.convert_markdown,
|
|
75
|
+
"text": text_mod.convert_text,
|
|
76
|
+
"csv": csv_mod.convert,
|
|
77
|
+
"epub": epub_mod.convert,
|
|
78
|
+
"image": image_mod.convert,
|
|
79
|
+
"audio": media_mod.convert_audio,
|
|
80
|
+
"video": media_mod.convert_video,
|
|
81
|
+
"doc_legacy": legacy_mod.convert_doc,
|
|
82
|
+
"ppt_legacy": legacy_mod.convert_ppt,
|
|
83
|
+
"xls_legacy": legacy_mod.convert_xls,
|
|
84
|
+
}
|
xdoc/converters/csv.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""CSV / TSV 转换。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import io
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from ..assets import AssetStore
|
|
10
|
+
from ..ir import Block, Document, Section
|
|
11
|
+
from ..options import ReadOptions
|
|
12
|
+
from .text import decode_text
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def convert(path: Path, options: ReadOptions, assets: AssetStore) -> Document:
|
|
16
|
+
text = decode_text(path)
|
|
17
|
+
sample = text[:4096]
|
|
18
|
+
try:
|
|
19
|
+
dialect = csv.Sniffer().sniff(sample, delimiters=",;\t|")
|
|
20
|
+
except csv.Error:
|
|
21
|
+
dialect = csv.excel_tab if path.suffix.lower() == ".tsv" else csv.excel
|
|
22
|
+
reader = csv.reader(io.StringIO(text), dialect)
|
|
23
|
+
rows = [[cell.strip() for cell in row] for row in reader]
|
|
24
|
+
rows = [r for r in rows if any(c for c in r)]
|
|
25
|
+
|
|
26
|
+
section = Section(label=path.name, anchor="doc:0")
|
|
27
|
+
if rows:
|
|
28
|
+
section.add(Block(kind="table", rows=rows, header=True))
|
|
29
|
+
meta = {"engine": "builtin-csv", "rows": len(rows),
|
|
30
|
+
"delimiter": dialect.delimiter}
|
|
31
|
+
return Document(source=str(path), kind="csv", sections=[section], meta=meta)
|
xdoc/converters/docx.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
"""DOCX 转换:段落顺序、标题层级、列表、表格、超链接、图片都保留。"""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from ..assets import AssetStore
|
|
9
|
+
from ..errors import XdocError
|
|
10
|
+
from ..ir import Block, Document, Section
|
|
11
|
+
from ..options import ReadOptions
|
|
12
|
+
|
|
13
|
+
HEADING_RE = re.compile(r"^(heading|标题)\s*(\d+)$", re.IGNORECASE)
|
|
14
|
+
LIST_RE = re.compile(r"(list|列表|项目符号|编号)", re.IGNORECASE)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _style_name(paragraph) -> str:
|
|
18
|
+
try:
|
|
19
|
+
return paragraph.style.name or ""
|
|
20
|
+
except Exception:
|
|
21
|
+
return ""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _paragraph_text(paragraph) -> str:
|
|
25
|
+
"""取段落文本,尽量带上超链接的 URL(忠实)。"""
|
|
26
|
+
parts: list[str] = []
|
|
27
|
+
try:
|
|
28
|
+
for item in paragraph.iter_inner_content():
|
|
29
|
+
if hasattr(item, "text") and hasattr(item, "url"):
|
|
30
|
+
url = item.url or ""
|
|
31
|
+
parts.append(f"[{item.text}]({url})" if url else item.text)
|
|
32
|
+
else:
|
|
33
|
+
parts.append(item.text)
|
|
34
|
+
return "".join(parts)
|
|
35
|
+
except AttributeError:
|
|
36
|
+
return paragraph.text
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _list_level(paragraph) -> int:
|
|
40
|
+
try:
|
|
41
|
+
pPr = paragraph._p.pPr
|
|
42
|
+
if pPr is not None and pPr.numPr is not None and pPr.numPr.ilvl is not None:
|
|
43
|
+
return int(pPr.numPr.ilvl.val)
|
|
44
|
+
except Exception:
|
|
45
|
+
pass
|
|
46
|
+
try:
|
|
47
|
+
return max(0, int(paragraph.paragraph_format.left_indent.pt // 18))
|
|
48
|
+
except Exception:
|
|
49
|
+
return 0
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _extract_images(paragraph, doc, assets: AssetStore, index: int) -> list[Block]:
|
|
53
|
+
blocks: list[Block] = []
|
|
54
|
+
try:
|
|
55
|
+
from docx.oxml.ns import qn
|
|
56
|
+
except ImportError: # pragma: no cover
|
|
57
|
+
return blocks
|
|
58
|
+
for blip in paragraph._p.xpath(".//a:blip"):
|
|
59
|
+
r_id = blip.get(qn("r:embed"))
|
|
60
|
+
if not r_id:
|
|
61
|
+
continue
|
|
62
|
+
try:
|
|
63
|
+
part = doc.part.related_parts[r_id]
|
|
64
|
+
ext = part.partname.ext or "png"
|
|
65
|
+
rel = assets.save(part.blob, f"img{index}.{ext}")
|
|
66
|
+
except Exception:
|
|
67
|
+
continue
|
|
68
|
+
if rel:
|
|
69
|
+
blocks.append(Block(kind="image", src=rel, text=f"文档图片 {index}"))
|
|
70
|
+
return blocks
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def convert(path: Path, options: ReadOptions, assets: AssetStore) -> Document:
|
|
74
|
+
try:
|
|
75
|
+
import docx
|
|
76
|
+
from docx.oxml.ns import qn
|
|
77
|
+
from docx.table import Table
|
|
78
|
+
from docx.text.paragraph import Paragraph
|
|
79
|
+
except ImportError as exc: # pragma: no cover
|
|
80
|
+
raise XdocError("缺少 python-docx") from exc
|
|
81
|
+
|
|
82
|
+
try:
|
|
83
|
+
doc = docx.Document(str(path))
|
|
84
|
+
except Exception as exc:
|
|
85
|
+
raise XdocError(f"无法打开 DOCX: {exc}") from exc
|
|
86
|
+
|
|
87
|
+
assets.bind(path)
|
|
88
|
+
section = Section(label="document", anchor="doc:0")
|
|
89
|
+
image_index = 0
|
|
90
|
+
table_count = 0
|
|
91
|
+
|
|
92
|
+
for child in doc.element.body.iterchildren():
|
|
93
|
+
tag = child.tag.split("}")[-1]
|
|
94
|
+
if tag == "p":
|
|
95
|
+
paragraph = Paragraph(child, doc)
|
|
96
|
+
text = _paragraph_text(paragraph).strip()
|
|
97
|
+
style = _style_name(paragraph)
|
|
98
|
+
heading = HEADING_RE.match(style.strip())
|
|
99
|
+
if heading and text:
|
|
100
|
+
section.add(Block(kind="heading", text=text, level=int(heading.group(2))))
|
|
101
|
+
elif LIST_RE.search(style) and text:
|
|
102
|
+
section.add(Block(kind="list_item", text=text, level=_list_level(paragraph)))
|
|
103
|
+
elif text:
|
|
104
|
+
section.add(Block(kind="text", text=text))
|
|
105
|
+
for block in _extract_images(paragraph, doc, assets, image_index):
|
|
106
|
+
section.add(block)
|
|
107
|
+
image_index += 1
|
|
108
|
+
elif tag == "tbl":
|
|
109
|
+
table = Table(child, doc)
|
|
110
|
+
rows = []
|
|
111
|
+
for row in table.rows:
|
|
112
|
+
rows.append([cell.text.strip() for cell in row.cells])
|
|
113
|
+
rows = [r for r in rows if any(c for c in r)]
|
|
114
|
+
if rows:
|
|
115
|
+
table_count += 1
|
|
116
|
+
section.add(Block(kind="table", rows=rows, header=True))
|
|
117
|
+
|
|
118
|
+
meta = {
|
|
119
|
+
"engine": "python-docx",
|
|
120
|
+
"paragraphs": len(section.blocks),
|
|
121
|
+
"tables": table_count,
|
|
122
|
+
}
|
|
123
|
+
return Document(source=str(path), kind="docx", sections=[section], meta=meta)
|