yimo-kit 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.
Files changed (70) hide show
  1. yimo/__init__.py +26 -0
  2. yimo/kit/__init__.py +98 -0
  3. yimo/kit/ai/__init__.py +110 -0
  4. yimo/kit/ai/_internal/__init__.py +27 -0
  5. yimo/kit/ai/_internal/failover.py +535 -0
  6. yimo/kit/ai/_internal/pool.py +526 -0
  7. yimo/kit/ai/_internal/rerank_transport.py +137 -0
  8. yimo/kit/ai/_internal/retry_after.py +51 -0
  9. yimo/kit/ai/_internal/sdk_client.py +463 -0
  10. yimo/kit/ai/_internal/service_base.py +115 -0
  11. yimo/kit/ai/_internal/types.py +28 -0
  12. yimo/kit/ai/agent/__init__.py +127 -0
  13. yimo/kit/ai/agent/approval.py +66 -0
  14. yimo/kit/ai/agent/errors.py +128 -0
  15. yimo/kit/ai/agent/loop.py +643 -0
  16. yimo/kit/ai/agent/mcp.py +278 -0
  17. yimo/kit/ai/agent/registry.py +203 -0
  18. yimo/kit/ai/agent/session.py +150 -0
  19. yimo/kit/ai/agent/skill.py +370 -0
  20. yimo/kit/ai/agent/types.py +161 -0
  21. yimo/kit/ai/chat_service.py +724 -0
  22. yimo/kit/ai/decision/__init__.py +57 -0
  23. yimo/kit/ai/decision/decima.py +853 -0
  24. yimo/kit/ai/decision/laya.py +552 -0
  25. yimo/kit/ai/embedding_service.py +198 -0
  26. yimo/kit/ai/exceptions.py +109 -0
  27. yimo/kit/ai/image_service.py +84 -0
  28. yimo/kit/ai/messages.py +105 -0
  29. yimo/kit/ai/model_builder.py +121 -0
  30. yimo/kit/ai/model_client.py +62 -0
  31. yimo/kit/ai/profiles.py +577 -0
  32. yimo/kit/ai/rerank_service.py +136 -0
  33. yimo/kit/ai/runner.py +1127 -0
  34. yimo/kit/common_kit.py +221 -0
  35. yimo/kit/config/__init__.py +44 -0
  36. yimo/kit/config/kit_config.py +210 -0
  37. yimo/kit/config/log_config.py +171 -0
  38. yimo/kit/crawl/__init__.py +71 -0
  39. yimo/kit/crawl/article_io.py +325 -0
  40. yimo/kit/crawl/article_models.py +172 -0
  41. yimo/kit/crawl/deepseek_kit.py +673 -0
  42. yimo/kit/crawl/web_article_kit.py +638 -0
  43. yimo/kit/crawl/wx_article_kit.py +692 -0
  44. yimo/kit/db/__init__.py +101 -0
  45. yimo/kit/db/audit.py +625 -0
  46. yimo/kit/db/base_db_kit.py +1265 -0
  47. yimo/kit/db/crud.py +423 -0
  48. yimo/kit/db/engine.py +235 -0
  49. yimo/kit/db/exceptions.py +45 -0
  50. yimo/kit/db/models/__init__.py +33 -0
  51. yimo/kit/db/models/base.py +56 -0
  52. yimo/kit/db/mysql_kit.py +348 -0
  53. yimo/kit/db/pg_kit.py +442 -0
  54. yimo/kit/db/query.py +338 -0
  55. yimo/kit/db/session.py +85 -0
  56. yimo/kit/db/sqlite_kit.py +462 -0
  57. yimo/kit/db/transaction.py +109 -0
  58. yimo/kit/docs/__init__.py +34 -0
  59. yimo/kit/docs/anydoc_kit.py +490 -0
  60. yimo/kit/docs/docx_kit.py +895 -0
  61. yimo/kit/docs/md2doc_kit.py +1801 -0
  62. yimo/kit/docs/mineru_kit.py +1497 -0
  63. yimo/kit/docs/rc_docparser_kit.py +654 -0
  64. yimo/kit/file_kit.py +518 -0
  65. yimo/kit/license_kit.py +533 -0
  66. yimo/kit/redis_kit.py +392 -0
  67. yimo_kit-0.1.0.dist-info/METADATA +1673 -0
  68. yimo_kit-0.1.0.dist-info/RECORD +70 -0
  69. yimo_kit-0.1.0.dist-info/WHEEL +4 -0
  70. yimo_kit-0.1.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,490 @@
