qikou 2.2.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.
qikou/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ # -*- coding: utf-8 -*-
2
+ """气口 / Cadence —— 让 AI 回复会呼吸。
3
+
4
+ 把一段长文本切成若干条短消息,读起来像真人一条条发出来的聊天内容。
5
+
6
+ ::
7
+
8
+ from qikou import split
9
+
10
+ for message in split(reply):
11
+ send(message)
12
+ """
13
+
14
+ from .config import Config
15
+ from .kaomoji import kaomoji_count, load_kaomojis
16
+ from .splitter import split
17
+
18
+ __version__ = "2.2.0"
19
+
20
+ __all__ = [
21
+ "Config",
22
+ "kaomoji_count",
23
+ "load_kaomojis",
24
+ "split",
25
+ ]
qikou/__main__.py ADDED
@@ -0,0 +1,7 @@
1
+ # -*- coding: utf-8 -*-
2
+ import sys
3
+
4
+ from .cli import main
5
+
6
+ if __name__ == '__main__':
7
+ sys.exit(main())
qikou/cli.py ADDED
@@ -0,0 +1,447 @@
1
+ # -*- coding: utf-8 -*-
2
+ """命令行接口。
3
+
4
+ 子命令形态::
5
+
6
+ qikou split [文件] 切分(默认从标准输入读取)
7
+ qikou test [文件] 跑测试用例
8
+ qikou menu 交互菜单
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import json
15
+ import os
16
+ import re
17
+ import sys
18
+ import time
19
+ from typing import Any, List, Optional, Sequence, TextIO, Tuple
20
+
21
+ from . import __version__, kaomoji
22
+ from .config import Config
23
+ from .splitter import split
24
+
25
+ __all__ = ["build_parser", "main"]
26
+
27
+ PROG = "qikou"
28
+ BANNER = "=" * 52
29
+
30
+ _HERE = os.path.dirname(os.path.abspath(__file__))
31
+ _ROOT = os.path.dirname(_HERE)
32
+
33
+ # 用例文件与报告目录属于源码仓库,不随 wheel 分发。装成包之后这两个变量
34
+ # 为 None:test 仍可跑指定文件,但报告写到当前工作目录,绝不写进
35
+ # site-packages。
36
+ _REPO = _ROOT if os.path.isdir(os.path.join(_ROOT, 'tests')) else None
37
+ TEST_FILE = os.path.join(_REPO, 'tests', 'test.txt') if _REPO else None
38
+ RESULT_DIR = os.path.join(_REPO, 'tests', 'results') if _REPO else None
39
+
40
+
41
+ # ============================================================
42
+ # 终端
43
+ # ============================================================
44
+
45
+ def _setup_streams() -> None:
46
+ """尽量把 stdout/stderr 切到 UTF-8。
47
+
48
+ 否则在非 UTF-8 控制台(或 PYTHONIOENCODING=ascii)下打印中文与边框
49
+ 会直接抛 UnicodeEncodeError。切不过就跳过,不影响功能。
50
+ """
51
+ for stream in (sys.stdout, sys.stderr):
52
+ reconfigure = getattr(stream, "reconfigure", None)
53
+ if reconfigure is None:
54
+ continue
55
+ try:
56
+ reconfigure(encoding="utf-8", errors="replace")
57
+ except (ValueError, OSError):
58
+ pass
59
+
60
+
61
+ def _isatty(stream: Any = None) -> bool:
62
+ try:
63
+ return bool((stream or sys.stdout).isatty())
64
+ except (AttributeError, ValueError):
65
+ return False
66
+
67
+
68
+ # ============================================================
69
+ # 输入
70
+ # ============================================================
71
+
72
+ def _read_input(path: Optional[str]) -> str:
73
+ """读入待切分文本;path 为 None 或 '-' 时读标准输入。"""
74
+ if path is None or path == '-':
75
+ return sys.stdin.read()
76
+ with open(path, 'r', encoding='utf-8-sig') as f:
77
+ return f.read()
78
+
79
+
80
+ # ============================================================
81
+ # 输出
82
+ # ============================================================
83
+
84
+ def effective_config(text: str, config: Optional[Config] = None) -> Config:
85
+ """返回这段文本实际生效的配置(与 split 内部一致)。"""
86
+ return (config or Config()).scaled_for_length(len(text.strip()))
87
+
88
+
89
+ def print_messages(messages: List[str], cfg: Config) -> None:
90
+ """带装饰地逐条打印。"""
91
+ print()
92
+ print(BANNER)
93
+ print(" 切分结果:%d 条" % len(messages))
94
+ print(" 参数:max=%d target=%d min=%d max_messages=%d"
95
+ % (cfg.max_chars, cfg.target_chars,
96
+ cfg.min_chars, cfg.max_messages))
97
+ print(BANNER)
98
+ for i, m in enumerate(messages, 1):
99
+ print()
100
+ print("─── [%d/%d] %d 字 ───" % (i, len(messages), len(m)))
101
+ print(m)
102
+ print()
103
+ print("-" * 52)
104
+ print("合计 %d 字(最长 %d 字)"
105
+ % (sum(len(m) for m in messages),
106
+ max((len(m) for m in messages), default=0)))
107
+
108
+
109
+ def print_plain(messages: List[str]) -> None:
110
+ """只输出消息正文,空行分隔,便于管道消费。"""
111
+ sys.stdout.write("\n\n".join(messages))
112
+ if messages:
113
+ sys.stdout.write("\n")
114
+
115
+
116
+ def print_json(messages: List[str]) -> None:
117
+ print(json.dumps(messages, ensure_ascii=False, indent=2))
118
+
119
+
120
+ # ============================================================
121
+ # 测试报告
122
+ # ============================================================
123
+
124
+ def write_case_report(f: TextIO, idx: int, total: int, name: str,
125
+ text: str, msgs: List[str]) -> None:
126
+ f.write("\n")
127
+ f.write("-" * 52 + "\n")
128
+ f.write("用例 %d/%d:%s\n" % (idx, total, name))
129
+ f.write("-" * 52 + "\n")
130
+ f.write("输入:\n")
131
+ for line in text.split('\n'):
132
+ f.write(" | " + line + "\n")
133
+ f.write("\n")
134
+ f.write("结果(%d 条):\n" % len(msgs))
135
+ for i, m in enumerate(msgs, 1):
136
+ preview = m.replace('\n', ' ⏎ ')
137
+ f.write(" [%d] %s\n" % (i, preview))
138
+
139
+
140
+ CASE_MARK_RE = re.compile(r'^\s*\[CASE\]\s*(.*?)\s*$', re.MULTILINE)
141
+
142
+
143
+ def load_test_cases(path: str) -> List[Tuple[str, str]]:
144
+ with open(path, 'r', encoding='utf-8-sig') as f:
145
+ content = f.read()
146
+ if '[CASE]' not in content:
147
+ text = content.strip()
148
+ return [("整个文件", text)] if text else []
149
+ parts = CASE_MARK_RE.split(content)
150
+ cases = []
151
+ for i in range(1, len(parts), 2):
152
+ name = parts[i].strip() or ("用例 %d" % ((i + 1) // 2))
153
+ raw = parts[i + 1] if i + 1 < len(parts) else ''
154
+ if raw.strip():
155
+ body = raw.strip()
156
+ else:
157
+ body = raw.strip('\n')
158
+ cases.append((name, body))
159
+ return cases
160
+
161
+
162
+ def run_auto_test(path: str,
163
+ out_path: Optional[str] = None) -> Tuple[Optional[str], float]:
164
+ """跑完所有用例并写报告,返回 (报告路径, 用时)。"""
165
+ if not os.path.isfile(path):
166
+ print("[错误] 找不到测试文件:%s" % path)
167
+ return None, 0.0
168
+ cases = load_test_cases(path)
169
+ if not cases:
170
+ print("[信息] 测试文件里没有用例。")
171
+ return None, 0.0
172
+ if out_path is None:
173
+ ts = time.strftime("%Y%m%d_%H%M%S")
174
+ if RESULT_DIR is not None:
175
+ os.makedirs(RESULT_DIR, exist_ok=True)
176
+ out_path = os.path.join(RESULT_DIR, "test_result_%s.txt" % ts)
177
+ else:
178
+ # 非源码仓库运行:报告写到当前工作目录
179
+ out_path = os.path.abspath("test_result_%s.txt" % ts)
180
+ start_time = time.time()
181
+ total_msgs = 0
182
+ max_name_len = max((len(name) for name, _ in cases), default=0)
183
+ with open(out_path, 'w', encoding='utf-8', newline='\n') as f:
184
+ f.write(BANNER + "\n")
185
+ f.write(" 气口 —— AI 回复分句器\n")
186
+ f.write(" 自动测试报告\n")
187
+ f.write(BANNER + "\n")
188
+ f.write(" 测试文件:%s\n" % os.path.abspath(path))
189
+ f.write(" 运行时间:%s\n"
190
+ % time.strftime("%Y-%m-%d %H:%M:%S"))
191
+ f.write(" 颜文字表:%d 条\n" % kaomoji.kaomoji_count())
192
+ f.write(" 用例数 :%d\n" % len(cases))
193
+ f.write(BANNER + "\n")
194
+ for idx, (name, text) in enumerate(cases, 1):
195
+ msgs = split(text)
196
+ total_msgs += len(msgs)
197
+ write_case_report(f, idx, len(cases), name, text, msgs)
198
+ print(" [%2d/%2d] %s → %d 条" %
199
+ (idx, len(cases), name.ljust(max_name_len), len(msgs)))
200
+ f.write("\n")
201
+ f.write(BANNER + "\n")
202
+ f.write(" 测试完成:%d 个用例,共 %d 条气泡\n"
203
+ % (len(cases), total_msgs))
204
+ f.write(BANNER + "\n")
205
+ return out_path, time.time() - start_time
206
+
207
+
208
+ def load_kaomojis_checked() -> bool:
209
+ """加载颜文字语料;加载为空时明确报错。
210
+
211
+ 语料缺失时切分仍能跑,只是颜文字不再被识别——结果悄悄变差。
212
+ 这里把它变成一个看得见的失败。
213
+ """
214
+ n = kaomoji.load_kaomojis()
215
+ if n <= 0:
216
+ print()
217
+ print("[错误] 颜文字语料为空(0 条),切分结果会明显变差。")
218
+ print(" 预期语料文件:%s" % kaomoji.default_path())
219
+ return False
220
+ print("[信息] 已加载 %d 条颜文字" % n)
221
+ return True
222
+
223
+
224
+ # ============================================================
225
+ # 子命令
226
+ # ============================================================
227
+
228
+ def cmd_split(args: argparse.Namespace) -> int:
229
+ path = args.file
230
+
231
+ if path is None and not sys.stdin.isatty():
232
+ path = '-' # 管道接进来的,按过滤器处理
233
+ elif path is None:
234
+ print("从标准输入读取,结束输入:Ctrl-Z 回车(Windows)/ Ctrl-D",
235
+ file=sys.stderr)
236
+
237
+ try:
238
+ text = _read_input(path)
239
+ except FileNotFoundError:
240
+ print("%s: 找不到文件:%s" % (PROG, path), file=sys.stderr)
241
+ return 1
242
+ except IsADirectoryError:
243
+ print("%s: 这是一个目录:%s" % (PROG, path), file=sys.stderr)
244
+ return 1
245
+ except UnicodeDecodeError as exc:
246
+ print("%s: 无法以 UTF-8 解码 %s(%s)" % (PROG, path, exc),
247
+ file=sys.stderr)
248
+ return 1
249
+ except OSError as exc:
250
+ print("%s: 读取失败:%s" % (PROG, exc), file=sys.stderr)
251
+ return 1
252
+
253
+ config = Config()
254
+ if args.max_chars is not None:
255
+ config.max_chars = args.max_chars
256
+ if args.target_chars is not None:
257
+ config.target_chars = args.target_chars
258
+ if args.max_messages is not None:
259
+ config.max_messages = args.max_messages
260
+
261
+ messages = split(text, config=config)
262
+
263
+ if args.json:
264
+ print_json(messages)
265
+ elif args.quiet or not _isatty():
266
+ print_plain(messages)
267
+ else:
268
+ print_messages(messages, effective_config(text, config))
269
+ return 0
270
+
271
+
272
+ def cmd_test(args: argparse.Namespace) -> int:
273
+ path = args.file
274
+ if path is None:
275
+ path = TEST_FILE
276
+ if path is None:
277
+ print("%s: 未找到内置用例文件(当前不是从源码仓库运行)。" % PROG,
278
+ file=sys.stderr)
279
+ print(" 可指定文件:%s test path/to/cases.txt" % PROG,
280
+ file=sys.stderr)
281
+ return 1
282
+
283
+ if not load_kaomojis_checked():
284
+ return 1
285
+
286
+ print()
287
+ print("开始自动测试:%s" % os.path.abspath(path))
288
+ print("-" * 52)
289
+ out_path, elapsed = run_auto_test(path)
290
+ if out_path is None:
291
+ return 1
292
+ print("-" * 52)
293
+ print("用时:%.2f 秒" % elapsed)
294
+ print("结果已保存到:")
295
+ print(" %s" % os.path.abspath(out_path))
296
+ return 0
297
+
298
+
299
+ def cmd_menu(args: argparse.Namespace) -> int:
300
+ print(BANNER)
301
+ print(" 气口 —— AI 回复分句器")
302
+ print(BANNER)
303
+ if not load_kaomojis_checked():
304
+ return 1
305
+
306
+ test_file = TEST_FILE
307
+ has_test = test_file is not None and os.path.isfile(test_file)
308
+ print()
309
+ print("请选择模式:")
310
+ print(" [1] 手动输入")
311
+ if has_test and test_file is not None:
312
+ print(" [2] 自动测试(读取 %s)" % os.path.basename(test_file))
313
+ elif test_file is None:
314
+ print(" [2] (当前不是从源码仓库运行,内置用例不可用)")
315
+ else:
316
+ print(" [2] (未找到 %s)" % os.path.basename(test_file))
317
+ print(" [q] 退出")
318
+ print()
319
+ try:
320
+ choice = input("> ").strip().lower()
321
+ except (EOFError, KeyboardInterrupt):
322
+ print()
323
+ return 0
324
+ if choice in ('q', 'quit', 'exit'):
325
+ return 0
326
+ if choice == '2':
327
+ if not has_test or test_file is None:
328
+ if test_file is None:
329
+ print("[提示] 当前不是从源码仓库运行,内置用例不可用。")
330
+ print(" 可用 test 子命令指定用例文件。")
331
+ else:
332
+ print("[提示] 未找到 %s。" % os.path.basename(test_file))
333
+ return 0
334
+ print()
335
+ print("开始自动测试:%s" % os.path.abspath(test_file))
336
+ print("-" * 52)
337
+ out_path, elapsed = run_auto_test(test_file)
338
+ if out_path is None:
339
+ return 1
340
+ print("-" * 52)
341
+ print("用时:%.2f 秒" % elapsed)
342
+ print("结果已保存到:")
343
+ print(" %s" % os.path.abspath(out_path))
344
+ return 0
345
+ return _manual_mode()
346
+
347
+
348
+ def _read_multiline() -> str:
349
+ print("请输入 AI 回复(可多行)。")
350
+ print(" 结束输入:单独一行输入 EOF,或 Ctrl-D")
351
+ print(" 取消 :Ctrl-C")
352
+ print("-" * 52)
353
+ lines: List[str] = []
354
+ while True:
355
+ prompt = "> " if not lines else " "
356
+ try:
357
+ line = input(prompt)
358
+ except EOFError:
359
+ print()
360
+ break
361
+ if line.strip().upper() == 'EOF':
362
+ break
363
+ lines.append(line)
364
+ return '\n'.join(lines)
365
+
366
+
367
+ def _manual_mode() -> int:
368
+ while True:
369
+ try:
370
+ text = _read_multiline()
371
+ except KeyboardInterrupt:
372
+ print("\n\n已取消。")
373
+ return 0
374
+ if not text.strip():
375
+ print("(没有输入内容)")
376
+ else:
377
+ messages = split(text)
378
+ print_messages(messages, effective_config(text))
379
+ print()
380
+ try:
381
+ again = input("继续输入?(y/N) ").strip().lower()
382
+ except (EOFError, KeyboardInterrupt):
383
+ print()
384
+ return 0
385
+ if again != 'y':
386
+ return 0
387
+
388
+
389
+ # ============================================================
390
+ # 入口
391
+ # ============================================================
392
+
393
+ def build_parser() -> argparse.ArgumentParser:
394
+ parser = argparse.ArgumentParser(
395
+ prog=PROG,
396
+ description="气口 / Cadence —— 把 AI 的长回复切成读起来像真人发出的短消息。",
397
+ epilog="不带子命令时显示本帮助。示例:echo \"长文本\" | qikou split",
398
+ )
399
+ parser.add_argument(
400
+ "--version", action="version", version="%(prog)s " + __version__,
401
+ )
402
+ sub = parser.add_subparsers(dest="command", metavar="命令")
403
+
404
+ p_split = sub.add_parser(
405
+ "split", help="切分文本(默认从标准输入读取)",
406
+ description="把一段文本切成若干条短消息。",
407
+ )
408
+ p_split.add_argument(
409
+ "file", nargs="?", metavar="文件",
410
+ help="要切分的文本文件;'-' 或省略表示标准输入",
411
+ )
412
+ p_split.add_argument("-j", "--json", action="store_true",
413
+ help="以 JSON 输出(字符串数组)")
414
+ p_split.add_argument("-q", "--quiet", action="store_true",
415
+ help="只输出消息正文,空行分隔")
416
+ p_split.add_argument("-c", "--max-chars", type=int, metavar="N",
417
+ help="单条硬上限,调小更碎")
418
+ p_split.add_argument("-T", "--target-chars", type=int, metavar="N",
419
+ help="理想长度")
420
+ p_split.add_argument("-m", "--max-messages", type=int, metavar="N",
421
+ help="条数上限(软)")
422
+ p_split.set_defaults(handler=cmd_split)
423
+
424
+ p_test = sub.add_parser(
425
+ "test", help="跑测试用例并输出报告(仅源码仓库可用)",
426
+ description="跑一份 [CASE] 格式的用例文件,报告写入 tests/results/。",
427
+ )
428
+ p_test.add_argument(
429
+ "file", nargs="?", metavar="文件",
430
+ help="用例文件,默认 tests/test.txt",
431
+ )
432
+ p_test.set_defaults(handler=cmd_test)
433
+
434
+ p_menu = sub.add_parser("menu", help="交互菜单")
435
+ p_menu.set_defaults(handler=cmd_menu)
436
+
437
+ return parser
438
+
439
+
440
+ def main(argv: Optional[Sequence[str]] = None) -> int:
441
+ _setup_streams()
442
+ parser = build_parser()
443
+ args = parser.parse_args(argv)
444
+ if getattr(args, "command", None) is None:
445
+ parser.print_help()
446
+ return 0
447
+ return int(args.handler(args))
qikou/config.py ADDED
@@ -0,0 +1,60 @@
1
+ # -*- coding: utf-8 -*-
2
+ """切分配置。"""
3
+
4
+ from __future__ import annotations
5
+
6
+ from dataclasses import dataclass, replace
7
+
8
+ __all__ = ["Config"]
9
+
10
+
11
+ @dataclass
12
+ class Config:
13
+ """切分参数,所有字段都有默认值,按需覆盖即可。
14
+
15
+ ::
16
+
17
+ from qikou import Config, split
18
+
19
+ split(text, config=Config(max_chars=80, max_messages=10))
20
+
21
+ 传入 :func:`~qikou.split` 的实例不会被修改——长度自适应由
22
+ :meth:`scaled_for_length` 返回一个新实例来完成。
23
+ """
24
+
25
+ #: 单条硬上限,超过触发切分。
26
+ max_chars: int = 60
27
+ #: 理想长度,切点优选位置。
28
+ target_chars: int = 20
29
+ #: 低于此长度尝试与相邻条目合并。
30
+ min_chars: int = 4
31
+ #: 条数上限(软)。结构类条目不参与合并,因此可能超过。
32
+ max_messages: int = 6
33
+ #: 短前缀 + 超长原子片段合并的阈值。
34
+ atomic_merge_prefix: int = 20
35
+ #: 合并后单条上限。
36
+ merge_max_chars: int = 60
37
+
38
+ def scaled_for_length(self, total: int) -> "Config":
39
+ """返回按文本总长放宽后的新配置,**不改动 self**。
40
+
41
+ 长文本放宽单条上限可以避免碎成一地;合并上限同步放大,否则
42
+ 长文本的相邻对全都超过它,条数上限永远够不到。
43
+ """
44
+ if total <= 150:
45
+ return replace(self)
46
+ if total <= 400:
47
+ max_chars, target_chars, max_messages = 90, 30, self.max_messages
48
+ elif total <= 800:
49
+ max_chars, target_chars, max_messages = 120, 45, 8
50
+ else:
51
+ max_chars, target_chars, max_messages = 160, 60, 10
52
+
53
+ new_max = max(self.max_chars, max_chars)
54
+ return replace(
55
+ self,
56
+ max_chars=new_max,
57
+ target_chars=max(self.target_chars, target_chars),
58
+ max_messages=max(self.max_messages, max_messages),
59
+ merge_max_chars=max(self.merge_max_chars, new_max),
60
+ )
qikou/kaomoji.py ADDED
@@ -0,0 +1,147 @@
1
+ # -*- coding: utf-8 -*-
2
+ """颜文字语料:Trie 索引。
3
+
4
+ 语料随包分发,直接放在包目录下,构建 wheel 时由 pyproject.toml 的
5
+ package-data 一并打包。
6
+
7
+ 历史教训:早期代码指向仓库根目录的 'kaomoji'(小写、且在包外),
8
+ 在 Windows 上被大小写不敏感的文件系统掩盖,Linux/macOS 上会静默加载
9
+ 0 条;而包外目录在 pip 安装后根本不存在。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import logging
15
+ import os
16
+ import threading
17
+ import time
18
+ from typing import Any, Dict, Optional, Union
19
+
20
+ __all__ = ["default_path", "ensure_loaded", "is_kaomoji", "kaomoji_count",
21
+ "kaomoji_len", "load_kaomojis"]
22
+
23
+ logger = logging.getLogger(__name__)
24
+
25
+ _PATH = Union[str, "os.PathLike[str]"]
26
+
27
+ _END = "\x00"
28
+ KAOMOJI_FILE = "kaomojis.txt"
29
+
30
+ _state: Dict[str, Any] = {
31
+ "trie": {},
32
+ "count": 0,
33
+ "loaded": False,
34
+ }
35
+
36
+ # 语料是进程级共享状态。用可重入锁保护"检查-加载"的竞态:多个线程同时
37
+ # 首次调用 split() 时,只会真正加载一次。
38
+ _lock = threading.RLock()
39
+
40
+
41
+ def default_path() -> str:
42
+ """返回包内语料文件的绝对路径。"""
43
+ here = os.path.dirname(os.path.abspath(__file__))
44
+ return os.path.join(here, KAOMOJI_FILE)
45
+
46
+
47
+ def load_kaomojis(path: Optional[_PATH] = None) -> int:
48
+ """把颜文字语料加载进 Trie,返回去重后的条目数。
49
+
50
+ Args:
51
+ path: 语料文件路径;默认用包内自带的那份。
52
+
53
+ Returns:
54
+ 去重后的条目数;文件不存在时返回 0。
55
+
56
+ 成功时不向 stdout 输出任何内容(信息走 :mod:`logging`)。语料缺失只
57
+ 记录一条 warning,切分仍可继续进行,只是不再识别颜文字。
58
+ """
59
+ target = default_path() if path is None else os.fspath(path)
60
+
61
+ trie: Dict[str, Any] = {}
62
+ count = 0
63
+
64
+ if not os.path.isfile(target):
65
+ logger.warning("未找到颜文字语料:%s", target)
66
+ with _lock:
67
+ _state["trie"] = trie
68
+ _state["count"] = 0
69
+ _state["loaded"] = True
70
+ return 0
71
+
72
+ t0 = time.perf_counter()
73
+ with open(target, "r", encoding="utf-8-sig") as f:
74
+ for line in f:
75
+ s = line.strip()
76
+ if not s or s.startswith("#"):
77
+ continue
78
+ node = trie
79
+ for c in s:
80
+ nxt = node.get(c)
81
+ if nxt is None:
82
+ nxt = {}
83
+ node[c] = nxt
84
+ node = nxt
85
+ if _END not in node:
86
+ count += 1
87
+ node[_END] = True
88
+
89
+ with _lock:
90
+ _state["trie"] = trie
91
+ _state["count"] = count
92
+ _state["loaded"] = True
93
+
94
+ logger.debug("已加载 %d 个颜文字,耗时 %.0f ms",
95
+ count, (time.perf_counter() - t0) * 1000.0)
96
+ return count
97
+
98
+
99
+ def ensure_loaded() -> None:
100
+ """首次使用时自动加载默认语料;已加载或已尝试过则直接返回。
101
+
102
+ 调用 :func:`load_kaomojis` 显式指定过语料后,这里不会再覆盖它。
103
+ 多线程并发首次调用只会真正加载一次。
104
+ """
105
+ if not _state["loaded"]:
106
+ with _lock:
107
+ if not _state["loaded"]:
108
+ load_kaomojis()
109
+
110
+
111
+ def kaomoji_count() -> int:
112
+ """返回当前已加载的颜文字条数。"""
113
+ return int(_state["count"])
114
+
115
+
116
+ def kaomoji_len(s: str, i: int) -> int:
117
+ """从 ``s[i]`` 起匹配颜文字,返回最长匹配长度;无匹配返回 0。"""
118
+ trie = _state["trie"]
119
+ if not trie or i >= len(s):
120
+ return 0
121
+ node = trie
122
+ j = i
123
+ n = len(s)
124
+ best = 0
125
+ while j < n:
126
+ nxt = node.get(s[j])
127
+ if nxt is None:
128
+ break
129
+ node = nxt
130
+ j += 1
131
+ if _END in node:
132
+ best = j - i
133
+ return best
134
+
135
+
136
+ def is_kaomoji(text: str) -> bool:
137
+ """判断整段文本是否精确命中颜文字表。"""
138
+ t = text.strip()
139
+ if not t:
140
+ return False
141
+ node = _state["trie"]
142
+ for c in t:
143
+ nxt = node.get(c)
144
+ if nxt is None:
145
+ return False
146
+ node = nxt
147
+ return _END in node