# -*- coding: utf-8 -*- r'''清掉 actions.py 里重复的 list_voices 和残留的旧 say 前半段。 == 怎么弄出来的 == fix_tts_fallback.py 里我写了两处替换,但 `NEW` 那个大块**自己也带了一份 list_voices**: t.replace(OLD_VOICES, NEW_VOICES) # 这是第一份 list_voices t.replace(OLD_SAY, NEW) # NEW 里又有一份 list_voices 于是 pyflakes 报: redefinition of unused 'list_voices' from line 540 redefinition of unused 'say' from line 575 local variable 'chosen' is assigned to but never used 第三条是**旧 say 的前半段残留** —— `chosen` / `speed` 算完就不用了, 真正干活的在后面那份里。 == 这一版怎么改 == 把**后面**那份 list_voices(`NEW` 带进来的)删掉,保留前面 NEW_VOICES 那份; 再把旧的 say 前半段(算 chosen/speed 那几行)删掉 —— 那些在新 say 里 已经算过一遍了。 **先全部定位好再动手**,避免又改一半。 ''' from __future__ import annotations import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent ACTIONS = ROOT / "windows" / "lanremote" / "actions.py" def main() -> int: print("=" * 58) print(" 清掉重复定义") print("=" * 58) print() raw = ACTIONS.read_bytes() bom = raw.startswith(b"\xef\xbb\xbf") t = raw.decode("utf-8-sig") lines = t.split("\n") # ---- 1. 找所有 list_voices / say 定义 ---- defs = {} for i, ln in enumerate(lines): m = re.match(r" def (list_voices|say|_tts_commands|_write_vbs|" r"_powershell_path)\(self", ln) if m: defs.setdefault(m.group(1), []).append(i) print(" 定义位置:") for name, spots in sorted(defs.items()): print(" %-18s %s" % (name, [s + 1 for s in spots])) # ---- 2. 删掉重复的 list_voices(保留第一个)---- dup_lv = defs.get("list_voices", []) if len(dup_lv) != 2: print(" ⚠ list_voices 有 %d 个定义,期望 2 个" % len(dup_lv)) else: start = dup_lv[1] # 找到下一个同级 def end = len(lines) for j in range(start + 1, len(lines)): if re.match(r" def \w+\(", lines[j]): end = j break # 往上把紧邻的注释也吃掉(那是我写的那段说明) s = start while s > 0 and (lines[s - 1].strip().startswith("#") or lines[s - 1].strip() == ""): s -= 1 if lines[s].strip() == "" and s + 1 < start: s += 1 break print(" 删除重复的 list_voices:第 %d-%d 行" % (start + 1, end)) del lines[start:end] # ---- 3. 删掉旧 say 的前半段(算 chosen/speed 那段)---- t2 = "\n".join(lines) old_head = ''' chosen = (voice or "").strip() or str(self.store.get("tts_voice") or "").strip() try: speed = int(rate) if rate else int(self.store.get("tts_rate", 0) or 0) except (TypeError, ValueError): speed = 0 speed = max(-10, min(10, speed)) ''' n = t2.count(old_head) print(" 旧 say 前半段残留:%d 处" % n) if n: # 只删最后一处之前的那一坨(如果出现两次,说明新 say 里也有一份, # 那份是**要保留的**)—— 所以删第一处。 t2 = t2.replace(old_head, "", 1) ACTIONS.write_bytes((b"\xef\xbb\xbf" if bom else b"") + t2.encode("utf-8")) print(" ✓ 清完了") # ---- 4. 复核 ---- back = ACTIONS.read_text(encoding="utf-8-sig") lv = len(re.findall(r"\n def list_voices\(self", back)) sy = len(re.findall(r"\n def say\(self", back)) tc = len(re.findall(r"\n def _tts_commands\(self", back)) print() print(" 复核:list_voices=%d(应 1) say=%d(应 1) _tts_commands=%d(应 1)" % (lv, sy, tc)) return 0 if (lv == 1 and sy == 1 and tc == 1) else 1 if __name__ == "__main__": sys.exit(main())