1
+ """
2
+ Copyright (c) 2021-2026 溢墨修心(Yimo). All Rights Reserved.
3
+
4
+ Licensed under the Apache License, Version 2.0 (the "License");
5
+ you may not use this file except in compliance with the License.
6
+ You may obtain a copy of the License at
7
+
8
+ http://www.apache.org/licenses/LICENSE-2.0
9
+
10
+ Unless required by applicable law or agreed to in writing, software
11
+ distributed under the License is distributed on an "AS IS" BASIS,
12
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ See the License for the specific language governing permissions and
14
+ limitations under the License.
15
+
16
+ Project: yimo
17
+ Author: 溢墨修心(Yimo)
18
+ """
19
+
20
+ # date: 2026-09-23
21
+ """AnyDocKit —— 文档转 Markdown 工具类(基于 firecrawl-anydoc)
22
+
23
+ 支持面:`.doc` / `.docx` / `.ppt` / `.pptx` / `.xls` / `.xlsx` / `.csv` / `.pdf`
24
+ (白名单为 anydoc 支持面的常用子集)。
25
+
26
+ 实现内容:
27
+ - 全部静态方法、无内部状态;低层 `convert_to_md` 直接抛异常,高层 `convert`
28
+ 返回 `AnyDocResult` 封装成功/失败,便于批量处理。
29
+ - PDF 结构非标(如知网件 `%%EOF` 后附加元数据)遇 `MalformedError` 时,用
30
+ pikepdf 重写为临时文件后重试一次;扫描页默认 reject,`ocr="hosted"` 走云端 OCR。
31
+ - 路径参数支持 `str` / `Path`;访问文件的方法内部 resolve 为绝对路径,
32
+ 纯扩展名判断方法不做 resolve。
33
+
34
+ 前提条件:
35
+ - 只产出 Markdown 文本,**不产出图片**(需要 `md + images/` 时用 `MarkerKit`
36
+ 或 `RcDocParserKit`)。
37
+ - 云端 OCR 需 `FIRECRAWL_API_KEY`(或显式传 `api_key`)。
38
+
39
+ 依赖:
40
+ - `firecrawl-anydoc`(extra `anydoc`,导入名 `anydoc`)+ `pikepdf`;
41
+ 未安装时导入报错并提示安装命令。
42
+
43
+ 异常:
44
+ - 沿用上游 `anydoc.ConvertError` 体系(不包装,保留 `MalformedError` /
45
+ `NeedsOcrError` 等子类可捕获性);`AnyDocError` 是该基类的别名。
46
+ """
47
+
48
+ import io
49
+ from dataclasses import dataclass
50
+ from pathlib import Path
51
+ from typing import Callable, Literal
52
+
53
+ try:
54
+ import anydoc
55
+ import pikepdf
56
+ except ImportError as e:
57
+ raise ImportError(
58
+ "anydoc_kit 需要可选依赖,请安装:pip install yimo-kit[anydoc]"
59
+ ) from e
60
+
61
+ from yimo.kit.config.log_config import get_default_logger
62
+
63
+ logger = get_default_logger(__name__)
64
+
65
+ # 异常别名:沿用 anydoc 的异常体系,不包装(保留上游子类可捕获性)
66
+ AnyDocError = anydoc.ConvertError
67
+
68
+ # kit 维护的扩展名白名单(用于本地快速校验与错误提示)。
69
+ # 注意:这是 anydoc 实际支持面的子集——anydoc 另支持 docm / pptm / ppsx / ppsm /
70
+ # xlsm / xlsb / pps / pot / odt / ods / odp / rtf / epub 等。
71
+ _SUPPORTED_EXTENSIONS: frozenset[str] = frozenset(
72
+ {
73
+ # Word
74
+ ".doc",
75
+ ".docx",
76
+ # PowerPoint
77
+ ".ppt",
78
+ ".pptx",
79
+ # Excel
80
+ ".xls",
81
+ ".xlsx",
82
+ # 其他
83
+ ".csv",
84
+ ".pdf",
85
+ }
86
+ )
87
+
88
+ # PDF 修复临时件后缀(同目录隐藏临时件模式,用后即清)
89
+ _REPAIR_TMP_SUFFIX = ".repair-tmp.pdf"
90
+
91
+
92
+ def _repair_pdf_file(src: Path) -> Path:
93
+ """pikepdf 重写修复结构非标的 PDF 文件(知网 WebFastLoad 尾部垃圾等)
94
+
95
+ anydoc 的严格解析器对 `%%EOF` 后附加自定义元数据等非标结构直接报
96
+ MalformedError;qpdf 引擎重写即得完全标准的 PDF。输出与源同目录的
97
+ 隐藏临时件,由调用方负责清理(彻底损坏的 PDF 由此抛 pikepdf 异常)。
98
+ """
99
+ dst = src.with_name(f".{src.stem}{_REPAIR_TMP_SUFFIX}")
100
+ with pikepdf.open(src) as pdf:
101
+ pdf.save(dst)
102
+ return dst
103
+
104
+
105
+ def _repair_pdf_bytes(data: bytes) -> bytes:
106
+ """pikepdf 内存内重写修复 PDF 字节流(不落盘),语义同 _repair_pdf_file"""
107
+ with pikepdf.open(io.BytesIO(data)) as pdf:
108
+ out = io.BytesIO()
109
+ pdf.save(out)
110
+ return out.getvalue()
111
+
112
+
113
+ def _convert_with_repair(
114
+ first: Callable[[], str],
115
+ *,
116
+ is_pdf: bool,
117
+ label: str,
118
+ repair: Callable[[], Path | bytes],
119
+ retry: Callable[..., str],
120
+ cleanup: Callable[[Path | bytes], None] | None = None,
121
+ ) -> str:
122
+ """转换并处理「非标 PDF 修复重试」的统一骨架
123
+
124
+ - 执行 first(),正常返回其转换结果;
125
+ - 仅当目标是 PDF 且 anydoc 报 MalformedError 时:调用 repair() 产出修复
126
+ 载荷(文件路径或字节流),再以 retry(载荷) 重试一次;
127
+ - 非 PDF 的 MalformedError 直接上抛;修复自身失败时上抛原始异常(修复
128
+ 异常为 __cause__);重试仍失败以重试异常为准(原始异常为 __cause__);
129
+ - 无论重试成败,均执行 cleanup(载荷) 清理临时产物。
130
+ """
131
+ try:
132
+ return first()
133
+ except anydoc.MalformedError as e:
134
+ if not is_pdf:
135
+ logger.error(f"{label}失败({type(e).__name__}): {e}")
136
+ raise
137
+ logger.warning(f"{label}解析失败,尝试 pikepdf 修复重试: {e}")
138
+ try:
139
+ payload = repair()
140
+ except Exception as repair_err: # noqa: BLE001 - 修复失败按原始异常上抛
141
+ logger.error(f"pikepdf 修复失败: {repair_err}")
142
+ raise e from repair_err
143
+ try:
144
+ return retry(payload)
145
+ except anydoc.ConvertError as e2:
146
+ logger.error(f"{label}失败(含修复重试,{type(e2).__name__}): {e2}")
147
+ raise e2 from e
148
+ finally:
149
+ if cleanup is not None:
150
+ cleanup(payload)
151
+ except anydoc.ConvertError as e:
152
+ logger.error(f"{label}失败({type(e).__name__}): {e}")
153
+ raise
154
+
155
+
156
+ @dataclass(frozen=True, slots=True)
157
+ class AnyDocResult:
158
+ """文档转换结果对象
159
+
160
+ 由 AnyDocKit.convert 返回,将成功与失败信息统一封装,调用方无需 try/except。
161
+
162
+ Attributes:
163
+ success: 转换是否成功
164
+ markdown: 转换后的 Markdown 文本,失败时为空字符串
165
+ file_path: 源文件的绝对路径
166
+ source_format: 由文件扩展名推断的规范格式名(如 'docx'、'pdf'),无法识别为 None
167
+ error: 失败原因描述(异常类型与信息),成功时为 None
168
+ """
169
+
170
+ success: bool
171
+ markdown: str
172
+ file_path: str
173
+ source_format: str | None = None
174
+ error: str | None = None
175
+
176
+
177
+ class AnyDocKit:
178
+ """文档解析工具类,基于 anydoc 将各类文档转为 Markdown
179
+
180
+ 支持 Word(.doc/.docx)、PowerPoint(.ppt/.pptx)、Excel(.xls/.xlsx)、
181
+ CSV、PDF 共 5 类 8 种扩展名,统一输出 GitHub-Flavored Markdown。
182
+
183
+ 使用方式:
184
+ # 1. 直接转换(异常向上抛出;非标 PDF 自动 pikepdf 修复重试)
185
+ markdown = AnyDocKit.convert_to_md("report.docx")
186
+
187
+ # 2. 安全转换(返回状态结果,不抛异常)
188
+ result = AnyDocKit.convert("report.pdf")
189
+ if result.success:
190
+ print(result.markdown)
191
+
192
+ # 3. 扫描件走云端 OCR(需 FIRECRAWL_API_KEY 或显式传 api_key)
193
+ md = AnyDocKit.convert_to_md("scan.pdf", ocr="hosted")
194
+
195
+ # 4. 转换并写入 .md 文件
196
+ AnyDocKit.convert_to_file("report.docx", "out/report.md")
197
+
198
+ # 5. 字节内容转换(无需落盘)
199
+ md = AnyDocKit.convert_bytes_to_md(file_bytes, "csv")
200
+
201
+ Markdown → Word/PDF/HTML 的反向转换见 yimo.kit.docs.md2doc_kit(Md2DocKit)。
202
+
203
+ 可与 FileKit 组合使用以访问 FILE_STORAGE_ROOT 下的相对路径文件:
204
+ full_path = FileKit.get_full_path("docs/report.docx")
205
+ markdown = AnyDocKit.convert_to_md(full_path)
206
+ """
207
+
208
+ SUPPORTED_EXTENSIONS: frozenset[str] = _SUPPORTED_EXTENSIONS
209
+
210
+ @staticmethod
211
+ def is_supported(file_path: str | Path) -> bool:
212
+ """检查文件格式是否受支持
213
+
214
+ Args:
215
+ file_path: 文件路径(仅依据扩展名判断)
216
+
217
+ Returns:
218
+ bool: 扩展名在支持列表中返回 True
219
+
220
+ Example:
221
+ >>> AnyDocKit.is_supported("report.docx")
222
+ True
223
+ >>> AnyDocKit.is_supported("photo.png")
224
+ False
225
+ """
226
+ ext = Path(file_path).suffix.lower()
227
+ return ext in AnyDocKit.SUPPORTED_EXTENSIONS
228
+
229
+ @staticmethod
230
+ def detect_format(file_path: str | Path) -> str | None:
231
+ """检测文档的 anydoc 规范格式名称
232
+
233
+ 通过文件扩展名推断规范格式(如 .pptm → 'pptx',.docx → 'docx')。
234
+ 无法识别的扩展名返回 None。
235
+
236
+ Args:
237
+ file_path: 文件路径
238
+
239
+ Returns:
240
+ str | None: 规范格式名称,无法识别返回 None
241
+
242
+ Example:
243
+ >>> AnyDocKit.detect_format("slides.pptm")
244
+ 'pptx'
245
+ """
246
+ return anydoc.format_from_path(str(Path(file_path)))
247
+
248
+ @staticmethod
249
+ def convert_to_md(
250
+ file_path: str | Path,
251
+ *,
252
+ ocr: Literal["reject", "hosted"] = "reject",
253
+ api_key: str | None = None,
254
+ api_url: str | None = None,
255
+ ) -> str:
256
+ """将文档文件转换为 Markdown 文本(核心转换方法)
257
+
258
+ 基于 anydoc,读取本地文件并转换为 GitHub-Flavored Markdown。
259
+ 文本型 PDF 可直接转换;加密、图片型 PDF 等无法转换的情况会抛出异常。
260
+
261
+ PDF 兼容性增强:
262
+ - 结构非标但内容完好的 PDF(如知网下载件在 %%EOF 后附加
263
+ WebFastLoad 元数据)遇 MalformedError 时,自动用 pikepdf 重写
264
+ 修复并重试一次,对调用方透明;
265
+ - ocr="hosted" 时扫描页走 Firecrawl 云端 OCR(api_key 缺省回落
266
+ FIRECRAWL_API_KEY 环境变量),默认 "reject" 保持 anydoc 原行为。
267
+
268
+ Args:
269
+ file_path: 文档文件路径(支持 str 或 Path)
270
+ ocr: 扫描页处理策略,"reject"(默认,扫描页报错)或
271
+ "hosted"(云端 OCR)
272
+ api_key: 云端 OCR 的 API key;None 时回落 FIRECRAWL_API_KEY
273
+ api_url: 云端 OCR 服务地址;None 时回落 FIRECRAWL_API_URL
274
+
275
+ Returns:
276
+ str: 转换后的 Markdown 文本
277
+
278
+ Raises:
279
+ FileNotFoundError: 文件不存在
280
+ ValueError: 文件不是常规文件或格式不受支持
281
+ anydoc.ConvertError: 文档转换失败(加密、损坏、格式异常等子类,
282
+ 修复重试仍失败时以修复后的异常为准、原始异常为 __cause__)
283
+ OSError: 文件读取失败
284
+
285
+ Example:
286
+ >>> markdown = AnyDocKit.convert_to_md("report.docx")
287
+ >>> print(markdown[:100])
288
+ >>> md = AnyDocKit.convert_to_md("scan.pdf", ocr="hosted")
289
+ """
290
+ path = Path(file_path).resolve()
291
+
292
+ if not path.exists():
293
+ raise FileNotFoundError(f"文件不存在: {path}")
294
+ if not path.is_file():
295
+ raise ValueError(f"路径不是有效文件: {path}")
296
+ if not AnyDocKit.is_supported(path):
297
+ raise ValueError(
298
+ f"不支持的文件格式: {path.suffix or '<无扩展名>'},"
299
+ f"支持的格式: {', '.join(sorted(AnyDocKit.SUPPORTED_EXTENSIONS))}"
300
+ )
301
+
302
+ logger.info(f"开始转换文档: {path.name}")
303
+ try:
304
+ markdown = _convert_with_repair(
305
+ lambda: anydoc.to_markdown(
306
+ str(path), ocr=ocr, api_key=api_key, api_url=api_url
307
+ ),
308
+ is_pdf=path.suffix.lower() == ".pdf",
309
+ label=f"文档转换({path.name})",
310
+ repair=lambda: _repair_pdf_file(path),
311
+ retry=lambda payload: anydoc.to_markdown(
312
+ str(payload), ocr=ocr, api_key=api_key, api_url=api_url
313
+ ),
314
+ cleanup=lambda payload: Path(str(payload)).unlink(missing_ok=True),
315
+ )
316
+ except OSError as e:
317
+ logger.error(f"文件读取失败: {path.name}: {e}")
318
+ raise
319
+
320
+ logger.info(f"✅ 文档转换成功: {path.name}({len(markdown)} 字符)")
321
+ return markdown
322
+
323
+ @staticmethod
324
+ def convert_bytes_to_md(
325
+ data: bytes,
326
+ fmt: str | None = None,
327
+ *,
328
+ ocr: Literal["reject", "hosted"] = "reject",
329
+ api_key: str | None = None,
330
+ api_url: str | None = None,
331
+ ) -> str:
332
+ """将文件字节内容转换为 Markdown 文本
333
+
334
+ 适用于从网络、数据库等渠道获取的字节数据,无需落盘即可转换。
335
+ 格式默认从内容自动检测;CSV 等无特征格式需通过 fmt 显式指定。
336
+
337
+ PDF 兼容性增强同 convert_to_md:结构非标但内容完好的 PDF 在
338
+ MalformedError 时自动 pikepdf 内存内重写修复并重试一次(不落盘);
339
+ ocr/api_key/api_url 透传给 anydoc。
340
+
341
+ Args:
342
+ data: 文档文件的字节内容
343
+ fmt: 显式指定的规范格式名称(如 'csv'),None 时自动检测
344
+ ocr: 扫描页处理策略,"reject"(默认)或 "hosted"(云端 OCR)
345
+ api_key: 云端 OCR 的 API key;None 时回落 FIRECRAWL_API_KEY
346
+ api_url: 云端 OCR 服务地址;None 时回落 FIRECRAWL_API_URL
347
+
348
+ Returns:
349
+ str: 转换后的 Markdown 文本
350
+
351
+ Raises:
352
+ TypeError: data 不是字节类型
353
+ ValueError: fmt 指定了不支持的格式名称
354
+ anydoc.ConvertError: 文档转换失败(修复重试仍失败时以修复后的
355
+ 异常为准、原始异常为 __cause__)
356
+
357
+ Example:
358
+ >>> with open("data.csv", "rb") as f:
359
+ ... md = AnyDocKit.convert_bytes_to_md(f.read(), "csv")
360
+ >>> md = AnyDocKit.convert_bytes_to_md(file_bytes) # 自动检测
361
+ """
362
+ if not isinstance(data, (bytes, bytearray)):
363
+ raise TypeError(f"data 必须为字节类型,当前类型: {type(data).__name__}")
364
+
365
+ def _to_md(payload: bytes) -> str:
366
+ if fmt is not None:
367
+ # fmt 为任意合法格式名,anydoc 内部会校验;stub 将其限定为
368
+ # Literal 联合,此处运行时由 anydoc 兜底校验。
369
+ return anydoc.to_markdown_bytes( # type: ignore[arg-type]
370
+ payload, fmt, ocr=ocr, api_key=api_key, api_url=api_url
371
+ )
372
+ return anydoc.to_markdown_bytes(
373
+ payload, ocr=ocr, api_key=api_key, api_url=api_url
374
+ )
375
+
376
+ return _convert_with_repair(
377
+ lambda: _to_md(bytes(data)),
378
+ # 显式指定非 PDF 格式时修复重试无意义(fmt 大小写不敏感)
379
+ is_pdf=fmt is None or str(fmt).lower() == "pdf",
380
+ label="字节内容转换",
381
+ repair=lambda: _repair_pdf_bytes(bytes(data)),
382
+ retry=_to_md,
383
+ )
384
+
385
+ @staticmethod
386
+ def convert(
387
+ file_path: str | Path,
388
+ *,
389
+ ocr: Literal["reject", "hosted"] = "reject",
390
+ api_key: str | None = None,
391
+ api_url: str | None = None,
392
+ ) -> AnyDocResult:
393
+ """安全转换文档为 Markdown,返回包含状态的结果对象
394
+
395
+ 与 convert_to_md 不同,本方法不抛出转换异常,而是将成功/失败信息
396
+ 封装到 AnyDocResult 中,便于批量处理或状态检查。
397
+ ocr/api_key/api_url 语义同 convert_to_md(PDF 自动修复对调用方
398
+ 透明,失败信息封装在 result.error 中)。
399
+ 边界:文件不存在 / 格式不支持 / 转换失败均封装为结果;若 file_path
400
+ 类型非法(如 None),Path 构造阶段仍会抛 TypeError。
401
+
402
+ Args:
403
+ file_path: 文档文件路径
404
+ ocr: 扫描页处理策略,"reject"(默认)或 "hosted"(云端 OCR)
405
+ api_key: 云端 OCR 的 API key;None 时回落 FIRECRAWL_API_KEY
406
+ api_url: 云端 OCR 服务地址;None 时回落 FIRECRAWL_API_URL
407
+
408
+ Returns:
409
+ AnyDocResult: 转换结果,包含 success/markdown/file_path/source_format/error
410
+
411
+ Example:
412
+ >>> result = AnyDocKit.convert("report.pdf")
413
+ >>> if result.success:
414
+ ... print(result.markdown[:100])
415
+ ... else:
416
+ ... print(f"转换失败: {result.error}")
417
+ """
418
+ path = Path(file_path).resolve()
419
+ source_format = AnyDocKit.detect_format(path)
420
+
421
+ try:
422
+ markdown = AnyDocKit.convert_to_md(
423
+ path, ocr=ocr, api_key=api_key, api_url=api_url
424
+ )
425
+ except (ValueError, anydoc.ConvertError, OSError) as e:
426
+ # OSError 同时覆盖 FileNotFoundError(文件不存在)与文件读取失败
427
+ logger.warning(f"文档转换失败: {path.name}({type(e).__name__}): {e}")
428
+ return AnyDocResult(
429
+ success=False,
430
+ markdown="",
431
+ file_path=str(path),
432
+ source_format=source_format,
433
+ error=f"{type(e).__name__}: {e}",
434
+ )
435
+
436
+ return AnyDocResult(
437
+ success=True,
438
+ markdown=markdown,
439
+ file_path=str(path),
440
+ source_format=source_format,
441
+ )
442
+
443
+ @staticmethod
444
+ def convert_to_file(
445
+ src_path: str | Path,
446
+ dest_path: str | Path | None = None,
447
+ *,
448
+ ocr: Literal["reject", "hosted"] = "reject",
449
+ api_key: str | None = None,
450
+ api_url: str | None = None,
451
+ ) -> str:
452
+ """转换文档并将 Markdown 输出到 .md 文件
453
+
454
+ ocr/api_key/api_url 语义同 convert_to_md(PDF 自动修复对调用方透明)。
455
+
456
+ Args:
457
+ src_path: 源文档路径
458
+ dest_path: 目标 .md 文件路径;None 时使用源文件名同目录加 .md 后缀
459
+ ocr: 扫描页处理策略,"reject"(默认)或 "hosted"(云端 OCR)
460
+ api_key: 云端 OCR 的 API key;None 时回落 FIRECRAWL_API_KEY
461
+ api_url: 云端 OCR 服务地址;None 时回落 FIRECRAWL_API_URL
462
+
463
+ Returns:
464
+ str: 实际写入的目标文件绝对路径
465
+
466
+ Raises:
467
+ FileNotFoundError: 源文件不存在
468
+ ValueError: 源文件格式不受支持
469
+ anydoc.ConvertError: 文档转换失败
470
+ OSError: 文件读取失败或目标 Markdown 写入失败
471
+
472
+ Example:
473
+ >>> AnyDocKit.convert_to_file("report.docx") # 生成同目录 report.md
474
+ >>> AnyDocKit.convert_to_file("report.docx", "out/report.md")
475
+ """
476
+ src = Path(src_path).resolve()
477
+ markdown = AnyDocKit.convert_to_md(
478
+ src, ocr=ocr, api_key=api_key, api_url=api_url
479
+ )
480
+
481
+ if dest_path is None:
482
+ dest = src.with_suffix(".md")
483
+ else:
484
+ # resolve 保证返回值兑现"绝对路径"承诺(非严格模式,目标可不存在)
485
+ dest = Path(dest_path).resolve()
486
+
487
+ dest.parent.mkdir(parents=True, exist_ok=True)
488
+ dest.write_text(markdown, encoding="utf-8")
489
+ logger.info(f"✅ Markdown 已写入: {dest}")
490
+ return str(dest)