common.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. from __future__ import annotations
  2. """GameUi 运行时的共享类型与工具函数。"""
  3. import inspect
  4. import re
  5. import traceback
  6. from pathlib import Path
  7. from typing import TYPE_CHECKING, Any, Callable
  8. from module.atom.click import RuleClick
  9. from module.atom.gif import RuleGif
  10. from module.atom.image import RuleImage
  11. from module.atom.list import RuleList
  12. from module.atom.ocr import RuleOcr
  13. if TYPE_CHECKING:
  14. from tasks.GameUi.action import ConditionalAction, ActionSequence
  15. else:
  16. ConditionalAction = Any
  17. ActionSequence = tuple[Any]
  18. # 页面识别条件允许直接使用现有 Rule 元对象或自定义函数。
  19. RecognizerLike = RuleImage | RuleGif | RuleOcr | Callable
  20. # 页面跳转动作和 hook 动作允许使用点击类元对象、自定义函数或组合动作。
  21. ActionLike = RuleImage | RuleGif | RuleOcr | RuleList | RuleClick | ActionSequence | ConditionalAction | Callable
  22. def camel_to_snake(value: str) -> str:
  23. """将驼峰或混合命名转换为下划线命名。
  24. Args:
  25. value: 待转换的字符串。
  26. Returns:
  27. 转换后的下划线命名字符串。
  28. """
  29. value = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", value)
  30. value = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", value)
  31. return value.replace("-", "_").lower()
  32. def infer_stack_symbol(stack_depth: int = 3) -> str:
  33. """根据调用栈推断页面变量名。
  34. Args:
  35. stack_depth: 需要读取的调用栈深度,默认与页面定义调用层一致。
  36. Returns:
  37. 推断出的变量名;若无法解析则返回基于行号的兜底名称。
  38. """
  39. filename, line_number, function_name, text = traceback.extract_stack()[-stack_depth]
  40. del filename, function_name
  41. if text and "=" in text:
  42. return text[: text.find("=")].strip()
  43. return f"page_{line_number}"
  44. def infer_page_key_and_name(stack_depth: int = 4) -> tuple[str, str]:
  45. """从调用栈中推断页面的 `key` 与 `name`。
  46. Args:
  47. stack_depth: 需要向上回溯的调用栈深度。`Page.__init__ -> infer_page_key_and_name
  48. -> infer_stack_symbol` 这一层级下,默认值 4 才能落到真正的页面定义语句。
  49. Returns:
  50. 一个 `(page_key, page_name)` 元组。
  51. """
  52. symbol = infer_stack_symbol(stack_depth=stack_depth)
  53. name = symbol.split(".")[-1]
  54. return symbol, name
  55. def infer_tasks_category_from_parts(parts: list[str], task_index: int, *, component_use_child: bool = False) -> str:
  56. """根据包含 `tasks` 的路径片段推断分类。
  57. Args:
  58. parts: 已拆分的路径或模块名片段。
  59. task_index: 片段列表中 `tasks` 所在的索引。
  60. component_use_child: 当目标目录为 `Component` 时,是否继续使用下一层目录名作为分类。
  61. Returns:
  62. 推断出的分类名。
  63. """
  64. if task_index + 1 >= len(parts):
  65. return "global"
  66. folder = parts[task_index + 1]
  67. if folder == "GameUi":
  68. return "global"
  69. if component_use_child and folder == "Component" and task_index + 2 < len(parts):
  70. return camel_to_snake(parts[task_index + 2])
  71. return camel_to_snake(folder)
  72. def infer_tasks_category_from_path(path: str | Path, *, component_use_child: bool = False) -> str:
  73. """根据绝对或相对路径推断任务分类。
  74. Args:
  75. path: 目标文件路径。
  76. component_use_child: 当路径位于 `tasks/Component/*` 下时,是否继续使用下一层目录名作为分类。
  77. Returns:
  78. 推断出的分类名;路径不在 `tasks` 目录下时返回 `global`。
  79. """
  80. parts = list(Path(path).resolve().parts)
  81. if "tasks" not in parts:
  82. return "global"
  83. return infer_tasks_category_from_parts(parts, parts.index("tasks"), component_use_child=component_use_child)
  84. def infer_category(filename: str | None = None, stack_depth: int = 3) -> str:
  85. """根据文件路径推断页面分类。
  86. Args:
  87. filename: 显式传入的文件路径;为空时从调用栈推断。
  88. stack_depth: 当 `filename` 为空时,读取调用栈的深度。
  89. Returns:
  90. 页面所属分类;`tasks/GameUi` 内的页面固定归为 `global`。
  91. """
  92. return infer_tasks_category_from_path(filename or traceback.extract_stack()[-stack_depth].filename)
  93. def invoke_task_callable(target: Callable, task):
  94. """调用用户自定义识别函数或 hook 函数。
  95. Args:
  96. target: 用户传入的可调用对象。
  97. task: 当前运行时任务对象。
  98. Returns:
  99. 目标函数的返回值。
  100. """
  101. try:
  102. signature = inspect.signature(target)
  103. except (TypeError, ValueError):
  104. return target(task)
  105. if len(signature.parameters) <= 0:
  106. return target()
  107. return target(task)