Przeglądaj źródła

feat(config): use pydantic to rewrite config

runhey 3 lat temu
rodzic
commit
b500319567

+ 32 - 12
module/config/config.py

@@ -9,11 +9,14 @@ import threading
 from module.config.config_updater import ConfigUpdater
 from module.config.config_manual import ConfigManual
 from module.config.config_watcher import ConfigWatcher
+from module.config.config_menu import ConfigMenu
+from module.config.config_model import ConfigModel
+from module.config.config_state import ConfigState
 from module.config.utils import *
 
 from module.logger import logger
 
-class Config(ConfigManual, ConfigWatcher, ConfigUpdater):
+class Config(ConfigState, ConfigManual, ConfigWatcher, ConfigMenu):
     """
     一个配置文件的集成类
     """
@@ -23,16 +26,31 @@ class Config(ConfigManual, ConfigWatcher, ConfigUpdater):
         :param config_name:
         :param task:
         """
-        self.config_name = config_name
-        self.data: dict = {}
-        self.is_template_config = config_name.startswith("template")
+        super().__init__(config_name)  # 调用 ConfigState 的初始化方法
+        super(ConfigManual, self).__init__()
+        super(ConfigWatcher, self).__init__()
+        super(ConfigMenu, self).__init__()
+        self.model = ConfigModel(config_name=config_name)
 
-        self.load()
-
-
-    def load(self) -> None:
-        self.data = self.read_file(self.config_name)
+    def __getattr__(self, name):
+        """
+        一开始是打算直接继承ConfigModel的,但是pydantic会接管所有的变量
+        故而选择持有ConfigModel
+        :param name:
+        :return:
+        """
+        try:
+            return getattr(self.model, name)
+        except AttributeError:
+            logger.error(f'can not ask this variable {name}')
+            return None  # 或者抛出异常,或者返回其他默认值
 
+    def gui_args(self) -> str:
+        """
+        获取给gui显示的参数
+        :return:
+        """
+        return self.model.gui_task()
 
     def get_arg(self, task: str, group: str, argument: str):
         """
@@ -62,6 +80,8 @@ class Config(ConfigManual, ConfigWatcher, ConfigUpdater):
             logger.exception(f'have no arg {task}.{group}.{argument}')
 
 if __name__ == '__main__':
-    config = Config(config_name='oas1')
-    logger.info(config.data)
-    logger.info(config.get_arg("Script", "Device", "Serial"))
+    config = Config(config_name='pydantic')
+    print(config.menu)
+    print(config.config_name)
+    print(config.script.device.serial)
+

+ 35 - 0
module/config/config_menu.py

@@ -0,0 +1,35 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import json
+
+from cached_property import cached_property
+from pydantic import BaseModel, ValidationError, validator, Field
+
+from module.config.utils import *
+
+class ConfigMenu:
+    # 手动的代码配置菜单
+    def __init__(self) -> None:
+        self.menu = {}
+        # 总览
+        self.menu["Overview"] = []
+        # 脚本设置
+        self.menu['Script'] = ['Script', 'General', 'Restart']
+        # 日常的任务
+        self.menu["DailyTask"] = ['TerritorialDemon', 'CoinChallenge']
+
+    @cached_property
+    def gui_menu(self) -> str:
+        """
+        生成的是json字符串
+        :return:
+        """
+        return json.dumps(self.menu, ensure_ascii=False, sort_keys=False, default=str)
+
+if __name__ == "__main__":
+    try:
+        m = ConfigMenu()
+        print(m.gui_menu)
+    except:
+        print('weih')

+ 81 - 0
module/config/config_model.py

@@ -0,0 +1,81 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+import json
+
+from pathlib import Path
+from pydantic import BaseModel, ValidationError, validator, Field
+
+from module.config.utils import *
+from module.logger import logger
+
+# 导入配置的Python文件
+from module.tasks.Script.config import Script
+from module.tasks.Restart.config import Restart
+
+
+
+
+
+
+class ConfigModel(BaseModel):
+    script: Script = Field(default_factory=Script)
+    restart: Restart = Field(default_factory=Restart)
+
+    # @validator('script')
+    # def script_validator(cls, v):
+    #     if v is None:
+    #         return Script()
+
+    def __init__(self, config_name: str) -> None:
+        """
+
+        :param config_name:
+        """
+        data = self.read_json(config_name)
+        super().__init__(**data)
+
+
+
+    @staticmethod
+    def read_json(config_name: str) -> dict:
+        """
+        读文件 没有额外操作
+        :param config_name:  不带后缀
+        :return:
+        """
+        filepath = Path.cwd() / "config" / f"{config_name}.json"
+        return read_file(filepath)
+
+    @staticmethod
+    def write_json(config_name: str, data) -> None:
+        """
+
+        :param config_name: 不带后缀
+        :param data:  字典而不是字符串
+        :return:
+        """
+        filepath = Path.cwd() / "config" / f"{config_name}.json"
+        write_file(filepath, data)
+
+    def gui_task(self, task: str) -> str:
+        """
+        返回提供给gui显示的参数
+        :param task: 输入的是任务的名称英文 如'Script' 或者是'script'都是可以的
+        :return: 返回的是pydantic给我们结构化的输出的信息, 如果不能获取就返回空的str
+        """
+        task = convert_to_underscore(task)
+        task_gui = getattr(self, task, None)
+        if task_gui is None:
+            logger.error(f'{task} is no inexistence')
+            return ''
+        return task_gui.schema_json()
+
+if __name__ == "__main__":
+    try:
+        c = ConfigModel("oas3")
+    except ValidationError as e:
+        print(e)
+        c = ConfigModel()
+    print(c.json())
+    # c.write_json('pydantic', json.loads(c.gui_task('Script')))

