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
yimo/kit/file_kit.py ADDED
@@ -0,0 +1,518 @@
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-08-22
21
+ """文件工具类,提供文件读写、移动、复制等跨平台操作功能
22
+
23
+ 重构说明(破坏性内部、外部零风险):
24
+ - 用 `_ROOT_PATH is None` 语义替代 `_INITIALIZED` 布尔标记,收敛初始化逻辑。
25
+ - 修正 `_get_root_path` 返回类型(不再返回可能为 None 的值却标注为 Path)。
26
+ - 补全 `walk_dir` 缺失的返回类型标注。
27
+ - 公开方法名、签名与语义不变。
28
+ """
29
+
30
+ import os
31
+ import subprocess
32
+ import sys
33
+ from collections.abc import Iterator
34
+ from pathlib import Path
35
+ from shutil import copy2, copytree, move, rmtree
36
+ from typing import Literal
37
+
38
+ from yimo.kit.config.kit_config import get_settings
39
+ from yimo.kit.config.log_config import get_default_logger
40
+
41
+ settings = get_settings()
42
+ logger = get_default_logger(__name__)
43
+
44
+ # 系统默认程序打开的结果:"opened" 已交给默认程序;"revealed" 已发起文件管理器定位
45
+ type OpenResult = Literal["opened", "revealed"]
46
+
47
+
48
+ class FileKit:
49
+ """文件工具类,提供文件读写、移动、复制等跨平台操作功能
50
+
51
+ 配置:
52
+ - 根文件存储路径通过配置文件 FILE_STORAGE_ROOT 获取
53
+ - 使用统一的 get_settings() 进行配置管理
54
+ - 使用统一的 get_default_logger() 进行日志记录
55
+ - 支持跨平台路径处理(Windows/Linux)
56
+
57
+ 所有方法均处理路径分隔符,确保跨平台兼容性。
58
+ """
59
+
60
+ # None 表示尚未初始化(未调用 configure,也未被惰性初始化)
61
+ _ROOT_PATH: Path | None = None
62
+
63
+ @classmethod
64
+ def _ensure_initialized(cls) -> None:
65
+ """惰性初始化根文件存储路径(首次使用时从配置读取)"""
66
+ if cls._ROOT_PATH is not None:
67
+ return
68
+
69
+ root_path_str = settings.FILE_STORAGE_ROOT
70
+ if not root_path_str:
71
+ raise RuntimeError("配置项 FILE_STORAGE_ROOT 未设置,请设置文件存储根路径")
72
+
73
+ root_path = cls._normalize_path(root_path_str)
74
+
75
+ if not root_path.exists():
76
+ raise RuntimeError(f"根路径不存在: {root_path}")
77
+ if not root_path.is_dir():
78
+ raise RuntimeError(f"根路径不是有效目录: {root_path}")
79
+
80
+ cls._ROOT_PATH = root_path
81
+ logger.info(f"✅ FileKit 已初始化,根路径: {root_path}")
82
+
83
+ @staticmethod
84
+ def _normalize_path(path: str) -> Path:
85
+ """规范化路径,处理跨平台路径分隔符"""
86
+ return Path(path).resolve()
87
+
88
+ @classmethod
89
+ def configure(cls, root_path: str) -> None:
90
+ """手动配置根文件存储路径
91
+
92
+ Args:
93
+ root_path: 文件存储根路径
94
+
95
+ Raises:
96
+ ValueError: 路径不存在或不是目录时抛出
97
+ """
98
+ normalized = cls._normalize_path(root_path)
99
+
100
+ if not normalized.exists():
101
+ raise ValueError(f"根路径不存在: {normalized}")
102
+ if not normalized.is_dir():
103
+ raise ValueError(f"根路径不是有效目录: {normalized}")
104
+
105
+ cls._ROOT_PATH = normalized
106
+
107
+ @classmethod
108
+ def read_file(cls, relative_path: str, encoding: str = "utf-8") -> str:
109
+ """读取文件内容
110
+
111
+ Args:
112
+ relative_path: 相对于根路径的文件路径
113
+ encoding: 文件编码,默认 utf-8
114
+
115
+ Returns:
116
+ str: 文件内容字符串
117
+ """
118
+ cls._ensure_initialized()
119
+
120
+ full_path = cls._get_full_path(relative_path)
121
+
122
+ if not full_path.exists():
123
+ raise FileNotFoundError(f"文件不存在: {full_path}")
124
+
125
+ try:
126
+ return full_path.read_text(encoding=encoding)
127
+ except UnicodeDecodeError as e:
128
+ raise UnicodeDecodeError(
129
+ e.encoding,
130
+ e.object,
131
+ e.start,
132
+ e.end,
133
+ f"文件编码错误,请尝试使用其他编码读取: {e}",
134
+ )
135
+
136
+ @classmethod
137
+ def write_file(
138
+ cls,
139
+ relative_path: str,
140
+ content: str,
141
+ mode: str = "overwrite",
142
+ encoding: str = "utf-8",
143
+ ) -> bool:
144
+ """写入文件内容
145
+
146
+ Args:
147
+ relative_path: 相对于根路径的文件路径
148
+ content: 要写入的内容
149
+ mode: 写入模式,"overwrite"(覆盖)或 "append"(追加)
150
+ encoding: 文件编码,默认 utf-8
151
+
152
+ Returns:
153
+ bool: 写入成功返回 True
154
+ """
155
+ if mode not in ("overwrite", "append"):
156
+ raise ValueError(
157
+ f"无效的写入模式: {mode},支持的模式: 'overwrite', 'append'"
158
+ )
159
+
160
+ cls._ensure_initialized()
161
+
162
+ full_path = cls._get_full_path(relative_path)
163
+ parent_dir = full_path.parent
164
+
165
+ if not parent_dir.exists():
166
+ parent_dir.mkdir(parents=True, exist_ok=True)
167
+
168
+ try:
169
+ if mode == "append":
170
+ with full_path.open("a", encoding=encoding) as f:
171
+ f.write(content)
172
+ else:
173
+ full_path.write_text(content, encoding=encoding)
174
+ return True
175
+ except Exception as e:
176
+ raise RuntimeError(f"写入文件失败: {e}")
177
+
178
+ @classmethod
179
+ def move_file(cls, src_relative_path: str, dest_relative_path: str) -> bool:
180
+ """移动文件(重命名)
181
+
182
+ Args:
183
+ src_relative_path: 源文件相对于根路径的路径
184
+ dest_relative_path: 目标文件相对于根路径的路径
185
+
186
+ Returns:
187
+ bool: 移动成功返回 True
188
+ """
189
+ cls._ensure_initialized()
190
+
191
+ src_path = cls._get_full_path(src_relative_path)
192
+ dest_path = cls._get_full_path(dest_relative_path)
193
+
194
+ if not src_path.exists():
195
+ raise FileNotFoundError(f"源文件不存在: {src_path}")
196
+
197
+ dest_parent = dest_path.parent
198
+ if dest_parent and not dest_parent.exists():
199
+ dest_parent.mkdir(parents=True, exist_ok=True)
200
+
201
+ try:
202
+ move(src_path, dest_path)
203
+ return True
204
+ except Exception as e:
205
+ raise RuntimeError(f"移动文件失败: {e}")
206
+
207
+ @classmethod
208
+ def copy_file(cls, src_relative_path: str, dest_relative_path: str) -> bool:
209
+ """复制文件
210
+
211
+ Args:
212
+ src_relative_path: 源文件相对于根路径的路径
213
+ dest_relative_path: 目标文件相对于根路径的路径
214
+
215
+ Returns:
216
+ bool: 复制成功返回 True
217
+ """
218
+ cls._ensure_initialized()
219
+
220
+ src_path = cls._get_full_path(src_relative_path)
221
+ dest_path = cls._get_full_path(dest_relative_path)
222
+
223
+ if not src_path.exists():
224
+ raise FileNotFoundError(f"源文件不存在: {src_path}")
225
+
226
+ dest_parent = dest_path.parent
227
+ if dest_parent and not dest_parent.exists():
228
+ dest_parent.mkdir(parents=True, exist_ok=True)
229
+
230
+ try:
231
+ copy2(src_path, dest_path)
232
+ return True
233
+ except Exception as e:
234
+ raise RuntimeError(f"复制文件失败: {e}")
235
+
236
+ @classmethod
237
+ def delete_file(cls, relative_path: str) -> bool:
238
+ """删除文件
239
+
240
+ Args:
241
+ relative_path: 要删除的文件相对于根路径的路径
242
+
243
+ Returns:
244
+ bool: 删除成功返回 True
245
+ """
246
+ cls._ensure_initialized()
247
+
248
+ full_path = cls._get_full_path(relative_path)
249
+
250
+ if not full_path.exists():
251
+ raise FileNotFoundError(f"文件不存在: {full_path}")
252
+
253
+ try:
254
+ full_path.unlink()
255
+ return True
256
+ except Exception as e:
257
+ raise RuntimeError(f"删除文件失败: {e}")
258
+
259
+ @classmethod
260
+ def file_exists(cls, relative_path: str) -> bool:
261
+ """检查文件是否存在"""
262
+ cls._ensure_initialized()
263
+
264
+ full_path = cls._get_full_path(relative_path)
265
+ return full_path.is_file()
266
+
267
+ @classmethod
268
+ def get_full_path(cls, relative_path: str) -> Path:
269
+ """获取文件的完整路径"""
270
+ cls._ensure_initialized()
271
+ return cls._get_full_path(relative_path)
272
+
273
+ @classmethod
274
+ def _get_full_path(cls, relative_path: str) -> Path:
275
+ """内部方法:获取完整路径"""
276
+ assert cls._ROOT_PATH is not None
277
+ return cls._ROOT_PATH / relative_path
278
+
279
+ @classmethod
280
+ def get_root_path(cls) -> str:
281
+ """获取当前配置的根路径"""
282
+ return str(cls._get_root_path())
283
+
284
+ @classmethod
285
+ def _get_root_path(cls) -> Path:
286
+ """获取根文件存储路径"""
287
+ cls._ensure_initialized()
288
+ assert cls._ROOT_PATH is not None
289
+ return cls._ROOT_PATH
290
+
291
+ @staticmethod
292
+ def generate_unique_id() -> str:
293
+ """生成唯一 ID(字符串类型)"""
294
+ from yimo.kit.common_kit import CommonKit
295
+
296
+ return CommonKit.generate_timestamp_id()
297
+
298
+ @staticmethod
299
+ def generate_filename(prefix: str = "", extension: str = "") -> str:
300
+ """生成带有时间戳的唯一文件名
301
+
302
+ Args:
303
+ prefix: 文件名前缀(可选),如 "log_"
304
+ extension: 文件扩展名(可选),如 "txt",可不带点
305
+
306
+ Returns:
307
+ str: 生成的文件名
308
+ """
309
+ from yimo.kit.common_kit import CommonKit
310
+
311
+ unique_id = CommonKit.generate_timestamp_id()
312
+ if extension:
313
+ if not extension.startswith("."):
314
+ extension = "." + extension
315
+ return f"{prefix}{unique_id}{extension}"
316
+ return f"{prefix}{unique_id}"
317
+
318
+ @classmethod
319
+ def move_dir(cls, src_relative_path: str, dest_relative_path: str) -> bool:
320
+ """移动目录
321
+
322
+ Args:
323
+ src_relative_path: 源目录相对于根路径的路径
324
+ dest_relative_path: 目标目录相对于根路径的路径
325
+
326
+ Returns:
327
+ bool: 移动成功返回 True
328
+ """
329
+ cls._ensure_initialized()
330
+
331
+ src_path = cls._get_full_path(src_relative_path)
332
+ dest_path = cls._get_full_path(dest_relative_path)
333
+
334
+ if not src_path.exists():
335
+ raise FileNotFoundError(f"源目录不存在: {src_path}")
336
+ if not src_path.is_dir():
337
+ raise ValueError(f"源路径不是目录: {src_path}")
338
+
339
+ try:
340
+ move(src_path, dest_path)
341
+ return True
342
+ except Exception as e:
343
+ raise RuntimeError(f"移动目录失败: {e}")
344
+
345
+ @classmethod
346
+ def delete_dir(cls, relative_path: str) -> bool:
347
+ """删除目录(递归删除)
348
+
349
+ Args:
350
+ relative_path: 要删除的目录相对于根路径的路径
351
+
352
+ Returns:
353
+ bool: 删除成功返回 True
354
+ """
355
+ cls._ensure_initialized()
356
+
357
+ full_path = cls._get_full_path(relative_path)
358
+
359
+ if not full_path.exists():
360
+ raise FileNotFoundError(f"目录不存在: {full_path}")
361
+ if not full_path.is_dir():
362
+ raise ValueError(f"路径不是目录: {full_path}")
363
+
364
+ try:
365
+ rmtree(full_path)
366
+ return True
367
+ except Exception as e:
368
+ raise RuntimeError(f"删除目录失败: {e}")
369
+
370
+ @classmethod
371
+ def copy_dir(cls, src_relative_path: str, dest_relative_path: str) -> bool:
372
+ """复制目录(递归复制)
373
+
374
+ Args:
375
+ src_relative_path: 源目录相对于根路径的路径
376
+ dest_relative_path: 目标目录相对于根路径的路径
377
+
378
+ Returns:
379
+ bool: 复制成功返回 True
380
+ """
381
+ cls._ensure_initialized()
382
+
383
+ src_path = cls._get_full_path(src_relative_path)
384
+ dest_path = cls._get_full_path(dest_relative_path)
385
+
386
+ if not src_path.exists():
387
+ raise FileNotFoundError(f"源目录不存在: {src_path}")
388
+ if not src_path.is_dir():
389
+ raise ValueError(f"源路径不是目录: {src_path}")
390
+
391
+ try:
392
+ copytree(src_path, dest_path)
393
+ return True
394
+ except Exception as e:
395
+ raise RuntimeError(f"复制目录失败: {e}")
396
+
397
+ @classmethod
398
+ def walk_dir(
399
+ cls,
400
+ relative_path: str = "",
401
+ top_down: bool = True,
402
+ on_error: str | None = None,
403
+ ) -> Iterator[tuple[Path, list[str], list[str]]]:
404
+ """遍历目录树(使用 Path.walk 方法)
405
+
406
+ Args:
407
+ relative_path: 要遍历的目录相对于根路径的路径,空字符串表示根目录
408
+ top_down: 遍历顺序,True 为自顶向下,False 为自底向上
409
+ on_error: 错误处理方式,None 或 "ignore" 或 "report"
410
+
411
+ Yields:
412
+ (root: Path, dirs: list[str], files: list[str]) 元组
413
+ """
414
+ cls._ensure_initialized()
415
+
416
+ full_path = cls._get_full_path(relative_path)
417
+ root_path = cls._get_root_path()
418
+
419
+ if not full_path.exists():
420
+ raise FileNotFoundError(f"目录不存在: {full_path}")
421
+ if not full_path.is_dir():
422
+ raise ValueError(f"路径不是目录: {full_path}")
423
+
424
+ def error_handler(os_error: OSError) -> None:
425
+ if on_error == "report":
426
+ raise os_error
427
+
428
+ for root, dirs, files in full_path.walk(
429
+ top_down=top_down,
430
+ on_error=error_handler if on_error in ("ignore", "report") else None,
431
+ ):
432
+ yield (
433
+ root.relative_to(root_path) if root != root_path else Path("."),
434
+ dirs,
435
+ files,
436
+ )
437
+
438
+ # ==================== 系统默认程序打开(宿主平台交互) ====================
439
+
440
+ @staticmethod
441
+ def open_with_default_app(path: str | Path) -> OpenResult:
442
+ """用系统默认程序打开本机文件或目录(在宿主机弹出窗口)。
443
+
444
+ 与 FILE_STORAGE_ROOT 无关:不做根路径解析、不做 resolve/expanduser、
445
+ 不做路径校验。调用方负责路径合法性;禁止直接传入未经校验的外部输入。
446
+
447
+ Args:
448
+ path: 目标文件或目录路径
449
+
450
+ Returns:
451
+ "opened":已交给系统默认程序
452
+ (Windows startfile / macOS open / Linux xdg-open)
453
+ "revealed":打开失败,已发起在文件管理器中定位
454
+ (Windows explorer /select、macOS open -R)
455
+
456
+ Raises:
457
+ FileNotFoundError: 目标不存在
458
+ OSError: 系统打开命令无法启动(含命令缺失)
459
+ """
460
+ target = Path(path)
461
+ if not target.exists():
462
+ raise FileNotFoundError(f"目标不存在: {target}")
463
+
464
+ if sys.platform == "win32":
465
+ try:
466
+ # os.startfile 仅 Windows 平台存在
467
+ os.startfile(str(target)) # type: ignore[attr-defined]
468
+ except OSError:
469
+ # 无默认关联程序等:降级资源管理器定位(返回码无意义,不检查)
470
+ FileKit._launch(["explorer", f"/select,{target}"])
471
+ return "revealed"
472
+ return "opened"
473
+
474
+ # TODO: 无 macOS / Linux 环境验证,以下分支仅按平台命令事实实现
475
+ if sys.platform == "darwin":
476
+ # macOS 只能靠退出码判断打开失败,故此处等待;失败则 open -R 定位
477
+ if FileKit._launch_and_wait(["open", str(target)]):
478
+ return "opened"
479
+ FileKit._launch(["open", "-R", str(target)])
480
+ return "revealed"
481
+
482
+ # 其他平台(Linux 等):仅打开,无降级语义
483
+ FileKit._launch(["xdg-open", str(target)])
484
+ return "opened"
485
+
486
+ @staticmethod
487
+ def _launch(argv: list[str]) -> None:
488
+ """发起宿主命令(不等待、不检查返回码)。
489
+
490
+ Args:
491
+ argv: 命令与参数(按 argv 传递,不使用 shell)
492
+
493
+ Raises:
494
+ OSError: 命令不存在或无法启动
495
+ (避免与「目标不存在」的 FileNotFoundError 混淆)
496
+ """
497
+ try:
498
+ subprocess.Popen(argv)
499
+ except FileNotFoundError as exc:
500
+ raise OSError(f"系统命令不可用: {argv[0]}") from exc
501
+
502
+ @staticmethod
503
+ def _launch_and_wait(argv: list[str]) -> bool:
504
+ """发起宿主命令并等待返回(macOS 判定打开失败用)。
505
+
506
+ Args:
507
+ argv: 命令与参数(按 argv 传递,不使用 shell)
508
+
509
+ Returns:
510
+ 命令是否以退出码 0 结束
511
+
512
+ Raises:
513
+ OSError: 命令不存在或无法启动(与 `_launch` 保持同一语义)
514
+ """
515
+ try:
516
+ return subprocess.run(argv, check=False).returncode == 0
517
+ except FileNotFoundError as exc:
518
+ raise OSError(f"系统命令不可用: {argv[0]}") from exc