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.
@@ -0,0 +1,68 @@
1
+ """EPUB 转换:按 spine 顺序逐章转 Markdown。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import zipfile
7
+ from pathlib import Path
8
+ from xml.etree import ElementTree as ET
9
+
10
+ from ..assets import AssetStore
11
+ from ..errors import XdocError
12
+ from ..ir import Block, Document, Section
13
+ from ..options import ReadOptions
14
+
15
+
16
+ def convert(path: Path, options: ReadOptions, assets: AssetStore) -> Document:
17
+ try:
18
+ from bs4 import BeautifulSoup
19
+ from markdownify import markdownify
20
+ except ImportError as exc: # pragma: no cover
21
+ raise XdocError("缺少 beautifulsoup4 / markdownify") from exc
22
+
23
+ try:
24
+ zf = zipfile.ZipFile(path)
25
+ except Exception as exc:
26
+ raise XdocError(f"无法打开 EPUB: {exc}") from exc
27
+
28
+ try:
29
+ container = ET.fromstring(zf.read("META-INF/container.xml"))
30
+ except Exception as exc:
31
+ raise XdocError(f"EPUB 缺少 container.xml: {exc}") from exc
32
+
33
+ opf_path = ""
34
+ for rootfile in container.iter():
35
+ if rootfile.tag.endswith("rootfile"):
36
+ opf_path = rootfile.attrib.get("full-path", "")
37
+ break
38
+ if not opf_path:
39
+ raise XdocError("EPUB 结构异常:找不到 OPF 文件")
40
+
41
+ base = Path(opf_path).parent
42
+ opf = ET.fromstring(zf.read(opf_path))
43
+ manifest: dict[str, str] = {}
44
+ for item in opf.iter():
45
+ if item.tag.endswith("item"):
46
+ manifest[item.attrib.get("id", "")] = item.attrib.get("href", "")
47
+
48
+ sections: list[Section] = []
49
+ for index, spine in enumerate(opf.iter()):
50
+ if not spine.tag.endswith("itemref"):
51
+ continue
52
+ href = manifest.get(spine.attrib.get("idref", ""), "")
53
+ if not href:
54
+ continue
55
+ item_path = (base / href).as_posix().lstrip("./")
56
+ try:
57
+ raw = zf.read(item_path).decode("utf-8", "replace")
58
+ except KeyError:
59
+ continue
60
+ soup = BeautifulSoup(raw, "html.parser")
61
+ title = soup.title.get_text(strip=True) if soup.title else f"第 {index + 1} 章"
62
+ md = markdownify(str(soup.body or soup), heading_style="ATX", bullets="-")
63
+ section = Section(label=title, anchor=f"chapter:{index + 1}")
64
+ section.add(Block(kind="text", text=md.strip()))
65
+ sections.append(section)
66
+
67
+ meta = {"engine": "builtin-epub", "chapters": len(sections)}
68
+ return Document(source=str(path), kind="epub", sections=sections, meta=meta)
@@ -0,0 +1,86 @@
1
+ """HTML / 富文本转换:按标题切段,结构化为 Markdown。"""
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
+ DROP_TAGS = ["script", "style", "noscript", "iframe", "svg", "canvas", "form"]
14
+
15
+
16
+ def _decode(raw: bytes) -> str:
17
+ for encoding in ("utf-8", "gb18030", "big5", "latin-1"):
18
+ try:
19
+ return raw.decode(encoding)
20
+ except UnicodeDecodeError:
21
+ continue
22
+ return raw.decode("utf-8", errors="replace")
23
+
24
+
25
+ def convert(path: Path, options: ReadOptions, assets: AssetStore) -> Document:
26
+ try:
27
+ from bs4 import BeautifulSoup
28
+ from markdownify import markdownify
29
+ except ImportError as exc: # pragma: no cover
30
+ raise XdocError("缺少 beautifulsoup4 / markdownify") from exc
31
+
32
+ raw = _decode(path.read_bytes())
33
+ soup = BeautifulSoup(raw, "html.parser")
34
+ title = soup.title.get_text(strip=True) if soup.title else None
35
+ for tag in soup(DROP_TAGS):
36
+ tag.decompose()
37
+
38
+ body = soup.body or soup
39
+ sections: list[Section] = []
40
+ current = Section(label=title or "document", anchor="section:0")
41
+ sections.append(current)
42
+
43
+ heading_re = re.compile(r"^#{1,6}\s+(.*)$")
44
+ for node in body.find_all(["h1", "h2", "h3", "p", "ul", "ol", "pre", "table", "blockquote"], recursive=True):
45
+ if node.name in ("h1", "h2", "h3"):
46
+ text = node.get_text(" ", strip=True)
47
+ if not text:
48
+ continue
49
+ level = int(node.name[1])
50
+ if level <= 2 and current.blocks:
51
+ current = Section(label=text, anchor=f"section:{len(sections)}")
52
+ sections.append(current)
53
+ current.add(Block(kind="heading", text=text, level=level))
54
+ elif node.name == "table":
55
+ rows = []
56
+ for tr in node.find_all("tr"):
57
+ cells = [td.get_text(" ", strip=True) for td in tr.find_all(["td", "th"])]
58
+ if any(cells):
59
+ rows.append(cells)
60
+ if rows:
61
+ current.add(Block(kind="table", rows=rows, header=True))
62
+ elif node.name in ("ul", "ol"):
63
+ for li in node.find_all("li", recursive=False):
64
+ text = li.get_text(" ", strip=True)
65
+ if text:
66
+ current.add(Block(kind="list_item", text=text))
67
+ elif node.name == "pre":
68
+ text = node.get_text("\n", strip=False).strip()
69
+ if text:
70
+ current.add(Block(kind="code", text=text))
71
+ elif node.name == "blockquote":
72
+ text = node.get_text(" ", strip=True)
73
+ if text:
74
+ current.add(Block(kind="quote", text=text))
75
+ else: # p
76
+ text = node.get_text(" ", strip=True)
77
+ if text:
78
+ current.add(Block(kind="text", text=text))
79
+
80
+ if not any(s.blocks for s in sections):
81
+ # 兜底:整页转 Markdown
82
+ md = markdownify(str(body), heading_style="ATX", bullets="-")
83
+ sections[0].add(Block(kind="text", text=md.strip()))
84
+
85
+ meta = {"engine": "beautifulsoup4+markdownify", "title": title}
86
+ return Document(source=str(path), kind="html", sections=sections, meta=meta)
@@ -0,0 +1,72 @@
1
+ """图片转换:元数据 + (装了 OCR 插件就)文字识别。
2
+
3
+ 识别结果保留行结构,并给出识别置信度,便于判断是否可信。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+
10
+ from ..assets import AssetStore
11
+ from ..errors import XdocError
12
+ from ..ir import Block, Document, Section
13
+ from ..options import ReadOptions
14
+ from ..plugins import PluginManager
15
+
16
+
17
+ def _dimensions(path: Path) -> tuple[int | None, int | None]:
18
+ try:
19
+ import pymupdf
20
+
21
+ doc = pymupdf.open(str(path))
22
+ page = doc[0]
23
+ rect = page.rect
24
+ doc.close()
25
+ return int(rect.width), int(rect.height)
26
+ except Exception:
27
+ pass
28
+ try:
29
+ from PIL import Image # type: ignore
30
+
31
+ with Image.open(path) as img:
32
+ return img.width, img.height
33
+ except Exception:
34
+ return None, None
35
+
36
+
37
+ def convert(path: Path, options: ReadOptions, assets: AssetStore) -> Document:
38
+ assets.bind(path)
39
+ section = Section(label=path.name, anchor="image:0")
40
+ meta: dict = {"engine": "builtin"}
41
+
42
+ width, height = _dimensions(path)
43
+ if width and height:
44
+ meta["width"] = width
45
+ meta["height"] = height
46
+ meta["bytes"] = path.stat().st_size
47
+ meta["format"] = path.suffix.lstrip(".").lower()
48
+
49
+ manager = PluginManager(Path(options.plugin_dir) if options.plugin_dir else None)
50
+ ocr_results: list[dict] = []
51
+ if options.ocr != "off" and manager.is_installed("ocr"):
52
+ payload = {"images": [str(path)]}
53
+ result = manager.run_worker("ocr", payload)
54
+ if result.get("error"):
55
+ raise XdocError(f"OCR 失败: {result['error']}")
56
+ ocr_results = result.get("results") or []
57
+
58
+ if ocr_results:
59
+ for item in ocr_results:
60
+ text = (item.get("text") or "").strip()
61
+ if not text:
62
+ continue
63
+ scores = [float(line.get("score", 0)) for line in item.get("lines", [])]
64
+ section.add(Block(kind="text", text=text, meta={
65
+ "ocr": True,
66
+ "avg_score": round(sum(scores) / len(scores), 4) if scores else None,
67
+ }))
68
+ meta["ocr"] = "installed plugin"
69
+ else:
70
+ section.add(Block(kind="note", text="(图片内容需要 OCR 插件:xdoc plugin add ocr)"))
71
+
72
+ return Document(source=str(path), kind="image", sections=[section], meta=meta)
@@ -0,0 +1,81 @@
1
+ """旧版 Office 格式(.doc/.ppt/.xls)转换。
2
+
3
+ 本机装有 LibreOffice,用无头模式先转成现代格式,再走标准转换器。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import os
9
+ import shutil
10
+ import subprocess
11
+ import tempfile
12
+ from pathlib import Path
13
+
14
+ from ..assets import AssetStore
15
+ from ..errors import XdocError
16
+ from ..ir import Document
17
+ from ..options import ReadOptions
18
+
19
+ CANDIDATES = [
20
+ r"C:\Program Files\LibreOffice\program\soffice.exe",
21
+ r"C:\Program Files (x86)\LibreOffice\program\soffice.exe",
22
+ "/usr/bin/soffice",
23
+ "/Applications/LibreOffice.app/Contents/MacOS/soffice",
24
+ ]
25
+
26
+
27
+ def find_soffice() -> str | None:
28
+ found = shutil.which("soffice") or shutil.which("libreoffice")
29
+ if found:
30
+ return found
31
+ for candidate in CANDIDATES:
32
+ if Path(candidate).exists():
33
+ return candidate
34
+ return None
35
+
36
+
37
+ def _convert_to(path: Path, target_ext: str) -> Path:
38
+ soffice = find_soffice()
39
+ if soffice is None:
40
+ raise XdocError("未找到 LibreOffice,无法转换旧版 Office 文件(可用 xdoc plugin add ... 或安装 LibreOffice)")
41
+ outdir = Path(tempfile.mkdtemp(prefix="xdoc-legacy-"))
42
+ profile = outdir / "profile"
43
+ cmd = [
44
+ soffice, "--headless", "--norestore", "--invisible",
45
+ f"-env:UserInstallation=file:///{profile.as_posix()}",
46
+ "--convert-to", target_ext, "--outdir", str(outdir), str(path),
47
+ ]
48
+ try:
49
+ proc = subprocess.run(cmd, capture_output=True, timeout=300)
50
+ except Exception as exc:
51
+ raise XdocError(f"LibreOffice 转换失败: {exc}") from exc
52
+ produced = list(outdir.glob(f"*.{target_ext.split(':')[0]}"))
53
+ if not produced:
54
+ detail = proc.stderr.decode("utf-8", "replace")[-400:]
55
+ raise XdocError(f"LibreOffice 未产出文件: {detail}")
56
+ return produced[0]
57
+
58
+
59
+ def _convert_legacy(path: Path, target: str, options: ReadOptions, assets: AssetStore) -> Document:
60
+ from . import convert as dispatch
61
+
62
+ converted = _convert_to(path, target)
63
+ try:
64
+ doc = dispatch(converted, options, assets)
65
+ finally:
66
+ shutil.rmtree(converted.parent, ignore_errors=True)
67
+ doc.source = str(path)
68
+ doc.meta["converted_via"] = "LibreOffice"
69
+ return doc
70
+
71
+
72
+ def convert_doc(path: Path, options: ReadOptions, assets: AssetStore) -> Document:
73
+ return _convert_legacy(path, "docx", options, assets)
74
+
75
+
76
+ def convert_ppt(path: Path, options: ReadOptions, assets: AssetStore) -> Document:
77
+ return _convert_legacy(path, "pptx", options, assets)
78
+
79
+
80
+ def convert_xls(path: Path, options: ReadOptions, assets: AssetStore) -> Document:
81
+ return _convert_legacy(path, "xlsx", options, assets)
@@ -0,0 +1,247 @@
1
+ """音频 / 视频转换。
2
+
3
+ 音频:有 ASR 插件就转写(带时间戳),没有就只给元数据并提示。
4
+ 视频:ffmpeg 抽音轨 + 抽关键帧,音轨再交给 ASR;关键帧以图片形式交给能看图的模型。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import shutil
11
+ import subprocess
12
+ import tempfile
13
+ import wave
14
+ from pathlib import Path
15
+
16
+ from ..assets import AssetStore
17
+ from ..errors import XdocError
18
+ from ..ir import Block, Document, Section
19
+ from ..options import ReadOptions
20
+ from ..plugins import PluginManager
21
+
22
+
23
+ def _timestamp(seconds: float) -> str:
24
+ seconds = max(0.0, float(seconds))
25
+ h, rem = divmod(int(seconds), 3600)
26
+ m, s = divmod(rem, 60)
27
+ frac = int(round((seconds - int(seconds)) * 1000))
28
+ if h:
29
+ return f"{h:02d}:{m:02d}:{s:02d}.{frac:03d}"
30
+ return f"{m:02d}:{s:02d}.{frac:03d}"
31
+
32
+
33
+ def _wav_duration(path: Path) -> float | None:
34
+ try:
35
+ with wave.open(str(path), "rb") as wf:
36
+ return wf.getnframes() / float(wf.getframerate())
37
+ except Exception:
38
+ return None
39
+
40
+
41
+ def _ffprobe(manager: PluginManager, path: Path) -> dict | None:
42
+ tool = manager.ffmpeg_path("ffprobe")
43
+ if tool is None:
44
+ return None
45
+ cmd = [
46
+ str(tool), "-v", "quiet", "-print_format", "json",
47
+ "-show_format", "-show_streams", str(path),
48
+ ]
49
+ try:
50
+ proc = subprocess.run(cmd, capture_output=True, timeout=120)
51
+ return json.loads(proc.stdout.decode("utf-8", "replace") or "{}")
52
+ except Exception:
53
+ return None
54
+
55
+
56
+ def _extract_audio(manager: PluginManager, path: Path, out_path: Path) -> bool:
57
+ ffmpeg = manager.ffmpeg_path("ffmpeg")
58
+ if ffmpeg is None:
59
+ return False
60
+ cmd = [str(ffmpeg), "-y", "-i", str(path), "-vn", "-ac", "1", "-ar", "16000",
61
+ "-c:a", "pcm_s16le", str(out_path)]
62
+ try:
63
+ proc = subprocess.run(cmd, capture_output=True, timeout=1800)
64
+ return proc.returncode == 0 and out_path.exists()
65
+ except Exception:
66
+ return False
67
+
68
+
69
+ def _asr_candidates(manager: PluginManager, options: ReadOptions) -> list[tuple[str, str]]:
70
+ """按用户偏好挑可用的 ASR 插件:返回 [(插件名, 后端)],已过滤掉没装的。"""
71
+ want = (options.asr or "auto").strip().lower()
72
+ if want == "off":
73
+ return []
74
+ if want in ("zh", "funasr", "asr-zh"):
75
+ order = [("asr-zh", "funasr"), ("asr", "faster-whisper")]
76
+ elif want in ("whisper", "faster-whisper", "asr"):
77
+ order = [("asr", "faster-whisper"), ("asr-zh", "funasr")]
78
+ else: # auto
79
+ order = [("asr", "faster-whisper"), ("asr-zh", "funasr")]
80
+ return [(name, backend) for name, backend in order if manager.is_installed(name)]
81
+
82
+
83
+ def _run_asr(manager: PluginManager, plugin: str, backend: str, audio: Path,
84
+ options: ReadOptions) -> dict:
85
+ payload = {
86
+ "audio": str(audio),
87
+ "model": options.asr_model or "small",
88
+ "language": options.extra.get("asr_language"),
89
+ "backend": backend,
90
+ }
91
+ result = manager.run_worker(plugin, payload)
92
+ if result.get("error"):
93
+ raise XdocError(f"ASR 失败: {result['error']}")
94
+ return result
95
+
96
+
97
+ def _transcribe(manager: PluginManager, audio: Path, options: ReadOptions) -> list[dict]:
98
+ candidates = _asr_candidates(manager, options)
99
+ if not candidates:
100
+ return []
101
+ plugin, backend = candidates[0]
102
+ result = _run_asr(manager, plugin, backend, audio, options)
103
+
104
+ language = str(result.get("language") or "")
105
+ want = (options.asr or "auto").strip().lower()
106
+ if want == "auto" and language.startswith("zh"):
107
+ # 自动模式下检测到中文:如果装了中文引擎,再用它转写一遍(中文精度更高)
108
+ zh = next((c for c in candidates if c[0] == "asr-zh"), None)
109
+ if zh and plugin != "asr-zh":
110
+ result = _run_asr(manager, "asr-zh", "funasr", audio, options)
111
+ return result.get("segments") or []
112
+
113
+
114
+ def _segments_to_blocks(segments: list[dict]) -> list[Block]:
115
+ blocks: list[Block] = []
116
+ for seg in segments:
117
+ text = (seg.get("text") or "").strip()
118
+ if not text:
119
+ continue
120
+ start = float(seg.get("start", 0))
121
+ end = float(seg.get("end", start))
122
+ blocks.append(Block(
123
+ kind="text",
124
+ text=f"[{_timestamp(start)}] {text}",
125
+ meta={"start": start, "end": end},
126
+ ))
127
+ return blocks
128
+
129
+
130
+ def convert_audio(path: Path, options: ReadOptions, assets: AssetStore) -> Document:
131
+ manager = PluginManager(Path(options.plugin_dir) if options.plugin_dir else None)
132
+ section = Section(label=path.name, anchor="time:00:00:00")
133
+ meta: dict = {"engine": "builtin"}
134
+
135
+ duration = _wav_duration(path)
136
+ if duration is None:
137
+ probe = _ffprobe(manager, path)
138
+ if probe:
139
+ fmt = probe.get("format", {})
140
+ duration = float(fmt.get("duration") or 0) or None
141
+ meta["container"] = fmt.get("format_name")
142
+ streams = probe.get("streams", [])
143
+ if streams:
144
+ meta["codec"] = streams[0].get("codec_name")
145
+ meta["sample_rate"] = streams[0].get("sample_rate")
146
+ meta["channels"] = streams[0].get("channels")
147
+ if duration:
148
+ meta["duration"] = round(duration, 2)
149
+
150
+ audio_for_asr = path
151
+ tmpdir = None
152
+ if path.suffix.lower() != ".wav":
153
+ tmpdir = Path(tempfile.mkdtemp(prefix="xdoc-audio-"))
154
+ target = tmpdir / "audio.wav"
155
+ if _extract_audio(manager, path, target):
156
+ audio_for_asr = target
157
+ else:
158
+ audio_for_asr = path
159
+
160
+ segments = _transcribe(manager, audio_for_asr, options)
161
+ if segments:
162
+ section.extend(_segments_to_blocks(segments))
163
+ meta["segments"] = len(segments)
164
+ meta["asr"] = "installed plugin"
165
+ else:
166
+ section.add(Block(kind="note", text="(未安装 ASR 插件,只返回元数据;执行 xdoc plugin add asr 可开启转写)"))
167
+
168
+ if tmpdir:
169
+ shutil.rmtree(tmpdir, ignore_errors=True)
170
+
171
+ meta.setdefault("duration", None)
172
+ return Document(source=str(path), kind="audio", sections=[section], meta=meta)
173
+
174
+
175
+ def _extract_frames(manager: PluginManager, path: Path, assets: AssetStore, duration: float | None,
176
+ section: Section, max_frames: int = 12) -> int:
177
+ ffmpeg = manager.ffmpeg_path("ffmpeg")
178
+ if ffmpeg is None or not duration:
179
+ return 0
180
+ step = max(1.0, duration / max_frames)
181
+ count = 0
182
+ for index in range(max_frames):
183
+ timestamp = index * step
184
+ if timestamp >= duration:
185
+ break
186
+ filename = f"frame-{_timestamp(timestamp).replace(':', '-')}.png"
187
+ target = assets.root / assets._rel_dir / filename
188
+ target.parent.mkdir(parents=True, exist_ok=True)
189
+ cmd = [str(ffmpeg), "-y", "-ss", f"{timestamp:.2f}", "-i", str(path),
190
+ "-frames:v", "1", str(target)]
191
+ try:
192
+ proc = subprocess.run(cmd, capture_output=True, timeout=120)
193
+ except Exception:
194
+ continue
195
+ if proc.returncode == 0 and target.exists():
196
+ rel = assets._rel(f"{assets._rel_dir}/{filename}")
197
+ section.add(Block(kind="image", src=rel, text=f"{_timestamp(timestamp)} 关键帧",
198
+ meta={"timestamp": timestamp}))
199
+ count += 1
200
+ return count
201
+
202
+
203
+ def convert_video(path: Path, options: ReadOptions, assets: AssetStore) -> Document:
204
+ manager = PluginManager(Path(options.plugin_dir) if options.plugin_dir else None)
205
+ assets.bind(path)
206
+ section = Section(label=path.name, anchor="time:00:00:00")
207
+ meta: dict = {"engine": "builtin"}
208
+
209
+ probe = _ffprobe(manager, path)
210
+ duration = None
211
+ if probe:
212
+ fmt = probe.get("format", {})
213
+ duration = float(fmt.get("duration") or 0) or None
214
+ meta["container"] = fmt.get("format_name")
215
+ video_streams = [s for s in probe.get("streams", []) if s.get("codec_type") == "video"]
216
+ audio_streams = [s for s in probe.get("streams", []) if s.get("codec_type") == "audio"]
217
+ if video_streams:
218
+ vs = video_streams[0]
219
+ meta["resolution"] = f"{vs.get('width')}x{vs.get('height')}"
220
+ meta["fps"] = vs.get("avg_frame_rate")
221
+ if audio_streams:
222
+ meta["has_audio"] = True
223
+ if duration:
224
+ meta["duration"] = round(duration, 2)
225
+
226
+ tmpdir = Path(tempfile.mkdtemp(prefix="xdoc-video-"))
227
+ try:
228
+ audio_path = tmpdir / "audio.wav"
229
+ if _extract_audio(manager, path, audio_path):
230
+ segments = _transcribe(manager, audio_path, options)
231
+ if segments:
232
+ for block in _segments_to_blocks(segments):
233
+ section.add(block)
234
+ meta["segments"] = len(segments)
235
+
236
+ frames = _extract_frames(manager, path, assets, duration, section)
237
+ if frames:
238
+ meta["frames"] = frames
239
+ elif manager.ffmpeg_path("ffmpeg") is None:
240
+ section.add(Block(kind="note", text="(未安装 media 插件,无法抽取关键帧;执行 xdoc plugin add media)"))
241
+ finally:
242
+ shutil.rmtree(tmpdir, ignore_errors=True)
243
+
244
+ if not section.blocks:
245
+ section.add(Block(kind="note", text="(没有可用内容:缺 media/asr 插件)"))
246
+
247
+ return Document(source=str(path), kind="video", sections=[section], meta=meta)