+ 13 - 0
module/config/config_state.py

@@ -0,0 +1,13 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+
+
+class ConfigState:
+    """
+    这个类用于 先定义运行过程中所需要的变量
+    """
+    def __init__(self, config_name: str) -> None:
+        self.config_name = config_name
+        self.pending_task = []
+        self.waiting_task = []

+ 2 - 1
module/config/config_updater.py

@@ -62,4 +62,5 @@ class ConfigUpdater:
             data (dict):
             mod_name (str):
         """
-        write_file(filepath_config(config_name, mod_name), data)
+        write_file(filepath_config(config_name, mod_name), data)
+

+ 30 - 1
module/config/utils.py

@@ -154,4 +154,33 @@ def get_server_next_update(daily_trigger):
         future = local_now + timedelta(seconds=s)
         trigger.append(future)
     update = sorted(trigger)[0]
-    return update
+    return update
+
+
+def convert_to_underscore(text: str) -> str:
+    """
+    大驼峰形式的字符串转换为下划线形式的字符串,并在数字前插入下划线。如果字符串中已经包含下划线,则会直接返回原始字符串。
+    :param text:
+    :return:
+    """
+    if '_' in text:
+        # If text already contains underscore, assume it's in the correct format
+        return text
+
+    result = ''
+    for i, char in enumerate(text):
+        if char.isupper():
+            if i > 0 and (text[i-1].islower() or (i < len(text) - 1 and text[i+1].islower())):
+                # Insert underscore before uppercase letter, except at the beginning
+                result += '_'
+            result += char.lower()
+        elif char.isdigit():
+            if i > 0 and (text[i-1].isalpha() or (i < len(text) - 1 and text[i+1].isalpha())):
+                # Insert underscore before digit, except at the beginning
+                result += '_'
+            result += char
+        else:
+            result += char
+
+    return result
+

+ 0 - 19
module/gui/fluent_app.py

@@ -58,25 +58,6 @@ class FluentApp():
         """
         FluentApp.engine.rootContext().setContextProperty(name, context)
 
-#     @classmethod
-#     def init_translator(cls) -> None:
-#         """
-#         初始化翻译
-#         :return:
-#         """
-#         path_en_US = Path.cwd() / "module" / "config" / "i18n" / "en_US.qm"
-#         path_zh_CN = Path.cwd() / "module" / "config" / "i18n" / "zh_CN.qm"
-#         FluentApp.translator = QTranslator()
-#         # FluentApp.translator.load(str(path_en_US.resolve()))
-#         print(FluentApp.translator.load(str(path_zh_CN.resolve())))
-#         QGuiApplication.installTranslator(FluentApp.translator)
-#         FluentApp.engine.retranslate()
-#         print(FluentApp.translator.language())
-# #        # locale = QLocale("en_US")  # 设置英文
-# #        locale = QLocale("zh_CN")  # 设置中文
-# #        FluentApp.app.setApplicationLocale(locale)
-
-
 class Translator(QObject):
 
     def __init__(self, engine, app) -> None:

+ 7 - 0
module/tasks/General/config.py

@@ -0,0 +1,7 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+
+from pydantic import BaseModel, ValidationError, validator, Field
+
+from module.logger import logger

+ 10 - 0
module/tasks/Restart/config.py

@@ -0,0 +1,10 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from pydantic import BaseModel, ValidationError, validator, Field
+
+from module.logger import logger
+from module.tasks.Restart.config_scheduler import Scheduler
+
+class Restart(BaseModel):
+    scheduler: Scheduler = Field(default_factory=Scheduler)

+ 22 - 0
module/tasks/Restart/config_scheduler.py

@@ -0,0 +1,22 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from enum import Enum
+from datetime import datetime, time
+from pydantic import BaseModel, ValidationError, validator, Field
+
+from module.logger import logger
+
+class Scheduler(BaseModel):
+    enable: bool = Field(default=False,
+                         description='none')
+    next_run: datetime = Field(default="2023-01-01 00:00:00",
+                               description='none')
+    command: str = Field(default='Restart',
+                         description='none')
+    success_interval: float = Field(default=0,
+                                    description='none')
+    failure_interval: float = Field(default=0,
+                                    description='none')
+    server_update: time = Field(default="00:00",
+                                description='none')

+ 14 - 0
module/tasks/Script/config.py

