diff --git a/gui/web_gui.py b/gui/web_gui.py index c4e6ef4..267133f 100644 --- a/gui/web_gui.py +++ b/gui/web_gui.py @@ -19,6 +19,22 @@ if project_root not in sys.path: from douyin.core import path_config +# 从子包 re-export 顶层 helper(保持兼容) +from gui.web_gui_pkg import ( + _LOGGER, + _wg_log, + strip_ansi_escape_codes, + find_adb_executable, + list_adb_devices, + resolve_adb_device, + read_config, + write_config, + get_nested_value, + _bucket, + _inc_map, + _parse_countdown_seconds, +) + BASE_DIR = path_config.PROJECT_ROOT CONFIG_PATH = path_config.get_config_path() WEBUI_DIR = path_config.get_webui_dir() @@ -30,88 +46,25 @@ import logging as _logging _LOGGER = _logging.getLogger("gui.web_gui") -def _wg_log(msg: str, level: str = "INFO") -> None: - """统一 web_gui 内部错误日志出口;失败兜底 stdout。""" - try: - lv = str(level or "INFO").upper() - if lv == "ERROR": - _LOGGER.error(str(msg)) - elif lv == "WARNING": - _LOGGER.warning(str(msg)) - elif lv == "DEBUG": - _LOGGER.debug(str(msg)) - else: - _LOGGER.info(str(msg)) - except Exception: - try: - print(str(msg)) - except Exception: - pass # CSRF token for POST request protection (local-only server) _CSRF_TOKEN = secrets.token_hex(32) -# ANSI转义序列清理正则表达式 -_ANSI_ESCAPE_RE = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])") - - -def strip_ansi_escape_codes(text: str) -> str: - """移除字符串中的ANSI转义序列(颜色代码等)。""" - if not isinstance(text, str): - return str(text) - return _ANSI_ESCAPE_RE.sub("", text) - - -def find_adb_executable() -> str: - """[兼容] 已迁移到 gui.gui_core。""" - from gui.gui_core import find_adb_executable as _impl - - return _impl() - - -def list_adb_devices(adb_exe: str) -> list[str]: - """[兼容] 已迁移到 gui.gui_core。""" - from gui.gui_core import list_adb_devices as _impl - - return _impl(adb_exe) - - -def resolve_adb_device(adb_exe: str, requested_device_id: str = "") -> str: - """[兼容] 已迁移到 gui.gui_core。""" - from gui.gui_core import resolve_adb_device as _impl - - return _impl(adb_exe, requested_device_id) - - -def read_config() -> dict: - """[兼容] 已迁移到 gui.gui_core。""" - from gui.gui_core import read_config as _impl - - return _impl() - - -def get_nested_value(obj: dict, key: str, default=None): - """读取支持点号路径的配置值,如 logging.keep_days。""" - try: - cur = obj - for part in str(key).split("."): - if not isinstance(cur, dict) or part not in cur: - return default - cur = cur[part] - return cur - except Exception: - return default - - -def write_config(cfg: dict) -> None: - """[兼容] 已迁移到 gui.gui_core。""" - from gui.gui_core import write_config as _impl - - return _impl(cfg) - class ProcRunner: + @staticmethod # type: ignore[misc] + def _parse_countdown_seconds(text): + return _parse_countdown_seconds(text) + + @staticmethod # type: ignore[misc] + def _bucket(value, edges): + return _bucket(value, edges) + + @staticmethod # type: ignore[misc] + def _inc_map(m, k, n=1): + return _inc_map(m, k, n) + def __init__(self) -> None: self._proc: Optional[subprocess.Popen] = None self._lock = threading.Lock() @@ -230,64 +183,6 @@ class ProcRunner: if len(self._wins) > self._wins_cap: self._wins = self._wins[-self._wins_cap :] - @staticmethod # type: ignore[misc] - def _parse_countdown_seconds(text: str) -> Optional[int]: - t = str(text or "").strip() - if not t: - return None - - # 优先解析 hh:mm:ss / mm:ss - if ":" in t: - parts = [p for p in t.split(":") if p != ""] - try: - nums = [int(p) for p in parts] - except Exception: - nums = [] - if len(nums) == 2: - mm, ss = nums - return max(0, mm * 60 + ss) - if len(nums) == 3: - hh, mm, ss = nums - return max(0, hh * 3600 + mm * 60 + ss) - - # 解析中文:xx小时xx分xx秒 - total = 0 - m = re.search(r"(\d+)\s*小时", t) - if m: - total += int(m.group(1)) * 3600 - m = re.search(r"(\d+)\s*分", t) - if m: - total += int(m.group(1)) * 60 - m = re.search(r"(\d+)\s*秒", t) - if m: - total += int(m.group(1)) - if total > 0: - return total - - # 兜底:纯数字当秒 - if re.fullmatch(r"\d+", t): - try: - return int(t) - except Exception: - return None - return None - - @staticmethod # type: ignore[misc] - def _bucket(value: float, edges: list[float]) -> str: - # edges 例如 [0,10,50,100] => 0-10,10-50,50-100,100+ - if not edges: - return "all" - for i in range(len(edges) - 1): - a = edges[i] - b = edges[i + 1] - if value >= a and value < b: - return f"{a:g}-{b:g}" - return f"{edges[-1]:g}+" - - @staticmethod # type: ignore[misc] - def _inc_map(m: dict, k: str, n: int = 1) -> None: - m[k] = int(m.get(k, 0)) + int(n) - def _snapshot_fudai(self) -> dict: return { "content": self._fudai_last.get("content") or "", diff --git a/gui/web_gui_pkg/__init__.py b/gui/web_gui_pkg/__init__.py new file mode 100644 index 0000000..a547b5e --- /dev/null +++ b/gui/web_gui_pkg/__init__.py @@ -0,0 +1,43 @@ +"""web_gui_pkg - gui/web_gui.py 的顶层 helper 子包。 + +原 gui/web_gui.py 拆出 11 个独立顶层 helper(8 个顶层函数 + 3 个 ProcRunner +@staticmethod),ProcRunner 巨型类(1514 行)/ Handler 类(588 行)/ main +留在原文件。 + +- logger _wg_log + module logger +- ansi strip_ansi_escape_codes +- adb_compat 5 个 thin wrapper(→ gui.gui_core_pkg) +- nested get_nested_value +- stats_helpers _parse_countdown_seconds / _bucket / _inc_map +""" + +from .logger import _LOGGER, _wg_log +from .ansi import strip_ansi_escape_codes +from .adb_compat import ( + find_adb_executable, + list_adb_devices, + read_config, + resolve_adb_device, + write_config, +) +from .nested import get_nested_value +from .stats_helpers import ( + _bucket, + _inc_map, + _parse_countdown_seconds, +) + +__all__ = [ + "_wg_log", + "_LOGGER", + "strip_ansi_escape_codes", + "find_adb_executable", + "list_adb_devices", + "resolve_adb_device", + "read_config", + "write_config", + "get_nested_value", + "_parse_countdown_seconds", + "_bucket", + "_inc_map", +] diff --git a/gui/web_gui_pkg/adb_compat.py b/gui/web_gui_pkg/adb_compat.py new file mode 100644 index 0000000..bcf5bb8 --- /dev/null +++ b/gui/web_gui_pkg/adb_compat.py @@ -0,0 +1,44 @@ +"""web_gui_pkg.adb_compat - ADB / 配置兼容 wrapper。 + +5 个 thin wrapper 转发到 ``gui.gui_core_pkg``: +- find_adb_executable / list_adb_devices / resolve_adb_device +- read_config / write_config + +历史外部代码 ``from gui.web_gui import find_adb_executable`` 等仍可用。 +""" +from __future__ import annotations + + +def find_adb_executable() -> str: + """[兼容] 已迁移到 gui.gui_core。""" + from gui.gui_core import find_adb_executable as _impl + + return _impl() + + +def list_adb_devices(adb_exe: str) -> list[str]: + """[兼容] 已迁移到 gui.gui_core。""" + from gui.gui_core import list_adb_devices as _impl + + return _impl(adb_exe) + + +def resolve_adb_device(adb_exe: str, requested_device_id: str = "") -> str: + """[兼容] 已迁移到 gui.gui_core。""" + from gui.gui_core import resolve_adb_device as _impl + + return _impl(adb_exe, requested_device_id) + + +def read_config() -> dict: + """[兼容] 已迁移到 gui.gui_core。""" + from gui.gui_core import read_config as _impl + + return _impl() + + +def write_config(cfg: dict) -> None: + """[兼容] 已迁移到 gui.gui_core。""" + from gui.gui_core import write_config as _impl + + return _impl(cfg) diff --git a/gui/web_gui_pkg/ansi.py b/gui/web_gui_pkg/ansi.py new file mode 100644 index 0000000..f16c8de --- /dev/null +++ b/gui/web_gui_pkg/ansi.py @@ -0,0 +1,17 @@ +"""web_gui_pkg.ansi - ANSI 转义码清理。 + +strip_ansi_escape_codes: 移除字符串中的 ANSI 颜色等转义序列。 +""" +from __future__ import annotations + +import re + +# ANSI转义序列清理正则表达式 +_ANSI_ESCAPE_RE = re.compile(r"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])") + + +def strip_ansi_escape_codes(text: str) -> str: + """移除字符串中的ANSI转义序列(颜色代码等)。""" + if not isinstance(text, str): + return str(text) + return _ANSI_ESCAPE_RE.sub("", text) diff --git a/gui/web_gui_pkg/logger.py b/gui/web_gui_pkg/logger.py new file mode 100644 index 0000000..38661a9 --- /dev/null +++ b/gui/web_gui_pkg/logger.py @@ -0,0 +1,29 @@ +"""web_gui_pkg.logger - 内部日志输出。 + +_wg_log: 统一 web_gui 内部错误日志出口;失败兜底 stdout。 +启动横幅和中断消息走 stdout(属于交互/CLI 输出)。 +""" +from __future__ import annotations + +import logging as _logging + +_LOGGER = _logging.getLogger("gui.web_gui") + + +def _wg_log(msg: str, level: str = "INFO") -> None: + """统一 web_gui 内部错误日志出口;失败兜底 stdout。""" + try: + lv = str(level or "INFO").upper() + if lv == "ERROR": + _LOGGER.error(str(msg)) + elif lv == "WARNING": + _LOGGER.warning(str(msg)) + elif lv == "DEBUG": + _LOGGER.debug(str(msg)) + else: + _LOGGER.info(str(msg)) + except Exception: + try: + print(str(msg)) + except Exception: + pass diff --git a/gui/web_gui_pkg/nested.py b/gui/web_gui_pkg/nested.py new file mode 100644 index 0000000..25a49d2 --- /dev/null +++ b/gui/web_gui_pkg/nested.py @@ -0,0 +1,18 @@ +"""web_gui_pkg.nested - 嵌套配置读取。 + +get_nested_value(obj, key, default): 读 ``logging.keep_days`` 这种点号路径。 +""" +from __future__ import annotations + + +def get_nested_value(obj: dict, key: str, default=None): + """读取支持点号路径的配置值,如 logging.keep_days。""" + try: + cur = obj + for part in str(key).split("."): + if not isinstance(cur, dict) or part not in cur: + return default + cur = cur[part] + return cur + except Exception: + return default diff --git a/gui/web_gui_pkg/stats_helpers.py b/gui/web_gui_pkg/stats_helpers.py new file mode 100644 index 0000000..4fc5597 --- /dev/null +++ b/gui/web_gui_pkg/stats_helpers.py @@ -0,0 +1,71 @@ +"""web_gui_pkg.stats_helpers - 统计辅助函数(从 ProcRunner @staticmethod 搬出)。 + +- _parse_countdown_seconds 解析倒计时文本到秒数(支持 hh:mm:ss / 中文 / 纯数字) +- _bucket 按 edges 数组将值分桶(用于直方图) +- _inc_map 字典内某 key 累加 n(缺失时初始为 0) +""" +from __future__ import annotations + +import re +from typing import Optional + + +def _parse_countdown_seconds(text: str) -> Optional[int]: + t = str(text or "").strip() + if not t: + return None + + # 优先解析 hh:mm:ss / mm:ss + if ":" in t: + parts = [p for p in t.split(":") if p != ""] + try: + nums = [int(p) for p in parts] + except Exception: + nums = [] + if len(nums) == 2: + mm, ss = nums + return max(0, mm * 60 + ss) + if len(nums) == 3: + hh, mm, ss = nums + return max(0, hh * 3600 + mm * 60 + ss) + + # 解析中文:xx小时xx分xx秒 + total = 0 + m = re.search(r"(\d+)\s*小时", t) + if m: + total += int(m.group(1)) * 3600 + m = re.search(r"(\d+)\s*分", t) + if m: + total += int(m.group(1)) * 60 + m = re.search(r"(\d+)\s*秒", t) + if m: + total += int(m.group(1)) + if total > 0: + return total + + # 兜底:纯数字当秒 + if re.fullmatch(r"\d+", t): + try: + return int(t) + except Exception: + return None + return None + + + +def _bucket(value: float, edges: list[float]) -> str: + # edges 例如 [0,10,50,100] => 0-10,10-50,50-100,100+ + if not edges: + return "all" + for i in range(len(edges) - 1): + a = edges[i] + b = edges[i + 1] + if value >= a and value < b: + return f"{a:g}-{b:g}" + return f"{edges[-1]:g}+" + + + +def _inc_map(m: dict, k: str, n: int = 1) -> None: + m[k] = int(m.get(k, 0)) + int(n) +