MaaDebugger 1.0.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 MaaXYZ
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.1
2
+ Name: MaaDebugger
3
+ Version: 1.0.0
4
+ Summary: MaaDebugger
5
+ Author: MaaXYZ
6
+ Project-URL: Homepage, https://github.com/MaaXYZ/MaaDebugger
7
+ Requires-Python: >=3.9
8
+ Requires-Dist: MaaFw
9
+ Requires-Dist: nicegui
10
+ Description-Content-Type: text/markdown
11
+
12
+ # MaaDebugger
@@ -0,0 +1 @@
1
+ # MaaDebugger
@@ -0,0 +1,30 @@
1
+ [project]
2
+ name = "MaaDebugger"
3
+ version = "1.0.0"
4
+ description = "MaaDebugger"
5
+ authors = [
6
+ { name = "MaaXYZ" },
7
+ ]
8
+ dependencies = [
9
+ "MaaFw",
10
+ "nicegui",
11
+ ]
12
+ readme = "README.md"
13
+ requires-python = ">=3.9"
14
+
15
+ [project.urls]
16
+ Homepage = "https://github.com/MaaXYZ/MaaDebugger"
17
+
18
+ [project.scripts]
19
+ MaaDebugger = "MaaDebugger.main:main"
20
+
21
+ [build-system]
22
+ requires = [
23
+ "pdm-backend",
24
+ ]
25
+ build-backend = "pdm.backend"
26
+
27
+ [tool.pdm.build]
28
+ includes = [
29
+ "src/MaaDebugger",
30
+ ]
@@ -0,0 +1,4 @@
1
+ from .main import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,138 @@
1
+ import asyncio
2
+ from pathlib import Path
3
+ from typing import Callable, List, Optional
4
+
5
+ from maa.controller import AdbController
6
+ from maa.instance import Instance
7
+ from maa.resource import Resource
8
+ from maa.toolkit import Toolkit
9
+ from PIL import Image
10
+
11
+ from ..utils import cvmat_to_image
12
+
13
+
14
+ class MaaFW:
15
+ def __init__(
16
+ self,
17
+ on_list_to_recognize: Callable = None,
18
+ on_miss_all: Callable = None,
19
+ on_recognition_result: Callable = None,
20
+ ):
21
+ Toolkit.init_option("./")
22
+ Instance.set_debug_message(True)
23
+
24
+ self.resource = None
25
+ self.controller = None
26
+ self.instance = None
27
+
28
+ self.screenshotter = Screenshotter(self.screencap)
29
+
30
+ self.on_list_to_recognize = on_list_to_recognize
31
+ self.on_miss_all = on_miss_all
32
+ self.on_recognition_result = on_recognition_result
33
+
34
+ @staticmethod
35
+ async def detect_adb() -> List["AdbDevice"]:
36
+ return await Toolkit.adb_devices()
37
+
38
+ async def connect_adb(self, path: Path, address: str) -> bool:
39
+ self.controller = AdbController(path, address)
40
+ connected = await self.controller.connect()
41
+ if not connected:
42
+ print(f"Failed to connect {path} {address}")
43
+ return False
44
+
45
+ return True
46
+
47
+ async def load_resource(self, dir: Path) -> bool:
48
+ if not self.resource:
49
+ self.resource = Resource()
50
+
51
+ return self.resource.clear() and await self.resource.load(dir)
52
+
53
+ async def run_task(self, entry: str, param: dict = {}) -> bool:
54
+ if not self.instance:
55
+ self.instance = Instance(callback=self._inst_callback)
56
+
57
+ self.instance.bind(self.resource, self.controller)
58
+ if not self.instance.inited:
59
+ print("Failed to init MaaFramework instance")
60
+ return False
61
+
62
+ return await self.instance.run_task(entry, param)
63
+
64
+ async def stop_task(self):
65
+ if not self.instance:
66
+ return
67
+
68
+ await self.instance.stop()
69
+
70
+ async def screencap(self, capture: bool = True) -> Optional[Image.Image]:
71
+ if not self.controller:
72
+ return None
73
+
74
+ im = await self.controller.screencap(capture)
75
+ if im is None:
76
+ return None
77
+
78
+ return cvmat_to_image(im)
79
+
80
+ async def click(self, x, y) -> None:
81
+ if not self.controller:
82
+ return None
83
+
84
+ await self.controller.click(x, y)
85
+
86
+ def _inst_callback(self, msg: str, detail: dict, arg):
87
+ match msg:
88
+ case "Task.Debug.ListToRecognize":
89
+ asyncio.run(self.screenshotter.refresh(False))
90
+ if self.on_list_to_recognize:
91
+ self.on_list_to_recognize(detail["pre_hit_task"], detail["list"])
92
+
93
+ case "Task.Debug.MissAll":
94
+ if self.on_miss_all:
95
+ self.on_miss_all(detail["pre_hit_task"], detail["list"])
96
+
97
+ case "Task.Debug.RecognitionResult":
98
+ reco_id = detail["recognition"]["id"]
99
+ name = detail["name"]
100
+ hit = detail["recognition"]["hit"]
101
+
102
+ if self.on_recognition_result:
103
+ self.on_recognition_result(reco_id, name, hit)
104
+
105
+
106
+ # class Screenshotter(threading.Thread):
107
+ class Screenshotter:
108
+ def __init__(self, screencap_func: Callable):
109
+ super().__init__()
110
+ self.source = None
111
+ self.screencap_func = screencap_func
112
+ # self.active = False
113
+
114
+ def __del__(self):
115
+ self.source = None
116
+ # self.active = False
117
+
118
+ async def refresh(self, capture: bool = True):
119
+ im = await self.screencap_func(capture)
120
+ if not im:
121
+ return
122
+
123
+ self.source = im
124
+
125
+ # def run(self):
126
+ # while self.active:
127
+ # self.refresh()
128
+ # time.sleep(0)
129
+
130
+ # def start(self):
131
+ # self.active = True
132
+ # super().start()
133
+
134
+ # def stop(self):
135
+ # self.active = False
136
+
137
+
138
+ maafw = MaaFW()
@@ -0,0 +1,11 @@
1
+ from nicegui import ui
2
+
3
+ from .webpage import index_page
4
+ from .webpage import reco_page
5
+
6
+
7
+ def main():
8
+ ui.dark_mode() # auto dark mode
9
+ ui.run(
10
+ title="Maa Debugger", storage_secret="maadbg", reload=False
11
+ ) # , root_path="/proxy/8080")
@@ -0,0 +1,8 @@
1
+ from numpy import ndarray
2
+ from PIL import Image
3
+
4
+
5
+ def cvmat_to_image(cvmat: ndarray) -> Image.Image:
6
+ pil = Image.fromarray(cvmat)
7
+ b, g, r = pil.split()
8
+ return Image.merge("RGB", (r, g, b))
@@ -0,0 +1,34 @@
1
+ from enum import Enum, auto
2
+
3
+ from nicegui import ui
4
+
5
+
6
+ class Status(Enum):
7
+ PENDING = auto()
8
+ RUNNING = auto()
9
+ SUCCESS = auto()
10
+ FAILURE = auto()
11
+
12
+
13
+ class StatusIndicator:
14
+ def __init__(self, target_object, target_name):
15
+ self._label = ui.label().bind_text_from(
16
+ target_object,
17
+ target_name,
18
+ backward=lambda s: StatusIndicator._text_backward(s),
19
+ )
20
+
21
+ def label(self):
22
+ return self._label
23
+
24
+ @staticmethod
25
+ def _text_backward(status: Status) -> str:
26
+ match status:
27
+ case Status.PENDING:
28
+ return "🟡"
29
+ case Status.RUNNING:
30
+ return "👀"
31
+ case Status.SUCCESS:
32
+ return "✅"
33
+ case Status.FAILURE:
34
+ return "❌"
@@ -0,0 +1,14 @@
1
+ from nicegui import ui
2
+
3
+ from .master_control import main as master_control
4
+ from .runtime_control import main as runtime_control
5
+
6
+
7
+ @ui.page("/")
8
+ async def index():
9
+
10
+ await master_control()
11
+
12
+ ui.separator()
13
+
14
+ await runtime_control()
@@ -0,0 +1,217 @@
1
+ import asyncio
2
+ from pathlib import Path
3
+
4
+ from nicegui import app, binding, ui
5
+
6
+ from ...maafw import maafw
7
+ from ...webpage.components.status_indicator import Status, StatusIndicator
8
+
9
+ binding.MAX_PROPAGATION_TIME = 1
10
+
11
+
12
+ class GlobalStatus:
13
+ adb_connecting: Status = Status.PENDING
14
+ adb_detecting: Status = Status.PENDING # not required
15
+ res_loading: Status = Status.PENDING
16
+ task_running: Status = Status.PENDING
17
+
18
+
19
+ async def main():
20
+ with ui.row():
21
+ with ui.column():
22
+ with ui.row().style("align-items: center;"):
23
+ await connect_adb_control()
24
+ with ui.row().style("align-items: center;"):
25
+ await load_resource_control()
26
+ with ui.row().style("align-items: center;"):
27
+ await run_task_control()
28
+
29
+ with ui.column():
30
+ await screenshot_control()
31
+
32
+
33
+ async def connect_adb_control():
34
+ StatusIndicator(GlobalStatus, "adb_connecting")
35
+
36
+ adb_path_input = (
37
+ ui.input(
38
+ "ADB Path",
39
+ placeholder="eg: C:/adb.exe",
40
+ )
41
+ .props("size=60")
42
+ .bind_value(app.storage.general, "adb_path")
43
+ )
44
+ adb_address_input = (
45
+ ui.input(
46
+ "ADB Address",
47
+ placeholder="eg: 127.0.0.1:5555",
48
+ )
49
+ .props("size=30")
50
+ .bind_value(app.storage.general, "adb_address")
51
+ )
52
+ ui.button(
53
+ "Connect",
54
+ on_click=lambda: on_click_connect(),
55
+ )
56
+
57
+ ui.button(
58
+ icon="wifi_find",
59
+ on_click=lambda: on_click_detect(),
60
+ )
61
+
62
+ devices_select = ui.select(
63
+ {}, on_change=lambda e: on_change_devices_select(e)
64
+ ).bind_visibility_from(
65
+ GlobalStatus,
66
+ "adb_detecting",
67
+ backward=lambda s: s == Status.SUCCESS,
68
+ )
69
+
70
+ StatusIndicator(GlobalStatus, "adb_detecting").label().bind_visibility_from(
71
+ GlobalStatus,
72
+ "adb_detecting",
73
+ backward=lambda s: s == Status.RUNNING or s == Status.FAILURE,
74
+ )
75
+
76
+ async def on_click_connect():
77
+ GlobalStatus.adb_connecting = Status.RUNNING
78
+
79
+ if not adb_path_input.value or not adb_address_input.value:
80
+ GlobalStatus.adb_connecting = Status.FAILURE
81
+ return
82
+
83
+ connected = await maafw.connect_adb(
84
+ Path(adb_path_input.value), adb_address_input.value
85
+ )
86
+ if not connected:
87
+ GlobalStatus.adb_connecting = Status.FAILURE
88
+ return
89
+
90
+ GlobalStatus.adb_connecting = Status.SUCCESS
91
+ GlobalStatus.adb_detecting = Status.PENDING
92
+
93
+ await maafw.screenshotter.refresh(True)
94
+
95
+ async def on_click_detect():
96
+ GlobalStatus.adb_detecting = Status.RUNNING
97
+
98
+ devices = await maafw.detect_adb()
99
+ options = {}
100
+ for d in devices:
101
+ v = (d.adb_path, d.address)
102
+ l = d.name + " " + d.address
103
+ options[v] = l
104
+
105
+ devices_select.options = options
106
+ devices_select.update()
107
+ if not options:
108
+ GlobalStatus.adb_detecting = Status.FAILURE
109
+ return
110
+
111
+ devices_select.value = next(iter(options))
112
+ GlobalStatus.adb_detecting = Status.SUCCESS
113
+
114
+ def on_change_devices_select(e):
115
+ adb_path_input.value = str(e.value[0])
116
+ adb_address_input.value = e.value[1]
117
+
118
+
119
+ async def screenshot_control():
120
+ with ui.row().style("align-items: flex-end;"):
121
+ with ui.card().tight():
122
+ ui.interactive_image(
123
+ cross="green",
124
+ on_mouse=lambda e: on_click_image(int(e.image_x), int(e.image_y)),
125
+ ).bind_source_from(maafw.screenshotter, "source").style(
126
+ "height: 200px;"
127
+ ).bind_visibility_from(
128
+ GlobalStatus, "adb_connecting", backward=lambda s: s == Status.SUCCESS
129
+ )
130
+
131
+ ui.button(
132
+ icon="refresh", on_click=lambda: on_click_refresh()
133
+ ).bind_visibility_from(
134
+ GlobalStatus, "adb_connecting", backward=lambda s: s == Status.SUCCESS
135
+ ).bind_enabled_from(
136
+ GlobalStatus, "task_running", backward=lambda s: s != Status.RUNNING
137
+ )
138
+
139
+ async def on_click_image(x, y):
140
+ print(f"on_click_image: {x}, {y}")
141
+ await maafw.click(x, y)
142
+ await asyncio.sleep(0.2)
143
+ await on_click_refresh()
144
+
145
+ async def on_click_refresh():
146
+ await maafw.screenshotter.refresh(True)
147
+
148
+
149
+ async def load_resource_control():
150
+ StatusIndicator(GlobalStatus, "res_loading")
151
+
152
+ dir_input = (
153
+ ui.input(
154
+ "Resource Directory",
155
+ placeholder="eg: C:/M9A/assets/resource/base",
156
+ )
157
+ .props("size=60")
158
+ .bind_value(app.storage.general, "resource_dir")
159
+ )
160
+
161
+ ui.button(
162
+ "Load",
163
+ on_click=lambda: on_click_load(),
164
+ )
165
+
166
+ async def on_click_load():
167
+ GlobalStatus.res_loading = Status.RUNNING
168
+
169
+ if not dir_input.value:
170
+ GlobalStatus.res_loading = Status.FAILURE
171
+ return
172
+
173
+ loaded = await maafw.load_resource(Path(dir_input.value))
174
+ if not loaded:
175
+ GlobalStatus.res_loading = Status.FAILURE
176
+ return
177
+
178
+ GlobalStatus.res_loading = Status.SUCCESS
179
+
180
+
181
+ async def run_task_control():
182
+ StatusIndicator(GlobalStatus, "task_running")
183
+
184
+ entry_input = (
185
+ ui.input(
186
+ "Task Entry",
187
+ placeholder="eg: StartUp",
188
+ )
189
+ .props("size=30")
190
+ .bind_value(app.storage.general, "task_entry")
191
+ )
192
+
193
+ ui.button("Start", on_click=lambda: on_click_start())
194
+ ui.button("Stop", on_click=lambda: on_click_stop())
195
+
196
+ async def on_click_start():
197
+ GlobalStatus.task_running = Status.RUNNING
198
+
199
+ if not entry_input.value:
200
+ GlobalStatus.task_running = Status.FAILURE
201
+ return
202
+
203
+ run = await maafw.run_task(entry_input.value)
204
+ if not run:
205
+ GlobalStatus.task_running = Status.FAILURE
206
+ return
207
+
208
+ GlobalStatus.task_running = Status.SUCCESS
209
+
210
+ async def on_click_stop():
211
+ stopped = await maafw.stop_task()
212
+ if not stopped:
213
+ GlobalStatus.task_running = Status.FAILURE
214
+ return
215
+
216
+ GlobalStatus.task_running = Status.PENDING
217
+ await maafw.screenshotter.refresh(True)
@@ -0,0 +1,95 @@
1
+ from collections import defaultdict
2
+ from dataclasses import dataclass
3
+
4
+ from nicegui import ui
5
+
6
+ from ...maafw import maafw
7
+ from ...webpage.components.status_indicator import Status, StatusIndicator
8
+ from ...webpage.reco_page import RecoData
9
+
10
+
11
+ async def main():
12
+ Controls.recognition_row.register()
13
+
14
+
15
+ class RecognitionRow:
16
+
17
+ def __init__(self) -> None:
18
+ self.row_len = 0
19
+ self.data = defaultdict(dict)
20
+
21
+ def register(self):
22
+ self.row = ui.row()
23
+
24
+ maafw.on_list_to_recognize = self.on_list_to_recognize
25
+ maafw.on_miss_all = self.on_miss_all
26
+ maafw.on_recognition_result = self.on_recognition_result
27
+
28
+ def on_list_to_recognize(self, pre_hit, list_to_reco):
29
+ self.row_len = self.row_len + 1
30
+
31
+ self.cur_list = list_to_reco
32
+ self.next_reco_index = 0
33
+
34
+ with self.row:
35
+ self._add_list(pre_hit, list_to_reco)
36
+
37
+ def _add_list(self, pre_hit, list_to_reco):
38
+ with ui.list().props("bordered separator"):
39
+ ui.item_label(pre_hit).props("header").classes("text-bold")
40
+ ui.separator()
41
+
42
+ for index in range(len(list_to_reco)):
43
+ name = list_to_reco[index]
44
+ self._add_item(index, name)
45
+
46
+ @dataclass
47
+ class ItemData:
48
+ col: int
49
+ row: int
50
+ name: str
51
+ reco_id: int = 0
52
+ status: Status = Status.PENDING
53
+
54
+ def _add_item(self, index, name):
55
+ data = RecognitionRow.ItemData(self.row_len, index, name)
56
+ self.data[self.row_len][index] = data
57
+
58
+ with ui.item(on_click=lambda data=data: self.on_click_item(data)):
59
+ with ui.item_section().props("side"):
60
+ StatusIndicator(data, "status")
61
+
62
+ with ui.item_section():
63
+ ui.item_label(name)
64
+
65
+ with ui.item_section().props("side"):
66
+ ui.item_label().bind_text_from(data, "reco_id").bind_visibility_from(
67
+ data, "reco_id", backward=lambda i: i != 0
68
+ ).props("caption")
69
+
70
+ def on_click_item(self, data: ItemData):
71
+ print(f"on_click_item ({data.col}, {data.row}): {data.name} ({data.reco_id})")
72
+
73
+ ui.navigate.to(f"reco/{data.reco_id}", new_tab=True)
74
+
75
+ def on_recognition_result(self, reco_id: int, name: str, hit: bool):
76
+ target = None
77
+ for item in self.data[self.row_len].values():
78
+ if item.status == Status.PENDING and item.name == name:
79
+ target = item
80
+ break
81
+
82
+ if not target:
83
+ return
84
+
85
+ target.reco_id = reco_id
86
+ target.status = hit and Status.SUCCESS or Status.FAILURE
87
+
88
+ RecoData.data[reco_id] = name, hit
89
+
90
+ def on_miss_all(self, pre_hit, list_to_reco):
91
+ pass
92
+
93
+
94
+ class Controls:
95
+ recognition_row = RecognitionRow()
@@ -0,0 +1,38 @@
1
+ from typing import Dict, Tuple
2
+
3
+ from maa.instance import Instance
4
+ from nicegui import ui
5
+
6
+ from ...utils import cvmat_to_image
7
+
8
+
9
+ class RecoData:
10
+ data: Dict[int, Tuple[str, bool]] = {}
11
+
12
+
13
+ @ui.page("/reco/{reco_id}")
14
+ def reco_page(reco_id: int):
15
+ if reco_id == 0 or not reco_id in RecoData.data:
16
+ ui.markdown("## Not Found")
17
+ return
18
+
19
+ name, hit = RecoData.data[reco_id]
20
+ status = hit and "✅" or "❌"
21
+ title = f"{status} {name} ({reco_id})"
22
+
23
+ ui.page_title(title)
24
+ ui.markdown(f"## {title}")
25
+
26
+ ui.separator()
27
+
28
+ details = Instance.query_recognition_detail(reco_id)
29
+ if not details:
30
+ ui.markdown("## Not Found")
31
+ return
32
+
33
+ ui.markdown(f"#### Hit: {str(details.hit_box)}")
34
+
35
+ for draw in details.draws:
36
+ ui.image(cvmat_to_image(draw)).props("fit=scale-down")
37
+
38
+ ui.json_editor({"content": {"json": details.detail}, "readOnly": True})