@@ -0,0 +1,14 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from pydantic import BaseModel, ValidationError, validator, Field
+
+from module.tasks.Script.config_device import Device
+from module.tasks.Script.config_error import Error
+from module.tasks.Script.config_optimization import Optimization
+from module.logger import logger
+
+class Script(BaseModel):
+    device: Device = Field(default_factory=Device)
+    error: Error = Field(default_factory=Error)
+    optimization: Optimization = Field(default_factory=Optimization)

+ 52 - 0
module/tasks/Script/config_device.py

@@ -0,0 +1,52 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from enum import Enum
+from pydantic import BaseModel, ValidationError, validator, Field
+
+from module.logger import logger
+
+class PackageName(str, Enum):
+    AUTO = 'auto'
+    NETEASE_ONMYOJI = 'com.netease.onmyoji.wyzymnqsd_cps'  # 网易自家的阴阳师
+
+class ScreenshotMethod(str, Enum):
+    ADB = 'adb'
+    ADB_NC = 'adb_nc'
+    UIAUTOMATOR2 = 'uiautomator2'
+    DROIDCAST = 'droidcast'
+    DROIDCAST_RAW = 'droidcast_raw'
+    SCRCPY = 'scrcpy'
+    WINDOW_BACKGROUND = 'window_background'
+
+class ControlMethod(str, Enum):
+    ADB = 'adb'
+    UIAUTOMATOR2 = 'uiautomator2'
+    MINITOUCH = 'minitouch'
+    WINDOW_MESSAGE = 'window_message'
+
+
+class Device(BaseModel):
+    serial: str = Field(default="127.0.0.1:7555",
+                        description='Common emulator Serial can be queried in the list belowUse "auto" to auto-detect emulators, but if multiple emulators are running or use emulators that do not support auto-detect, "auto" cannot be used and serial must be filled in manually')
+    handle: str = Field(default='auto',
+                        description='you can use auto or your emulator title')
+    package_name: PackageName = Field(default=PackageName.AUTO,
+                                      description='package name')
+    screenshot_method: ScreenshotMethod = Field(default=ScreenshotMethod.WINDOW_BACKGROUND,
+                                                description='only support window')
+    control_method: ControlMethod = Field(default=ControlMethod.WINDOW_MESSAGE,
+                                          description='only support window')
+    adb_restart: bool = Field(default=False,
+                              description='')
+
+
+
+if __name__ == '__main__':
+    d = Device()
+    print(d.json())
+    print(d.schema_json())
+    try:
+        d.control_method = 'adb'
+    except ValidationError as e:
+        print(e)

+ 15 - 0
module/tasks/Script/config_error.py

@@ -0,0 +1,15 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from pydantic import BaseModel, ValidationError, validator, Field
+
+from module.logger import logger
+
+
+class Error(BaseModel):
+    handle_error: bool = Field(default=False,
+                               description='none')
+    save_error: bool = Field(default=False,
+                             description='none')
+    screenshot_length: int = Field(default=1,
+                                   description='The number of recent screenshots to save when something goes wrong')

+ 21 - 0
module/tasks/Script/config_optimization.py

@@ -0,0 +1,21 @@
+# This Python file uses the following encoding: utf-8
+# @author runhey
+# github https://github.com/runhey
+from enum import Enum
+from pydantic import BaseModel, ValidationError, validator, Field
+
+from module.logger import logger
+
+class WhenTaskQueueEmpty(str, Enum):
+    GOTO_HOME = 'goto_home'
+    CLOSE_GAME = 'close_game'
+
+class Optimization(BaseModel):
+    screenshot_interval: float = Field(default=0.3,
+                                       description='none')
+    combat_screenshot_interval: float = Field(default=1.0,
+                                              description='none')
+    task_hoarding_duration: float = Field(default=0,
+                                          description='none')
+    when_task_queue_empty: WhenTaskQueueEmpty = Field(default=WhenTaskQueueEmpty.GOTO_HOME,
+                                                      description='you can select goto home where nothing to do')

+ 2 - 1
requirements-in.txt

@@ -10,4 +10,5 @@ websockets==11.0.3
 anytree==2.8.0
 pywin32==306
 zerorpc==0.6.3
-wrapt==1.15.0
+wrapt==1.15.0
+pydantic==1.10.7

+ 12 - 12
script.py

@@ -27,18 +27,18 @@ class Script:
             logger.exception(e)
             exit(1)
 
-    @cached_property
-    def device(self) -> "Device":
-        try:
-            from module.device.device import Device
-            device = Device(config=self.config)
-            return device
-        except RequestHumanTakeover:
-            logger.critical('Request human takeover')
-            exit(1)
-        except Exception as e:
-            logger.exception(e)
-            exit(1)
+    # @cached_property
+    # def device(self) -> "Device":
+    #     try:
+    #         from module.device.device import Device
+    #         device = Device(config=self.config)
+    #         return device
+    #     except RequestHumanTakeover:
+    #         logger.critical('Request human takeover')
+    #         exit(1)
+    #     except Exception as e:
+    #         logger.exception(e)
+    #         exit(1)
 
     def init_server(self, port: int) -> int:
         """