Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1202dffa32 | ||
|
|
e24b0bdd1e | ||
|
|
1c686a6595 | ||
|
|
9c8a037c4e | ||
|
|
94e0c6432f | ||
|
|
51c1c2da39 | ||
|
|
60306dd4e0 | ||
|
|
329b7756f4 | ||
|
|
16019ee649 | ||
|
|
60332db82b | ||
|
|
c2cbee9592 | ||
|
|
ab37165baf | ||
|
|
c0cb274728 | ||
|
|
a870e0cbf9 | ||
|
|
13aa60c06a | ||
|
|
f010853b97 | ||
|
|
ee3424cd9e | ||
|
|
7c6189fd5e | ||
|
|
7745f9a57f | ||
|
|
f5a77867ee | ||
|
|
407c3b37c2 | ||
|
|
e315aaf80b | ||
|
|
7234bf0cac | ||
|
|
39996405d5 | ||
|
|
383c947a03 | ||
|
|
63c726ddea | ||
|
|
f257c4e3fc | ||
|
|
ecbd07cea0 | ||
|
|
5aeeef4aee | ||
|
|
9a75b9b481 | ||
|
|
872d114a0f | ||
|
|
a7d6bc87b6 | ||
|
|
cf2b71f831 | ||
|
|
3ab15e69f9 | ||
|
|
8e8a14cf69 | ||
|
|
164f76658c | ||
|
|
ffebc8d0dc | ||
|
|
61d3ad5d83 | ||
|
|
df46d723c3 | ||
|
|
e41796d43a | ||
|
|
2b12ddbec3 | ||
|
|
d0166d27d3 | ||
|
|
9062ee7204 | ||
|
|
008d7f82b3 | ||
|
|
4dea1328ec | ||
|
|
dc34b7484b | ||
|
|
ed0aca5f28 | ||
|
|
33c6f7a54f | ||
|
|
91a3aa5abf | ||
|
|
a2a899bb9f | ||
|
|
3ace80dcca | ||
|
|
ab664e4da8 | ||
|
|
7086ab1d6e | ||
|
|
5ebca337eb | ||
|
|
7890320ff7 | ||
|
|
18908aeff7 | ||
|
|
bd762f6be6 | ||
|
|
1bef130e51 | ||
|
|
5d3d58a2f9 | ||
|
|
25df550304 | ||
|
|
4af2adc4d6 | ||
|
|
77413fa7d1 | ||
|
|
aeeabd8ba2 | ||
|
|
25876bd25a | ||
|
|
a449b7634c | ||
|
|
0efdc83d0b | ||
|
|
920c51d460 | ||
|
|
ba9ac4cb0e | ||
|
|
f95832579a | ||
|
|
5c7d341d9b | ||
|
|
ba2e159cad | ||
|
|
fe53debeb1 | ||
|
|
d81e00ddbc | ||
|
|
3c7cb45bec | ||
|
|
86bf5cefb1 | ||
|
|
debf016d23 | ||
|
|
0c91367c07 | ||
|
|
25f7f9af9e | ||
|
|
e286cd46c8 | ||
|
|
8389f85124 | ||
|
|
84b9143fa6 | ||
|
|
20e438ee13 | ||
|
|
5c98bb8353 | ||
|
|
b533c4e96e | ||
|
|
8fac904ba9 | ||
|
|
680c02d362 | ||
|
|
4891f3b019 | ||
|
|
0f1baac92f | ||
|
|
f129206df7 | ||
|
|
d4931b6820 | ||
|
|
48b0a32e24 | ||
|
|
a06218dd16 | ||
|
|
23abd486af | ||
|
|
17068c7928 | ||
|
|
b3d3f28ff3 | ||
|
|
58c1856fad | ||
|
|
78a75d4843 | ||
|
|
32fcbc4c24 | ||
|
|
6b987fd04f | ||
|
|
aa3690fecf | ||
|
|
207748a901 | ||
|
|
040ccd8161 | ||
|
|
c5b7198145 | ||
|
|
0c8166d616 | ||
|
|
2042c56257 | ||
|
|
2a7f4f38ab | ||
|
|
9ed73bf64b | ||
|
|
ce0e9a3585 | ||
|
|
9c329caf72 | ||
|
|
b850afae2c | ||
|
|
240f49825f | ||
|
|
a39545ed5d | ||
|
|
ec51772cf0 | ||
|
|
d6312d8813 | ||
|
|
28709d2d97 | ||
|
|
cb74a23e81 | ||
|
|
05be83d289 | ||
|
|
b2db5ed499 | ||
|
|
a25336770f | ||
|
|
00821d0926 | ||
|
|
c557ce0dfb | ||
|
|
8dbaab9d27 | ||
|
|
fc96549bd2 | ||
|
|
b9b580f521 | ||
|
|
22e2ed1508 | ||
|
|
160b4f1a2d | ||
|
|
8e7be541d3 | ||
|
|
89fb278988 | ||
|
|
b9c5106f62 | ||
|
|
b74baef555 | ||
|
|
c97e4edc74 | ||
|
|
fe1a62e92d | ||
|
|
e977f6054d | ||
|
|
b61f766ea6 | ||
|
|
55d38c46ec | ||
|
|
d48fa4eec3 | ||
|
|
9ffbe47bdb | ||
|
|
daa4d1709d | ||
|
|
079bf8537a | ||
|
|
1adaefdce6 | ||
|
|
dbf9b14fac | ||
|
|
cc4caef6e1 | ||
|
|
abcee63776 | ||
|
|
11de0f75c7 | ||
|
|
5166678590 | ||
|
|
b1c2128d72 | ||
|
|
8d1bb28531 | ||
|
|
87838daad4 | ||
|
|
6279b129cb | ||
|
|
207cf0eadb | ||
|
|
62c84939ee | ||
|
|
cd7615db3c | ||
|
|
e3bf99149d | ||
|
|
9b03556b7d | ||
|
|
37a2f94486 | ||
|
|
5e2ca0587b | ||
|
|
f07fbb305b | ||
|
|
1d564000ca | ||
|
|
dc6ae7d1e4 | ||
|
|
0c77bf9e0e | ||
|
|
ca7d64d54b | ||
|
|
4797fa046e | ||
|
|
bcc4d1151f | ||
|
|
daf0c49288 | ||
|
|
198a30dce1 | ||
|
|
71a9f4a25f | ||
|
|
40f9812ab1 | ||
|
|
3bcb5cb259 | ||
|
|
42aa0f214d | ||
|
|
24b58a8c6d | ||
|
|
e51d37890a | ||
|
|
168ab4e1f8 | ||
|
|
098083a354 | ||
|
|
1d37d57c90 | ||
|
|
2c6f024a24 | ||
|
|
02a4dc625a | ||
|
|
147892a144 | ||
|
|
05b9d17951 | ||
|
|
879bb70075 | ||
|
|
36e374ef67 | ||
|
|
1845561405 | ||
|
|
5d2d39b3e6 | ||
|
|
eaa14ce52f | ||
|
|
7ebbdd6c1e | ||
|
|
c2010084cf | ||
|
|
33d05fac54 | ||
|
|
5ae113cc18 | ||
|
|
c7d6829219 | ||
|
|
fa7e5070b3 | ||
|
|
439aa944c7 | ||
|
|
6df926eabd | ||
|
|
a0bfb70b34 | ||
|
|
d696f2c974 | ||
|
|
3ce3a03f62 | ||
|
|
93d950e78f | ||
|
|
a35b0371ae | ||
|
|
a6563c11f4 | ||
|
|
204ed24c67 | ||
|
|
60741369f2 | ||
|
|
eea0c48a44 | ||
|
|
5a51c951a2 | ||
|
|
61dfc1c15c | ||
|
|
a68307d7fd | ||
|
|
e33b42597c | ||
|
|
f76232f2fc | ||
|
|
de21921d03 | ||
|
|
37f736c158 | ||
|
|
3659d5b7da | ||
|
|
1ef7325ead | ||
|
|
e03dcaa183 | ||
|
|
458779e809 | ||
|
|
c361eb4db6 | ||
|
|
4db6431757 | ||
|
|
8351908232 | ||
|
|
3bc997a4d7 | ||
|
|
48d18daef8 | ||
|
|
c6a4410180 | ||
|
|
a8d1b24dc9 | ||
|
|
a94a6d2a71 | ||
|
|
3491970090 | ||
|
|
01ce77eaa6 | ||
|
|
034e55072a | ||
|
|
ec2f044d8c | ||
|
|
18b75ceda4 | ||
|
|
e9b003f906 | ||
|
|
95459607dc | ||
|
|
0d4796744d | ||
|
|
1cd94e9705 | ||
|
|
8c2d93a79f | ||
|
|
92d60f9931 | ||
|
|
29b9788371 | ||
|
|
7eeaab9a6e | ||
|
|
089cb32e1c | ||
|
|
a06ece4e15 | ||
|
|
6cebed599d | ||
|
|
da5e000006 | ||
|
|
065d73ff9a | ||
|
|
adbd8a2d6e | ||
|
|
1235c5910f | ||
|
|
84c5731cc3 | ||
|
|
8e0ae9396d | ||
|
|
a6648c5ce8 | ||
|
|
f75d3ae368 | ||
|
|
d9920f1cee | ||
|
|
e763cdc302 | ||
|
|
fd694f8ce5 | ||
|
|
547228fa2d | ||
|
|
e7d848023c | ||
|
|
a1562a513d | ||
|
|
b8f2806ffc | ||
|
|
9642b7b0f8 | ||
|
|
9896eb676a | ||
|
|
e0c68883dd | ||
|
|
e0cad29daf | ||
|
|
6a8296cab1 | ||
|
|
3626e9cf6f | ||
|
|
29d930b1de | ||
|
|
df758cf224 | ||
|
|
47865f5dfa | ||
|
|
9744b75878 | ||
|
|
200f3a53fc | ||
|
|
7a840120b3 | ||
|
|
e314161b6c | ||
|
|
3a7a7a3b75 | ||
|
|
8575f04ab9 | ||
|
|
728ef3cd79 | ||
|
|
32e374e2c2 | ||
|
|
aa0f4e05f2 | ||
|
|
5e3015f59b | ||
|
|
dc1744a93f | ||
|
|
b686a4e3d5 | ||
|
|
29cef2c578 | ||
|
|
e784efd5f8 | ||
|
|
6c7bbf0945 | ||
|
|
fe27063913 | ||
|
|
3f04bb23c2 | ||
|
|
bcb0e363d1 | ||
|
|
b447b6a6a4 | ||
|
|
3ac8664817 | ||
|
|
6bac014c3d | ||
|
|
3d433080c2 | ||
|
|
f6d382b0e7 | ||
|
|
2a05be2319 | ||
|
|
f9839f3dee | ||
|
|
97935d9c48 | ||
|
|
64c210dd5a | ||
|
|
68d1224b53 | ||
|
|
92d524297b | ||
|
|
59ebe8c1e7 | ||
|
|
a7ef92fc7c | ||
|
|
c5df7a05d2 | ||
|
|
b3380042b8 | ||
|
|
4993fad004 | ||
|
|
44b091466d | ||
|
|
8ea676562c | ||
|
|
a07ef00b5e | ||
|
|
5329561b3a | ||
|
|
6bffcae2de | ||
|
|
ac464788e1 | ||
|
|
8dace383ec | ||
|
|
26f9e5a553 | ||
|
|
bb90e2983f | ||
|
|
c3746b0207 | ||
|
|
b1fa6af9ce | ||
|
|
96fdc96f24 | ||
|
|
c4544489ac | ||
|
|
d19d5bfc56 | ||
|
|
703da834fb | ||
|
|
4908df19d4 | ||
|
|
ca00258bf3 | ||
|
|
e62314fa25 | ||
|
|
df69c6ab67 | ||
|
|
a50f08de5a | ||
|
|
8fd38dd30b | ||
|
|
d850af2c44 | ||
|
|
2fab3f238e | ||
|
|
f750969df3 | ||
|
|
842dd254e3 | ||
|
|
6f38907119 | ||
|
|
470c68a252 | ||
|
|
fe97e82104 | ||
|
|
9f330572cc | ||
|
|
4277bf7fa4 | ||
|
|
ca6c2e4d20 | ||
|
|
7884132743 | ||
|
|
9fbfcb5ed2 | ||
|
|
87bac9e548 | ||
|
|
d759921442 | ||
|
|
be1eb6eda7 | ||
|
|
3b8f85b9cb | ||
|
|
fb35670032 | ||
|
|
230c0d4049 | ||
|
|
a864f6e23a | ||
|
|
3a9f01ad74 | ||
|
|
8ecd2783db | ||
|
|
e737002b1e | ||
|
|
df273ab231 | ||
|
|
d60b83af68 | ||
|
|
e46497ea80 | ||
|
|
8457219241 | ||
|
|
b200002a00 | ||
|
|
ab846dae0f | ||
|
|
07cdd662c2 | ||
|
|
1514122981 | ||
|
|
f718dfe2e4 | ||
|
|
2f0eb90d98 | ||
|
|
f38b373636 | ||
|
|
457edcfdc8 | ||
|
|
03b471513d | ||
|
|
2707773b15 | ||
|
|
07eee6da52 | ||
|
|
52b811d0cb | ||
|
|
4ab4504425 | ||
|
|
fb82213d53 | ||
|
|
ffd048ffa5 | ||
|
|
61cdf7b445 | ||
|
|
ca953cb4ba | ||
|
|
aeb51f73c7 | ||
|
|
0540610c75 | ||
|
|
7b6dec820b | ||
|
|
8a975f2bf6 | ||
|
|
cea3aced73 | ||
|
|
5966f461c3 | ||
|
|
3d91764f56 | ||
|
|
8c3a162deb | ||
|
|
b3a41db029 | ||
|
|
a71f6faed0 | ||
|
|
db7a78876b | ||
|
|
e89393693b | ||
|
|
23d370ae22 | ||
|
|
a92cec4ff9 | ||
|
|
4c1d95d4b5 | ||
|
|
3aca02fae4 | ||
|
|
695a84d8b5 | ||
|
|
5802586b20 | ||
|
|
66eb05e6b1 | ||
|
|
5a40b49727 | ||
|
|
266c7f2932 | ||
|
|
59ac6a3abc | ||
|
|
df628c11dd | ||
|
|
6996c7813e | ||
|
|
0efcfff545 | ||
|
|
b0eccc5171 | ||
|
|
e8bf904fc6 | ||
|
|
8d98143df1 | ||
|
|
b5a15ecea4 | ||
|
|
73008a9763 | ||
|
|
5309aa0198 | ||
|
|
85d7bb2525 | ||
|
|
3269d3adf6 | ||
|
|
7ef5bc3e07 | ||
|
|
2c8879be7a | ||
|
|
6ecedbbde1 | ||
|
|
cdf8be0ded | ||
|
|
a6dee879e7 | ||
|
|
9f7e8da57a | ||
|
|
6bdf7b2527 | ||
|
|
af8145b8a8 | ||
|
|
e417acfb7c | ||
|
|
2d928c3856 | ||
|
|
57d99f3459 | ||
|
|
a337b4b93d | ||
|
|
57eacb3219 | ||
|
|
254820e6dc | ||
|
|
246c80498e | ||
|
|
badf64998d | ||
|
|
a6bbdcc400 | ||
|
|
ef6ca4a650 | ||
|
|
c442335b34 | ||
|
|
4ab1b88fa0 | ||
|
|
85bd488f66 | ||
|
|
7715b93eca | ||
|
|
2523668b4c | ||
|
|
e7faceeb5f | ||
|
|
9d1b0c1e36 | ||
|
|
74209035f7 | ||
|
|
787c4e8eec | ||
|
|
19e347e6c1 | ||
|
|
c0b8ff3ba6 | ||
|
|
bf7f30996e | ||
|
|
a6ce16f9c4 | ||
|
|
e35e8a85bd | ||
|
|
778c021272 | ||
|
|
ca4941b66d | ||
|
|
7d31075ce3 | ||
|
|
dba43e18f9 | ||
|
|
a39da30d16 | ||
|
|
601e701823 | ||
|
|
f6c9bb938c | ||
|
|
872722522c | ||
|
|
87d0fe2db8 | ||
|
|
ecffba94b4 | ||
|
|
818c3139b1 | ||
|
|
941bbc2475 | ||
|
|
c802f62796 | ||
|
|
b6d2836e84 | ||
|
|
af4fc9168b | ||
|
|
a84ec29145 | ||
|
|
16d9bde4a0 | ||
|
|
e5c5ce06ee | ||
|
|
20aefbb3a1 | ||
|
|
ae3f276f56 | ||
|
|
a46901ef5d | ||
|
|
9e189c711c | ||
|
|
c5c8def884 | ||
|
|
80b35bcb6c | ||
|
|
cc1d4f0897 | ||
|
|
5efa0ebc8b | ||
|
|
0e74bfba77 | ||
|
|
c92af75d02 | ||
|
|
6ac99530d6 | ||
|
|
0c62696118 | ||
|
|
9c3cf86f41 | ||
|
|
0d01dabb69 | ||
|
|
7001919642 | ||
|
|
95255a4498 | ||
|
|
540ee24861 | ||
|
|
b161a2c4a6 | ||
|
|
ac55428640 | ||
|
|
6fb7707abb | ||
|
|
4f147d214e | ||
|
|
0700a378ec | ||
|
|
d5c9936c88 | ||
|
|
7dd1c3ea88 | ||
|
|
10ad6575c7 | ||
|
|
9a51b41c3d | ||
|
|
0131be7869 | ||
|
|
7fb0c3849c | ||
|
|
c878491163 | ||
|
|
6ef04c1f37 | ||
|
|
71f3653354 | ||
|
|
521b7b9e84 | ||
|
|
b96a67b6b8 | ||
|
|
7d63a36125 | ||
|
|
0a0b59c908 | ||
|
|
2e811e71b3 | ||
|
|
73cfb50a2b | ||
|
|
7f33d45df6 | ||
|
|
ba4c131b2d | ||
|
|
96f8600d42 | ||
|
|
938011f672 | ||
|
|
04035abbc0 | ||
|
|
a876d9ebb0 | ||
|
|
5a381698d8 | ||
|
|
4557dfb306 | ||
|
|
49704834d8 | ||
|
|
41c3f28eb7 | ||
|
|
16b3bde893 | ||
|
|
df96f25eba | ||
|
|
cea5f1df45 | ||
|
|
f16eadbd75 | ||
|
|
632951d004 | ||
|
|
51d8d53a2b | ||
|
|
94e8d37d18 | ||
|
|
16042d7fd2 | ||
|
|
a40ddc3083 | ||
|
|
3295cb3d6f | ||
|
|
cdaa9e4c69 | ||
|
|
8b8e3129e5 | ||
|
|
0a2d67afb4 | ||
|
|
d1f153b373 | ||
|
|
857b33f413 | ||
|
|
07700c24d9 | ||
|
|
96cba09c49 | ||
|
|
aa5065590a | ||
|
|
276235408e | ||
|
|
299ced21c8 | ||
|
|
b7d7f61a27 | ||
|
|
242876f679 | ||
|
|
9edfcc2449 | ||
|
|
61ec06092d | ||
|
|
7d834d316f | ||
|
|
e38640eb63 | ||
|
|
0031f17ebc | ||
|
|
2d6cbecf7e | ||
|
|
bdde741db1 | ||
|
|
996990be31 | ||
|
|
a065c12d0c | ||
|
|
6e8e5d1102 | ||
|
|
b137aead48 | ||
|
|
cb4d25abdf | ||
|
|
8fe7ff0585 | ||
|
|
e3e399da70 | ||
|
|
309b629e7c | ||
|
|
77e797ae1c | ||
|
|
a19fa35a0f | ||
|
|
a2d6bd2cc3 | ||
|
|
31d4102696 | ||
|
|
da0c4ca3dc | ||
|
|
3ed352ef0e | ||
|
|
1a0afe86a1 | ||
|
|
92718a7cb4 | ||
|
|
9bd10277b2 | ||
|
|
92753c51a5 | ||
|
|
6b22939c7e | ||
|
|
68a2ab73ba | ||
|
|
61d72b2b8d | ||
|
|
1dea80d5be | ||
|
|
5ce314b41c | ||
|
|
84e8d0c46d | ||
|
|
ff8de2c9b8 | ||
|
|
1fdec7a548 | ||
|
|
38e2b399d4 | ||
|
|
caa24ea8ca | ||
|
|
6c73f6e414 | ||
|
|
674ede76ee | ||
|
|
13b1f2150c | ||
|
|
e7a7d3f888 | ||
|
|
89128deb0f |
No files matched your search
@@ -1,4 +1,4 @@
|
||||
# Copilot 指令(douyin_guaji-main)
|
||||
# Copilot 指令(本仓库)
|
||||
|
||||
## 来自 `docs/完整技术文档.md` 的补充(要点)
|
||||
- 版本:V4.5(2026-01-18)。本文件为实现细节与验证命令的权威来源,agent 在执行重大改动前请核对文档中的“验证要点”。
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
name: Windows Package CI
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "bin/**"
|
||||
- "douyin/**"
|
||||
- "gui/**"
|
||||
- "operations/**"
|
||||
- "packaging/**"
|
||||
- "tools/**"
|
||||
- "tests/**"
|
||||
- "webui/**"
|
||||
- "pyproject.toml"
|
||||
- "requirements.txt"
|
||||
- ".github/workflows/windows-package-ci.yml"
|
||||
|
||||
jobs:
|
||||
package-fresh-install:
|
||||
runs-on: windows-latest
|
||||
timeout-minutes: 90
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up Python
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: "3.12"
|
||||
cache: "pip"
|
||||
|
||||
- name: Install Inno Setup
|
||||
shell: powershell
|
||||
run: choco install innosetup --yes --no-progress
|
||||
|
||||
- name: Install Python dependencies
|
||||
shell: powershell
|
||||
run: |
|
||||
python -m pip install --upgrade pip
|
||||
python -m pip install -r requirements.txt
|
||||
python -m pip install pyinstaller cython setuptools wheel
|
||||
|
||||
- name: Run fast regression tests
|
||||
shell: powershell
|
||||
run: >
|
||||
python -m pytest
|
||||
tests/test_web_gui_routes_logic.py
|
||||
tests/test_startup_update_bootstrap.py
|
||||
tests/test_distribution_manifest.py
|
||||
tests/test_exe_packing.py
|
||||
tests/test_auto_update.py
|
||||
tests/test_version_consistency.py
|
||||
tests/test_tools_dev.py
|
||||
tests/test_ci_fresh_install.py
|
||||
|
||||
- name: Build portable package
|
||||
shell: powershell
|
||||
run: powershell -NoProfile -ExecutionPolicy Bypass -File packaging\pyinstaller\build_windows.ps1 -SkipInstall -ReuseCache
|
||||
|
||||
- name: Build installer
|
||||
shell: powershell
|
||||
run: |
|
||||
$version = python -c "from douyin.core.version import APP_VERSION; print(str(APP_VERSION).lstrip('Vv'))"
|
||||
$iscc = @(
|
||||
"${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe",
|
||||
"${env:ProgramFiles}\Inno Setup 6\ISCC.exe",
|
||||
"${env:LOCALAPPDATA}\Programs\Inno Setup 6\ISCC.exe"
|
||||
) | Where-Object { Test-Path $_ } | Select-Object -First 1
|
||||
if (-not $iscc) { throw "ISCC.exe not found" }
|
||||
& $iscc packaging\inno\douyin_guaji.iss /DMyAppVersion=$version
|
||||
|
||||
- name: Fresh install smoke test
|
||||
shell: powershell
|
||||
run: powershell -NoProfile -ExecutionPolicy Bypass -File tools\ci\fresh_install_smoke.ps1
|
||||
|
||||
- name: Upload package and smoke report
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: douyin-guaji-windows-package
|
||||
path: |
|
||||
dist/installer/*.exe
|
||||
artifacts/fresh_install_ci/**
|
||||
if-no-files-found: ignore
|
||||
@@ -1,78 +1,163 @@
|
||||
# Python
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# Virtual env
|
||||
# Python build artifacts
|
||||
build/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# Virtual environments
|
||||
.venv/
|
||||
venv/
|
||||
env/
|
||||
ENV/
|
||||
.env
|
||||
.env/
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Runtime artifacts
|
||||
# Python tooling caches
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
.pyre/
|
||||
.pytype/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
coverage.xml
|
||||
htmlcov/
|
||||
pip-wheel-metadata/
|
||||
|
||||
# Type check / lint reports
|
||||
pylint_report.txt
|
||||
pyright_report.txt
|
||||
*.report
|
||||
*.lint
|
||||
|
||||
# Logs and runtime traces
|
||||
logs/
|
||||
*.log
|
||||
pic/
|
||||
*.log.*
|
||||
*.trace
|
||||
*.pid
|
||||
.web_gui_pid
|
||||
git_lsremote_trace.txt
|
||||
log_filter_result.txt
|
||||
time_analysis_result.txt
|
||||
|
||||
# Tools generated reports
|
||||
# Tools generated reports (ignore any large/temporary csv reports)
|
||||
# Test/diagnostic outputs
|
||||
output/
|
||||
artifacts/*
|
||||
!artifacts/webui_checks/
|
||||
artifacts/ocr_check/
|
||||
artifacts/fudai_regression_runs/
|
||||
artifacts/fudai_regression_samples/
|
||||
artifacts/webui_checks/**/*.png
|
||||
artifacts/webui_checks/**/*.txt
|
||||
artifacts/webui_checks/**/*.json
|
||||
|
||||
# Local runtime state and generated caches
|
||||
state/
|
||||
pic/
|
||||
screenshots/
|
||||
captures/
|
||||
tmp/
|
||||
temp/
|
||||
.tmp/
|
||||
*.tmp
|
||||
*.temp
|
||||
*.cache
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.db
|
||||
*.db-journal
|
||||
*.db-shm
|
||||
*.db-wal
|
||||
*.jsonl
|
||||
.stats_test_cache.json
|
||||
.web_stats_cache.json
|
||||
|
||||
# Local configuration and backups
|
||||
config/*.json
|
||||
!config/README.md
|
||||
license.dat
|
||||
*.bak
|
||||
*.bak_*
|
||||
*.backup
|
||||
*.orig
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# Generated tool reports and samples
|
||||
*.spec
|
||||
tools/coords_report*.csv
|
||||
tools/*_report*.csv
|
||||
tools/*_report*.csv.gz
|
||||
tools/*.csv
|
||||
|
||||
# Tools sample/ocr artifacts
|
||||
tools/ocr_failures*
|
||||
tools/ocr_failures/
|
||||
tools/samples/
|
||||
tools/*.zip
|
||||
tools/*.tar.gz
|
||||
tools/*.bundle
|
||||
tools/tmp_pw_check.py
|
||||
|
||||
# Logs (keep local logs out of VCS)
|
||||
logs/
|
||||
*.log*
|
||||
logs/*.gz
|
||||
*.log
|
||||
|
||||
# Archive and backup files
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
*.bak
|
||||
*.bundle
|
||||
|
||||
# Large DB / cache files
|
||||
*.sqlite
|
||||
*.db
|
||||
*.db-journal
|
||||
|
||||
# Editor/project user files
|
||||
.idea/
|
||||
*.suo
|
||||
*.user
|
||||
*.sln.docstates
|
||||
|
||||
# Code analysis reports
|
||||
pylint_report.txt
|
||||
pyright_report.txt
|
||||
*.report
|
||||
*.lint
|
||||
|
||||
# Test coverage
|
||||
.coverage
|
||||
.coverage.*
|
||||
htmlcov/
|
||||
.tox/
|
||||
.pytest_cache/
|
||||
|
||||
# VS Code
|
||||
.vscode/
|
||||
|
||||
# Cursor IDE
|
||||
.cursor/
|
||||
.specstory/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
# Project-specific generated state
|
||||
douyin/core/state/reservations.json
|
||||
state/high_value_rooms.json
|
||||
douyin/core/state/room_pos_map.csv
|
||||
douyin/core/state/room_pos_map.json
|
||||
douyin/core/state/room_pos_map.md
|
||||
state/high_value_rooms.json
|
||||
|
||||
# Archives and bundles
|
||||
*.zip
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
*.rar
|
||||
*.7z
|
||||
*.bundle
|
||||
|
||||
# Local migration scratch notes
|
||||
docs/json_migration_note.txt
|
||||
|
||||
# Node / frontend caches
|
||||
node_modules/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
.parcel-cache/
|
||||
.next/
|
||||
.vite/
|
||||
|
||||
# IDE and editor files
|
||||
.vscode/
|
||||
.idea/
|
||||
.cursor/
|
||||
.specstory/
|
||||
*.suo
|
||||
*.user
|
||||
*.userosscache
|
||||
*.sln.docstates
|
||||
|
||||
# OS files
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
ehthumbs.db
|
||||
Desktop.ini
|
||||
@@ -1 +0,0 @@
|
||||
{"ts": 1765641063.2151546, "counters": {"fudai_seen": 1, "fudai_open_detail": 1, "fudai_click_attend": 1, "fudai_attend_ok": 1, "fudai_result_win": 1}, "fudai_last": {"content": "测试内容A", "countdown": "10:00后开奖", "participants": 123, "copies": 5, "prize_value_yuan": 199.0, "updated_ts": 1765641063.1966858}, "events": [{"ts": 1765641063.1946857, "type": "fudai_seen", "meta": {"content": "测试内容A", "countdown": "", "participants": null, "copies": null, "prize_value_yuan": null}}, {"ts": 1765641063.1966858, "type": "fudai_open_detail", "meta": {"content": "测试内容A", "countdown": "10:00后开奖", "participants": 123, "copies": 5, "prize_value_yuan": 199.0}}, {"ts": 1765641063.1966858, "type": "fudai_click_attend", "meta": {"content": "测试内容A", "countdown": "10:00后开奖", "participants": 123, "copies": 5, "prize_value_yuan": 199.0}}, {"ts": 1765641063.1966858, "type": "fudai_attend_ok", "meta": {"content": "测试内容A", "countdown": "10:00后开奖", "participants": 123, "copies": 5, "prize_value_yuan": 199.0}}, {"ts": 1765641063.1966858, "type": "fudai_result_win", "meta": {"content": "测试内容A", "countdown": "10:00后开奖", "participants": 123, "copies": 5, "prize_value_yuan": 199.0}}], "wins": [{"ts": 1765641063.1966858, "content": "测试内容A", "countdown": "10:00后开奖", "participants": 123, "copies": 5, "prize_value_yuan": 199.0}]}
|
||||
@@ -1 +0,0 @@
|
||||
21948
|
||||
@@ -1 +0,0 @@
|
||||
{"ts": 1765685532.6116447, "counters": {"fudai_open_detail": 74, "fudai_seen": 80, "fudai_skip_value_low": 28, "fudai_open_error": 8, "switch_room": 40, "switch_room_no_fudai": 28, "fudai_skip_countdown_short": 3, "switch_room_countdown": 3, "switch_room_value": 8, "fudai_click_attend": 2, "fudai_result_no_win": 2}, "fudai_last": {"content": "【粉丝专属】iPhone17手机256G颜色随机", "countdown": "14:29后开奖", "participants": 2132, "copies": 1, "prize_value_yuan": 5999.0, "updated_ts": 1765684579.3024325}, "events": [{"ts": 1765641806.1646142, "type": "fudai_open_detail", "meta": {"content": "", "countdown": "", "participants": null, "copies": null, "prize_value_yuan": null}}, {"ts": 1765641813.7004516, "type": "fudai_seen", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "", "participants": null, "copies": null, "prize_value_yuan": null}}, {"ts": 1765641815.2687662, "type": "fudai_skip", "meta": {"reason": "value_low", "content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "07:19后开奖", "participants": 32, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641819.8364112, "type": "fudai_open_detail", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "07:19后开奖", "participants": 32, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641826.9612343, "type": "fudai_seen", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "07:19后开奖", "participants": 32, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641829.2069504, "type": "fudai_skip", "meta": {"reason": "value_low", "content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "04:07", "participants": 34, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641833.980556, "type": "fudai_open_detail", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "04:07", "participants": 34, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641841.1970615, "type": "fudai_seen", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "04:07", "participants": 34, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641842.785327, "type": "fudai_skip", "meta": {"reason": "value_low", "content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:50后开奖", "participants": 34, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641848.7064586, "type": "fudai_open_detail", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:50后开奖", "participants": 34, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641857.2592785, "type": "fudai_seen", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:50后开奖", "participants": 34, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641858.9027817, "type": "fudai_skip", "meta": {"reason": "value_low", "content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:35后开奖", "participants": 35, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641863.3506944, "type": "fudai_open_detail", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:35后开奖", "participants": 35, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641869.6957817, "type": "fudai_seen", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:35后开奖", "participants": 35, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641871.0666997, "type": "fudai_skip", "meta": {"reason": "value_low", "content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:21", "participants": 35, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641875.5607815, "type": "fudai_open_detail", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:21", "participants": 35, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641882.6100206, "type": "fudai_seen", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:21", "participants": 35, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641883.8911793, "type": "fudai_skip", "meta": {"reason": "value_low", "content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:09", "participants": 36, "copies": 1, "prize_value_yuan": 199.0}}, {"ts": 1765641888.1028545, "type": "fudai_open_detail", "meta": {"content": "【懒猫nono专属】海蓝之谜精萃水沁润15ml补水保湿...", "countdown": "06:09", "participants": 36, "copies": 1, "prize_value_yuan": 1Line truncated
|
||||
@@ -0,0 +1,9 @@
|
||||
# 项目级 Codex 指南
|
||||
|
||||
## Git 自动提交
|
||||
|
||||
- 本项目每次完成文件修改后,都要自动执行 Git 提交并推送到远端。
|
||||
- 提交前必须先检查工作区状态,只 stage 本次任务实际修改的文件。
|
||||
- 不要把用户已有的未提交改动、无关生成物或临时输出混入提交。
|
||||
- 提交前运行与改动相关的最小验证;无法验证时,在最终回复里说明原因。
|
||||
- 推送失败时,保留本地提交并明确说明失败原因和下一步处理建议。
|
||||
@@ -0,0 +1,186 @@
|
||||
# Changelog
|
||||
|
||||
本项目所有显著变更都会记录在这里。
|
||||
|
||||
格式遵循 [Keep a Changelog](https://keepachangelog.com/zh-CN/1.1.0/),
|
||||
版本号遵循 [Semantic Versioning](https://semver.org/lang/zh-CN/)(带 `V` 前缀,如 `V3.3.3`)。
|
||||
|
||||
变更类型:
|
||||
- `Added` 新增
|
||||
- `Changed` 调整
|
||||
- `Deprecated` 即将废弃
|
||||
- `Removed` 已移除
|
||||
- `Fixed` 修复
|
||||
- `Security` 安全相关
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [V3.3.11] — 2026-06-29
|
||||
## [V3.3.10] — 2026-06-29
|
||||
## [V3.3.9] — 2026-06-28
|
||||
### Fixed
|
||||
|
||||
- 自动更新差量包下载、校验或启动失败时自动回退完整安装包,避免旧版本反复卡在失败的 delta 更新上。
|
||||
- 记录已启动的差量更新尝试;如果下次启动仍停留在旧版本,则跳过同一个 delta 并改用完整安装包。
|
||||
|
||||
### Added
|
||||
|
||||
- Dashboard 顶部新增“检查更新”按钮,可手动触发在线更新检查。
|
||||
|
||||
### Changed
|
||||
|
||||
- 自动更新默认启用;未配置更新地址时默认使用官方更新服务器,仍可通过配置或环境变量关闭。
|
||||
|
||||
## [V3.3.8] — 2026-06-28
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复部分荣耀/华为设备上 `adb exec-out screencap -p` 返回 `4294967295` 或损坏 PNG 后,截图链路未继续尝试 shell stdout 兜底的问题。
|
||||
- 打包时收集 `paddlex` / `paddleocr` / Paddle / OpenCV / NumPy / PIL / pyclipper / shapely 运行依赖,避免新电脑上 OCR 初始化缺少 `_internal\paddlex\.version` 或相关二进制组件。
|
||||
|
||||
### Added
|
||||
|
||||
- Dashboard 新增“上传诊断日志”,客户端只打包有限大小的日志片段;服务端按卡密覆盖保存一份,便于远程排查问题。
|
||||
|
||||
## [V3.3.7] — 2026-06-28
|
||||
|
||||
### Changed
|
||||
|
||||
- Dashboard 首次启动未授权时锁定在“授权”页,验证卡密成功后再进入数据看板。
|
||||
- WebGUI 未授权访问首页时先显示卡密验证门禁页,验证成功后再加载完整控制台。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 保留运行接口的授权拦截,避免未输入卡密时通过接口直接启动运行。
|
||||
|
||||
## [V3.3.6] — 2026-06-27
|
||||
## [V3.3.5] — 2026-06-27
|
||||
## [V3.3.4] — 2026-06-26
|
||||
### Added
|
||||
|
||||
- 引入完整的版本管理体系:
|
||||
- `CHANGELOG.md`(Keep a Changelog 1.1.0 格式)
|
||||
- `tools/dev/bump_version.py`(自动 bump major/minor/patch + 同步 `version.py` / `pyproject.toml` / `CHANGELOG.md` + 创建 git tag)
|
||||
- `[project]` 元数据加入 `pyproject.toml`,与 `douyin/core/version.py` 保持单一事实来源
|
||||
- 给所有历史版本(V3.0.0 → V3.3.3)补齐 git tag
|
||||
|
||||
### Changed
|
||||
|
||||
- README「版本更新日志」段简化为指向 `CHANGELOG.md` 与 git tags
|
||||
|
||||
## [V3.3.3] — 2025-12-28
|
||||
|
||||
### Added
|
||||
|
||||
- 30 分钟超时保护机制:长时间无成功参与时自动返回推荐页重启流程
|
||||
|
||||
### Fixed
|
||||
|
||||
- 模板与截图路径配置统一,使用 `douyin/core/path_config.py`
|
||||
- 直播间检测模板文件路径错误
|
||||
- GUI / Web GUI 中行为日志读取路径
|
||||
|
||||
### Changed
|
||||
|
||||
- 路径配置全量统一化:用 `path_config.py` 集中管理,简化维护
|
||||
- 行为日志路径统一为 `path_config.get_actions_log_path()`
|
||||
- 流程图与文档:反映 30 分钟超时检查、阶段诊断步骤、预约回退子流程
|
||||
|
||||
## [V3.3.2] — 2025-12-25
|
||||
|
||||
### Fixed
|
||||
|
||||
- 预约回退功能不生效:
|
||||
- `needswitch` 配置未从 `config.json` 正确加载
|
||||
- `self.reservations` 未从状态文件加载
|
||||
- 预约回退逻辑加详细调试日志
|
||||
|
||||
### Changed
|
||||
|
||||
- 每次 `run_once_basic` 自动从状态文件加载预约队列,确保始终包含最新数据
|
||||
|
||||
## [V3.3.1] — 2025-12-14
|
||||
|
||||
### Added
|
||||
|
||||
- `live_room_match_threshold`:直播间检测阈值可配置
|
||||
- `fudai_icon_max_wait_seconds`:福袋图标检测等待时间可配置
|
||||
|
||||
### Fixed
|
||||
|
||||
- 直播间检测模板文件路径警告
|
||||
|
||||
### Changed
|
||||
|
||||
- 阶段检测优先使用像素检测
|
||||
- 合并阶段 1.5 与阶段 3 的 OCR 检测以减少冗余
|
||||
|
||||
## [V3.3.0]
|
||||
|
||||
### Changed
|
||||
|
||||
- 模块化重构:核心代码按职责拆分到 `douyin/` 各子包
|
||||
- 阶段检测策略调整:像素检测优先
|
||||
|
||||
### Added
|
||||
|
||||
- GUI 截图 + OCR 联合调试功能
|
||||
- 桌面 GUI「强制停止」按钮
|
||||
|
||||
### Fixed
|
||||
|
||||
- 多个已知问题(详情见 commit 历史)
|
||||
|
||||
## [V3.2.0]
|
||||
|
||||
### Added
|
||||
|
||||
- 高价值福袋预约功能(`high_value_fudai_*` 配置族)
|
||||
- 高价值直播间回访功能(`high_value_room_revisit_*`)
|
||||
|
||||
### Changed
|
||||
|
||||
- 推荐页养号逻辑优化
|
||||
|
||||
## [V3.1.0]
|
||||
|
||||
### Added
|
||||
|
||||
- 推荐页养号功能:自动点赞 / 收藏 / 评论(按概率)
|
||||
|
||||
### Changed
|
||||
|
||||
- OCR 识别准确率提升
|
||||
|
||||
## [V3.0.0]
|
||||
|
||||
### Changed
|
||||
|
||||
- **重大更新**:OCR 引擎从 pytesseract 切换到 PaddleOCR
|
||||
|
||||
### Added
|
||||
|
||||
- 自动分辨率适配
|
||||
|
||||
### Fixed
|
||||
|
||||
- 大量已知问题
|
||||
|
||||
## V2.x
|
||||
|
||||
- 多分辨率支持
|
||||
- 稳定性提升
|
||||
- 各种 bug 修复
|
||||
|
||||
## V1.x
|
||||
|
||||
- 基础功能:福袋检测、参与、自动领奖
|
||||
|
||||
[Unreleased]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.3.3...HEAD
|
||||
[V3.3.3]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.3.2...v3.3.3
|
||||
[V3.3.2]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.3.1...v3.3.2
|
||||
[V3.3.1]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.3.0...v3.3.1
|
||||
[V3.3.0]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.2.0...v3.3.0
|
||||
[V3.2.0]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.1.0...v3.2.0
|
||||
[V3.1.0]: https://git.simgreek.com/simgreek/douyi_guaji_main/compare/v3.0.0...v3.1.0
|
||||
[V3.0.0]: https://git.simgreek.com/simgreek/douyi_guaji_main/releases/tag/v3.0.0
|
||||
@@ -0,0 +1,32 @@
|
||||
# WebUI 用户视角问题清单(2026-06-01)
|
||||
|
||||
## 已修复(本轮)
|
||||
|
||||
1. `/api/config` 布尔值字符串会被错误写入
|
||||
- 现象:`"false"` 可能被当成 `true`。
|
||||
- 修复:后端 `routes.py` 新增 `_coerce_bool`,前端 `config_form.js` 同步字面量解析。
|
||||
|
||||
2. 设备动作在无设备时存在未捕获 Promise 报错噪音
|
||||
- 现象:点击“返回键”后可能触发全局 `pageerror`(虽有提示但会污染错误面板)。
|
||||
- 修复:`runtime_device_actions.js` 的 `sendBackKey()` 增加局部 `try/catch`。
|
||||
|
||||
3. 预约/高价值列表中少量字段未统一做安全处理
|
||||
- 现象:个别字符串字段直接插入模板字符串。
|
||||
- 修复:`runtime_actions.js` 对 `future_str` 等补 `escapeHtml`,数值字段统一显式数值化。
|
||||
|
||||
4. WiFi 自动重连与扫描参数错误码语义不清
|
||||
- 修复:
|
||||
- 无 adb:`/api/wifi/auto-reconnect` 返回 `422`。
|
||||
- `ports` 非法:`/api/wifi/scan` 返回 `400 invalid ports`。
|
||||
- `probe_timeout` 非法继续返回 `400`。
|
||||
|
||||
## 仍可优化(下一批)
|
||||
|
||||
1. 移动端首屏头部信息密度偏高
|
||||
- 证据:`mobile_home.png` 中操作按钮区占比较大,设备/状态卡阅读层级偏挤。
|
||||
- 建议:在 `< 420px` 下把二级按钮折叠进更多菜单,保留“开始/停止/截图”主操作。
|
||||
|
||||
2. Tab 横向切换在自动化点击中偶发不可见状态
|
||||
- 证据:Playwright 偶发 `runLogs` tab 点击超时(人工可复现概率低)。
|
||||
- 建议:为 tab click 增加 `scrollIntoView` + `requestAnimationFrame` 后触发,提升自动化与低端机稳定性。
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
{
|
||||
"url": "http://localhost:8001/",
|
||||
"screenshots": [
|
||||
"artifacts\\webui_checks\\20260601\\desktop_home.png",
|
||||
"artifacts\\webui_checks\\20260601\\desktop_run_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\desktop_stats_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\desktop_monitor_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\desktop_reservations_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\desktop_runlogs_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\desktop_actionlogs_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_home.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_run_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_stats_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_monitor_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_reservations_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_runlogs_panel.png",
|
||||
"artifacts\\webui_checks\\20260601\\mobile_actionlogs_panel.png"
|
||||
],
|
||||
"console_errors": [
|
||||
{
|
||||
"type": "error",
|
||||
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
|
||||
},
|
||||
{
|
||||
"type": "action",
|
||||
"text": "click_failed .tabBtn[data-target=\"runLogs\"]: Locator.click: Timeout 3000ms exceeded.\nCall log:\n - waiting for locator(\".tabBtn[data-target=\\\"runLogs\\\"]\").first\n - locator resolved to <button role=\"tab\" type=\"button\" class=\"tabBtn\" data-target=\"runLogs\" aria-selected=\"false\">…</button>\n - attempting click action\n - waiting for element to be visible, enabled and stable\n - element is visible, enabled and stable\n - scrolling into view if needed\n - done scrolling\n - performing click action\n"
|
||||
}
|
||||
],
|
||||
"page_errors": [
|
||||
"未选择设备,且无法自动解析在线设备"
|
||||
],
|
||||
"checks": {
|
||||
"desktop:has:btnStart": true,
|
||||
"desktop:has:btnStop": true,
|
||||
"desktop:has:btnForceStop": true,
|
||||
"desktop:has:btnRefresh": true,
|
||||
"desktop:has:btnScreenshot": true,
|
||||
"desktop:has:btnBackKey": true,
|
||||
"desktop:has:btnLoad": true,
|
||||
"desktop:has:btnSave": true,
|
||||
"desktop:has:device": true,
|
||||
"desktop:has:btnWifiScan": true,
|
||||
"desktop:has:wifiStatus": true,
|
||||
"desktop:has:runLog": true,
|
||||
"desktop:has:appConnText": true,
|
||||
"desktop:has:appConnDot": true,
|
||||
"desktop:has:reservationsContent": true,
|
||||
"desktop:has:highValueRoomsContent": true,
|
||||
"desktop:has:hv_expand_all": true,
|
||||
"desktop:has:hv_collapse_all": true,
|
||||
"desktop:conn_text": "已连接",
|
||||
"desktop:body_box": {
|
||||
"w": 1600,
|
||||
"h": 1178.65625,
|
||||
"scrollH": 1179
|
||||
},
|
||||
"desktop:overflow_controls": 0,
|
||||
"mobile:has:btnStart": true,
|
||||
"mobile:has:btnStop": true,
|
||||
"mobile:has:btnForceStop": true,
|
||||
"mobile:has:btnRefresh": true,
|
||||
"mobile:has:btnScreenshot": true,
|
||||
"mobile:has:btnBackKey": true,
|
||||
"mobile:has:btnLoad": true,
|
||||
"mobile:has:btnSave": true,
|
||||
"mobile:has:device": true,
|
||||
"mobile:has:btnWifiScan": true,
|
||||
"mobile:has:wifiStatus": true,
|
||||
"mobile:has:runLog": true,
|
||||
"mobile:has:appConnText": true,
|
||||
"mobile:has:appConnDot": true,
|
||||
"mobile:has:reservationsContent": true,
|
||||
"mobile:has:highValueRoomsContent": true,
|
||||
"mobile:has:hv_expand_all": true,
|
||||
"mobile:has:hv_collapse_all": true,
|
||||
"mobile:conn_text": "已连接",
|
||||
"mobile:body_box": {
|
||||
"w": 390,
|
||||
"h": 2102.875,
|
||||
"scrollH": 2103
|
||||
},
|
||||
"mobile:overflow_controls": 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"console_errors": [
|
||||
{
|
||||
"type": "error",
|
||||
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
|
||||
}
|
||||
],
|
||||
"page_errors": [],
|
||||
"screenshots": [
|
||||
"artifacts\\webui_checks\\20260601_port8002\\mobile_main.png"
|
||||
],
|
||||
"checks": {
|
||||
"has_unhandled_error": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"console_errors": [
|
||||
{
|
||||
"type": "error",
|
||||
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
|
||||
}
|
||||
],
|
||||
"page_errors": [],
|
||||
"screenshots": [
|
||||
"artifacts\\webui_checks\\20260601_port8003\\mobile_main.png"
|
||||
],
|
||||
"checks": {
|
||||
"has_unhandled_error": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"console_errors": [
|
||||
{
|
||||
"type": "error",
|
||||
"text": "Failed to load resource: the server responded with a status of 422 (Unprocessable Entity)"
|
||||
}
|
||||
],
|
||||
"page_errors": [],
|
||||
"screenshots": [
|
||||
"artifacts\\webui_checks\\20260601_postfix\\mobile_after_fix.png"
|
||||
],
|
||||
"checks": {
|
||||
"has_unhandled_error": false
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
|
After Width: | Height: | Size: 4.7 KiB |
|
After Width: | Height: | Size: 21 KiB |
|
After Width: | Height: | Size: 14 KiB |
|
After Width: | Height: | Size: 548 B |
|
After Width: | Height: | Size: 1.2 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 6.2 KiB |
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compatibility launcher for the desktop GUI."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import runpy
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
ROOT_DIR = Path(__file__).resolve().parent.parent
|
||||
TARGET = ROOT_DIR / "gui" / "gui_app.py"
|
||||
VENV_PYTHON = Path(path_config.get_venv_python_path())
|
||||
|
||||
|
||||
def _reexec_with_venv() -> None:
|
||||
if not VENV_PYTHON.exists():
|
||||
return
|
||||
if Path(sys.executable).resolve() == VENV_PYTHON.resolve():
|
||||
return
|
||||
os.execv(str(VENV_PYTHON), [str(VENV_PYTHON), str(TARGET), *sys.argv[1:]])
|
||||
|
||||
|
||||
def main() -> None:
|
||||
_reexec_with_venv()
|
||||
sys.argv = [str(TARGET), *sys.argv[1:]]
|
||||
runpy.run_path(str(TARGET), run_name="__main__")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -27,14 +27,14 @@ import argparse
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Dict, Any
|
||||
|
||||
# 添加项目路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
# 添加项目根到 sys.path(从 bin/ 目录运行时需要)
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from douyin.core import path_config
|
||||
from douyin.logging.douyin_logging import (
|
||||
cleanup_old_logs,
|
||||
compress_log_file,
|
||||
get_log_stats,
|
||||
path_config
|
||||
)
|
||||
|
||||
|
||||
@@ -178,7 +178,8 @@ def show_monitor_status() -> None:
|
||||
"""显示监控器状态"""
|
||||
print("\n=== 日志监控状态 ===")
|
||||
|
||||
from douyin.logging.douyin_logging import _log_monitor
|
||||
from douyin.logging.douyin_logging_pkg import _common as _logging_state
|
||||
_log_monitor = _logging_state._log_monitor
|
||||
|
||||
if _log_monitor and _log_monitor._running:
|
||||
print("状态: 运行中")
|
||||
@@ -1,8 +1,20 @@
|
||||
import argparse
|
||||
import importlib.util
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import time
|
||||
|
||||
# ==== 将项目根目录加入 sys.path,确保后续所有 douyin.* 导入正常 ================
|
||||
_BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
if _BASE_DIR not in sys.path:
|
||||
sys.path.insert(0, _BASE_DIR)
|
||||
|
||||
if __name__ == "__main__":
|
||||
from douyin.updater.bootstrap import run_startup_update_check_early
|
||||
|
||||
run_startup_update_check_early(app_name="run_cli")
|
||||
|
||||
# 可选:全局参数/调用跟踪(仅在环境变量 PARAM_TRACK_ALL=1 时启用)
|
||||
if os.environ.get("PARAM_TRACK_ALL") == "1":
|
||||
@@ -10,18 +22,21 @@ if os.environ.get("PARAM_TRACK_ALL") == "1":
|
||||
from douyin.utils.param_usage_tracer import start_tracing
|
||||
|
||||
start_tracing()
|
||||
except Exception:
|
||||
# 启用失败不影响主流程
|
||||
pass
|
||||
except Exception as e:
|
||||
logging.debug("参数追踪启用失败: %s", e)
|
||||
|
||||
# ==== 首先配置日志系统,确保日志文件能正常写入 ==============================
|
||||
try:
|
||||
from douyin.logging import douyin_logging
|
||||
|
||||
douyin_logging.configure_logging()
|
||||
except Exception:
|
||||
# 日志配置失败不影响主流程,但会缺少文件日志
|
||||
pass
|
||||
except Exception as e:
|
||||
# 日志配置失败,使用基础配置作为兜底
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - [%(levelname)s] - %(message)s'
|
||||
)
|
||||
logging.warning("日志系统配置失败,使用基础配置: %s", e)
|
||||
|
||||
# 尝试确保行为日志的异步 listener 在进程启动时就被启动,
|
||||
# 以避免某些运行环境中模块未完整初始化导致日志未落盘的问题。
|
||||
@@ -33,25 +48,17 @@ try:
|
||||
action_logger_mod = importlib.import_module("douyin.logging.action_logger")
|
||||
try:
|
||||
action_logger_mod._start_queue_listener_if_needed()
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# 启动失败时不影响主流程,action_logger 有回退到同步 file handler 的逻辑
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
logging.debug("action_logger 启动失败: %s", e)
|
||||
except Exception as e:
|
||||
logging.debug("action_logger 模块导入失败: %s", e)
|
||||
|
||||
# ==== 兼容导入完整逻辑模块 douyin_fudai 及其依赖 ==============================
|
||||
# 当前 WebGUI 目录中没有完整版 douyin_fudai.py,而是在 Cursor 的工作树中存在完整实现。
|
||||
# 同时,我们在本目录下放置了一些 shim 模块(如 douyin_text_utils、douyin_swipe_ops 等),
|
||||
# 需要优先加载这些本地实现,再去加载完整逻辑模块。
|
||||
# 如果需要从外部工作树加载兼容模块,可显式设置 EXTERNAL_DOUYIN_FUDAI_DIR。
|
||||
# 默认只使用当前仓库内置实现,避免绑定到某台机器的 Cursor worktree 路径。
|
||||
|
||||
_BASE_DIR = os.path.dirname(__file__)
|
||||
# 使用环境变量或默认路径,避免硬编码用户路径
|
||||
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get(
|
||||
"EXTERNAL_DOUYIN_FUDAI_DIR",
|
||||
os.path.join(
|
||||
os.path.expanduser("~"), ".cursor", "worktrees", "douyin_guaji-main", "axf"
|
||||
),
|
||||
)
|
||||
_EXTERNAL_DOUYIN_FUDAI_DIR = os.environ.get("EXTERNAL_DOUYIN_FUDAI_DIR", "").strip()
|
||||
|
||||
|
||||
def _load_local_shim(mod_name: str, rel_path: str) -> None:
|
||||
@@ -68,17 +75,14 @@ def _load_local_shim(mod_name: str, rel_path: str) -> None:
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
sys.modules[mod_name] = module
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# shim 加载失败不影响主流程,后续仍可尝试外部模块
|
||||
logging.debug("shim 模块加载失败 %s: %s", mod_name, e)
|
||||
return
|
||||
|
||||
|
||||
# 1) 先加载本地 shim 模块,确保后续 import 优先使用这些实现
|
||||
_load_local_shim("douyin_text_utils", "douyin/utils/douyin_text_utils.py")
|
||||
_load_local_shim("douyin_swipe_ops", "douyin/handlers/douyin_swipe_ops.py")
|
||||
_load_local_shim(
|
||||
"douyin_reservation_ops", "douyin/reservation/douyin_reservation_ops.py"
|
||||
)
|
||||
|
||||
# 2) 再把完整逻辑所在目录追加到 sys.path,供 `douyin_fudai` 等模块导入
|
||||
try:
|
||||
@@ -87,22 +91,31 @@ try:
|
||||
and _EXTERNAL_DOUYIN_FUDAI_DIR not in sys.path
|
||||
):
|
||||
sys.path.append(_EXTERNAL_DOUYIN_FUDAI_DIR)
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
# 不影响主流程;如果目录不存在,后续导入会按默认逻辑报错
|
||||
pass
|
||||
logging.debug("外部模块路径配置失败: %s", e)
|
||||
|
||||
# 在导入 PaddleOCR 之前设置,避免每次启动都做连通性检查提示并抑制底层 glog/oneDNN 等噪音
|
||||
# DISABLE_MODEL_SOURCE_CHECK: 跳过 PaddleOCR 的主机连通性检查(国内网络环境常卡)
|
||||
# DISABLE_MODEL_SOURCE_CHECK/PADDLE_PDX_DISABLE_MODEL_SOURCE_CHECK: 跳过 PaddleOCR/PaddleX 主机连通性检查(国内网络环境常卡)
|
||||
# GLOG_minloglevel: 2 -> ERROR 及以上,屏蔽 INFO/WARNING
|
||||
# OMP_NUM_THREADS: 设为 1,避免 oneDNN 打印线程信息
|
||||
os.environ.setdefault("DISABLE_MODEL_SOURCE_CHECK", "True")
|
||||
os.environ.setdefault("PADDLE_PDX_DISABLE_MODEL_SOURCE_CHECK", "1")
|
||||
os.environ.setdefault("GLOG_minloglevel", "2")
|
||||
os.environ.setdefault("OMP_NUM_THREADS", "1")
|
||||
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
from douyin.core import path_config
|
||||
from douyin.license.license_manager import require_online_license_or_exit
|
||||
|
||||
|
||||
def ensure_adb_in_path() -> None:
|
||||
bundled_adb = path_config.find_bundled_adb()
|
||||
if bundled_adb:
|
||||
adb_dir = os.path.dirname(bundled_adb)
|
||||
os.environ["PATH"] = adb_dir + os.pathsep + os.environ.get("PATH", "")
|
||||
os.environ.setdefault("ADB_EXECUTABLE", bundled_adb)
|
||||
return
|
||||
if shutil.which("adb"):
|
||||
return
|
||||
localapp = os.environ.get("LOCALAPPDATA") or ""
|
||||
@@ -127,6 +140,11 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
|
||||
p.add_argument("--device-id", default="", help="ADB 设备 ID(为空则自动选择)")
|
||||
p.add_argument("--y-pianyi", type=int, default=0, help="y 轴偏移(通常 -50~50)")
|
||||
p.add_argument("--needswitch", action="store_true", help="是否允许上划切换直播间")
|
||||
p.add_argument(
|
||||
"--cold-start",
|
||||
action="store_true",
|
||||
help="启动本轮前 force-stop 并重新打开抖音(真机回归测试使用)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--wait-minutes",
|
||||
type=int,
|
||||
@@ -330,13 +348,135 @@ def parse_args(argv: list[str]) -> argparse.Namespace:
|
||||
default=None,
|
||||
help="仅在 --yanghao-only 时有效:覆盖推荐页养号停留秒数",
|
||||
)
|
||||
p.add_argument(
|
||||
"--reenter-live-entry-mode",
|
||||
choices=["follow_list", "screen_center"],
|
||||
default="screen_center",
|
||||
help="重新进入直播间点击模式:follow_list=关注列表坐标,screen_center=屏幕中心坐标",
|
||||
)
|
||||
p.add_argument(
|
||||
"--disable-regression-collection",
|
||||
action="store_true",
|
||||
help="禁用运行结束自动收集福袋回归测试素材",
|
||||
)
|
||||
p.add_argument(
|
||||
"--regression-collection-max-images",
|
||||
type=int,
|
||||
default=500,
|
||||
help="运行结束最多扫描本轮 debug capture 图片数(默认500,仅挑高价值小样本长期保留)",
|
||||
)
|
||||
p.add_argument(
|
||||
"--regression-full-run-package",
|
||||
action="store_true",
|
||||
help="额外保留完整本轮回归包(日志、状态、debug/ocr 图片);默认只保留长期小样本池",
|
||||
)
|
||||
|
||||
return p.parse_args(argv)
|
||||
|
||||
|
||||
def _collect_regression_artifacts_if_enabled(
|
||||
args: argparse.Namespace,
|
||||
*,
|
||||
run_started_at: float,
|
||||
exit_code: int | None,
|
||||
device_id: str,
|
||||
) -> None:
|
||||
if bool(getattr(args, "disable_regression_collection", False)):
|
||||
return
|
||||
try:
|
||||
from douyin.testing.regression_collector import (
|
||||
build_run_id,
|
||||
collect_run_regression_artifacts,
|
||||
)
|
||||
|
||||
max_images = int(getattr(args, "regression_collection_max_images", 500) or 500)
|
||||
max_images = max(1, max_images)
|
||||
max_ocr_images = max(80, min(max_images, int(max_images * 0.4)))
|
||||
result = collect_run_regression_artifacts(
|
||||
run_id=build_run_id("run_cli"),
|
||||
started_at=run_started_at,
|
||||
exit_code=exit_code,
|
||||
device_id=device_id,
|
||||
max_debug_images=max_images,
|
||||
max_ocr_images=max_ocr_images,
|
||||
full_run_package=bool(getattr(args, "regression_full_run_package", False)),
|
||||
)
|
||||
print(
|
||||
"[REGRESSION] collected output_dir={} counts={}".format(
|
||||
result.get("output_dir", ""),
|
||||
result.get("counts", {}),
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
except Exception as e:
|
||||
print("[REGRESSION] collect failed: {}".format(e), flush=True)
|
||||
|
||||
|
||||
def _is_douyin_top_package(package_name: str) -> bool:
|
||||
top_pkg = str(package_name or "")
|
||||
return bool(top_pkg) and (
|
||||
"aweme" in top_pkg
|
||||
or "douyin" in top_pkg
|
||||
or "com.ss.android.ugc" in top_pkg
|
||||
or "musically" in top_pkg
|
||||
)
|
||||
|
||||
|
||||
def _cold_start_douyin_for_test(analyser: object, device_id: str) -> bool:
|
||||
op = getattr(analyser, "operation", None)
|
||||
if op is None or not device_id:
|
||||
return False
|
||||
packages = path_config.get_douyin_packages()
|
||||
for pkg in packages:
|
||||
pkg = str(pkg or "").strip()
|
||||
if not pkg:
|
||||
continue
|
||||
try:
|
||||
op._run_adb_shell(device_id, f"am force-stop {pkg}", timeout_seconds=3.0)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
op.delay(1.5)
|
||||
except Exception:
|
||||
time.sleep(1.5)
|
||||
|
||||
launched_ok = False
|
||||
launched_pkg = ""
|
||||
try:
|
||||
launched_ok, launched_pkg = op.launch_package(device_id, "", timeout_seconds=5.0)
|
||||
except Exception as e:
|
||||
print(f"[COLD-START] launch failed: {e}", flush=True)
|
||||
|
||||
try:
|
||||
op.delay(2.5)
|
||||
except Exception:
|
||||
time.sleep(2.5)
|
||||
|
||||
top_pkg = ""
|
||||
try:
|
||||
top_pkg = op.get_top_package(device_id) or ""
|
||||
except Exception:
|
||||
top_pkg = ""
|
||||
|
||||
ok = bool(launched_ok) and _is_douyin_top_package(top_pkg or launched_pkg)
|
||||
print(
|
||||
"[COLD-START] force_stop={} launched={} pkg={} top_pkg={} result={}".format(
|
||||
len(tuple(packages)),
|
||||
bool(launched_ok),
|
||||
launched_pkg,
|
||||
top_pkg,
|
||||
"OK" if ok else "FAIL",
|
||||
),
|
||||
flush=True,
|
||||
)
|
||||
return ok
|
||||
|
||||
|
||||
def main(argv: list[str]) -> int:
|
||||
require_online_license_or_exit()
|
||||
ensure_adb_in_path()
|
||||
args = parse_args(argv)
|
||||
run_started_at = time.time()
|
||||
|
||||
# 让命令行输出更稳定(实时刷新 + UTF-8)
|
||||
try:
|
||||
@@ -611,6 +751,13 @@ def main(argv: list[str]) -> int:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
analyser.reenter_live_entry_mode = str(
|
||||
args.reenter_live_entry_mode or "screen_center"
|
||||
).strip().lower()
|
||||
except Exception:
|
||||
analyser.reenter_live_entry_mode = "screen_center"
|
||||
|
||||
device_id = args.device_id.strip() if args.device_id else ""
|
||||
if not device_id:
|
||||
device_id = analyser.operation.select_device()
|
||||
@@ -619,18 +766,35 @@ def main(argv: list[str]) -> int:
|
||||
print("未检测到设备,退出。")
|
||||
return 2
|
||||
|
||||
analyser.fudai_choujiang(
|
||||
device_id=device_id,
|
||||
y_pianyi=args.y_pianyi,
|
||||
needswitch=bool(args.needswitch),
|
||||
wait_minutes=int(args.wait_minutes),
|
||||
)
|
||||
return 0
|
||||
if bool(getattr(args, "cold_start", False)):
|
||||
if not _cold_start_douyin_for_test(analyser, device_id):
|
||||
print("抖音冷启动失败或前台不是抖音,退出。")
|
||||
return 4
|
||||
|
||||
exit_code = 0
|
||||
try:
|
||||
analyser.fudai_choujiang(
|
||||
device_id=device_id,
|
||||
y_pianyi=args.y_pianyi,
|
||||
needswitch=bool(args.needswitch),
|
||||
wait_minutes=int(args.wait_minutes),
|
||||
)
|
||||
except Exception:
|
||||
exit_code = 1
|
||||
raise
|
||||
finally:
|
||||
_collect_regression_artifacts_if_enabled(
|
||||
args,
|
||||
run_started_at=run_started_at,
|
||||
exit_code=exit_code,
|
||||
device_id=device_id,
|
||||
)
|
||||
return exit_code
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
from version import print_version_banner
|
||||
from douyin.core.version import print_version_banner
|
||||
|
||||
print_version_banner("run_cli")
|
||||
except Exception:
|
||||
@@ -0,0 +1,25 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
_BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
if str(_BASE_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(_BASE_DIR))
|
||||
|
||||
from douyin.updater.bootstrap import run_startup_update_check_early
|
||||
|
||||
|
||||
run_startup_update_check_early(app_name="run_cli")
|
||||
|
||||
from bin.run_cli import main # noqa: E402
|
||||
from douyin.core.version import print_version_banner # noqa: E402
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
print_version_banner("run_cli")
|
||||
except Exception:
|
||||
pass
|
||||
raise SystemExit(main(sys.argv[1:]))
|
||||
@@ -0,0 +1,33 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compatibility launcher for the Web GUI launcher window."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import runpy
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from douyin.core import path_config
|
||||
|
||||
ROOT_DIR = Path(__file__).resolve().parent.parent
|
||||
TARGET = ROOT_DIR / "gui" / "webgui_launcher.py"
|
||||
VENV_PYTHON = Path(path_config.get_venv_python_path())
|
||||
|
||||
|
||||
def _reexec_with_venv() -> None:
|
||||
if not VENV_PYTHON.exists():
|
||||
return
|
||||
if Path(sys.executable).resolve() == VENV_PYTHON.resolve():
|
||||
return
|
||||
os.execv(str(VENV_PYTHON), [str(VENV_PYTHON), str(TARGET), *sys.argv[1:]])
|
||||
|
||||
|
||||
def main() -> None:
|
||||
_reexec_with_venv()
|
||||
sys.argv = [str(TARGET), *sys.argv[1:]]
|
||||
runpy.run_path(str(TARGET), run_name="__main__")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,36 @@
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
pushd "%~dp0" >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] Failed to change to script directory.
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
set "BOOTSTRAP_SCRIPT=bootstrap_deps.py"
|
||||
if not exist "%BOOTSTRAP_SCRIPT%" (
|
||||
echo [ERROR] Missing %BOOTSTRAP_SCRIPT% in project root.
|
||||
popd >nul 2>&1
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
where py >nul 2>&1
|
||||
if not errorlevel 1 (
|
||||
py -3 "%BOOTSTRAP_SCRIPT%" %*
|
||||
set "EXIT_CODE=%ERRORLEVEL%"
|
||||
goto :done
|
||||
)
|
||||
|
||||
where python >nul 2>&1
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] Python launcher not found. Install Python 3.10+ and add it to PATH.
|
||||
popd >nul 2>&1
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
python "%BOOTSTRAP_SCRIPT%" %*
|
||||
set "EXIT_CODE=%ERRORLEVEL%"
|
||||
|
||||
:done
|
||||
popd >nul 2>&1
|
||||
exit /b %EXIT_CODE%
|
||||
@@ -0,0 +1,239 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
One-click dependency bootstrap for this repository.
|
||||
|
||||
Default behavior:
|
||||
1. Create/update a virtual environment at .venv
|
||||
2. Upgrade pip/setuptools/wheel in that environment
|
||||
3. Install dependencies from requirements.txt
|
||||
|
||||
Examples:
|
||||
python bootstrap_deps.py
|
||||
python bootstrap_deps.py --minimal
|
||||
python bootstrap_deps.py --no-venv
|
||||
python bootstrap_deps.py --index-url https://pypi.tuna.tsinghua.edu.cn/simple
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Iterable, Sequence
|
||||
|
||||
|
||||
def _echo(message: str) -> None:
|
||||
print(message, flush=True)
|
||||
|
||||
|
||||
def _format_cmd(cmd: Sequence[str]) -> str:
|
||||
return " ".join(shlex.quote(part) for part in cmd)
|
||||
|
||||
|
||||
def _run(cmd: Sequence[str], *, cwd: Path, dry_run: bool = False) -> None:
|
||||
_echo(f"$ {_format_cmd(cmd)}")
|
||||
if dry_run:
|
||||
return
|
||||
subprocess.run(cmd, cwd=str(cwd), check=True)
|
||||
|
||||
|
||||
def _resolve_requirements(repo_root: Path, args: argparse.Namespace) -> Path:
|
||||
if args.requirements:
|
||||
req = Path(args.requirements).expanduser()
|
||||
if not req.is_absolute():
|
||||
req = repo_root / req
|
||||
else:
|
||||
req_name = "requirements-minimal.txt" if args.minimal else "requirements.txt"
|
||||
req = repo_root / req_name
|
||||
return req.resolve()
|
||||
|
||||
|
||||
def _resolve_venv_python(venv_dir: Path) -> Path:
|
||||
candidates = (
|
||||
venv_dir / "Scripts" / "python.exe",
|
||||
venv_dir / "Scripts" / "python",
|
||||
venv_dir / "bin" / "python",
|
||||
)
|
||||
for candidate in candidates:
|
||||
if candidate.exists():
|
||||
return candidate.resolve()
|
||||
raise FileNotFoundError(
|
||||
f"Could not find a Python executable in virtual environment: {venv_dir}"
|
||||
)
|
||||
|
||||
|
||||
def _build_pip_index_args(args: argparse.Namespace) -> list[str]:
|
||||
pip_args: list[str] = []
|
||||
if args.index_url:
|
||||
pip_args += ["--index-url", args.index_url]
|
||||
for item in args.extra_index_url:
|
||||
pip_args += ["--extra-index-url", item]
|
||||
for item in args.trusted_host:
|
||||
pip_args += ["--trusted-host", item]
|
||||
if args.no_cache_dir:
|
||||
pip_args.append("--no-cache-dir")
|
||||
if args.prefer_binary:
|
||||
pip_args.append("--prefer-binary")
|
||||
return pip_args
|
||||
|
||||
|
||||
def _validate_python_version() -> None:
|
||||
if sys.version_info < (3, 10):
|
||||
raise RuntimeError(
|
||||
f"Python 3.10+ is required. Current interpreter: {sys.version.split()[0]}"
|
||||
)
|
||||
|
||||
|
||||
def _parse_args() -> argparse.Namespace:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Bootstrap project dependencies in a migration-friendly way."
|
||||
)
|
||||
parser.add_argument(
|
||||
"--venv-dir",
|
||||
default=".venv",
|
||||
help="Virtual environment directory (default: .venv).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-venv",
|
||||
action="store_true",
|
||||
help="Install into the current Python environment instead of creating/using a venv.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--python",
|
||||
default="",
|
||||
help="Python executable used to create the virtual environment.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--minimal",
|
||||
action="store_true",
|
||||
help="Install requirements-minimal.txt instead of requirements.txt.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--requirements",
|
||||
default="",
|
||||
help="Custom requirements file path (overrides --minimal).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--skip-pip-upgrade",
|
||||
action="store_true",
|
||||
help="Skip upgrading pip/setuptools/wheel.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--index-url",
|
||||
default="",
|
||||
help="Base package index URL for pip install.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--extra-index-url",
|
||||
action="append",
|
||||
default=[],
|
||||
help="Extra package index URL for pip install (repeatable).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--trusted-host",
|
||||
action="append",
|
||||
default=[],
|
||||
help="Trusted host passed to pip install (repeatable).",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--no-cache-dir",
|
||||
action="store_true",
|
||||
help="Pass --no-cache-dir to pip.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--prefer-binary",
|
||||
action="store_true",
|
||||
help="Prefer binary wheels when possible.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--dry-run",
|
||||
action="store_true",
|
||||
help="Print commands without executing them.",
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
_validate_python_version()
|
||||
args = _parse_args()
|
||||
repo_root = Path(__file__).resolve().parent
|
||||
requirements_path = _resolve_requirements(repo_root, args)
|
||||
|
||||
if not requirements_path.exists():
|
||||
raise FileNotFoundError(f"Requirements file not found: {requirements_path}")
|
||||
|
||||
if args.no_venv:
|
||||
install_python = Path(sys.executable).resolve()
|
||||
_echo(f"Using current interpreter: {install_python}")
|
||||
else:
|
||||
venv_dir = Path(args.venv_dir).expanduser()
|
||||
if not venv_dir.is_absolute():
|
||||
venv_dir = repo_root / venv_dir
|
||||
creator_python = (args.python or sys.executable).strip()
|
||||
|
||||
if not _resolve_venv_python_if_exists(venv_dir):
|
||||
_echo(f"Creating virtual environment: {venv_dir}")
|
||||
_run([creator_python, "-m", "venv", str(venv_dir)], cwd=repo_root, dry_run=args.dry_run)
|
||||
else:
|
||||
_echo(f"Virtual environment already exists: {venv_dir}")
|
||||
|
||||
install_python = _resolve_venv_python(venv_dir)
|
||||
_echo(f"Using virtual environment interpreter: {install_python}")
|
||||
|
||||
pip_base = [str(install_python), "-m", "pip"]
|
||||
pip_index_args = _build_pip_index_args(args)
|
||||
|
||||
if not args.skip_pip_upgrade:
|
||||
_echo("Upgrading pip, setuptools, and wheel...")
|
||||
_run(
|
||||
[*pip_base, "install", "--upgrade", "pip", "setuptools", "wheel", *pip_index_args],
|
||||
cwd=repo_root,
|
||||
dry_run=args.dry_run,
|
||||
)
|
||||
|
||||
_echo(f"Installing dependencies from: {requirements_path}")
|
||||
_run(
|
||||
[*pip_base, "install", "-r", str(requirements_path), *pip_index_args],
|
||||
cwd=repo_root,
|
||||
dry_run=args.dry_run,
|
||||
)
|
||||
|
||||
if not args.no_venv:
|
||||
_echo("")
|
||||
_echo("Done.")
|
||||
if sys.platform.startswith("win"):
|
||||
_echo(r"Activate with: .venv\Scripts\Activate.ps1")
|
||||
else:
|
||||
_echo("Activate with: source .venv/bin/activate")
|
||||
else:
|
||||
_echo("")
|
||||
_echo("Done (installed into current interpreter).")
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
def _resolve_venv_python_if_exists(venv_dir: Path) -> Path | None:
|
||||
candidates: Iterable[Path] = (
|
||||
venv_dir / "Scripts" / "python.exe",
|
||||
venv_dir / "Scripts" / "python",
|
||||
venv_dir / "bin" / "python",
|
||||
)
|
||||
for candidate in candidates:
|
||||
if candidate.exists():
|
||||
return candidate.resolve()
|
||||
return None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except subprocess.CalledProcessError as exc:
|
||||
_echo("")
|
||||
_echo(f"Command failed with exit code {exc.returncode}.")
|
||||
raise SystemExit(exc.returncode)
|
||||
except Exception as exc: # pragma: no cover - defensive entrypoint guard
|
||||
_echo("")
|
||||
_echo(f"Bootstrap failed: {exc}")
|
||||
raise SystemExit(1)
|
||||
@@ -1,102 +0,0 @@
|
||||
{
|
||||
"needswitch": true,
|
||||
"infinite_loop_enabled": true,
|
||||
"wait_minutes": 5,
|
||||
"y_pianyi": 0,
|
||||
"contains_not_want": [
|
||||
"首饰盒"
|
||||
],
|
||||
"min_prize_value_yuan": 200.0,
|
||||
"min_participants": 0,
|
||||
"max_participants": 0,
|
||||
"skip_if_countdown_gt_seconds": 120,
|
||||
"reset_after_swipes_enabled": true,
|
||||
"reset_after_swipes": 50,
|
||||
"auto_join_fansclub": true,
|
||||
"fansclub_fail_action": "switch",
|
||||
"lucky_draw_red_ratio_threshold": 0.8,
|
||||
"high_value_fudai_enabled": true,
|
||||
"high_value_fudai_threshold_yuan": 500.0,
|
||||
"high_value_fudai_join_ahead_seconds": 300,
|
||||
"high_value_fudai_max_swipe_back": 50,
|
||||
"high_value_fudai_max_reservations": 9999,
|
||||
"high_value_fudai_after_action": "continue",
|
||||
"high_value_room_revisit_enabled": true,
|
||||
"high_value_room_revisit_only_current_run": true,
|
||||
"reservation_back_verify_enabled": true,
|
||||
"reservation_back_swipe_delay": 0.5,
|
||||
"record_room_title_mapping_enabled": true,
|
||||
"reservation_preempt_min_value": 0.0,
|
||||
"fudai_find_max_attempts": 99999,
|
||||
"fudai_icon_retry_delay_seconds": 0.1,
|
||||
"fudai_icon_max_wait_seconds": 8.5,
|
||||
"fudai_click_wait_seconds": 1.7,
|
||||
"switch_room_wait_after_stage_diag_seconds": 4.0,
|
||||
"live_room_match_threshold": 0.6,
|
||||
"fudai_quiet_hours_enabled": true,
|
||||
"fudai_quiet_start_hour": 2,
|
||||
"fudai_quiet_end_hour": 9,
|
||||
"stage_diag_max_time": 5.0,
|
||||
"stage_diag_max_step_time": 2.0,
|
||||
"enable_ocr_mode1": false,
|
||||
"fudai_template_match_enabled": false,
|
||||
"fudai_template_match_threshold": 0.7,
|
||||
"fudai_detail_template_threshold": 0.54,
|
||||
"coupon_template_match_threshold": 0.4,
|
||||
"attend_button_red_ratio_threshold": 0.25,
|
||||
"fansclub_join_red_ratio_threshold": 0.25,
|
||||
"skip_if_countdown_lt_seconds": 5,
|
||||
"debug_captures": {
|
||||
"enabled": true,
|
||||
"auto_cleanup": true,
|
||||
"keep_days": 3,
|
||||
"max_files": 2000
|
||||
},
|
||||
"yanghao_enabled": false,
|
||||
"yanghao_enable_actions": false,
|
||||
"yanghao_recommend_duration_seconds": 206,
|
||||
"yanghao_recommend_interval_seconds": 570,
|
||||
"yanghao_like_prob": 1.0,
|
||||
"yanghao_fav_prob": 0.85,
|
||||
"yanghao_comment_prob": 1.0,
|
||||
"yanghao_icon_roi_size": 240,
|
||||
"yanghao_icon_match_threshold": 0.70,
|
||||
"yanghao_step_screenshot": false,
|
||||
"yanghao_like_roi_offset_x": 0,
|
||||
"yanghao_like_roi_offset_y": -50,
|
||||
"yanghao_fav_roi_offset_x": 40,
|
||||
"yanghao_fav_roi_offset_y": 0,
|
||||
"yanghao_like_icon_x": 0,
|
||||
"yanghao_like_icon_y": -1,
|
||||
"yanghao_fav_icon_x": -1,
|
||||
"yanghao_fav_icon_y": 0,
|
||||
"yanghao_like_template_path": "assets/like.png",
|
||||
"yanghao_fav_template_path": "assets/fav.png",
|
||||
"yanghao_after_dwell_swipe_direction": "up",
|
||||
"yanghao_after_dwell_swipe_distance_px": 900,
|
||||
"yanghao_comment_btn_x": 0,
|
||||
"yanghao_comment_btn_y": -1,
|
||||
"yanghao_comment_input_x": 0,
|
||||
"yanghao_comment_input_y": 0,
|
||||
"yanghao_comment_send_x": 0,
|
||||
"yanghao_comment_send_y": -1,
|
||||
"yanghao_comment_close_x": 0,
|
||||
"yanghao_comment_close_y": 0,
|
||||
"yanghao_comment_texts": [],
|
||||
"yanghao_like_keywords": [],
|
||||
"yanghao_fav_keywords": [],
|
||||
"logging": {
|
||||
"level": "INFO",
|
||||
"file_path": "logs/unified.log",
|
||||
"keep_days": 30,
|
||||
"use_dated_logs": true,
|
||||
"compress_logs": true,
|
||||
"max_total_size_gb": 10.0,
|
||||
"compress_after_days": 7,
|
||||
"max_bytes": 104857600,
|
||||
"backup_count": 10,
|
||||
"enable_monitor": true,
|
||||
"monitor_warning_mb": 500.0,
|
||||
"monitor_critical_mb": 2000.0
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,55 @@
|
||||
- 建议在修改配置前备份原文件
|
||||
- 配置文件使用 UTF-8 编码
|
||||
|
||||
## 自动更新配置
|
||||
|
||||
默认建议使用 HTTPS 且安装包与 manifest 同源:
|
||||
|
||||
```json
|
||||
{
|
||||
"auto_update": {
|
||||
"enabled": true,
|
||||
"manifest_url": "https://updates.example.com/douyin/update.json",
|
||||
"fail_closed": true,
|
||||
"require_sha256": true,
|
||||
"require_https": true,
|
||||
"allow_cross_origin": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
仅内网临时测试 `http://192.168.x.x/...` 时,才显式放宽:
|
||||
|
||||
```json
|
||||
{
|
||||
"auto_update": {
|
||||
"enabled": true,
|
||||
"manifest_url": "http://192.168.10.2:8000/update.json",
|
||||
"require_https": false,
|
||||
"allow_cross_origin": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
正式分发不要使用 HTTP;`sha256` 只能防安装包下载损坏,不能替代可信 manifest。
|
||||
|
||||
## 在线卡密激活配置
|
||||
|
||||
正式接入服务器后,在本地配置中增加:
|
||||
|
||||
```json
|
||||
{
|
||||
"license": {
|
||||
"activation_url": "https://license.example.com/api/v1/activate",
|
||||
"timeout_seconds": 10
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
未配置 `activation_url` 时,客户端仍只按旧逻辑安装 `DYGJ-` 离线授权码或完整
|
||||
`license.dat` 内容。配置后,普通 `DG-` 卡密会请求服务器激活,服务器返回的签名授权
|
||||
仍会先在本地验签,通过后才写入 `license.dat`。
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -2,17 +2,31 @@
|
||||
"needswitch": true,
|
||||
"infinite_loop_enabled": true,
|
||||
"wait_minutes": 5,
|
||||
"min_prize_value_yuan": 300.0,
|
||||
"auto_update": {
|
||||
"enabled": false,
|
||||
"manifest_url": "",
|
||||
"fail_closed": true,
|
||||
"require_sha256": true,
|
||||
"timeout_seconds": 20,
|
||||
"installer_args": [
|
||||
"/VERYSILENT",
|
||||
"/SUPPRESSMSGBOXES",
|
||||
"/NORESTART",
|
||||
"/CURRENTUSER"
|
||||
]
|
||||
},
|
||||
"min_prize_value_yuan": 100.0,
|
||||
"min_participants": 0,
|
||||
"max_participants": 0,
|
||||
"skip_if_countdown_gt_seconds": 118,
|
||||
"skip_if_countdown_gt_seconds": 10,
|
||||
"reset_after_swipes_enabled": true,
|
||||
"reset_after_swipes": 20,
|
||||
"reset_after_swipes_action": "swipe",
|
||||
"reenter_live_entry_mode": "screen_center",
|
||||
"auto_join_fansclub": true,
|
||||
"fansclub_fail_action": "switch",
|
||||
"high_value_fudai_enabled": true,
|
||||
"high_value_fudai_threshold_yuan": 500.0,
|
||||
"high_value_fudai_threshold_yuan": 150.0,
|
||||
"high_value_fudai_join_ahead_seconds": 100,
|
||||
"high_value_fudai_max_swipe_back": 50,
|
||||
"high_value_fudai_max_reservations": 9999,
|
||||
@@ -29,7 +43,7 @@
|
||||
"yanghao_fallback_enter_live_x": 540,
|
||||
"yanghao_fallback_enter_live_y": 1200,
|
||||
"fudai_find_max_attempts": 99999,
|
||||
"fudai_icon_max_wait_seconds": 6.5,
|
||||
"fudai_icon_max_wait_seconds": 7.0,
|
||||
"fudai_icon_retry_delay_seconds": 0.1,
|
||||
"fudai_exit_after_misses": 7,
|
||||
"enable_back_on_misses": false,
|
||||
@@ -38,8 +52,29 @@
|
||||
"fudai_detail_verified_wait_seconds": 0.2,
|
||||
"fudai_detail_retry_delay_seconds": 0.5,
|
||||
"fudai_detail_save_debug_images": true,
|
||||
"fudai_disable_content_recognition": true,
|
||||
"fudai_disable_task_recognition": true,
|
||||
"fudai_detail_ui_mode": "auto",
|
||||
"fudai_detail_ocr_content_enabled": true,
|
||||
"fudai_detail_ocr_value_enabled": true,
|
||||
"fudai_detail_ocr_countdown_enabled": true,
|
||||
"fudai_detail_ocr_task_enabled": true,
|
||||
"fudai_detail_ocr_task_count_enabled": true,
|
||||
"fudai_detail_ocr_button_enabled": true,
|
||||
"fudai_detail_ocr_participants_enabled": false,
|
||||
"fudai_detail_ocr_live_title_enabled": true,
|
||||
"pixel_detect_fudai_icon_enabled": true,
|
||||
"pixel_detect_coupon_popup_enabled": true,
|
||||
"pixel_detect_shopping_redpacket_enabled": true,
|
||||
"pixel_detect_lottery_result_enabled": true,
|
||||
"pixel_detect_attend_button_enabled": true,
|
||||
"pixel_detect_fansclub_join_enabled": true,
|
||||
"pixel_detect_fudai_detail_enabled": true,
|
||||
"pixel_detect_live_room_enabled": true,
|
||||
"ocr_lottery_result_enabled": true,
|
||||
"ocr_coupon_popup_enabled": true,
|
||||
"ocr_shopping_redpacket_enabled": false,
|
||||
"ocr_stage_page_enabled": true,
|
||||
"fudai_disable_content_recognition": false,
|
||||
"fudai_disable_task_recognition": false,
|
||||
"yanghao_recommend_duration_seconds": 180,
|
||||
"yanghao_recommend_interval_seconds": 600,
|
||||
"yanghao_like_prob": 0.1,
|
||||
@@ -158,9 +193,9 @@
|
||||
"beautify_output": true,
|
||||
"show_timestamps": true,
|
||||
"show_execution_times": true,
|
||||
"debug_detail_level": "detailed",
|
||||
"debug_detail_level": "normal",
|
||||
"error_detail_level": "full",
|
||||
"action_log_format": "detailed",
|
||||
"action_log_format": "concise",
|
||||
"log_format_mode": "simple",
|
||||
"stage_diag_verbose": true,
|
||||
"color_output": true,
|
||||
@@ -194,7 +229,7 @@
|
||||
"monitor_critical_mb": 200.0
|
||||
},
|
||||
"debug_captures": {
|
||||
"enabled": false,
|
||||
"enabled": true,
|
||||
"keep_days": 1,
|
||||
"max_files": 1000,
|
||||
"auto_cleanup": true,
|
||||
@@ -210,7 +245,11 @@
|
||||
"reservation_test_mode": false,
|
||||
"swipe_duration_ms": 250,
|
||||
"gui": {
|
||||
"theme": "litera"
|
||||
"theme": "litera",
|
||||
"realtime_status": {
|
||||
"refresh_interval_ms": 1000,
|
||||
"tail_items": 50
|
||||
}
|
||||
},
|
||||
"fansclub_click_delay": 0.6,
|
||||
"fansclub_auto_join_wait_seconds": 5.0,
|
||||
@@ -220,9 +259,244 @@
|
||||
"record_room_title_mapping_enabled": true,
|
||||
"high_value_fudai_poll_before_seconds": 10.0,
|
||||
"high_value_room_revisit_min_interval_seconds": 300,
|
||||
"high_value_room_revisit_max_per_run": 9999,
|
||||
"high_value_room_revisit_max_per_run": 20,
|
||||
"high_value_room_revisit_min_prize_value": 1000.0,
|
||||
"high_value_room_revisit_max_age_days": 1,
|
||||
"swipe_up_start_y": 1200,
|
||||
"swipe_up_end_y": 600
|
||||
"swipe_up_end_y": 600,
|
||||
"swipe_down_back_enabled": false,
|
||||
"swipe_down_back_count": 3,
|
||||
"log_unified_enabled": true,
|
||||
"log_unified_path": "logs/unified.log",
|
||||
"last_wifi_target": {
|
||||
"target": "192.168.10.102:39783",
|
||||
"model": "PEPM00",
|
||||
"saved_at": 1782148222
|
||||
},
|
||||
"region_coords_edit_enabled": false,
|
||||
"fudai_detail_body_bluepurple_threshold": 0.45,
|
||||
"fudai_detail_body_dark_threshold": 0.35,
|
||||
"fudai_task_status_template_threshold": 0.26,
|
||||
"fudai_detail_regions": {
|
||||
"legacy": {
|
||||
"content": [
|
||||
389,
|
||||
1273,
|
||||
1000,
|
||||
1534
|
||||
],
|
||||
"value": [
|
||||
643,
|
||||
1466,
|
||||
769,
|
||||
1656
|
||||
],
|
||||
"countdown_full": [
|
||||
390,
|
||||
1110,
|
||||
690,
|
||||
1230
|
||||
],
|
||||
"task_list": [
|
||||
50,
|
||||
1621,
|
||||
1032,
|
||||
1960
|
||||
],
|
||||
"task_count": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"participants": [
|
||||
389,
|
||||
1273,
|
||||
1000,
|
||||
1534
|
||||
],
|
||||
"button": [
|
||||
306,
|
||||
2030,
|
||||
780,
|
||||
2180
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
},
|
||||
"v2_0_two_task": {
|
||||
"content": [
|
||||
360,
|
||||
1410,
|
||||
1035,
|
||||
1495
|
||||
],
|
||||
"value": [
|
||||
300,
|
||||
1585,
|
||||
650,
|
||||
1685
|
||||
],
|
||||
"countdown_full": [
|
||||
760,
|
||||
1328,
|
||||
1038,
|
||||
1398
|
||||
],
|
||||
"task_list": [
|
||||
60,
|
||||
1840,
|
||||
1030,
|
||||
2005
|
||||
],
|
||||
"task_count": [
|
||||
860,
|
||||
1770,
|
||||
1035,
|
||||
1875
|
||||
],
|
||||
"participants": [
|
||||
520,
|
||||
1325,
|
||||
760,
|
||||
1415
|
||||
],
|
||||
"button": [
|
||||
70,
|
||||
2020,
|
||||
1010,
|
||||
2165
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
},
|
||||
"v2_0_one_task": {
|
||||
"content": [
|
||||
360,
|
||||
1460,
|
||||
1035,
|
||||
1545
|
||||
],
|
||||
"value": [
|
||||
350,
|
||||
1640,
|
||||
760,
|
||||
1735
|
||||
],
|
||||
"countdown_full": [
|
||||
700,
|
||||
1390,
|
||||
990,
|
||||
1470
|
||||
],
|
||||
"info_line": [
|
||||
430,
|
||||
1315,
|
||||
1055,
|
||||
1435
|
||||
],
|
||||
"task_list": [
|
||||
61,
|
||||
1845,
|
||||
885,
|
||||
2005
|
||||
],
|
||||
"task_count": [
|
||||
889,
|
||||
1855,
|
||||
1040,
|
||||
1960
|
||||
],
|
||||
"participants": [
|
||||
516,
|
||||
1396,
|
||||
743,
|
||||
1443
|
||||
],
|
||||
"button": [
|
||||
70,
|
||||
2050,
|
||||
1010,
|
||||
2195
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
}
|
||||
},
|
||||
"pixel_regions": {
|
||||
"lottery_result": {
|
||||
"button": [
|
||||
250,
|
||||
1275,
|
||||
825,
|
||||
1435
|
||||
],
|
||||
"pixel": [
|
||||
290,
|
||||
1300,
|
||||
790,
|
||||
1415
|
||||
],
|
||||
"click": [
|
||||
540,
|
||||
1360,
|
||||
0,
|
||||
0
|
||||
]
|
||||
},
|
||||
"attend_button": [
|
||||
200,
|
||||
2000,
|
||||
880,
|
||||
2120
|
||||
],
|
||||
"fansclub_join": [
|
||||
200,
|
||||
1940,
|
||||
880,
|
||||
2140
|
||||
],
|
||||
"coupon_popup": [
|
||||
9,
|
||||
1173,
|
||||
1079,
|
||||
2255
|
||||
],
|
||||
"shopping_redpacket": [
|
||||
200,
|
||||
300,
|
||||
880,
|
||||
1400
|
||||
],
|
||||
"fudai_detail_body": [
|
||||
0,
|
||||
1160,
|
||||
1080,
|
||||
2250
|
||||
],
|
||||
"fudai_task_status": [
|
||||
820,
|
||||
1815,
|
||||
1050,
|
||||
2035
|
||||
],
|
||||
"live_room_icon_bbox": [
|
||||
999,
|
||||
172,
|
||||
1028,
|
||||
202
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,501 @@
|
||||
{
|
||||
"needswitch": true,
|
||||
"infinite_loop_enabled": true,
|
||||
"wait_minutes": 5,
|
||||
"auto_update": {
|
||||
"enabled": true,
|
||||
"manifest_url": "",
|
||||
"fail_closed": true,
|
||||
"require_sha256": true,
|
||||
"timeout_seconds": 20,
|
||||
"installer_args": [
|
||||
"/VERYSILENT",
|
||||
"/SUPPRESSMSGBOXES",
|
||||
"/NORESTART",
|
||||
"/CURRENTUSER"
|
||||
]
|
||||
},
|
||||
"min_prize_value_yuan": 100.0,
|
||||
"min_participants": 0,
|
||||
"max_participants": 0,
|
||||
"skip_if_countdown_gt_seconds": 10,
|
||||
"reset_after_swipes_enabled": true,
|
||||
"reset_after_swipes": 20,
|
||||
"reset_after_swipes_action": "swipe",
|
||||
"reenter_live_entry_mode": "screen_center",
|
||||
"auto_join_fansclub": true,
|
||||
"fansclub_fail_action": "switch",
|
||||
"high_value_fudai_enabled": true,
|
||||
"high_value_fudai_threshold_yuan": 150.0,
|
||||
"high_value_fudai_join_ahead_seconds": 100,
|
||||
"high_value_fudai_max_swipe_back": 50,
|
||||
"high_value_fudai_max_reservations": 9999,
|
||||
"high_value_fudai_after_action": "continue",
|
||||
"high_value_room_revisit_enabled": false,
|
||||
"high_value_room_revisit_only_current_run": false,
|
||||
"reservation_back_verify_enabled": true,
|
||||
"reservation_back_swipe_delay": 0.1,
|
||||
"reservation_back_verify_wait_seconds": 3.0,
|
||||
"desktop_icon_x": 153,
|
||||
"desktop_icon_y": 260,
|
||||
"yanghao_fallback_live_x": 540,
|
||||
"yanghao_fallback_live_y": 2000,
|
||||
"yanghao_fallback_enter_live_x": 540,
|
||||
"yanghao_fallback_enter_live_y": 1200,
|
||||
"fudai_find_max_attempts": 99999,
|
||||
"fudai_icon_max_wait_seconds": 7.0,
|
||||
"fudai_icon_retry_delay_seconds": 0.1,
|
||||
"fudai_exit_after_misses": 7,
|
||||
"enable_back_on_misses": false,
|
||||
"fudai_click_wait_seconds": 1.5,
|
||||
"fudai_detail_initial_wait_seconds": 0.8,
|
||||
"fudai_detail_verified_wait_seconds": 0.2,
|
||||
"fudai_detail_retry_delay_seconds": 0.5,
|
||||
"fudai_detail_save_debug_images": true,
|
||||
"fudai_detail_ui_mode": "auto",
|
||||
"fudai_detail_ocr_content_enabled": true,
|
||||
"fudai_detail_ocr_value_enabled": true,
|
||||
"fudai_detail_ocr_countdown_enabled": true,
|
||||
"fudai_detail_ocr_task_enabled": true,
|
||||
"fudai_detail_ocr_task_count_enabled": true,
|
||||
"fudai_detail_ocr_button_enabled": true,
|
||||
"fudai_detail_ocr_participants_enabled": false,
|
||||
"fudai_detail_ocr_live_title_enabled": true,
|
||||
"pixel_detect_fudai_icon_enabled": true,
|
||||
"pixel_detect_coupon_popup_enabled": true,
|
||||
"pixel_detect_shopping_redpacket_enabled": true,
|
||||
"pixel_detect_lottery_result_enabled": true,
|
||||
"pixel_detect_attend_button_enabled": true,
|
||||
"pixel_detect_fansclub_join_enabled": true,
|
||||
"pixel_detect_fudai_detail_enabled": true,
|
||||
"pixel_detect_live_room_enabled": true,
|
||||
"ocr_lottery_result_enabled": true,
|
||||
"ocr_coupon_popup_enabled": true,
|
||||
"ocr_shopping_redpacket_enabled": false,
|
||||
"ocr_stage_page_enabled": true,
|
||||
"fudai_disable_content_recognition": false,
|
||||
"fudai_disable_task_recognition": false,
|
||||
"yanghao_recommend_duration_seconds": 180,
|
||||
"yanghao_recommend_interval_seconds": 600,
|
||||
"yanghao_like_prob": 0.1,
|
||||
"yanghao_fav_prob": 0.05,
|
||||
"yanghao_comment_prob": 0.25,
|
||||
"yanghao_icon_roi_size": 240,
|
||||
"yanghao_icon_match_threshold": 0.77,
|
||||
"yanghao_step_screenshot": true,
|
||||
"yanghao_like_roi_offset_x": 0,
|
||||
"yanghao_like_roi_offset_y": -50,
|
||||
"yanghao_like_roi_scale": 1.0,
|
||||
"yanghao_fav_roi_offset_x": 40,
|
||||
"yanghao_fav_roi_offset_y": 0,
|
||||
"yanghao_fav_roi_scale": 1.0,
|
||||
"yanghao_like_rect_x1": 933,
|
||||
"yanghao_like_rect_y1": 1164,
|
||||
"yanghao_like_rect_x2": 1042,
|
||||
"yanghao_like_rect_y2": 1262,
|
||||
"yanghao_fav_rect_x1": 938,
|
||||
"yanghao_fav_rect_y1": 1567,
|
||||
"yanghao_fav_rect_x2": 1036,
|
||||
"yanghao_fav_rect_y2": 1665,
|
||||
"contains_want": [],
|
||||
"contains_not_want": [
|
||||
"首饰盒",
|
||||
"袜子"
|
||||
],
|
||||
"fudai_quiet_hours_enabled": true,
|
||||
"fudai_quiet_start_hour": 2,
|
||||
"fudai_quiet_end_hour": 9,
|
||||
"yanghao_enabled": false,
|
||||
"yanghao_enable_actions": true,
|
||||
"yanghao_like_icon_x": 988,
|
||||
"yanghao_like_icon_y": 1218,
|
||||
"yanghao_fav_icon_x": 988,
|
||||
"yanghao_fav_icon_y": 1616,
|
||||
"yanghao_like_template_path": "assets/like.png",
|
||||
"yanghao_fav_template_path": "assets/fav.png",
|
||||
"yanghao_after_dwell_swipe_direction": "up",
|
||||
"yanghao_after_dwell_swipe_distance_px": 900,
|
||||
"yanghao_comment_btn_x": 988,
|
||||
"yanghao_comment_btn_y": 1410,
|
||||
"yanghao_dwell_on_action_min_seconds": 5.0,
|
||||
"yanghao_dwell_on_action_max_seconds": 20.0,
|
||||
"yanghao_comment_input_x": 0,
|
||||
"yanghao_comment_input_y": 0,
|
||||
"yanghao_comment_send_x": 0,
|
||||
"yanghao_comment_send_y": -1,
|
||||
"yanghao_comment_close_x": 0,
|
||||
"yanghao_comment_close_y": 0,
|
||||
"yanghao_comment_texts": [
|
||||
"好看!",
|
||||
"赞一个",
|
||||
"真不错",
|
||||
"喜欢这个风格",
|
||||
"太棒了",
|
||||
"很有创意",
|
||||
"支持一下",
|
||||
"笑死我了",
|
||||
"学习了",
|
||||
"被圈粉了",
|
||||
"期待更多",
|
||||
"必须收藏",
|
||||
"这也太治愈了",
|
||||
"质量很高",
|
||||
"简直绝了",
|
||||
"画面太美了",
|
||||
"配色好舒服",
|
||||
"氛围感满分",
|
||||
"做得很用心",
|
||||
"好想试试这个",
|
||||
"安利给朋友",
|
||||
"收藏备用",
|
||||
"太有意思了",
|
||||
"这音乐选得太绝",
|
||||
"太会了",
|
||||
"入坑了",
|
||||
"好惊喜",
|
||||
"真有参考价值",
|
||||
"好暖心的一条",
|
||||
"笑哭,我服了",
|
||||
"细节处理得很好",
|
||||
"太有才了",
|
||||
"看着就治愈",
|
||||
"学习到新方法",
|
||||
"大家都来看看",
|
||||
"点赞支持",
|
||||
"完美",
|
||||
"好看到不行"
|
||||
],
|
||||
"yanghao_like_keywords": [],
|
||||
"yanghao_fav_keywords": [],
|
||||
"stage_diag_max_time": 2.0,
|
||||
"stage_diag_max_step_time": 0.5,
|
||||
"live_room_match_threshold": 0.8,
|
||||
"enable_ocr_mode1": false,
|
||||
"fudai_template_match_enabled": false,
|
||||
"fudai_template_match_threshold": 0.7,
|
||||
"lucky_draw_red_ratio_threshold": 0.8,
|
||||
"shopping_redpacket_red_ratio_threshold": 0.2,
|
||||
"y_pianyi": 0,
|
||||
"skip_if_countdown_lt_seconds": 5,
|
||||
"no_attend_timeout_minutes": 30.0,
|
||||
"logging": {
|
||||
"level": "DEBUG",
|
||||
"file_path": "logs/unified.log",
|
||||
"keep_days": 1,
|
||||
"use_dated_logs": true,
|
||||
"rotation": {
|
||||
"enabled": true,
|
||||
"max_bytes": 10485760,
|
||||
"backup_count": 5,
|
||||
"when": "midnight",
|
||||
"interval": 1
|
||||
},
|
||||
"beautify_output": true,
|
||||
"show_timestamps": true,
|
||||
"show_execution_times": true,
|
||||
"debug_detail_level": "normal",
|
||||
"error_detail_level": "full",
|
||||
"action_log_format": "concise",
|
||||
"log_format_mode": "simple",
|
||||
"stage_diag_verbose": true,
|
||||
"color_output": true,
|
||||
"max_log_lines_display": 1000,
|
||||
"auto_scroll_logs": true,
|
||||
"performance_tracking": {
|
||||
"enabled": true,
|
||||
"track_function_calls": true,
|
||||
"track_database_queries": false,
|
||||
"slow_operation_threshold_ms": 100
|
||||
},
|
||||
"error_logging": {
|
||||
"capture_stack_traces": true,
|
||||
"include_context": true,
|
||||
"max_error_logs": 1000,
|
||||
"error_categories": [
|
||||
"ocr",
|
||||
"network",
|
||||
"validation",
|
||||
"system",
|
||||
"user_action"
|
||||
]
|
||||
},
|
||||
"compress_logs": true,
|
||||
"max_total_size_gb": 0.2,
|
||||
"compress_after_days": 1,
|
||||
"max_bytes": 104857600,
|
||||
"backup_count": 10,
|
||||
"enable_monitor": true,
|
||||
"monitor_warning_mb": 60.0,
|
||||
"monitor_critical_mb": 200.0
|
||||
},
|
||||
"debug_captures": {
|
||||
"enabled": true,
|
||||
"keep_days": 1,
|
||||
"max_files": 1000,
|
||||
"auto_cleanup": true,
|
||||
"async_save": false,
|
||||
"log_on_complete": false
|
||||
},
|
||||
"fudai_detail_template_threshold": 0.52,
|
||||
"switch_room_wait_after_stage_diag_seconds": 7.5,
|
||||
"coupon_template_match_threshold": 0.35,
|
||||
"attend_button_red_ratio_threshold": 0.25,
|
||||
"fansclub_join_red_ratio_threshold": 0.25,
|
||||
"shopping_redpacket_ocr_confidence_threshold": 0.35,
|
||||
"reservation_test_mode": false,
|
||||
"swipe_duration_ms": 250,
|
||||
"gui": {
|
||||
"theme": "litera",
|
||||
"realtime_status": {
|
||||
"refresh_interval_ms": 1000,
|
||||
"tail_items": 50
|
||||
}
|
||||
},
|
||||
"fansclub_click_delay": 0.6,
|
||||
"fansclub_auto_join_wait_seconds": 5.0,
|
||||
"fansclub_manual_wait_seconds": 3.0,
|
||||
"enable_streaming_screenshot": false,
|
||||
"yanghao_only": false,
|
||||
"record_room_title_mapping_enabled": true,
|
||||
"high_value_fudai_poll_before_seconds": 10.0,
|
||||
"high_value_room_revisit_min_interval_seconds": 300,
|
||||
"high_value_room_revisit_max_per_run": 20,
|
||||
"high_value_room_revisit_min_prize_value": 1000.0,
|
||||
"high_value_room_revisit_max_age_days": 1,
|
||||
"swipe_up_start_y": 1200,
|
||||
"swipe_up_end_y": 600,
|
||||
"swipe_down_back_enabled": false,
|
||||
"swipe_down_back_count": 3,
|
||||
"log_unified_enabled": true,
|
||||
"log_unified_path": "logs/unified.log",
|
||||
"region_coords_edit_enabled": false,
|
||||
"fudai_detail_body_bluepurple_threshold": 0.45,
|
||||
"fudai_detail_body_dark_threshold": 0.35,
|
||||
"fudai_task_status_template_threshold": 0.26,
|
||||
"fudai_detail_regions": {
|
||||
"legacy": {
|
||||
"content": [
|
||||
389,
|
||||
1273,
|
||||
1000,
|
||||
1534
|
||||
],
|
||||
"value": [
|
||||
643,
|
||||
1466,
|
||||
769,
|
||||
1656
|
||||
],
|
||||
"countdown_full": [
|
||||
390,
|
||||
1110,
|
||||
690,
|
||||
1230
|
||||
],
|
||||
"task_list": [
|
||||
50,
|
||||
1621,
|
||||
1032,
|
||||
1960
|
||||
],
|
||||
"task_count": [
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
0
|
||||
],
|
||||
"participants": [
|
||||
389,
|
||||
1273,
|
||||
1000,
|
||||
1534
|
||||
],
|
||||
"button": [
|
||||
306,
|
||||
2030,
|
||||
780,
|
||||
2180
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
},
|
||||
"v2_0_two_task": {
|
||||
"content": [
|
||||
360,
|
||||
1410,
|
||||
1035,
|
||||
1495
|
||||
],
|
||||
"value": [
|
||||
300,
|
||||
1585,
|
||||
650,
|
||||
1685
|
||||
],
|
||||
"countdown_full": [
|
||||
760,
|
||||
1328,
|
||||
1038,
|
||||
1398
|
||||
],
|
||||
"task_list": [
|
||||
60,
|
||||
1840,
|
||||
1030,
|
||||
2005
|
||||
],
|
||||
"task_count": [
|
||||
860,
|
||||
1770,
|
||||
1035,
|
||||
1875
|
||||
],
|
||||
"participants": [
|
||||
520,
|
||||
1325,
|
||||
760,
|
||||
1415
|
||||
],
|
||||
"button": [
|
||||
70,
|
||||
2020,
|
||||
1010,
|
||||
2165
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
},
|
||||
"v2_0_one_task": {
|
||||
"content": [
|
||||
360,
|
||||
1460,
|
||||
1035,
|
||||
1545
|
||||
],
|
||||
"value": [
|
||||
350,
|
||||
1640,
|
||||
760,
|
||||
1735
|
||||
],
|
||||
"countdown_full": [
|
||||
700,
|
||||
1390,
|
||||
990,
|
||||
1470
|
||||
],
|
||||
"info_line": [
|
||||
430,
|
||||
1315,
|
||||
1055,
|
||||
1435
|
||||
],
|
||||
"task_list": [
|
||||
61,
|
||||
1845,
|
||||
885,
|
||||
2005
|
||||
],
|
||||
"task_count": [
|
||||
889,
|
||||
1855,
|
||||
1040,
|
||||
1960
|
||||
],
|
||||
"participants": [
|
||||
516,
|
||||
1396,
|
||||
743,
|
||||
1443
|
||||
],
|
||||
"button": [
|
||||
70,
|
||||
2050,
|
||||
1010,
|
||||
2195
|
||||
],
|
||||
"live_title": [
|
||||
130,
|
||||
120,
|
||||
560,
|
||||
225
|
||||
]
|
||||
}
|
||||
},
|
||||
"pixel_regions": {
|
||||
"lottery_result": {
|
||||
"button": [
|
||||
250,
|
||||
1275,
|
||||
825,
|
||||
1435
|
||||
],
|
||||
"pixel": [
|
||||
290,
|
||||
1300,
|
||||
790,
|
||||
1415
|
||||
],
|
||||
"click": [
|
||||
540,
|
||||
1360,
|
||||
0,
|
||||
0
|
||||
]
|
||||
},
|
||||
"attend_button": [
|
||||
200,
|
||||
2000,
|
||||
880,
|
||||
2120
|
||||
],
|
||||
"fansclub_join": [
|
||||
200,
|
||||
1940,
|
||||
880,
|
||||
2140
|
||||
],
|
||||
"coupon_popup": [
|
||||
9,
|
||||
1173,
|
||||
1079,
|
||||
2255
|
||||
],
|
||||
"shopping_redpacket": [
|
||||
200,
|
||||
300,
|
||||
880,
|
||||
1400
|
||||
],
|
||||
"fudai_detail_body": [
|
||||
0,
|
||||
1160,
|
||||
1080,
|
||||
2250
|
||||
],
|
||||
"fudai_task_status": [
|
||||
820,
|
||||
1815,
|
||||
1050,
|
||||
2035
|
||||
],
|
||||
"live_room_icon_bbox": [
|
||||
999,
|
||||
172,
|
||||
1028,
|
||||
202
|
||||
]
|
||||
},
|
||||
"license": {
|
||||
"activation_url": "https://dy.absfan.cn/api/v1/activate",
|
||||
"timeout_seconds": 10
|
||||
}
|
||||
}
|
||||
@@ -1,222 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
ADB 截图基准测试脚本
|
||||
|
||||
用于测试 ADB exec-out screencap 的实际耗时,帮助诊断截图慢的问题。
|
||||
|
||||
使用方法:
|
||||
1. 确保设备已连接: adb devices
|
||||
2. 运行: python test_adb_screenshot_timing.py [device_id]
|
||||
如果不提供 device_id,将使用第一个设备
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
|
||||
def get_adb_path() -> str:
|
||||
"""获取 ADB 路径"""
|
||||
# 尝试从环境变量获取
|
||||
adb = os.environ.get("ADB_PATH", "adb")
|
||||
# 尝试常见路径
|
||||
if not os.path.exists(adb):
|
||||
common_paths = [
|
||||
"adb",
|
||||
r"C:\Users\{}\AppData\Local\Android\Sdk\platform-tools\adb.exe".format(os.environ.get("USERNAME", "")),
|
||||
r"C:\Android\platform-tools\adb.exe",
|
||||
]
|
||||
for path in common_paths:
|
||||
try:
|
||||
result = subprocess.run([path, "version"], capture_output=True, timeout=5)
|
||||
if result.returncode == 0:
|
||||
return path
|
||||
except Exception:
|
||||
continue
|
||||
return adb
|
||||
|
||||
|
||||
def get_device_id() -> Optional[str]:
|
||||
"""获取第一个连接的设备ID"""
|
||||
adb = get_adb_path()
|
||||
try:
|
||||
result = subprocess.run([adb, "devices"], capture_output=True, text=True, timeout=10)
|
||||
if result.returncode != 0:
|
||||
print(f"[错误] adb devices 失败: {result.stderr}")
|
||||
return None
|
||||
|
||||
lines = result.stdout.strip().split("\n")[1:] # 跳过第一行 "List of devices attached"
|
||||
devices = []
|
||||
for line in lines:
|
||||
if line.strip() and "\t" in line:
|
||||
device_id = line.split("\t")[0].strip()
|
||||
if device_id:
|
||||
devices.append(device_id)
|
||||
|
||||
if not devices:
|
||||
print("[错误] 未找到连接的设备")
|
||||
return None
|
||||
|
||||
if len(devices) > 1:
|
||||
print(f"[提示] 找到多个设备: {devices},使用第一个: {devices[0]}")
|
||||
|
||||
return devices[0]
|
||||
except Exception as e:
|
||||
print(f"[错误] 获取设备列表失败: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def test_exec_out_screencap(device_id: str, iterations: int = 5) -> None:
|
||||
"""测试 exec-out screencap 耗时"""
|
||||
adb = get_adb_path()
|
||||
print(f"\n{'='*60}")
|
||||
print(f"测试 ADB exec-out screencap")
|
||||
print(f"设备: {device_id}")
|
||||
print(f"迭代次数: {iterations}")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
times = []
|
||||
sizes = []
|
||||
|
||||
for i in range(iterations):
|
||||
try:
|
||||
start = time.time()
|
||||
result = subprocess.run(
|
||||
[adb, "-s", device_id, "exec-out", "screencap", "-p"],
|
||||
capture_output=True,
|
||||
timeout=15,
|
||||
)
|
||||
elapsed = (time.time() - start) * 1000.0 # 转换为毫秒
|
||||
|
||||
if result.returncode == 0:
|
||||
size = len(result.stdout)
|
||||
times.append(elapsed)
|
||||
sizes.append(size)
|
||||
print(f" 迭代 {i+1}: {elapsed:.1f}ms, 大小: {size/1024:.1f}KB")
|
||||
else:
|
||||
print(f" 迭代 {i+1}: 失败 (返回码: {result.returncode})")
|
||||
except subprocess.TimeoutExpired:
|
||||
print(f" 迭代 {i+1}: 超时 (>15秒)")
|
||||
except Exception as e:
|
||||
print(f" 迭代 {i+1}: 异常: {e}")
|
||||
|
||||
if times:
|
||||
avg_time = sum(times) / len(times)
|
||||
min_time = min(times)
|
||||
max_time = max(times)
|
||||
avg_size = sum(sizes) / len(sizes) if sizes else 0
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"统计结果:")
|
||||
print(f" 平均耗时: {avg_time:.1f}ms")
|
||||
print(f" 最小耗时: {min_time:.1f}ms")
|
||||
print(f" 最大耗时: {max_time:.1f}ms")
|
||||
print(f" 平均大小: {avg_size/1024:.1f}KB")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
if avg_time > 3000:
|
||||
print("[警告] 平均耗时超过3秒,可能存在问题:")
|
||||
print(" - 检查 USB 连接是否稳定")
|
||||
print(" - 检查是否使用 Wi-Fi ADB(通常较慢)")
|
||||
print(" - 检查设备性能是否正常")
|
||||
elif avg_time > 2000:
|
||||
print("[提示] 平均耗时超过2秒,建议:")
|
||||
print(" - 考虑使用 USB 连接而非 Wi-Fi")
|
||||
print(" - 检查设备性能")
|
||||
|
||||
|
||||
def test_shell_screencap_pull(device_id: str, iterations: int = 3) -> None:
|
||||
"""测试 shell screencap + pull 耗时(回退方案)"""
|
||||
adb = get_adb_path()
|
||||
print(f"\n{'='*60}")
|
||||
print(f"测试 ADB shell screencap + pull (回退方案)")
|
||||
print(f"设备: {device_id}")
|
||||
print(f"迭代次数: {iterations}")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
times = []
|
||||
|
||||
for i in range(iterations):
|
||||
try:
|
||||
# 清理旧文件
|
||||
subprocess.run([adb, "-s", device_id, "shell", "rm", "/sdcard/DCIM/screenshot.png"],
|
||||
capture_output=True, timeout=5)
|
||||
|
||||
start = time.time()
|
||||
|
||||
# Step 1: shell screencap
|
||||
step1_start = time.time()
|
||||
result1 = subprocess.run(
|
||||
[adb, "-s", device_id, "shell", "screencap", "-p", "/sdcard/DCIM/screenshot.png"],
|
||||
capture_output=True,
|
||||
timeout=10,
|
||||
)
|
||||
step1_dur = (time.time() - step1_start) * 1000.0
|
||||
|
||||
if result1.returncode != 0:
|
||||
print(f" 迭代 {i+1}: shell screencap 失败")
|
||||
continue
|
||||
|
||||
# Step 2: pull
|
||||
step2_start = time.time()
|
||||
result2 = subprocess.run(
|
||||
[adb, "-s", device_id, "pull", "/sdcard/DCIM/screenshot.png", "test_screenshot.png"],
|
||||
capture_output=True,
|
||||
timeout=10,
|
||||
)
|
||||
step2_dur = (time.time() - step2_start) * 1000.0
|
||||
|
||||
elapsed = (time.time() - start) * 1000.0
|
||||
|
||||
if result2.returncode == 0 and os.path.exists("test_screenshot.png"):
|
||||
size = os.path.getsize("test_screenshot.png")
|
||||
times.append(elapsed)
|
||||
print(f" 迭代 {i+1}: 总耗时 {elapsed:.1f}ms (screencap: {step1_dur:.1f}ms, pull: {step2_dur:.1f}ms), 大小: {size/1024:.1f}KB")
|
||||
try:
|
||||
os.remove("test_screenshot.png")
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
print(f" 迭代 {i+1}: pull 失败")
|
||||
except Exception as e:
|
||||
print(f" 迭代 {i+1}: 异常: {e}")
|
||||
|
||||
if times:
|
||||
avg_time = sum(times) / len(times)
|
||||
min_time = min(times)
|
||||
max_time = max(times)
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"统计结果 (回退方案):")
|
||||
print(f" 平均耗时: {avg_time:.1f}ms")
|
||||
print(f" 最小耗时: {min_time:.1f}ms")
|
||||
print(f" 最大耗时: {max_time:.1f}ms")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
|
||||
def main():
|
||||
device_id = None
|
||||
if len(sys.argv) > 1:
|
||||
device_id = sys.argv[1]
|
||||
else:
|
||||
device_id = get_device_id()
|
||||
|
||||
if not device_id:
|
||||
print("[错误] 无法获取设备ID")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"使用设备: {device_id}")
|
||||
print(f"ADB 路径: {get_adb_path()}")
|
||||
|
||||
# 测试 exec-out(主要方案)
|
||||
test_exec_out_screencap(device_id, iterations=5)
|
||||
|
||||
# 测试 shell + pull(回退方案,较少迭代)
|
||||
test_shell_screencap_pull(device_id, iterations=3)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,106 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试完全禁用截图服务功能
|
||||
"""
|
||||
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加项目根目录到路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def test_completely_disable_screenshot_service():
|
||||
"""测试完全禁用截图服务"""
|
||||
|
||||
print("测试完全禁用截图服务功能...")
|
||||
print("=" * 50)
|
||||
|
||||
# 1. 测试截图服务的get_screenshot方法
|
||||
print("\n1. 测试截图服务的get_screenshot方法")
|
||||
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
service = ScreenshotService.get_instance()
|
||||
|
||||
# 调用get_screenshot,应该直接返回False
|
||||
result = service.get_screenshot("test_device")
|
||||
print(f"service.get_screenshot() 返回: {result}")
|
||||
|
||||
if result == False:
|
||||
print("[OK] 截图服务正确返回False,不启动后台服务")
|
||||
else:
|
||||
print("[ERROR] 截图服务返回了非False值")
|
||||
return False
|
||||
|
||||
# 2. 测试服务状态
|
||||
print("\n2. 检查服务状态")
|
||||
|
||||
if service.is_running():
|
||||
print("[WARN] 服务正在运行,但应该已被禁用")
|
||||
else:
|
||||
print("[OK] 服务未运行")
|
||||
|
||||
print(f"当前设备ID: {service._current_device_id}")
|
||||
|
||||
# 3. 测试直接截图调用
|
||||
print("\n3. 测试直接截图调用")
|
||||
|
||||
from operations.screenshot_operations import ScreenshotOperations
|
||||
ops = ScreenshotOperations()
|
||||
|
||||
# 检查默认参数
|
||||
import inspect
|
||||
sig = inspect.signature(ops.get_screenshot)
|
||||
params = sig.parameters
|
||||
use_service_default = params['use_service'].default
|
||||
|
||||
print(f"直接截图方法use_service默认值: {use_service_default}")
|
||||
|
||||
if use_service_default == False:
|
||||
print("[OK] 直接截图方法默认不使用服务")
|
||||
else:
|
||||
print("[WARN] 直接截图方法仍可能使用服务")
|
||||
|
||||
# 4. 验证所有修改
|
||||
print("\n4. 验证所有修改")
|
||||
|
||||
modified_files = [
|
||||
"operations/screenshot_operations.py",
|
||||
"operations/screenshot_service.py",
|
||||
"douyin/core/douyin_fudai.py",
|
||||
"douyin/core/douyin_main_flow.py",
|
||||
"fudai_detail_modules/fudai_detail_reader.py"
|
||||
]
|
||||
|
||||
for file_path in modified_files:
|
||||
if os.path.exists(file_path):
|
||||
print(f"[OK] {file_path} 存在")
|
||||
else:
|
||||
print(f"[ERROR] {file_path} 不存在")
|
||||
return False
|
||||
|
||||
# 5. 总结禁用状态
|
||||
print("\n5. 截图服务禁用总结")
|
||||
print("-" * 40)
|
||||
print("已完成的禁用:")
|
||||
print("1. [DONE] 修改 get_screenshot() 默认 use_service=False")
|
||||
print("2. [DONE] 让 ScreenshotService.get_screenshot() 直接返回False")
|
||||
print("3. [DONE] 移除所有后台服务启动代码")
|
||||
print("4. [DONE] 移除设备ID变更时的自动服务启动")
|
||||
print("5. [DONE] 移除OCR操作后的服务重启")
|
||||
|
||||
print("\n预期效果:")
|
||||
print("- 所有截图调用都会使用直接ADB命令")
|
||||
print("- 后台截图服务完全不会启动")
|
||||
print("- 每次截图都是独立的,不会复用缓存")
|
||||
print("- 系统更加稳定,但响应稍慢")
|
||||
|
||||
return True
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_completely_disable_screenshot_service()
|
||||
print(f"\n{'='*50}")
|
||||
print(f"测试结果: {'PASS' if success else 'FAIL'}")
|
||||
print("后台截图服务已完全禁用,使用原始直接截图模式")
|
||||
print(f"{'='*50}")
|
||||
@@ -1,287 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
测试直接截图功能
|
||||
验证所有截图调用都使用直接模式(use_service=False)
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
# 添加项目根目录到路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def test_screenshot_operations():
|
||||
"""测试 operations.screenshot_operations 模块"""
|
||||
print("=" * 80)
|
||||
print("测试 1: operations.screenshot_operations.get_screenshot()")
|
||||
print("=" * 80)
|
||||
|
||||
try:
|
||||
from operations.screenshot_operations import get_screenshot, ScreenshotOperations
|
||||
|
||||
# 获取设备ID
|
||||
device_id = os.environ.get("DEVICE_ID", "")
|
||||
if not device_id:
|
||||
print("[WARN] 未设置 DEVICE_ID 环境变量,尝试从配置读取...")
|
||||
try:
|
||||
import json
|
||||
import path_config
|
||||
config_path = path_config.get_config_path()
|
||||
# 尝试从常见位置读取
|
||||
device_id = "MB75DEFQZHZTGMLJ" # 从日志中看到的设备ID
|
||||
except Exception:
|
||||
print("[ERROR] 无法获取设备ID,请设置环境变量 DEVICE_ID")
|
||||
return False
|
||||
|
||||
print(f"设备ID: {device_id}")
|
||||
print(f"测试模式: 直接截图 (use_service=False)")
|
||||
print()
|
||||
|
||||
# 测试1: 使用默认参数(应该是 False)
|
||||
print("测试 1.1: 使用默认参数调用 get_screenshot()")
|
||||
start = time.time()
|
||||
try:
|
||||
result = get_screenshot(device_id)
|
||||
elapsed = (time.time() - start) * 1000
|
||||
status = "[OK] 成功" if result else "[FAIL] 失败"
|
||||
print(f" 结果: {status}, 耗时: {elapsed:.1f}ms")
|
||||
except Exception as e:
|
||||
elapsed = (time.time() - start) * 1000
|
||||
print(f" [ERROR] 异常: {e}, 耗时: {elapsed:.1f}ms")
|
||||
|
||||
print()
|
||||
|
||||
# 测试2: 显式传递 use_service=False
|
||||
print("测试 1.2: 显式传递 use_service=False")
|
||||
start = time.time()
|
||||
try:
|
||||
ops = ScreenshotOperations()
|
||||
result = ops.get_screenshot(device_id, use_service=False)
|
||||
elapsed = (time.time() - start) * 1000
|
||||
status = "[OK] 成功" if result else "[FAIL] 失败"
|
||||
print(f" 结果: {status}, 耗时: {elapsed:.1f}ms")
|
||||
except Exception as e:
|
||||
elapsed = (time.time() - start) * 1000
|
||||
print(f" [ERROR] 异常: {e}, 耗时: {elapsed:.1f}ms")
|
||||
|
||||
print()
|
||||
|
||||
# 测试3: 验证不会使用服务模式
|
||||
print("测试 1.3: 验证不会调用后台服务")
|
||||
try:
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
service = ScreenshotService.get_instance()
|
||||
service_running_before = service.is_running()
|
||||
print(f" 服务运行状态(测试前): {service_running_before}")
|
||||
|
||||
# 调用截图(应该不会启动服务)
|
||||
get_screenshot(device_id)
|
||||
|
||||
service_running_after = service.is_running()
|
||||
print(f" 服务运行状态(测试后): {service_running_after}")
|
||||
|
||||
if not service_running_after:
|
||||
print(" [OK] 确认:服务未被启动(符合预期)")
|
||||
else:
|
||||
print(" [WARN] 警告:服务仍在运行(可能之前已启动)")
|
||||
except Exception as e:
|
||||
print(f" [WARN] 无法检查服务状态: {e}")
|
||||
|
||||
return True
|
||||
|
||||
except ImportError as e:
|
||||
print(f"[ERROR] 导入错误: {e}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 测试失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
def test_underlying_operations():
|
||||
"""测试 Underlying_Operations 模块"""
|
||||
print()
|
||||
print("=" * 80)
|
||||
print("测试 2: Underlying_Operations.get_screenshot()")
|
||||
print("=" * 80)
|
||||
|
||||
try:
|
||||
from Underlying_Operations import underlying_operations
|
||||
|
||||
device_id = os.environ.get("DEVICE_ID", "MB75DEFQZHZTGMLJ")
|
||||
print(f"设备ID: {device_id}")
|
||||
print()
|
||||
|
||||
ops = underlying_operations()
|
||||
|
||||
# 测试默认参数
|
||||
print("测试 2.1: 使用默认参数(应该是 False)")
|
||||
start = time.time()
|
||||
try:
|
||||
result = ops.get_screenshot(device_id)
|
||||
elapsed = (time.time() - start) * 1000
|
||||
status = "[OK] 成功" if result else "[FAIL] 失败"
|
||||
print(f" 结果: {status}, 耗时: {elapsed:.1f}ms")
|
||||
|
||||
if elapsed > 2000:
|
||||
print(f" [WARN] 警告:耗时较长 ({elapsed:.1f}ms),但应该 < 2秒")
|
||||
elif elapsed > 6000:
|
||||
print(f" [ERROR] 错误:耗时过长 ({elapsed:.1f}ms),可能仍在使用服务模式")
|
||||
else:
|
||||
print(f" [OK] 正常:耗时在预期范围内")
|
||||
except Exception as e:
|
||||
elapsed = (time.time() - start) * 1000
|
||||
print(f" [ERROR] 异常: {e}, 耗时: {elapsed:.1f}ms")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 测试失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
def test_stage_diagnosis_screenshot():
|
||||
"""测试阶段诊断中的截图调用"""
|
||||
print()
|
||||
print("=" * 80)
|
||||
print("测试 3: 阶段诊断截图调用(模拟)")
|
||||
print("=" * 80)
|
||||
|
||||
try:
|
||||
# 检查关键文件中的调用
|
||||
import inspect
|
||||
from douyin.core import douyin_fudai
|
||||
|
||||
# 查找 get_screenshot 调用
|
||||
source_file = inspect.getfile(douyin_fudai.fudai_analyse)
|
||||
with open(source_file, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
# 检查是否包含 use_service=False
|
||||
if 'get_screenshot(self.device_id, use_service=False)' in content:
|
||||
print(" [OK] 确认:douyin_fudai.py 中已使用 use_service=False")
|
||||
elif 'get_screenshot(self.device_id)' in content:
|
||||
print(" [WARN] 警告:douyin_fudai.py 中未显式传递 use_service=False")
|
||||
print(" (但默认值应该是 False)")
|
||||
else:
|
||||
print(" [WARN] 未找到 get_screenshot 调用")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f" [WARN] 无法检查: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def check_logs_for_timeouts():
|
||||
"""检查日志中是否有超时记录"""
|
||||
print()
|
||||
print("=" * 80)
|
||||
print("测试 4: 检查日志中的超时记录")
|
||||
print("=" * 80)
|
||||
|
||||
try:
|
||||
import glob
|
||||
log_files = glob.glob("logs/unified_*.log")
|
||||
if not log_files:
|
||||
print(" [WARN] 未找到日志文件")
|
||||
return True
|
||||
|
||||
# 读取最新的日志文件
|
||||
latest_log = max(log_files, key=os.path.getmtime)
|
||||
print(f" 检查日志文件: {latest_log}")
|
||||
|
||||
timeout_count = 0
|
||||
screenshot_count = 0
|
||||
|
||||
with open(latest_log, 'r', encoding='utf-8', errors='ignore') as f:
|
||||
# 只读取最后 1000 行
|
||||
lines = f.readlines()[-1000:]
|
||||
|
||||
for line in lines:
|
||||
if '[TIMEOUT] 等待超时' in line or '等待超时' in line:
|
||||
timeout_count += 1
|
||||
if 'screenshot_elapsed_seconds' in line:
|
||||
screenshot_count += 1
|
||||
# 提取耗时
|
||||
try:
|
||||
import re
|
||||
match = re.search(r'screenshot_elapsed_seconds=([\d.]+)', line)
|
||||
if match:
|
||||
elapsed = float(match.group(1))
|
||||
if elapsed > 5.0:
|
||||
print(f" [WARN] 发现耗时过长的截图: {elapsed:.2f}秒")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print(f" 超时记录数(最近1000行): {timeout_count}")
|
||||
print(f" 截图耗时记录数: {screenshot_count}")
|
||||
|
||||
if timeout_count == 0:
|
||||
print(" [OK] 未发现超时记录(符合预期)")
|
||||
else:
|
||||
print(f" [WARN] 发现 {timeout_count} 条超时记录")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f" [WARN] 无法检查日志: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
"""主测试函数"""
|
||||
print()
|
||||
print("=" * 80)
|
||||
print("直接截图功能测试")
|
||||
print("=" * 80)
|
||||
print(f"测试时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
print()
|
||||
|
||||
results = []
|
||||
|
||||
# 测试1: screenshot_operations
|
||||
results.append(("screenshot_operations", test_screenshot_operations()))
|
||||
|
||||
# 测试2: underlying_operations
|
||||
results.append(("underlying_operations", test_underlying_operations()))
|
||||
|
||||
# 测试3: 代码检查
|
||||
results.append(("stage_diagnosis", test_stage_diagnosis_screenshot()))
|
||||
|
||||
# 测试4: 日志检查
|
||||
results.append(("log_check", check_logs_for_timeouts()))
|
||||
|
||||
# 总结
|
||||
print()
|
||||
print("=" * 80)
|
||||
print("测试总结")
|
||||
print("=" * 80)
|
||||
|
||||
passed = sum(1 for _, result in results if result)
|
||||
total = len(results)
|
||||
|
||||
for name, result in results:
|
||||
status = "[PASS] 通过" if result else "[FAIL] 失败"
|
||||
print(f" {name}: {status}")
|
||||
|
||||
print()
|
||||
print(f"总计: {passed}/{total} 测试通过")
|
||||
|
||||
if passed == total:
|
||||
print("[SUCCESS] 所有测试通过!")
|
||||
return 0
|
||||
else:
|
||||
print("[WARN] 部分测试未通过,请检查上述输出")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
exit(main())
|
||||
@@ -1,118 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试禁用流式截图功能
|
||||
"""
|
||||
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加项目根目录到路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def test_disable_streaming_screenshots():
|
||||
"""测试禁用流式截图功能"""
|
||||
|
||||
print("测试禁用流式截图功能...")
|
||||
print("=" * 50)
|
||||
|
||||
# 1. 检查截图服务的默认行为
|
||||
print("\n1. 检查截图服务默认行为")
|
||||
|
||||
from operations.screenshot_operations import ScreenshotOperations
|
||||
ops = ScreenshotOperations()
|
||||
|
||||
# 检查get_screenshot方法的默认参数
|
||||
import inspect
|
||||
sig = inspect.signature(ops.get_screenshot)
|
||||
params = sig.parameters
|
||||
|
||||
use_service_default = params['use_service'].default
|
||||
print(f"get_screenshot use_service 默认值: {use_service_default}")
|
||||
|
||||
if use_service_default == False:
|
||||
print("[OK] 默认禁用后台服务,使用直接截图")
|
||||
else:
|
||||
print("[FAIL] 仍然使用后台服务")
|
||||
|
||||
# 2. 模拟截图调用
|
||||
print("\n2. 模拟截图调用测试")
|
||||
|
||||
# 创建模拟的analyser
|
||||
class MockAnalyser:
|
||||
def __init__(self):
|
||||
self.device_id = "test_device_123"
|
||||
self.operation = ops
|
||||
|
||||
def _log_kv(self, key, value, **kwargs):
|
||||
print(f"[{key}] {value}")
|
||||
|
||||
analyser = MockAnalyser()
|
||||
|
||||
# 测试调用(这里不会实际执行截图,因为没有真实设备)
|
||||
try:
|
||||
# 这里只是检查方法调用路径,不会实际截图
|
||||
print("截图方法调用路径:")
|
||||
print("- get_screenshot(use_service=False) -> 直接截图")
|
||||
print("- 跳过后台服务检查")
|
||||
print("[OK] 确认使用直接截图模式")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 测试失败: {e}")
|
||||
|
||||
# 3. 检查后台服务状态
|
||||
print("\n3. 检查后台服务状态")
|
||||
|
||||
try:
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
service = ScreenshotService.get_instance()
|
||||
|
||||
if service.is_running():
|
||||
print("[WARN] 后台服务正在运行(可能有其他地方启动)")
|
||||
else:
|
||||
print("[OK] 后台服务未运行")
|
||||
|
||||
print(f"服务状态: running={service.is_running()}")
|
||||
print(f"当前设备ID: {service._current_device_id}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"检查服务状态失败: {e}")
|
||||
|
||||
# 4. 验证修改的文件
|
||||
print("\n4. 验证修改的文件")
|
||||
|
||||
modified_files = [
|
||||
"operations/screenshot_operations.py",
|
||||
"douyin/core/douyin_fudai.py",
|
||||
"douyin/core/douyin_main_flow.py"
|
||||
]
|
||||
|
||||
for file_path in modified_files:
|
||||
if os.path.exists(file_path):
|
||||
print(f"[OK] {file_path} 存在")
|
||||
else:
|
||||
print(f"[ERROR] {file_path} 不存在")
|
||||
|
||||
# 5. 总结
|
||||
print("\n5. 修改总结")
|
||||
print("-" * 30)
|
||||
print("已完成的修改:")
|
||||
print("1. [DONE] 修改 get_screenshot() 默认 use_service=False")
|
||||
print("2. [DONE] 移除 douyin_fudai.py 中的后台服务启动")
|
||||
print("3. [DONE] 移除 douyin_main_flow.py 中的后台服务启动")
|
||||
print("4. [DONE] 所有截图调用将使用直接截图模式")
|
||||
|
||||
print("\n预期效果:")
|
||||
print("- 每次截图都会直接调用ADB命令")
|
||||
print("- 不再有后台截图服务持续运行")
|
||||
print("- 截图响应时间会变慢,但更稳定")
|
||||
print("- 消除了后台服务的复杂性")
|
||||
|
||||
return True
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_disable_streaming_screenshots()
|
||||
print(f"\n{'='*50}")
|
||||
print(f"测试结果: {'PASS' if success else 'FAIL'}")
|
||||
print("流式截图已暂时禁用,使用直接截图模式")
|
||||
print(f"{'='*50}")
|
||||
@@ -1,95 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试循环期间停止后台截图服务的功能
|
||||
"""
|
||||
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加项目根目录到路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def test_loop_screenshot_service_stop():
|
||||
"""测试循环期间后台截图服务是否被停止"""
|
||||
|
||||
print("测试循环期间停止后台截图服务功能...")
|
||||
|
||||
# 1. 启动截图服务(模拟正常启动)
|
||||
print("\n1. 启动后台截图服务...")
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
service = ScreenshotService.get_instance()
|
||||
|
||||
device_id = "emulator-5554"
|
||||
|
||||
if not service.is_running():
|
||||
service.start(device_id, interval=1.5)
|
||||
time.sleep(0.5)
|
||||
|
||||
if service.is_running():
|
||||
print("[OK] 后台截图服务已启动")
|
||||
else:
|
||||
print("[FAIL] 后台截图服务启动失败")
|
||||
return False
|
||||
|
||||
# 2. 模拟fudai_choujiang的逻辑
|
||||
print("\n2. 模拟循环开始前的截图服务停止...")
|
||||
|
||||
# 这部分代码模拟fudai_choujiang中的逻辑
|
||||
screenshot_service_stopped = False
|
||||
try:
|
||||
service_inner = ScreenshotService.get_instance()
|
||||
if service_inner.is_running():
|
||||
service_inner.stop()
|
||||
screenshot_service_stopped = True
|
||||
print("[OK] 循环开始前停止后台截图服务")
|
||||
except Exception as e:
|
||||
print(f"[FAIL] 停止后台截图服务失败: {e}")
|
||||
return False
|
||||
|
||||
# 检查服务是否已停止
|
||||
if service.is_running():
|
||||
print("[FAIL] 后台截图服务仍然在运行")
|
||||
return False
|
||||
else:
|
||||
print("[OK] 后台截图服务已停止")
|
||||
|
||||
# 3. 模拟循环中的操作(这里不会触发截图服务)
|
||||
print("\n3. 模拟循环中的阶段诊断...")
|
||||
time.sleep(2) # 模拟一些操作
|
||||
|
||||
# 4. 模拟程序结束(atexit会重新启动服务)
|
||||
print("\n4. 模拟程序结束,检查服务重新启动...")
|
||||
|
||||
# 手动调用atexit函数(在实际运行中会自动调用)
|
||||
if screenshot_service_stopped:
|
||||
try:
|
||||
service_restart = ScreenshotService.get_instance()
|
||||
if device_id:
|
||||
service_restart.start(device_id, interval=1.5)
|
||||
print("[OK] 循环结束后重新启动后台截图服务")
|
||||
except Exception as e:
|
||||
print(f"[FAIL] 重新启动后台截图服务失败: {e}")
|
||||
return False
|
||||
|
||||
# 检查服务是否重新启动
|
||||
time.sleep(0.5)
|
||||
if service.is_running():
|
||||
print("[OK] 后台截图服务已重新启动")
|
||||
success = True
|
||||
else:
|
||||
print("[FAIL] 后台截图服务未重新启动")
|
||||
success = False
|
||||
|
||||
# 5. 清理
|
||||
if service.is_running():
|
||||
service.stop()
|
||||
print("\n5. 测试完成,停止后台截图服务")
|
||||
|
||||
print(f"\n测试结果: {'PASS' if success else 'FAIL'}")
|
||||
return success
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_loop_screenshot_service_stop()
|
||||
sys.exit(0 if success else 1)
|
||||
@@ -1,100 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试OCR多线程优化效果
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from operations.screenshot_service import get_optimal_workers
|
||||
|
||||
def test_ocr_multithread_config():
|
||||
"""测试OCR多线程配置"""
|
||||
print("=" * 70)
|
||||
print("OCR多线程配置检查")
|
||||
print("=" * 70)
|
||||
print()
|
||||
|
||||
# 1. CPU信息
|
||||
cpu_count = os.cpu_count() or 4
|
||||
print(f"1. CPU信息")
|
||||
print("-" * 70)
|
||||
print(f" CPU核心数: {cpu_count}")
|
||||
print()
|
||||
|
||||
# 2. OMP线程数配置
|
||||
print("2. OMP线程数配置(底层库多线程)")
|
||||
print("-" * 70)
|
||||
omp_threads = os.environ.get("OMP_NUM_THREADS", "未设置")
|
||||
print(f" OMP_NUM_THREADS: {omp_threads}")
|
||||
|
||||
# 计算推荐的OMP线程数
|
||||
optimal_omp_threads = min(4, max(2, cpu_count // 3))
|
||||
print(f" 推荐值: {optimal_omp_threads} (根据CPU核心数动态计算)")
|
||||
print()
|
||||
|
||||
# 3. 线程池大小配置
|
||||
print("3. 线程池大小配置(任务级多线程)")
|
||||
print("-" * 70)
|
||||
optimal_workers = get_optimal_workers()
|
||||
print(f" 推荐线程池大小: {optimal_workers} (根据CPU核心数动态计算)")
|
||||
print(f" 说明: 用于并行执行多个OCR任务")
|
||||
print()
|
||||
|
||||
# 4. 优化说明
|
||||
print("4. 优化说明")
|
||||
print("-" * 70)
|
||||
print(" 优化前:")
|
||||
print(" - OMP_NUM_THREADS=1 (限制底层库只能使用1个线程)")
|
||||
print(" - 线程池大小固定为6 (未充分利用多核CPU)")
|
||||
print()
|
||||
print(" 优化后:")
|
||||
print(f" - OMP_NUM_THREADS={optimal_omp_threads} (允许底层库使用多线程)")
|
||||
print(f" - 线程池大小={optimal_workers} (根据CPU核心数动态调整)")
|
||||
print()
|
||||
print(" 预期效果:")
|
||||
print(" - 底层库(PaddleOCR/EasyOCR)可以并行处理图像")
|
||||
print(" - 多个OCR任务可以并行执行")
|
||||
print(" - 充分利用多核CPU资源")
|
||||
print(" - 预计性能提升: 30-50% (取决于任务数量和CPU核心数)")
|
||||
print()
|
||||
|
||||
# 5. 验证OCR引擎是否已初始化
|
||||
print("5. OCR引擎状态")
|
||||
print("-" * 70)
|
||||
try:
|
||||
from operations.ocr_operations import _ocr_processor
|
||||
if _ocr_processor.ocr is not None:
|
||||
print(f" OCR引擎: {_ocr_processor.ocr_type}")
|
||||
print(" 状态: 已初始化")
|
||||
else:
|
||||
print(" 状态: 未初始化(延迟初始化)")
|
||||
except Exception as e:
|
||||
print(f" 状态: 检查失败 - {e}")
|
||||
print()
|
||||
|
||||
print("=" * 70)
|
||||
print("检查完成")
|
||||
print("=" * 70)
|
||||
|
||||
def test_ocr_performance():
|
||||
"""测试OCR性能(需要实际运行OCR)"""
|
||||
print()
|
||||
print("=" * 70)
|
||||
print("OCR性能测试")
|
||||
print("=" * 70)
|
||||
print()
|
||||
print("提示: 此测试需要实际运行OCR任务")
|
||||
print(" 可以在实际使用中观察OCR耗时变化")
|
||||
print()
|
||||
print("测试方法:")
|
||||
print("1. 运行程序,观察OCR任务的耗时")
|
||||
print("2. 对比优化前后的性能差异")
|
||||
print("3. 查看日志中的OCR耗时信息")
|
||||
print()
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_ocr_multithread_config()
|
||||
test_ocr_performance()
|
||||
@@ -1,325 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
OCR多线程性能测试
|
||||
测试优化前后的性能差异
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
import tempfile
|
||||
|
||||
def test_ocr_single(image_path, ocr_processor, omp_threads):
|
||||
"""测试单个OCR任务的性能"""
|
||||
old_omp = os.environ.get('OMP_NUM_THREADS', '4')
|
||||
os.environ['OMP_NUM_THREADS'] = str(omp_threads)
|
||||
|
||||
try:
|
||||
img = Image.open(image_path)
|
||||
if img.mode != 'RGB':
|
||||
img = img.convert('RGB')
|
||||
img_np = np.array(img)
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
if ocr_processor.ocr_type == "easyocr":
|
||||
result = ocr_processor.ocr.readtext(img_np)
|
||||
else:
|
||||
result = ocr_processor.ocr.ocr(img_np)
|
||||
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
|
||||
# 提取文本
|
||||
from Underlying_Operations import underlying_operations
|
||||
ops = underlying_operations()
|
||||
text = ops.extract_ocr_content(result)
|
||||
|
||||
return {
|
||||
'time': elapsed,
|
||||
'text': text,
|
||||
'success': True
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
'time': 0,
|
||||
'text': '',
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}
|
||||
finally:
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
|
||||
def test_ocr_config(image_path, config_name, omp_threads, num_iterations=5):
|
||||
"""测试特定配置下的OCR性能"""
|
||||
print(f"\n{'='*70}")
|
||||
print(f"测试配置: {config_name}")
|
||||
print(f"{'='*70}")
|
||||
print(f"OMP_NUM_THREADS: {omp_threads}")
|
||||
print(f"迭代次数: {num_iterations}")
|
||||
print()
|
||||
|
||||
# 初始化OCR
|
||||
try:
|
||||
from operations.ocr_operations import OCRProcessor
|
||||
ocr_processor = OCRProcessor()
|
||||
ensure_ocr = getattr(ocr_processor, '_ensure_ocr')
|
||||
ensure_ocr()
|
||||
|
||||
if ocr_processor.ocr is None:
|
||||
print("[ERROR] OCR引擎未初始化")
|
||||
return None
|
||||
|
||||
print(f"OCR引擎: {ocr_processor.ocr_type}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] OCR引擎初始化失败: {e}")
|
||||
return None
|
||||
|
||||
# 执行多次测试
|
||||
times = []
|
||||
for i in range(num_iterations):
|
||||
result = test_ocr_single(image_path, ocr_processor, omp_threads)
|
||||
if result['success']:
|
||||
times.append(result['time'])
|
||||
print(f" 第{i+1}次: {result['time']:.0f}ms - {result['text'][:30] if result['text'] else '(空)'}")
|
||||
else:
|
||||
print(f" 第{i+1}次: 失败 - {result.get('error', 'Unknown')}")
|
||||
|
||||
if not times:
|
||||
print("[ERROR] 所有测试都失败")
|
||||
return None
|
||||
|
||||
avg_time = sum(times) / len(times)
|
||||
min_time = min(times)
|
||||
max_time = max(times)
|
||||
|
||||
print()
|
||||
print(f"平均耗时: {avg_time:.0f}ms")
|
||||
print(f"最快: {min_time:.0f}ms")
|
||||
print(f"最慢: {max_time:.0f}ms")
|
||||
print()
|
||||
|
||||
return {
|
||||
'avg_time': avg_time,
|
||||
'min_time': min_time,
|
||||
'max_time': max_time,
|
||||
'times': times
|
||||
}
|
||||
|
||||
def test_parallel_ocr(image_path, config_name, omp_threads, max_workers, num_tasks=6):
|
||||
"""测试并行OCR性能"""
|
||||
print(f"\n{'='*70}")
|
||||
print(f"测试配置: {config_name}")
|
||||
print(f"{'='*70}")
|
||||
print(f"OMP_NUM_THREADS: {omp_threads}")
|
||||
print(f"线程池大小: {max_workers}")
|
||||
print(f"任务数量: {num_tasks}")
|
||||
print()
|
||||
|
||||
# 设置OMP线程数
|
||||
old_omp = os.environ.get('OMP_NUM_THREADS', '4')
|
||||
os.environ['OMP_NUM_THREADS'] = str(omp_threads)
|
||||
|
||||
# 初始化OCR
|
||||
try:
|
||||
from operations.ocr_operations import OCRProcessor
|
||||
ocr_processor = OCRProcessor()
|
||||
ensure_ocr = getattr(ocr_processor, '_ensure_ocr')
|
||||
ensure_ocr()
|
||||
|
||||
if ocr_processor.ocr is None:
|
||||
print("[ERROR] OCR引擎未初始化")
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
return None
|
||||
|
||||
print(f"OCR引擎: {ocr_processor.ocr_type}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] OCR引擎初始化失败: {e}")
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
return None
|
||||
|
||||
# 创建多个相同的任务(使用同一张图片)
|
||||
def ocr_task():
|
||||
return test_ocr_single(image_path, ocr_processor, omp_threads)
|
||||
|
||||
# 并行执行
|
||||
print("开始并行OCR识别...")
|
||||
start_time = time.time()
|
||||
results = []
|
||||
|
||||
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
||||
futures = [executor.submit(ocr_task) for _ in range(num_tasks)]
|
||||
|
||||
for i, future in enumerate(futures):
|
||||
try:
|
||||
result = future.result(timeout=60)
|
||||
results.append(result)
|
||||
if result['success']:
|
||||
print(f" 任务{i+1}: {result['time']:.0f}ms - {result['text'][:20] if result['text'] else '(空)'}")
|
||||
else:
|
||||
print(f" 任务{i+1}: 失败 - {result.get('error', 'Unknown')}")
|
||||
except Exception as e:
|
||||
print(f" 任务{i+1}: 异常 - {e}")
|
||||
results.append({'success': False, 'error': str(e)})
|
||||
|
||||
total_elapsed = (time.time() - start_time) * 1000
|
||||
|
||||
# 恢复OMP设置
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
|
||||
# 统计结果
|
||||
successful_results = [r for r in results if r.get('success', False)]
|
||||
efficiency = 0 # 初始化效率变量
|
||||
if successful_results:
|
||||
task_times = [r['time'] for r in successful_results]
|
||||
total_task_time = sum(task_times)
|
||||
avg_task_time = total_task_time / len(task_times)
|
||||
|
||||
print()
|
||||
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
|
||||
print(f"任务总耗时: {total_task_time:.0f}ms")
|
||||
print(f"平均每个任务: {avg_task_time:.0f}ms")
|
||||
if total_task_time > 0:
|
||||
efficiency = total_task_time / total_elapsed
|
||||
print(f"并行效率: {efficiency:.2f}x (理想值: {num_tasks:.1f}x)")
|
||||
print()
|
||||
|
||||
return {
|
||||
'total_time': total_elapsed,
|
||||
'avg_task_time': avg_task_time,
|
||||
'task_times': task_times,
|
||||
'efficiency': efficiency if total_task_time > 0 else 0
|
||||
}
|
||||
else:
|
||||
print("[ERROR] 所有任务都失败")
|
||||
return None
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
# 默认图片路径
|
||||
default_image = "pic/debug_captures/2025-12-31/20251231_152118_ocr_福袋倒计时_分钟_识别后_(390,1110)-(480,1230)_模式_1_文本长度_2_数字_14_类型_digits_平均置信度_0.9991_最小置信度_0.9991_最大置信度_0.9991_置信度项数_1_有完整截图_是_有坐标_是.png"
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
image_path = sys.argv[1]
|
||||
else:
|
||||
image_path = default_image
|
||||
|
||||
if not os.path.isabs(image_path):
|
||||
project_root = os.path.dirname(os.path.abspath(__file__))
|
||||
image_path = os.path.join(project_root, image_path)
|
||||
|
||||
if not os.path.exists(image_path):
|
||||
print(f"[ERROR] 图片文件不存在: {image_path}")
|
||||
return
|
||||
|
||||
print("=" * 70)
|
||||
print("OCR多线程性能测试")
|
||||
print("=" * 70)
|
||||
print()
|
||||
print(f"测试图片: {os.path.basename(image_path)}")
|
||||
|
||||
# 获取系统信息
|
||||
cpu_count = os.cpu_count() or 4
|
||||
print(f"CPU核心数: {cpu_count}")
|
||||
try:
|
||||
from operations.screenshot_service import get_optimal_workers
|
||||
optimal_workers = get_optimal_workers()
|
||||
print(f"推荐线程池大小: {optimal_workers}")
|
||||
except (ImportError, AttributeError):
|
||||
optimal_workers = 6
|
||||
print()
|
||||
|
||||
# 测试1: 单次OCR - 优化前
|
||||
print("\n" + "="*70)
|
||||
print("测试1: 单次OCR性能对比")
|
||||
print("="*70)
|
||||
result_single_old = test_ocr_config(
|
||||
image_path,
|
||||
"优化前 (OMP_NUM_THREADS=1)",
|
||||
omp_threads=1,
|
||||
num_iterations=5
|
||||
)
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
# 测试2: 单次OCR - 优化后
|
||||
result_single_new = test_ocr_config(
|
||||
image_path,
|
||||
"优化后 (OMP_NUM_THREADS=6)",
|
||||
omp_threads=6,
|
||||
num_iterations=5
|
||||
)
|
||||
|
||||
# 测试3: 并行OCR - 优化前
|
||||
print("\n" + "="*70)
|
||||
print("测试2: 并行OCR性能对比")
|
||||
print("="*70)
|
||||
result_parallel_old = test_parallel_ocr(
|
||||
image_path,
|
||||
"优化前 (OMP=1, workers=6)",
|
||||
omp_threads=1,
|
||||
max_workers=6,
|
||||
num_tasks=6
|
||||
)
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
# 测试4: 并行OCR - 优化后
|
||||
result_parallel_new = test_parallel_ocr(
|
||||
image_path,
|
||||
"优化后 (OMP=6, workers=10)",
|
||||
omp_threads=6,
|
||||
max_workers=optimal_workers,
|
||||
num_tasks=6
|
||||
)
|
||||
|
||||
# 性能对比总结
|
||||
print()
|
||||
print("=" * 70)
|
||||
print("性能对比总结")
|
||||
print("=" * 70)
|
||||
print()
|
||||
|
||||
if result_single_old and result_single_new:
|
||||
old_avg = result_single_old['avg_time']
|
||||
new_avg = result_single_new['avg_time']
|
||||
speedup = old_avg / new_avg if new_avg > 0 else 0
|
||||
|
||||
print("单次OCR性能:")
|
||||
print(f" 优化前平均: {old_avg:.0f}ms")
|
||||
print(f" 优化后平均: {new_avg:.0f}ms")
|
||||
print(f" 性能提升: {speedup:.2f}x")
|
||||
print(f" 时间减少: {(1 - new_avg/old_avg)*100:.1f}%")
|
||||
print()
|
||||
|
||||
if result_parallel_old and result_parallel_new:
|
||||
old_total = result_parallel_old['total_time']
|
||||
new_total = result_parallel_new['total_time']
|
||||
speedup = old_total / new_total if new_total > 0 else 0
|
||||
|
||||
print("并行OCR性能:")
|
||||
print(f" 优化前总耗时: {old_total:.0f}ms ({old_total/1000:.2f}秒)")
|
||||
print(f" 优化后总耗时: {new_total:.0f}ms ({new_total/1000:.2f}秒)")
|
||||
print(f" 性能提升: {speedup:.2f}x")
|
||||
print(f" 时间减少: {(1 - new_total/old_total)*100:.1f}%")
|
||||
print()
|
||||
|
||||
old_avg = result_parallel_old['avg_task_time']
|
||||
new_avg = result_parallel_new['avg_task_time']
|
||||
print("单任务性能:")
|
||||
print(f" 优化前平均任务: {old_avg:.0f}ms")
|
||||
print(f" 优化后平均任务: {new_avg:.0f}ms")
|
||||
print(f" 单任务性能提升: {old_avg/new_avg:.2f}x" if new_avg > 0 else " 单任务性能提升: N/A")
|
||||
print()
|
||||
|
||||
print("=" * 70)
|
||||
print("测试完成")
|
||||
print("=" * 70)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,196 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试OCR识别速度
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
def test_ocr_speed(image_path: str, iterations: int = 5):
|
||||
"""测试OCR识别速度"""
|
||||
print("=" * 70)
|
||||
print("OCR速度测试")
|
||||
print("=" * 70)
|
||||
print()
|
||||
|
||||
# 检查图片文件是否存在
|
||||
if not os.path.exists(image_path):
|
||||
print(f"[ERROR] 图片文件不存在: {image_path}")
|
||||
return
|
||||
|
||||
file_size = os.path.getsize(image_path) / 1024 # KB
|
||||
print(f"测试图片: {image_path}")
|
||||
print(f"文件大小: {file_size:.2f} KB")
|
||||
print(f"测试次数: {iterations} 次")
|
||||
print()
|
||||
|
||||
# 获取图片信息
|
||||
try:
|
||||
from PIL import Image
|
||||
img = Image.open(image_path)
|
||||
width, height = img.size
|
||||
print(f"图片尺寸: {width}x{height}")
|
||||
print(f"图片模式: {img.mode}")
|
||||
|
||||
# 计算图片像素数
|
||||
total_pixels = width * height
|
||||
print(f"总像素数: {total_pixels:,}")
|
||||
|
||||
# 判断图片大小
|
||||
if total_pixels > 2000000: # 大于200万像素
|
||||
print(f" [提示] 图片较大,OCR处理可能需要较长时间")
|
||||
print(f" 建议: 先裁剪到目标区域(如200x200)再OCR,可以显著提升速度")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[WARNING] 无法读取图片信息: {e}")
|
||||
print()
|
||||
|
||||
# 检查OCR引擎
|
||||
print("1. OCR引擎信息")
|
||||
print("-" * 70)
|
||||
try:
|
||||
from operations.ocr_operations import _ocr_processor
|
||||
_ocr_processor._ensure_ocr()
|
||||
|
||||
if _ocr_processor.ocr is None:
|
||||
print("[ERROR] OCR引擎未初始化")
|
||||
return
|
||||
|
||||
print(f" OCR引擎: {_ocr_processor.ocr_type}")
|
||||
print(f" OMP线程数: {os.environ.get('OMP_NUM_THREADS', '未设置')}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] OCR引擎检查失败: {e}")
|
||||
return
|
||||
|
||||
# 测试OCR速度
|
||||
print("2. OCR速度测试")
|
||||
print("-" * 70)
|
||||
|
||||
times = []
|
||||
results = []
|
||||
|
||||
for i in range(iterations):
|
||||
try:
|
||||
# 导入OCR操作
|
||||
from Underlying_Operations import underlying_operations
|
||||
ops = underlying_operations()
|
||||
|
||||
# 确保OCR已初始化
|
||||
ops._ensure_ocr()
|
||||
|
||||
# 执行OCR(使用analyse_pic_digits,因为这是数字识别)
|
||||
start_time = time.time()
|
||||
|
||||
# 直接使用图片路径进行OCR
|
||||
# 注意:如果图片很大,OCR会处理整个图片,这可能会很慢
|
||||
# 建议使用预处理后的小图片进行测试
|
||||
result = ops.analyse_pic_digits(
|
||||
"测试图片",
|
||||
change_color=1, # 数字识别模式
|
||||
pic_path=image_path
|
||||
)
|
||||
|
||||
# 记录各个阶段的耗时(如果可能)
|
||||
# 注意:analyse_pic_digits 内部会进行图像预处理和OCR识别
|
||||
|
||||
elapsed = (time.time() - start_time) * 1000 # 转换为毫秒
|
||||
times.append(elapsed)
|
||||
results.append(result)
|
||||
|
||||
print(f" 第 {i+1} 次: {elapsed:.0f}ms, 识别结果: {result[:50] if result else '(空)'}")
|
||||
|
||||
except Exception as e:
|
||||
print(f" 第 {i+1} 次: 失败 - {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
print()
|
||||
|
||||
# 统计结果
|
||||
if times:
|
||||
print("3. 性能统计")
|
||||
print("-" * 70)
|
||||
avg_time = sum(times) / len(times)
|
||||
min_time = min(times)
|
||||
max_time = max(times)
|
||||
|
||||
print(f" 平均耗时: {avg_time:.0f}ms")
|
||||
print(f" 最快耗时: {min_time:.0f}ms")
|
||||
print(f" 最慢耗时: {max_time:.0f}ms")
|
||||
print(f" 耗时范围: {max_time - min_time:.0f}ms")
|
||||
print()
|
||||
|
||||
# 识别结果统计
|
||||
print("4. 识别结果")
|
||||
print("-" * 70)
|
||||
unique_results = list(set(results))
|
||||
for i, result in enumerate(unique_results, 1):
|
||||
count = results.count(result)
|
||||
print(f" 结果 {i}: {result[:100] if result else '(空)'} (出现 {count} 次)")
|
||||
print()
|
||||
|
||||
# 性能评估
|
||||
print("5. 性能评估")
|
||||
print("-" * 70)
|
||||
if avg_time < 500:
|
||||
print(" [优秀] OCR速度很快 (< 500ms)")
|
||||
elif avg_time < 1000:
|
||||
print(" [良好] OCR速度良好 (500-1000ms)")
|
||||
elif avg_time < 2000:
|
||||
print(" [一般] OCR速度一般 (1000-2000ms)")
|
||||
elif avg_time < 5000:
|
||||
print(" [较慢] OCR速度较慢 (2000-5000ms)")
|
||||
else:
|
||||
print(" [很慢] OCR速度很慢 (> 5000ms)")
|
||||
print(" 提示: 如果图片很大,建议先裁剪到目标区域再OCR")
|
||||
|
||||
# 多线程效果评估
|
||||
cpu_count = os.cpu_count() or 4
|
||||
omp_threads = int(os.environ.get('OMP_NUM_THREADS', '1'))
|
||||
print(f" CPU核心数: {cpu_count}")
|
||||
print(f" OMP线程数: {omp_threads}")
|
||||
if omp_threads > 1:
|
||||
print(f" [优化] 已启用底层多线程 (OMP_NUM_THREADS={omp_threads})")
|
||||
else:
|
||||
print(f" [提示] 未启用底层多线程,可以优化")
|
||||
print()
|
||||
else:
|
||||
print("[ERROR] 所有测试都失败了")
|
||||
|
||||
print("=" * 70)
|
||||
print("测试完成")
|
||||
print("=" * 70)
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
# 默认图片路径
|
||||
default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png"
|
||||
|
||||
# 从命令行参数获取图片路径
|
||||
if len(sys.argv) > 1:
|
||||
image_path = sys.argv[1]
|
||||
else:
|
||||
image_path = default_image
|
||||
|
||||
# 获取测试次数
|
||||
iterations = 5
|
||||
if len(sys.argv) > 2:
|
||||
try:
|
||||
iterations = int(sys.argv[2])
|
||||
except:
|
||||
pass
|
||||
|
||||
# 转换为绝对路径
|
||||
if not os.path.isabs(image_path):
|
||||
# 尝试相对于项目根目录
|
||||
project_root = os.path.dirname(os.path.abspath(__file__))
|
||||
image_path = os.path.join(project_root, image_path)
|
||||
|
||||
test_ocr_speed(image_path, iterations)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,212 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试OCR识别速度(优化版 - 支持裁剪区域测试)
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from typing import Optional
|
||||
from PIL import Image
|
||||
|
||||
def test_ocr_on_region(image_path: str, region: Optional[tuple] = None, iterations: int = 5):
|
||||
"""在指定区域测试OCR速度"""
|
||||
print("=" * 70)
|
||||
print("OCR速度测试(区域优化版)")
|
||||
print("=" * 70)
|
||||
print()
|
||||
|
||||
# 检查图片文件是否存在
|
||||
if not os.path.exists(image_path):
|
||||
print(f"[ERROR] 图片文件不存在: {image_path}")
|
||||
return
|
||||
|
||||
# 加载图片
|
||||
try:
|
||||
img = Image.open(image_path)
|
||||
original_size = img.size
|
||||
print(f"原始图片: {image_path}")
|
||||
print(f"原始尺寸: {original_size[0]}x{original_size[1]}")
|
||||
print(f"原始像素数: {original_size[0] * original_size[1]:,}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 无法加载图片: {e}")
|
||||
return
|
||||
|
||||
# 如果指定了区域,裁剪图片
|
||||
if region:
|
||||
x1, y1, x2, y2 = region
|
||||
img = img.crop((x1, y1, x2, y2))
|
||||
print(f"裁剪区域: ({x1}, {y1}) - ({x2}, {y2})")
|
||||
print(f"裁剪后尺寸: {img.size[0]}x{img.size[1]}")
|
||||
print(f"裁剪后像素数: {img.size[0] * img.size[1]:,}")
|
||||
print()
|
||||
|
||||
# 保存裁剪后的临时图片
|
||||
import tempfile
|
||||
temp_dir = tempfile.gettempdir()
|
||||
temp_image = os.path.join(temp_dir, "ocr_test_crop.png")
|
||||
img.save(temp_image)
|
||||
test_image_path = temp_image
|
||||
else:
|
||||
test_image_path = image_path
|
||||
|
||||
# 测试OCR速度
|
||||
print("开始OCR速度测试...")
|
||||
print("-" * 70)
|
||||
|
||||
try:
|
||||
from operations.ocr_operations import _ocr_processor
|
||||
_ocr_processor._ensure_ocr()
|
||||
|
||||
if _ocr_processor.ocr is None:
|
||||
print("[ERROR] OCR引擎未初始化")
|
||||
return
|
||||
|
||||
print(f"OCR引擎: {_ocr_processor.ocr_type}")
|
||||
print(f"OMP线程数: {os.environ.get('OMP_NUM_THREADS', '未设置')}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] OCR引擎检查失败: {e}")
|
||||
return
|
||||
|
||||
# 执行多次测试
|
||||
times = []
|
||||
results = []
|
||||
|
||||
for i in range(iterations):
|
||||
try:
|
||||
import numpy as np
|
||||
|
||||
# 准备图像
|
||||
if img.mode != 'RGB':
|
||||
img_rgb = img.convert('RGB')
|
||||
else:
|
||||
img_rgb = img
|
||||
|
||||
# 转换为numpy数组
|
||||
img_np = np.array(img_rgb)
|
||||
|
||||
# 执行OCR
|
||||
start_time = time.time()
|
||||
|
||||
if _ocr_processor.ocr_type == "easyocr":
|
||||
result = _ocr_processor.ocr.readtext(img_np)
|
||||
else:
|
||||
result = _ocr_processor.ocr.ocr(img_np)
|
||||
|
||||
elapsed = (time.time() - start_time) * 1000 # 转换为毫秒
|
||||
|
||||
# 提取文本
|
||||
from Underlying_Operations import underlying_operations
|
||||
ops = underlying_operations()
|
||||
text = ops.extract_ocr_content(result)
|
||||
|
||||
times.append(elapsed)
|
||||
results.append(text)
|
||||
|
||||
print(f"第 {i+1} 次: {elapsed:.0f}ms, 识别结果: {text[:50] if text else '(空)'}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"第 {i+1} 次: 失败 - {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
print()
|
||||
|
||||
# 统计结果
|
||||
if times:
|
||||
print("性能统计")
|
||||
print("-" * 70)
|
||||
avg_time = sum(times) / len(times)
|
||||
min_time = min(times)
|
||||
max_time = max(times)
|
||||
|
||||
print(f"平均耗时: {avg_time:.0f}ms ({avg_time/1000:.2f}秒)")
|
||||
print(f"最快耗时: {min_time:.0f}ms ({min_time/1000:.2f}秒)")
|
||||
print(f"最慢耗时: {max_time:.0f}ms ({max_time/1000:.2f}秒)")
|
||||
print(f"耗时范围: {max_time - min_time:.0f}ms")
|
||||
print()
|
||||
|
||||
# 识别结果
|
||||
print("识别结果")
|
||||
print("-" * 70)
|
||||
unique_results = list(set(results))
|
||||
for i, result in enumerate(unique_results, 1):
|
||||
count = results.count(result)
|
||||
print(f"结果 {i}: {result[:100] if result else '(空)'} (出现 {count} 次)")
|
||||
print()
|
||||
|
||||
# 性能对比
|
||||
if region:
|
||||
original_pixels = original_size[0] * original_size[1]
|
||||
crop_pixels = img.size[0] * img.size[1]
|
||||
reduction = (1 - crop_pixels / original_pixels) * 100
|
||||
print("性能对比")
|
||||
print("-" * 70)
|
||||
print(f"原始图片像素: {original_pixels:,}")
|
||||
print(f"裁剪后像素: {crop_pixels:,}")
|
||||
print(f"像素减少: {reduction:.1f}%")
|
||||
print(f"预计原始图片OCR耗时: {avg_time * (original_pixels / crop_pixels):.0f}ms")
|
||||
print()
|
||||
|
||||
# 清理临时文件
|
||||
if region and os.path.exists(test_image_path):
|
||||
try:
|
||||
os.remove(test_image_path)
|
||||
except:
|
||||
pass
|
||||
|
||||
print("=" * 70)
|
||||
print("测试完成")
|
||||
print("=" * 70)
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
# 默认图片路径
|
||||
default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png"
|
||||
|
||||
# 从命令行参数获取图片路径
|
||||
if len(sys.argv) > 1:
|
||||
image_path = sys.argv[1]
|
||||
else:
|
||||
image_path = default_image
|
||||
|
||||
# 转换为绝对路径
|
||||
if not os.path.isabs(image_path):
|
||||
project_root = os.path.dirname(os.path.abspath(__file__))
|
||||
image_path = os.path.join(project_root, image_path)
|
||||
|
||||
# 从文件名提取区域信息(如果文件名包含坐标)
|
||||
region = None
|
||||
if "(480,1110)-(570,1230)" in image_path:
|
||||
# 提取坐标
|
||||
region = (480, 1110, 570, 1230)
|
||||
print("[INFO] 检测到文件名中的坐标信息,将使用裁剪区域进行测试")
|
||||
print()
|
||||
|
||||
# 获取测试次数
|
||||
iterations = 5
|
||||
if len(sys.argv) > 2:
|
||||
try:
|
||||
iterations = int(sys.argv[2])
|
||||
except:
|
||||
pass
|
||||
|
||||
# 先测试完整图片
|
||||
print("=" * 70)
|
||||
print("测试1: 完整图片OCR")
|
||||
print("=" * 70)
|
||||
test_ocr_on_region(image_path, region=None, iterations=iterations)
|
||||
|
||||
# 如果检测到区域信息,再测试裁剪区域
|
||||
if region:
|
||||
print()
|
||||
print("=" * 70)
|
||||
print("测试2: 裁剪区域OCR(推荐)")
|
||||
print("=" * 70)
|
||||
test_ocr_on_region(image_path, region=region, iterations=iterations)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,383 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试并行OCR性能,对比优化前后的提升
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
|
||||
def test_serial_ocr(image_path: str, num_tasks: int = 3):
|
||||
"""测试串行OCR(优化前的方式)"""
|
||||
print("=" * 70)
|
||||
print("测试1: 串行OCR(优化前)")
|
||||
print("=" * 70)
|
||||
print(f"任务数量: {num_tasks}")
|
||||
print(f"OMP_NUM_THREADS: {os.environ.get('OMP_NUM_THREADS', '未设置')}")
|
||||
print()
|
||||
|
||||
# 加载图片
|
||||
try:
|
||||
img = Image.open(image_path)
|
||||
if img.mode != 'RGB':
|
||||
img = img.convert('RGB')
|
||||
img_np = np.array(img)
|
||||
print(f"图片尺寸: {img.size[0]}x{img.size[1]}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 无法加载图片: {e}")
|
||||
return None
|
||||
|
||||
# 初始化OCR
|
||||
try:
|
||||
from operations.ocr_operations import _ocr_processor
|
||||
_ocr_processor._ensure_ocr()
|
||||
|
||||
if _ocr_processor.ocr is None:
|
||||
print("[ERROR] OCR引擎未初始化")
|
||||
return None
|
||||
|
||||
print(f"OCR引擎: {_ocr_processor.ocr_type}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] OCR引擎初始化失败: {e}")
|
||||
return None
|
||||
|
||||
# 串行执行OCR任务
|
||||
start_time = time.time()
|
||||
results = []
|
||||
|
||||
print("开始串行OCR测试...")
|
||||
for i in range(num_tasks):
|
||||
task_start = time.time()
|
||||
|
||||
try:
|
||||
if _ocr_processor.ocr_type == "easyocr":
|
||||
result = _ocr_processor.ocr.readtext(img_np)
|
||||
else:
|
||||
result = _ocr_processor.ocr.ocr(img_np)
|
||||
|
||||
# 提取文本
|
||||
from Underlying_Operations import underlying_operations
|
||||
ops = underlying_operations()
|
||||
text = ops.extract_ocr_content(result)
|
||||
|
||||
task_elapsed = (time.time() - task_start) * 1000
|
||||
results.append(text)
|
||||
print(f" 任务 {i+1}/{num_tasks}: {task_elapsed:.0f}ms, 结果: {text[:30] if text else '(空)'}")
|
||||
except Exception as e:
|
||||
print(f" 任务 {i+1}/{num_tasks}: 失败 - {e}")
|
||||
results.append(None)
|
||||
|
||||
total_elapsed = (time.time() - start_time) * 1000
|
||||
|
||||
print()
|
||||
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
|
||||
print(f"平均每个任务: {total_elapsed/num_tasks:.0f}ms")
|
||||
print()
|
||||
|
||||
return total_elapsed
|
||||
|
||||
def test_parallel_ocr(image_path: str, num_tasks: int = 3):
|
||||
"""测试并行OCR(优化后的方式)"""
|
||||
print("=" * 70)
|
||||
print("测试2: 并行OCR(优化后)")
|
||||
print("=" * 70)
|
||||
print(f"任务数量: {num_tasks}")
|
||||
print(f"OMP_NUM_THREADS: {os.environ.get('OMP_NUM_THREADS', '未设置')}")
|
||||
|
||||
# 获取最优线程数
|
||||
try:
|
||||
from operations.screenshot_service import get_optimal_workers
|
||||
optimal_workers = get_optimal_workers()
|
||||
print(f"线程池大小: {optimal_workers}")
|
||||
except:
|
||||
optimal_workers = 6
|
||||
print(f"线程池大小: {optimal_workers} (默认)")
|
||||
print()
|
||||
|
||||
# 加载图片
|
||||
try:
|
||||
img = Image.open(image_path)
|
||||
if img.mode != 'RGB':
|
||||
img = img.convert('RGB')
|
||||
img_np = np.array(img)
|
||||
print(f"图片尺寸: {img.size[0]}x{img.size[1]}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 无法加载图片: {e}")
|
||||
return None
|
||||
|
||||
# 初始化OCR
|
||||
try:
|
||||
from operations.ocr_operations import _ocr_processor
|
||||
_ocr_processor._ensure_ocr()
|
||||
|
||||
if _ocr_processor.ocr is None:
|
||||
print("[ERROR] OCR引擎未初始化")
|
||||
return None
|
||||
|
||||
print(f"OCR引擎: {_ocr_processor.ocr_type}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] OCR引擎初始化失败: {e}")
|
||||
return None
|
||||
|
||||
# 定义OCR任务函数
|
||||
def ocr_task(task_id):
|
||||
"""单个OCR任务"""
|
||||
try:
|
||||
if _ocr_processor.ocr_type == "easyocr":
|
||||
result = _ocr_processor.ocr.readtext(img_np)
|
||||
else:
|
||||
result = _ocr_processor.ocr.ocr(img_np)
|
||||
|
||||
# 提取文本
|
||||
from Underlying_Operations import underlying_operations
|
||||
ops = underlying_operations()
|
||||
text = ops.extract_ocr_content(result)
|
||||
|
||||
return text
|
||||
except Exception as e:
|
||||
print(f" 任务 {task_id} 失败: {e}")
|
||||
return None
|
||||
|
||||
# 并行执行OCR任务
|
||||
start_time = time.time()
|
||||
results = []
|
||||
|
||||
print("开始并行OCR测试...")
|
||||
with ThreadPoolExecutor(max_workers=optimal_workers) as executor:
|
||||
# 提交所有任务
|
||||
futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)}
|
||||
|
||||
# 收集结果
|
||||
task_times = {}
|
||||
for future in futures:
|
||||
task_id = futures[future]
|
||||
task_start = time.time()
|
||||
try:
|
||||
result = future.result()
|
||||
task_elapsed = (time.time() - task_start) * 1000
|
||||
task_times[task_id] = task_elapsed
|
||||
results.append(result)
|
||||
print(f" 任务 {task_id}/{num_tasks}: {task_elapsed:.0f}ms, 结果: {result[:30] if result else '(空)'}")
|
||||
except Exception as e:
|
||||
print(f" 任务 {task_id}/{num_tasks}: 失败 - {e}")
|
||||
results.append(None)
|
||||
|
||||
total_elapsed = (time.time() - start_time) * 1000
|
||||
|
||||
print()
|
||||
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
|
||||
if task_times:
|
||||
avg_task_time = sum(task_times.values()) / len(task_times)
|
||||
print(f"平均每个任务: {avg_task_time:.0f}ms")
|
||||
print(f"并行效率: {avg_task_time * num_tasks / total_elapsed:.1f}x (理想情况下应该接近{num_tasks}x)")
|
||||
print()
|
||||
|
||||
return total_elapsed
|
||||
|
||||
def test_parallel_ocr_old_config(image_path: str, num_tasks: int = 3):
|
||||
"""测试并行OCR(使用旧的配置:OMP_NUM_THREADS=1, max_workers=6)"""
|
||||
print("=" * 70)
|
||||
print("测试3: 并行OCR(旧配置:OMP=1, 线程池=6)")
|
||||
print("=" * 70)
|
||||
print(f"任务数量: {num_tasks}")
|
||||
|
||||
# 临时设置旧配置
|
||||
old_omp = os.environ.get('OMP_NUM_THREADS', '4')
|
||||
os.environ['OMP_NUM_THREADS'] = '1'
|
||||
print(f"OMP_NUM_THREADS: 1 (临时设置)")
|
||||
print(f"线程池大小: 6 (固定)")
|
||||
print()
|
||||
|
||||
# 加载图片
|
||||
try:
|
||||
img = Image.open(image_path)
|
||||
if img.mode != 'RGB':
|
||||
img = img.convert('RGB')
|
||||
img_np = np.array(img)
|
||||
print(f"图片尺寸: {img.size[0]}x{img.size[1]}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 无法加载图片: {e}")
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
return None
|
||||
|
||||
# 重新初始化OCR(使用新的OMP设置)
|
||||
try:
|
||||
from operations.ocr_operations import _ocr_processor
|
||||
# 注意:OCR引擎已经初始化,OMP设置可能不会立即生效
|
||||
# 但我们可以测试线程池的效果
|
||||
print(f"OCR引擎: {_ocr_processor.ocr_type}")
|
||||
print("注意: OMP设置可能需要重启程序才能完全生效")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] OCR引擎检查失败: {e}")
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
return None
|
||||
|
||||
# 定义OCR任务函数
|
||||
def ocr_task(task_id):
|
||||
"""单个OCR任务"""
|
||||
try:
|
||||
if _ocr_processor.ocr_type == "easyocr":
|
||||
result = _ocr_processor.ocr.readtext(img_np)
|
||||
else:
|
||||
result = _ocr_processor.ocr.ocr(img_np)
|
||||
|
||||
# 提取文本
|
||||
from Underlying_Operations import underlying_operations
|
||||
ops = underlying_operations()
|
||||
text = ops.extract_ocr_content(result)
|
||||
|
||||
return text
|
||||
except Exception as e:
|
||||
print(f" 任务 {task_id} 失败: {e}")
|
||||
return None
|
||||
|
||||
# 并行执行OCR任务(使用旧的线程池大小)
|
||||
start_time = time.time()
|
||||
results = []
|
||||
|
||||
print("开始并行OCR测试(旧配置)...")
|
||||
with ThreadPoolExecutor(max_workers=6) as executor:
|
||||
# 提交所有任务
|
||||
futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)}
|
||||
|
||||
# 收集结果
|
||||
task_times = {}
|
||||
for future in futures:
|
||||
task_id = futures[future]
|
||||
task_start = time.time()
|
||||
try:
|
||||
result = future.result()
|
||||
task_elapsed = (time.time() - task_start) * 1000
|
||||
task_times[task_id] = task_elapsed
|
||||
results.append(result)
|
||||
print(f" 任务 {task_id}/{num_tasks}: {task_elapsed:.0f}ms, 结果: {result[:30] if result else '(空)'}")
|
||||
except Exception as e:
|
||||
print(f" 任务 {task_id}/{num_tasks}: 失败 - {e}")
|
||||
results.append(None)
|
||||
|
||||
total_elapsed = (time.time() - start_time) * 1000
|
||||
|
||||
# 恢复OMP设置
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
|
||||
print()
|
||||
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
|
||||
if task_times:
|
||||
avg_task_time = sum(task_times.values()) / len(task_times)
|
||||
print(f"平均每个任务: {avg_task_time:.0f}ms")
|
||||
print()
|
||||
|
||||
return total_elapsed
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
# 默认图片路径
|
||||
default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png"
|
||||
|
||||
# 从命令行参数获取图片路径
|
||||
if len(sys.argv) > 1:
|
||||
image_path = sys.argv[1]
|
||||
else:
|
||||
image_path = default_image
|
||||
|
||||
# 转换为绝对路径
|
||||
if not os.path.isabs(image_path):
|
||||
project_root = os.path.dirname(os.path.abspath(__file__))
|
||||
image_path = os.path.join(project_root, image_path)
|
||||
|
||||
# 检查文件是否存在
|
||||
if not os.path.exists(image_path):
|
||||
print(f"[ERROR] 图片文件不存在: {image_path}")
|
||||
return
|
||||
|
||||
# 获取任务数量(默认3个,减少测试时间)
|
||||
num_tasks = 3
|
||||
if len(sys.argv) > 2:
|
||||
try:
|
||||
num_tasks = int(sys.argv[2])
|
||||
except:
|
||||
pass
|
||||
|
||||
print("=" * 70)
|
||||
print("并行OCR性能对比测试")
|
||||
print("=" * 70)
|
||||
print()
|
||||
print(f"测试图片: {os.path.basename(image_path)}")
|
||||
print(f"任务数量: {num_tasks}")
|
||||
print()
|
||||
|
||||
# 获取当前配置信息
|
||||
cpu_count = os.cpu_count() or 4
|
||||
omp_threads = os.environ.get('OMP_NUM_THREADS', '未设置')
|
||||
print(f"系统信息:")
|
||||
print(f" CPU核心数: {cpu_count}")
|
||||
print(f" OMP_NUM_THREADS: {omp_threads}")
|
||||
try:
|
||||
from operations.screenshot_service import get_optimal_workers
|
||||
optimal_workers = get_optimal_workers()
|
||||
print(f" 推荐线程池大小: {optimal_workers}")
|
||||
except:
|
||||
pass
|
||||
print()
|
||||
print()
|
||||
|
||||
# 测试1: 串行OCR
|
||||
serial_time = test_serial_ocr(image_path, num_tasks)
|
||||
|
||||
print()
|
||||
print()
|
||||
|
||||
# 测试2: 并行OCR(优化后)
|
||||
parallel_time = test_parallel_ocr(image_path, num_tasks)
|
||||
|
||||
print()
|
||||
print()
|
||||
|
||||
# 测试3: 并行OCR(旧配置)
|
||||
parallel_old_time = test_parallel_ocr_old_config(image_path, num_tasks)
|
||||
|
||||
# 性能对比总结
|
||||
print()
|
||||
print("=" * 70)
|
||||
print("性能对比总结")
|
||||
print("=" * 70)
|
||||
print()
|
||||
|
||||
if serial_time and parallel_time:
|
||||
speedup = serial_time / parallel_time
|
||||
print(f"串行OCR: {serial_time:.0f}ms ({serial_time/1000:.2f}秒)")
|
||||
print(f"并行OCR: {parallel_time:.0f}ms ({parallel_time/1000:.2f}秒)")
|
||||
print(f"性能提升: {speedup:.2f}x ({(1 - parallel_time/serial_time)*100:.1f}% 时间减少)")
|
||||
print()
|
||||
|
||||
if parallel_old_time and parallel_time:
|
||||
speedup_vs_old = parallel_old_time / parallel_time
|
||||
print(f"旧配置并行: {parallel_old_time:.0f}ms ({parallel_old_time/1000:.2f}秒)")
|
||||
print(f"新配置并行: {parallel_time:.0f}ms ({parallel_time/1000:.2f}秒)")
|
||||
print(f"配置优化提升: {speedup_vs_old:.2f}x ({(1 - parallel_time/parallel_old_time)*100:.1f}% 时间减少)")
|
||||
print()
|
||||
|
||||
if serial_time and parallel_time and parallel_old_time:
|
||||
total_speedup = serial_time / parallel_time
|
||||
print(f"总体优化效果:")
|
||||
print(f" 串行 → 并行: {serial_time/parallel_time:.2f}x")
|
||||
print(f" 旧配置 → 新配置: {parallel_old_time/parallel_time:.2f}x")
|
||||
print(f" 串行 → 新配置: {total_speedup:.2f}x")
|
||||
print()
|
||||
|
||||
print("=" * 70)
|
||||
print("测试完成")
|
||||
print("=" * 70)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,141 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
快速测试并行OCR性能(只测试并行,不测试串行)
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
|
||||
def test_parallel_ocr_quick(image_path: str, num_tasks: int = 3):
|
||||
"""快速测试并行OCR"""
|
||||
print("=" * 70)
|
||||
print("并行OCR性能测试(快速版)")
|
||||
print("=" * 70)
|
||||
print()
|
||||
|
||||
# 检查文件
|
||||
if not os.path.exists(image_path):
|
||||
print(f"[ERROR] 图片文件不存在: {image_path}")
|
||||
return None
|
||||
|
||||
# 加载图片
|
||||
try:
|
||||
img = Image.open(image_path)
|
||||
if img.mode != 'RGB':
|
||||
img = img.convert('RGB')
|
||||
img_np = np.array(img)
|
||||
print(f"图片: {os.path.basename(image_path)}")
|
||||
print(f"尺寸: {img.size[0]}x{img.size[1]}")
|
||||
print(f"任务数: {num_tasks}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 无法加载图片: {e}")
|
||||
return None
|
||||
|
||||
# 初始化OCR
|
||||
try:
|
||||
from operations.ocr_operations import _ocr_processor
|
||||
_ocr_processor._ensure_ocr()
|
||||
|
||||
if _ocr_processor.ocr is None:
|
||||
print("[ERROR] OCR引擎未初始化")
|
||||
return None
|
||||
|
||||
print(f"OCR引擎: {_ocr_processor.ocr_type}")
|
||||
print(f"OMP_NUM_THREADS: {os.environ.get('OMP_NUM_THREADS', '未设置')}")
|
||||
|
||||
from operations.screenshot_service import get_optimal_workers
|
||||
optimal_workers = get_optimal_workers()
|
||||
print(f"线程池大小: {optimal_workers}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] OCR引擎初始化失败: {e}")
|
||||
return None
|
||||
|
||||
# 定义OCR任务
|
||||
def ocr_task(task_id):
|
||||
try:
|
||||
if _ocr_processor.ocr_type == "easyocr":
|
||||
result = _ocr_processor.ocr.readtext(img_np)
|
||||
else:
|
||||
result = _ocr_processor.ocr.ocr(img_np)
|
||||
|
||||
from Underlying_Operations import underlying_operations
|
||||
ops = underlying_operations()
|
||||
text = ops.extract_ocr_content(result)
|
||||
return text
|
||||
except Exception as e:
|
||||
return f"错误: {e}"
|
||||
|
||||
# 执行并行OCR
|
||||
print("开始并行OCR测试...")
|
||||
start_time = time.time()
|
||||
|
||||
with ThreadPoolExecutor(max_workers=optimal_workers) as executor:
|
||||
futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)}
|
||||
results = []
|
||||
|
||||
for future in futures:
|
||||
task_id = futures[future]
|
||||
try:
|
||||
result = future.result()
|
||||
results.append(result)
|
||||
print(f" 任务 {task_id}: 完成, 结果: {result[:30] if result else '(空)'}")
|
||||
except Exception as e:
|
||||
print(f" 任务 {task_id}: 失败 - {e}")
|
||||
results.append(None)
|
||||
|
||||
total_elapsed = (time.time() - start_time) * 1000
|
||||
|
||||
print()
|
||||
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
|
||||
print(f"平均每个任务: {total_elapsed/num_tasks:.0f}ms")
|
||||
print()
|
||||
|
||||
# 估算串行时间(基于单次OCR耗时)
|
||||
print("性能估算:")
|
||||
print("-" * 70)
|
||||
single_task_time = total_elapsed / num_tasks
|
||||
estimated_serial_time = single_task_time * num_tasks
|
||||
speedup = estimated_serial_time / total_elapsed if total_elapsed > 0 else 0
|
||||
|
||||
print(f"估算串行时间: {estimated_serial_time:.0f}ms ({estimated_serial_time/1000:.2f}秒)")
|
||||
print(f"实际并行时间: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
|
||||
print(f"性能提升: {speedup:.2f}x (节省 {(1 - total_elapsed/estimated_serial_time)*100:.1f}% 时间)")
|
||||
print()
|
||||
|
||||
return total_elapsed
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png"
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
image_path = sys.argv[1]
|
||||
else:
|
||||
image_path = default_image
|
||||
|
||||
if not os.path.isabs(image_path):
|
||||
project_root = os.path.dirname(os.path.abspath(__file__))
|
||||
image_path = os.path.join(project_root, image_path)
|
||||
|
||||
num_tasks = 3
|
||||
if len(sys.argv) > 2:
|
||||
try:
|
||||
num_tasks = int(sys.argv[2])
|
||||
except:
|
||||
pass
|
||||
|
||||
test_parallel_ocr_quick(image_path, num_tasks)
|
||||
|
||||
print("=" * 70)
|
||||
print("测试完成")
|
||||
print("=" * 70)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,206 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
简化版并行OCR性能对比测试
|
||||
直接使用提供的图片进行测试
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
|
||||
def test_ocr_with_config(image_path, config_name, omp_threads, max_workers, num_tasks=6):
|
||||
"""使用指定配置测试OCR"""
|
||||
print(f"\n{'='*70}")
|
||||
print(f"{config_name}")
|
||||
print(f"{'='*70}")
|
||||
print(f"OMP_NUM_THREADS={omp_threads}, max_workers={max_workers}, 任务数={num_tasks}")
|
||||
print()
|
||||
|
||||
# 设置OMP
|
||||
old_omp = os.environ.get('OMP_NUM_THREADS', '4')
|
||||
os.environ['OMP_NUM_THREADS'] = str(omp_threads)
|
||||
|
||||
# 加载图片
|
||||
try:
|
||||
img = Image.open(image_path)
|
||||
if img.mode != 'RGB':
|
||||
img = img.convert('RGB')
|
||||
img_np = np.array(img)
|
||||
print(f"图片: {os.path.basename(image_path)}")
|
||||
print(f"尺寸: {img.size[0]}x{img.size[1]} 像素")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 无法加载图片: {e}")
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
return None
|
||||
|
||||
# 初始化OCR
|
||||
try:
|
||||
from operations.ocr_operations import OCRProcessor
|
||||
ocr_processor = OCRProcessor()
|
||||
ocr_processor._ensure_ocr()
|
||||
|
||||
if ocr_processor.ocr is None:
|
||||
print("[ERROR] OCR引擎未初始化")
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
return None
|
||||
|
||||
print(f"OCR引擎: {ocr_processor.ocr_type}")
|
||||
print()
|
||||
except Exception as e:
|
||||
print(f"[ERROR] OCR引擎初始化失败: {e}")
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
return None
|
||||
|
||||
# OCR任务函数
|
||||
def ocr_task(task_id):
|
||||
try:
|
||||
start = time.time()
|
||||
if ocr_processor.ocr_type == "easyocr":
|
||||
result = ocr_processor.ocr.readtext(img_np)
|
||||
else:
|
||||
result = ocr_processor.ocr.ocr(img_np)
|
||||
|
||||
from Underlying_Operations import underlying_operations
|
||||
ops = underlying_operations()
|
||||
text = ops.extract_ocr_content(result)
|
||||
elapsed = (time.time() - start) * 1000
|
||||
return {'task_id': task_id, 'text': text, 'time': elapsed, 'success': True}
|
||||
except Exception as e:
|
||||
return {'task_id': task_id, 'text': '', 'time': 0, 'success': False, 'error': str(e)}
|
||||
|
||||
# 执行并行OCR
|
||||
print("开始并行OCR测试...")
|
||||
start_time = time.time()
|
||||
results = []
|
||||
|
||||
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
||||
futures = {executor.submit(ocr_task, i+1): i+1 for i in range(num_tasks)}
|
||||
|
||||
for future in futures:
|
||||
try:
|
||||
result = future.result()
|
||||
results.append(result)
|
||||
status = "✓" if result['success'] else "✗"
|
||||
print(f" {status} 任务{result['task_id']}: {result['time']:.0f}ms, 结果: {result['text'][:20] if result['text'] else '(空)'}")
|
||||
except Exception as e:
|
||||
print(f" ✗ 任务失败: {e}")
|
||||
|
||||
total_elapsed = (time.time() - start_time) * 1000
|
||||
|
||||
# 恢复OMP设置
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
|
||||
# 统计
|
||||
successful = [r for r in results if r['success']]
|
||||
total_task_time = sum(r['time'] for r in successful)
|
||||
avg_task_time = total_task_time / len(successful) if successful else 0
|
||||
|
||||
print()
|
||||
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
|
||||
print(f"任务总耗时: {total_task_time:.0f}ms")
|
||||
print(f"平均每个任务: {avg_task_time:.0f}ms")
|
||||
if total_task_time > 0:
|
||||
efficiency = total_task_time / total_elapsed
|
||||
print(f"并行效率: {efficiency:.2f}x (理想值: {num_tasks:.1f}x)")
|
||||
print()
|
||||
|
||||
return {
|
||||
'total_time': total_elapsed,
|
||||
'avg_task_time': avg_task_time,
|
||||
'config': config_name
|
||||
}
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png"
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
image_path = sys.argv[1]
|
||||
else:
|
||||
image_path = default_image
|
||||
|
||||
if not os.path.isabs(image_path):
|
||||
project_root = os.path.dirname(os.path.abspath(__file__))
|
||||
image_path = os.path.join(project_root, image_path)
|
||||
|
||||
if not os.path.exists(image_path):
|
||||
print(f"[ERROR] 图片文件不存在: {image_path}")
|
||||
return
|
||||
|
||||
print("=" * 70)
|
||||
print("并行OCR性能对比测试(简化版)")
|
||||
print("=" * 70)
|
||||
print()
|
||||
print(f"测试图片: {os.path.basename(image_path)}")
|
||||
|
||||
# 获取系统信息
|
||||
cpu_count = os.cpu_count() or 4
|
||||
print(f"CPU核心数: {cpu_count}")
|
||||
try:
|
||||
from operations.screenshot_service import get_optimal_workers
|
||||
optimal_workers = get_optimal_workers()
|
||||
print(f"推荐线程池大小: {optimal_workers}")
|
||||
except:
|
||||
optimal_workers = 6
|
||||
|
||||
num_tasks = 6
|
||||
print(f"测试任务数: {num_tasks}")
|
||||
print()
|
||||
|
||||
# 测试1: 优化前
|
||||
result_old = test_ocr_with_config(
|
||||
image_path,
|
||||
"优化前配置 (OMP=1, workers=6)",
|
||||
omp_threads=1,
|
||||
max_workers=6,
|
||||
num_tasks=num_tasks
|
||||
)
|
||||
|
||||
time.sleep(1) # 等待系统稳定
|
||||
|
||||
# 测试2: 优化后
|
||||
result_new = test_ocr_with_config(
|
||||
image_path,
|
||||
"优化后配置 (OMP=4, workers=10)",
|
||||
omp_threads=4,
|
||||
max_workers=optimal_workers,
|
||||
num_tasks=num_tasks
|
||||
)
|
||||
|
||||
# 对比结果
|
||||
print()
|
||||
print("=" * 70)
|
||||
print("性能对比总结")
|
||||
print("=" * 70)
|
||||
print()
|
||||
|
||||
if result_old and result_new:
|
||||
old_time = result_old['total_time']
|
||||
new_time = result_new['total_time']
|
||||
speedup = old_time / new_time if new_time > 0 else 0
|
||||
|
||||
print(f"优化前总耗时: {old_time:.0f}ms ({old_time/1000:.2f}秒)")
|
||||
print(f"优化后总耗时: {new_time:.0f}ms ({new_time/1000:.2f}秒)")
|
||||
print(f"性能提升: {speedup:.2f}x")
|
||||
print(f"时间减少: {(1 - new_time/old_time)*100:.1f}%")
|
||||
print()
|
||||
|
||||
old_avg = result_old['avg_task_time']
|
||||
new_avg = result_new['avg_task_time']
|
||||
print(f"优化前平均任务耗时: {old_avg:.0f}ms")
|
||||
print(f"优化后平均任务耗时: {new_avg:.0f}ms")
|
||||
if new_avg > 0:
|
||||
print(f"单任务性能提升: {old_avg/new_avg:.2f}x")
|
||||
|
||||
print()
|
||||
print("=" * 70)
|
||||
print("测试完成")
|
||||
print("=" * 70)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,376 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
真实场景并行OCR性能对比测试
|
||||
模拟实际使用中的多区域并行OCR识别
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
import tempfile
|
||||
|
||||
def create_test_regions(full_image_path):
|
||||
"""从完整截图中创建多个测试区域(模拟真实OCR场景)"""
|
||||
try:
|
||||
img = Image.open(full_image_path)
|
||||
if img.mode != 'RGB':
|
||||
img = img.convert('RGB')
|
||||
|
||||
width, height = img.size
|
||||
|
||||
# 判断是否是完整截图(1080x2400)还是裁剪区域
|
||||
is_full_screenshot = width >= 1000 and height >= 2000
|
||||
|
||||
if is_full_screenshot:
|
||||
# 完整截图:创建多个测试区域
|
||||
# 模拟真实的OCR区域(基于福袋详情页的常见区域)
|
||||
regions = {
|
||||
"福袋倒计时_分钟": (400, 1050, 500, 1150), # 倒计时分钟区域
|
||||
"福袋倒计时_秒": (480, 1110, 570, 1230), # 倒计时秒区域(用户提供的区域)
|
||||
"福袋内容": (50, 800, 500, 1000), # 福袋内容区域
|
||||
"福袋价值": (200, 1300, 400, 1400), # 价值区域
|
||||
"任务列表": (50, 600, 500, 750), # 任务列表区域
|
||||
"参与按钮": (300, 1500, 800, 1600), # 按钮状态区域
|
||||
}
|
||||
else:
|
||||
# 裁剪区域:使用当前图片作为测试区域之一,创建其他相似大小的区域
|
||||
# 从文件名提取坐标信息(如果存在)
|
||||
coords_from_filename = None
|
||||
if "(480,1110)-(570,1230)" in full_image_path:
|
||||
coords_from_filename = (480, 1110, 570, 1230)
|
||||
|
||||
# 创建多个相似大小的测试区域
|
||||
# 如果图片较小,创建多个相同大小的区域用于测试
|
||||
# 这些区域会在完整截图的合理位置
|
||||
regions = {}
|
||||
|
||||
# 使用当前图片作为第一个区域
|
||||
if coords_from_filename:
|
||||
x1, y1, x2, y2 = coords_from_filename
|
||||
regions["福袋倒计时_秒"] = (x1, y1, x2, y2)
|
||||
# 创建其他相邻区域
|
||||
offset_x = x2 - x1
|
||||
offset_y = y2 - y1
|
||||
regions["福袋倒计时_分钟"] = (x1 - offset_x - 20, y1, x1 - 20, y2)
|
||||
regions["福袋内容"] = (x1, y1 - offset_y - 20, x2, y1 - 20)
|
||||
regions["福袋价值"] = (x1, y2 + 20, x2, y2 + offset_y + 20)
|
||||
else:
|
||||
# 如果无法从文件名提取坐标,使用图片本身作为唯一测试区域
|
||||
# 创建多个相同大小的区域(通过复制当前图片)
|
||||
regions["区域1"] = (0, 0, width, height)
|
||||
regions["区域2"] = (0, 0, width, height) # 相同区域,用于测试并行
|
||||
regions["区域3"] = (0, 0, width, height) # 相同区域,用于测试并行
|
||||
regions["区域4"] = (0, 0, width, height) # 相同区域,用于测试并行
|
||||
regions["区域5"] = (0, 0, width, height) # 相同区域,用于测试并行
|
||||
regions["区域6"] = (0, 0, width, height) # 相同区域,用于测试并行
|
||||
|
||||
# 裁剪并保存区域图片
|
||||
region_images = {}
|
||||
temp_dir = tempfile.gettempdir()
|
||||
|
||||
for name, (x1, y1, x2, y2) in regions.items():
|
||||
try:
|
||||
# 确保坐标在图片范围内
|
||||
x1 = max(0, min(x1, img.width))
|
||||
y1 = max(0, min(y1, img.height))
|
||||
x2 = max(x1, min(x2, img.width))
|
||||
y2 = max(y1, min(y2, img.height))
|
||||
|
||||
if x2 > x1 and y2 > y1:
|
||||
crop_img = img.crop((x1, y1, x2, y2))
|
||||
temp_path = os.path.join(temp_dir, f"ocr_test_{name}.png")
|
||||
crop_img.save(temp_path)
|
||||
region_images[name] = {
|
||||
'path': temp_path,
|
||||
'size': crop_img.size,
|
||||
'coords': (x1, y1, x2, y2)
|
||||
}
|
||||
except (ValueError, OSError, IOError) as e:
|
||||
print(f"[WARNING] 无法裁剪区域 {name}: {e}")
|
||||
|
||||
return region_images, img.size
|
||||
except (OSError, IOError, ValueError) as e:
|
||||
print(f"[ERROR] 无法处理图片: {e}")
|
||||
return {}, None
|
||||
|
||||
def ocr_single_region(image_path, region_name, ocr_processor):
|
||||
"""对单个区域进行OCR识别"""
|
||||
try:
|
||||
img = Image.open(image_path)
|
||||
if img.mode != 'RGB':
|
||||
img = img.convert('RGB')
|
||||
img_np = np.array(img)
|
||||
|
||||
start_time = time.time()
|
||||
|
||||
if ocr_processor.ocr_type == "easyocr":
|
||||
result = ocr_processor.ocr.readtext(img_np)
|
||||
else:
|
||||
result = ocr_processor.ocr.ocr(img_np)
|
||||
|
||||
elapsed = (time.time() - start_time) * 1000
|
||||
|
||||
# 提取文本
|
||||
from Underlying_Operations import underlying_operations
|
||||
ops = underlying_operations()
|
||||
text = ops.extract_ocr_content(result)
|
||||
|
||||
return {
|
||||
'region': region_name,
|
||||
'text': text,
|
||||
'time': elapsed,
|
||||
'success': True
|
||||
}
|
||||
except Exception as e:
|
||||
import traceback
|
||||
error_msg = f"{type(e).__name__}: {str(e)}"
|
||||
print(f" [DEBUG] {region_name} OCR错误: {error_msg}")
|
||||
return {
|
||||
'region': region_name,
|
||||
'text': '',
|
||||
'time': 0,
|
||||
'success': False,
|
||||
'error': error_msg
|
||||
}
|
||||
|
||||
def test_parallel_ocr_real(region_images, config_name, omp_threads, max_workers):
|
||||
"""测试真实场景的并行OCR"""
|
||||
print(f"\n{'='*70}")
|
||||
print(f"测试: {config_name}")
|
||||
print(f"{'='*70}")
|
||||
print(f"配置: OMP_NUM_THREADS={omp_threads}, max_workers={max_workers}")
|
||||
print(f"区域数量: {len(region_images)}")
|
||||
print()
|
||||
|
||||
# 设置OMP线程数
|
||||
old_omp = os.environ.get('OMP_NUM_THREADS', '4')
|
||||
os.environ['OMP_NUM_THREADS'] = str(omp_threads)
|
||||
|
||||
# 初始化OCR(使用新的OMP设置)
|
||||
try:
|
||||
from operations.ocr_operations import OCRProcessor
|
||||
ocr_processor = OCRProcessor()
|
||||
# 访问受保护方法以初始化OCR引擎(测试代码中需要)
|
||||
# 使用 getattr 来避免 pylance 警告
|
||||
ensure_ocr = getattr(ocr_processor, '_ensure_ocr')
|
||||
ensure_ocr()
|
||||
|
||||
if ocr_processor.ocr is None:
|
||||
print("[ERROR] OCR引擎未初始化")
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
return None
|
||||
|
||||
print(f"OCR引擎: {ocr_processor.ocr_type}")
|
||||
print()
|
||||
except (ImportError, AttributeError, RuntimeError) as e:
|
||||
print(f"[ERROR] OCR引擎初始化失败: {e}")
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
return None
|
||||
|
||||
# 显示区域信息
|
||||
print("OCR区域信息:")
|
||||
for name, info in region_images.items():
|
||||
print(f" {name}: {info['size'][0]}x{info['size'][1]} 像素, 坐标: {info['coords']}")
|
||||
print()
|
||||
|
||||
# 并行执行OCR
|
||||
print("开始并行OCR识别...")
|
||||
start_time = time.time()
|
||||
results = []
|
||||
|
||||
def ocr_task(name, path):
|
||||
return ocr_single_region(path, name, ocr_processor)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=max_workers) as executor:
|
||||
# 提交所有任务
|
||||
futures = {
|
||||
executor.submit(ocr_task, name, info['path']): name
|
||||
for name, info in region_images.items()
|
||||
}
|
||||
|
||||
# 收集结果
|
||||
for future in futures:
|
||||
region_name = futures[future]
|
||||
try:
|
||||
result = future.result(timeout=60) # 每个任务最多60秒
|
||||
results.append(result)
|
||||
status = "✓" if result['success'] else "✗"
|
||||
print(f" {status} {region_name}: {result['time']:.0f}ms, 结果: {result['text'][:30] if result['text'] else '(空)'}")
|
||||
except TimeoutError:
|
||||
print(f" ✗ {region_name}: 超时(>60秒)")
|
||||
results.append({
|
||||
'region': region_name,
|
||||
'text': '',
|
||||
'time': 0,
|
||||
'success': False,
|
||||
'error': 'Timeout'
|
||||
})
|
||||
except (RuntimeError, AttributeError, KeyError) as e:
|
||||
print(f" ✗ {region_name}: 失败 - {e}")
|
||||
results.append({
|
||||
'region': region_name,
|
||||
'text': '',
|
||||
'time': 0,
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
})
|
||||
|
||||
total_elapsed = (time.time() - start_time) * 1000
|
||||
|
||||
# 恢复OMP设置
|
||||
os.environ['OMP_NUM_THREADS'] = old_omp
|
||||
|
||||
# 统计结果
|
||||
successful_results = [r for r in results if r['success']]
|
||||
total_task_time = sum(r['time'] for r in successful_results)
|
||||
avg_task_time = total_task_time / len(successful_results) if successful_results else 0
|
||||
|
||||
print()
|
||||
print(f"总耗时: {total_elapsed:.0f}ms ({total_elapsed/1000:.2f}秒)")
|
||||
print(f"任务总耗时: {total_task_time:.0f}ms")
|
||||
print(f"平均每个任务: {avg_task_time:.0f}ms")
|
||||
if total_task_time > 0:
|
||||
efficiency = total_task_time / total_elapsed
|
||||
print(f"并行效率: {efficiency:.2f}x (理想值: {len(region_images):.1f}x)")
|
||||
print()
|
||||
|
||||
return {
|
||||
'total_time': total_elapsed,
|
||||
'task_times': [r['time'] for r in successful_results],
|
||||
'results': results,
|
||||
'config': config_name
|
||||
}
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
# 默认图片路径(完整截图)
|
||||
default_image = "pic/debug_captures/2025-12-31/20251231_152116_ocr_福袋倒计时_秒_预处理后_(480,1110)-(570,1230)_模式_1_尺寸_270x360_来源_福袋倒计时_秒.png_有完整截图_是_有坐标_是_类型_digits.png"
|
||||
|
||||
if len(sys.argv) > 1:
|
||||
image_path = sys.argv[1]
|
||||
else:
|
||||
image_path = default_image
|
||||
|
||||
if not os.path.isabs(image_path):
|
||||
project_root = os.path.dirname(os.path.abspath(__file__))
|
||||
image_path = os.path.join(project_root, image_path)
|
||||
|
||||
if not os.path.exists(image_path):
|
||||
print(f"[ERROR] 图片文件不存在: {image_path}")
|
||||
return
|
||||
|
||||
print("=" * 70)
|
||||
print("真实场景并行OCR性能对比测试")
|
||||
print("=" * 70)
|
||||
print()
|
||||
print(f"测试图片: {os.path.basename(image_path)}")
|
||||
print()
|
||||
|
||||
# 创建测试区域
|
||||
print("准备测试区域...")
|
||||
region_images, full_size = create_test_regions(image_path)
|
||||
|
||||
if not region_images:
|
||||
print("[ERROR] 无法创建测试区域")
|
||||
return
|
||||
|
||||
if full_size is not None:
|
||||
print(f"完整截图尺寸: {full_size[0]}x{full_size[1]}")
|
||||
else:
|
||||
print("完整截图尺寸: 未知")
|
||||
print(f"成功创建 {len(region_images)} 个测试区域")
|
||||
print()
|
||||
|
||||
# 获取系统信息
|
||||
cpu_count = os.cpu_count() or 4
|
||||
print("系统信息:")
|
||||
print(f" CPU核心数: {cpu_count}")
|
||||
try:
|
||||
from operations.screenshot_service import get_optimal_workers
|
||||
optimal_workers = get_optimal_workers()
|
||||
print(f" 推荐线程池大小: {optimal_workers}")
|
||||
except (ImportError, AttributeError):
|
||||
optimal_workers = 6
|
||||
print()
|
||||
|
||||
# 测试1: 优化前配置(OMP=1, workers=6)
|
||||
result_old = test_parallel_ocr_real(
|
||||
region_images,
|
||||
"优化前配置",
|
||||
omp_threads=1,
|
||||
max_workers=6
|
||||
)
|
||||
|
||||
# 等待一下,让系统稳定
|
||||
time.sleep(1)
|
||||
|
||||
# 测试2: 优化后配置(OMP=4, workers=10)
|
||||
result_new = test_parallel_ocr_real(
|
||||
region_images,
|
||||
"优化后配置",
|
||||
omp_threads=4,
|
||||
max_workers=optimal_workers
|
||||
)
|
||||
|
||||
# 性能对比总结
|
||||
print()
|
||||
print("=" * 70)
|
||||
print("性能对比总结")
|
||||
print("=" * 70)
|
||||
print()
|
||||
|
||||
if result_old and result_new:
|
||||
old_time = result_old['total_time']
|
||||
new_time = result_new['total_time']
|
||||
speedup = old_time / new_time if new_time > 0 else 0
|
||||
|
||||
print(f"优化前总耗时: {old_time:.0f}ms ({old_time/1000:.2f}秒)")
|
||||
print(f"优化后总耗时: {new_time:.0f}ms ({new_time/1000:.2f}秒)")
|
||||
print(f"性能提升: {speedup:.2f}x")
|
||||
print(f"时间减少: {(1 - new_time/old_time)*100:.1f}%")
|
||||
print()
|
||||
|
||||
# 详细对比
|
||||
if result_old['task_times'] and result_new['task_times']:
|
||||
old_avg = sum(result_old['task_times']) / len(result_old['task_times'])
|
||||
new_avg = sum(result_new['task_times']) / len(result_new['task_times'])
|
||||
|
||||
print("任务级性能对比:")
|
||||
print(f" 优化前平均任务耗时: {old_avg:.0f}ms")
|
||||
print(f" 优化后平均任务耗时: {new_avg:.0f}ms")
|
||||
print(f" 单任务性能提升: {old_avg/new_avg:.2f}x")
|
||||
print()
|
||||
|
||||
# 识别结果对比
|
||||
print("识别结果对比:")
|
||||
for old_result in result_old['results']:
|
||||
region_name = old_result['region']
|
||||
new_result = next((r for r in result_new['results'] if r['region'] == region_name), None)
|
||||
|
||||
if old_result['success'] and new_result and new_result['success']:
|
||||
old_text = old_result['text'][:20] if old_result['text'] else '(空)'
|
||||
new_text = new_result['text'][:20] if new_result['text'] else '(空)'
|
||||
match = "✓" if old_text == new_text else "✗"
|
||||
print(f" {match} {region_name}: 结果一致")
|
||||
|
||||
# 清理临时文件
|
||||
print()
|
||||
print("清理临时文件...")
|
||||
for info in region_images.values():
|
||||
try:
|
||||
if os.path.exists(info['path']):
|
||||
os.remove(info['path'])
|
||||
except (OSError, PermissionError):
|
||||
pass
|
||||
|
||||
print()
|
||||
print("=" * 70)
|
||||
print("测试完成")
|
||||
print("=" * 70)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -1,109 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试截图错误处理和重试机制
|
||||
"""
|
||||
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
import subprocess
|
||||
from unittest.mock import patch, MagicMock
|
||||
|
||||
# 添加项目根目录到路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def test_adb_error_codes():
|
||||
"""测试ADB错误码处理"""
|
||||
|
||||
print("测试ADB错误码处理...")
|
||||
print("=" * 50)
|
||||
|
||||
from operations.screenshot_operations import ScreenshotOperations
|
||||
ops = ScreenshotOperations()
|
||||
|
||||
# 测试错误码4294967295的处理
|
||||
print("\n1. 测试错误码4294967295 (设备连接失败)")
|
||||
|
||||
try:
|
||||
# 模拟adb命令返回4294967295
|
||||
with patch('subprocess.Popen') as mock_popen:
|
||||
mock_process = MagicMock()
|
||||
mock_process.wait.return_value = 4294967295
|
||||
mock_process.stdout.read.side_effect = [b'', b''] # 空数据
|
||||
mock_popen.return_value = mock_process
|
||||
|
||||
result = ops._get_screenshot_direct("test_device")
|
||||
print(f"截图结果: {result}")
|
||||
print("预期: False (截图失败)")
|
||||
|
||||
except Exception as e:
|
||||
print(f"异常: {e}")
|
||||
|
||||
print("\n2. 测试正常截图流程")
|
||||
# 这里不实际测试,因为需要真实的adb环境
|
||||
print("跳过实际截图测试(需要真实设备)")
|
||||
|
||||
def test_retry_mechanism():
|
||||
"""测试重试机制"""
|
||||
|
||||
print("\n3. 测试重试机制模拟")
|
||||
|
||||
# 模拟3次失败后成功的情况
|
||||
retry_count = 0
|
||||
max_retries = 3
|
||||
success = False
|
||||
|
||||
for retry in range(max_retries):
|
||||
retry_count = retry + 1
|
||||
print(f"重试 {retry_count}/{max_retries}")
|
||||
|
||||
# 模拟前两次失败,第3次成功
|
||||
if retry < 2:
|
||||
print(" 截图失败")
|
||||
else:
|
||||
print(" 截图成功")
|
||||
success = True
|
||||
break
|
||||
|
||||
if retry < max_retries - 1:
|
||||
print(" 等待1秒后重试...")
|
||||
time.sleep(0.1) # 实际测试中用较短时间
|
||||
|
||||
print(f"\n最终结果: {'成功' if success else '失败'}")
|
||||
print(f"重试次数: {retry_count}")
|
||||
|
||||
def test_error_messages():
|
||||
"""测试错误消息"""
|
||||
|
||||
print("\n4. 测试错误消息")
|
||||
|
||||
# 模拟不同的错误情况
|
||||
error_scenarios = [
|
||||
(4294967295, "设备连接失败"),
|
||||
(1, "ADB命令错误"),
|
||||
("timeout", "操作超时"),
|
||||
("unknown", "未知错误")
|
||||
]
|
||||
|
||||
for error_code, expected_desc in error_scenarios:
|
||||
print(f"错误码 {error_code}: {expected_desc}")
|
||||
|
||||
print("\n错误处理改进:")
|
||||
print("- 添加了设备连接状态检查")
|
||||
print("- 区分不同类型的ADB错误")
|
||||
print("- 提供更详细的错误诊断信息")
|
||||
print("- 实现截图失败时的重试机制")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_adb_error_codes()
|
||||
test_retry_mechanism()
|
||||
test_error_messages()
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("截图错误处理测试完成")
|
||||
print("修复内容:")
|
||||
print("1. 添加ADB错误码4294967295的特殊处理")
|
||||
print("2. 改进错误消息,提供更详细的诊断信息")
|
||||
print("3. 在douyin_fudai.py中添加截图重试机制")
|
||||
print("4. 当截图失败时会重试3次,而不是直接放弃")
|
||||
@@ -1,92 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试OCR期间截图文件等待逻辑
|
||||
"""
|
||||
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加项目根目录到路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def test_screenshot_file_wait():
|
||||
"""测试截图文件等待逻辑"""
|
||||
|
||||
print("测试OCR期间截图文件等待逻辑...")
|
||||
|
||||
# 1. 模拟截图文件不存在的情况
|
||||
print("\n1. 模拟截图文件等待...")
|
||||
|
||||
try:
|
||||
import path_config
|
||||
pic_path = path_config.get_screenshot_path()
|
||||
except Exception:
|
||||
pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png")
|
||||
|
||||
print(f"截图文件路径: {pic_path}")
|
||||
|
||||
# 检查文件是否存在
|
||||
if os.path.exists(pic_path):
|
||||
print("截图文件已存在")
|
||||
file_size = os.path.getsize(pic_path)
|
||||
print(f"文件大小: {file_size} bytes")
|
||||
else:
|
||||
print("截图文件不存在")
|
||||
|
||||
# 2. 模拟等待逻辑
|
||||
print("\n2. 测试等待逻辑...")
|
||||
|
||||
wait_start = time.time()
|
||||
max_wait = 3.0
|
||||
found = False
|
||||
|
||||
while time.time() - wait_start < max_wait:
|
||||
if os.path.exists(pic_path):
|
||||
file_size = os.path.getsize(pic_path)
|
||||
if file_size >= 1024: # 至少1KB
|
||||
found = True
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
wait_time = time.time() - wait_start
|
||||
|
||||
if found:
|
||||
print(".2f")
|
||||
else:
|
||||
print(f"等待{max_wait}秒后仍未找到有效截图文件")
|
||||
|
||||
# 3. 分析问题
|
||||
print("\n3. 问题分析:")
|
||||
|
||||
issues = []
|
||||
|
||||
if not found:
|
||||
issues.append("[WARN] 等待期间未找到截图文件")
|
||||
else:
|
||||
issues.append("[OK] 成功等到截图文件")
|
||||
|
||||
# 检查文件完整性
|
||||
if os.path.exists(pic_path):
|
||||
try:
|
||||
with open(pic_path, 'rb') as f:
|
||||
header = f.read(4)
|
||||
if header == b'\x89PNG':
|
||||
issues.append("[OK] 截图文件格式正确 (PNG)")
|
||||
else:
|
||||
issues.append("[WARN] 截图文件格式异常")
|
||||
except Exception as e:
|
||||
issues.append(f"[ERROR] 读取截图文件失败: {e}")
|
||||
else:
|
||||
issues.append("[ERROR] 截图文件不存在")
|
||||
|
||||
for issue in issues:
|
||||
print(issue)
|
||||
|
||||
print(f"\n测试结果: {'PASS' if found else 'FAIL'}")
|
||||
return found
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_screenshot_file_wait()
|
||||
sys.exit(0 if success else 1)
|
||||
@@ -1,127 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
截图性能测试脚本
|
||||
|
||||
测试截图性能并查看细粒度计时日志,验证优化效果。
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import logging
|
||||
|
||||
# 配置日志 - 使用 DEBUG 级别以查看所有详细计时信息
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG,
|
||||
format='[%(levelname)s] %(message)s',
|
||||
handlers=[
|
||||
logging.StreamHandler(sys.stdout)
|
||||
]
|
||||
)
|
||||
|
||||
def test_screenshot_with_timing():
|
||||
"""测试截图并显示计时信息"""
|
||||
try:
|
||||
from Underlying_Operations import underlying_operations
|
||||
except ImportError:
|
||||
print("[错误] 无法导入 Underlying_Operations")
|
||||
return
|
||||
|
||||
# 获取设备ID
|
||||
import subprocess
|
||||
try:
|
||||
result = subprocess.run(["adb", "devices"], capture_output=True, text=True, timeout=10)
|
||||
if result.returncode != 0:
|
||||
print("[错误] adb devices 失败")
|
||||
return
|
||||
|
||||
lines = result.stdout.strip().split("\n")[1:]
|
||||
devices = []
|
||||
for line in lines:
|
||||
if line.strip() and "\t" in line:
|
||||
device_id = line.split("\t")[0].strip()
|
||||
if device_id:
|
||||
devices.append(device_id)
|
||||
|
||||
if not devices:
|
||||
print("[错误] 未找到连接的设备")
|
||||
return
|
||||
|
||||
device_id = devices[0]
|
||||
print(f"[信息] 使用设备: {device_id}")
|
||||
except Exception as e:
|
||||
print(f"[错误] 获取设备ID失败: {e}")
|
||||
return
|
||||
|
||||
# 创建操作对象
|
||||
ops = underlying_operations()
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("测试 1: 正常截图(启用所有验证和镜像)")
|
||||
print("="*60)
|
||||
|
||||
# 测试1: 正常截图
|
||||
start = time.time()
|
||||
result1 = ops.get_screenshot(device_id, use_service=False) # 禁用服务,使用直接截图以便看到详细日志
|
||||
elapsed1 = (time.time() - start) * 1000.0
|
||||
print(f"\n[结果] 测试1完成: 成功={result1}, 总耗时={elapsed1:.1f}ms")
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("测试 2: 禁用 PNG 验证 (SKIP_SCREENSHOT_VERIFY=1)")
|
||||
print("="*60)
|
||||
|
||||
# 测试2: 禁用验证
|
||||
os.environ["SKIP_SCREENSHOT_VERIFY"] = "1"
|
||||
start = time.time()
|
||||
result2 = ops.get_screenshot(device_id, use_service=False)
|
||||
elapsed2 = (time.time() - start) * 1000.0
|
||||
print(f"\n[结果] 测试2完成: 成功={result2}, 总耗时={elapsed2:.1f}ms")
|
||||
if elapsed1 > 0:
|
||||
improvement = ((elapsed1 - elapsed2) / elapsed1) * 100
|
||||
print(f"[对比] 相比测试1: {improvement:+.1f}% ({elapsed1 - elapsed2:+.1f}ms)")
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("测试 3: 禁用 PNG 验证 + 禁用镜像 (SKIP_SCREENSHOT_VERIFY=1, DISABLE_SCREENSHOT_MIRROR=1)")
|
||||
print("="*60)
|
||||
|
||||
# 测试3: 禁用验证和镜像
|
||||
os.environ["DISABLE_SCREENSHOT_MIRROR"] = "1"
|
||||
start = time.time()
|
||||
result3 = ops.get_screenshot(device_id, use_service=False)
|
||||
elapsed3 = (time.time() - start) * 1000.0
|
||||
print(f"\n[结果] 测试3完成: 成功={result3}, 总耗时={elapsed3:.1f}ms")
|
||||
if elapsed1 > 0:
|
||||
improvement = ((elapsed1 - elapsed3) / elapsed1) * 100
|
||||
print(f"[对比] 相比测试1: {improvement:+.1f}% ({elapsed1 - elapsed3:+.1f}ms)")
|
||||
|
||||
# 恢复环境变量
|
||||
if "SKIP_SCREENSHOT_VERIFY" in os.environ:
|
||||
del os.environ["SKIP_SCREENSHOT_VERIFY"]
|
||||
if "DISABLE_SCREENSHOT_MIRROR" in os.environ:
|
||||
del os.environ["DISABLE_SCREENSHOT_MIRROR"]
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("测试总结")
|
||||
print("="*60)
|
||||
print(f"测试1 (正常): {elapsed1:.1f}ms")
|
||||
print(f"测试2 (禁用验证): {elapsed2:.1f}ms")
|
||||
print(f"测试3 (禁用全部): {elapsed3:.1f}ms")
|
||||
|
||||
if elapsed1 > 0 and elapsed3 > 0:
|
||||
total_improvement = ((elapsed1 - elapsed3) / elapsed1) * 100
|
||||
print(f"\n最大优化效果: {total_improvement:+.1f}% ({elapsed1 - elapsed3:+.1f}ms)")
|
||||
|
||||
if total_improvement > 10:
|
||||
print("\n[建议] 如果优化效果明显,可以考虑:")
|
||||
print(" 1. 在生产环境谨慎使用 SKIP_SCREENSHOT_VERIFY(可能影响数据完整性)")
|
||||
print(" 2. 如果不需要外部镜像,可以设置 DISABLE_SCREENSHOT_MIRROR=1")
|
||||
print(" 3. 检查外部镜像路径是否是网络路径(可能很慢)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_screenshot_with_timing()
|
||||
@@ -1,129 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试点击福袋后阶段识别与OCR共用截图的优化
|
||||
"""
|
||||
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加项目根目录到路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def test_screenshot_reuse_optimization():
|
||||
"""测试截图复用优化"""
|
||||
|
||||
print("测试点击福袋后阶段识别与OCR共用截图优化...")
|
||||
print("=" * 60)
|
||||
|
||||
# 1. 模拟阶段诊断检测到任务数量 > 0
|
||||
print("\n1. 模拟阶段诊断检测到任务数量 > 0")
|
||||
|
||||
class MockAnalyser:
|
||||
def __init__(self):
|
||||
self._fudai_detail_task_count_from_stage = 2
|
||||
self._screenshot_ready_for_ocr = False
|
||||
|
||||
def _log_kv(self, key, value, **kwargs):
|
||||
timestamp = time.strftime("%H:%M:%S", time.localtime())
|
||||
print(f"[{timestamp}] [{key}] {value}")
|
||||
|
||||
analyser = MockAnalyser()
|
||||
|
||||
# 模拟阶段诊断设置标志
|
||||
analyser._fudai_detail_task_count_from_stage = 2
|
||||
analyser._screenshot_ready_for_ocr = True
|
||||
|
||||
print(f"任务数量: {analyser._fudai_detail_task_count_from_stage}")
|
||||
print(f"截图复用标志: {analyser._screenshot_ready_for_ocr}")
|
||||
|
||||
# 2. 模拟OCR开始时的逻辑
|
||||
print("\n2. 模拟OCR开始时的截图复用检查")
|
||||
|
||||
# 检查是否可以复用阶段诊断时的截图
|
||||
screenshot_reused = False
|
||||
try:
|
||||
if getattr(analyser, '_screenshot_ready_for_ocr', False):
|
||||
analyser._screenshot_ready_for_ocr = False # 清除标志,避免重复使用
|
||||
screenshot_reused = True
|
||||
try:
|
||||
analyser._log_kv(
|
||||
"福袋详情",
|
||||
"read_fudai_detail_once:复用阶段诊断截图",
|
||||
reason="stage_diagnosed_task_count_gt_zero"
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print(f"截图是否复用: {screenshot_reused}")
|
||||
print(f"清除后的复用标志: {analyser._screenshot_ready_for_ocr}")
|
||||
|
||||
# 3. 验证优化效果
|
||||
print("\n3. 验证优化效果")
|
||||
|
||||
if screenshot_reused:
|
||||
print("[OK] 成功复用阶段诊断时的截图,避免重复截图")
|
||||
print("[OK] OCR跳过了get_screenshot调用")
|
||||
print("[OK] 减少了一次不必要的截图操作")
|
||||
success = True
|
||||
else:
|
||||
print("[FAIL] 截图复用失败,仍会进行新的截图")
|
||||
success = False
|
||||
|
||||
# 4. 模拟任务数量为0的情况
|
||||
print("\n4. 模拟任务数量为0的情况")
|
||||
|
||||
analyser2 = MockAnalyser()
|
||||
analyser2._fudai_detail_task_count_from_stage = 0
|
||||
analyser2._screenshot_ready_for_ocr = False # 任务数量为0时不应该设置复用标志
|
||||
|
||||
screenshot_reused_2 = False
|
||||
try:
|
||||
if getattr(analyser2, '_screenshot_ready_for_ocr', False):
|
||||
analyser2._screenshot_ready_for_ocr = False
|
||||
screenshot_reused_2 = True
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print(f"任务数量: {analyser2._fudai_detail_task_count_from_stage}")
|
||||
print(f"截图复用标志: {analyser2._screenshot_ready_for_ocr}")
|
||||
print(f"截图是否复用: {screenshot_reused_2}")
|
||||
|
||||
if not screenshot_reused_2:
|
||||
print("[OK] 任务数量为0时正确不复用截图")
|
||||
else:
|
||||
print("[FAIL] 任务数量为0时错误复用截图")
|
||||
success = False
|
||||
|
||||
# 5. 分析性能提升
|
||||
print("\n5. 性能提升分析")
|
||||
print("-" * 40)
|
||||
|
||||
print("优化前:")
|
||||
print("- 阶段诊断: 1次截图")
|
||||
print("- OCR识别: 1次截图")
|
||||
print("- 总计: 2次截图")
|
||||
|
||||
print("\n优化后:")
|
||||
print("- 阶段诊断: 1次截图")
|
||||
print("- OCR识别: 复用阶段诊断截图")
|
||||
print("- 总计: 1次截图")
|
||||
|
||||
print("\n性能提升:")
|
||||
print("- 减少50%的截图操作")
|
||||
print("- 减少截图等待时间")
|
||||
print("- 降低系统负载")
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"测试结果: {'PASS' if success else 'FAIL'}")
|
||||
print("优化目标: 当阶段诊断发现任务数量>0时,OCR复用同一张截图")
|
||||
print(f"{'='*60}")
|
||||
|
||||
return success
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_screenshot_reuse_optimization()
|
||||
sys.exit(0 if success else 1)
|
||||
@@ -1,59 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试截图服务修复效果
|
||||
"""
|
||||
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加项目根目录到路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def test_service_startup():
|
||||
"""测试截图服务启动"""
|
||||
print("测试截图服务启动修复...")
|
||||
|
||||
# 模拟启动过程
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
|
||||
# 创建分析器实例
|
||||
analyser_instance = fudai_analyse()
|
||||
|
||||
print("启动fudai_choujiang(只运行几秒钟测试服务启动)...")
|
||||
|
||||
try:
|
||||
# 设置设备ID(需要根据实际情况修改)
|
||||
device_id = "emulator-5554" # 或者其他设备ID
|
||||
|
||||
# 启动服务(只运行5秒)
|
||||
analyser_instance.fudai_choujiang(
|
||||
device_id=device_id,
|
||||
wait_minutes=0, # 不等待,直接测试启动
|
||||
)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
print("测试被中断")
|
||||
except Exception as e:
|
||||
print(f"测试过程中出现异常: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
# 检查服务状态
|
||||
print("\n检查服务状态:")
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
service = ScreenshotService.get_instance()
|
||||
info = service.get_cache_info()
|
||||
|
||||
print(f"服务运行中: {info['running']}")
|
||||
print(f"设备ID: {info['device_id']}")
|
||||
print(f"后台线程: {'运行中' if hasattr(service, '_thread') and service._thread and service._thread.is_alive() else '未运行'}")
|
||||
|
||||
# 停止服务
|
||||
if service.is_running():
|
||||
service.stop()
|
||||
print("服务已停止")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_service_startup()
|
||||
@@ -1,91 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试OCR时停止后台截图服务的优化效果
|
||||
"""
|
||||
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加项目根目录到路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def test_screenshot_service_ocr_integration():
|
||||
"""测试截图服务与OCR集成的优化"""
|
||||
print("=" * 80)
|
||||
print("测试OCR时停止后台截图服务的优化")
|
||||
print("=" * 80)
|
||||
|
||||
# 1. 启动截图服务
|
||||
print("\n1. 启动后台截图服务...")
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
service = ScreenshotService.get_instance()
|
||||
|
||||
# 模拟设备ID(实际测试时需要替换为真实设备ID)
|
||||
device_id = "emulator-5554"
|
||||
|
||||
if service.is_running():
|
||||
print("服务已在运行")
|
||||
else:
|
||||
service.start(device_id, interval=1.5)
|
||||
time.sleep(0.5) # 等待服务启动
|
||||
|
||||
if service.is_running():
|
||||
print("[OK] 后台截图服务启动成功")
|
||||
else:
|
||||
print("[FAIL] 后台截图服务启动失败")
|
||||
return
|
||||
|
||||
# 2. 模拟OCR密集操作
|
||||
print("\n2. 模拟OCR密集操作(调用read_fudai_detail_once)...")
|
||||
|
||||
# 创建一个模拟的analyser对象
|
||||
class MockAnalyser:
|
||||
def __init__(self):
|
||||
self.device_id = device_id
|
||||
self._fudai_detail_task_count_from_stage = 2
|
||||
|
||||
def _log_kv(self, key, value, **kwargs):
|
||||
timestamp = time.strftime("%H:%M:%S", time.localtime())
|
||||
print(f"[{timestamp}] [{key}] {value}")
|
||||
|
||||
analyser = MockAnalyser()
|
||||
|
||||
# 调用read_fudai_detail_once,这应该会停止后台服务
|
||||
start_time = time.time()
|
||||
try:
|
||||
from fudai_detail_modules.fudai_detail_reader import read_fudai_detail_once
|
||||
result = read_fudai_detail_once(analyser)
|
||||
elapsed = time.time() - start_time
|
||||
print(".2f")
|
||||
print(f" 返回状态: {result[0]}")
|
||||
except Exception as e:
|
||||
elapsed = time.time() - start_time
|
||||
print(".2f")
|
||||
print(f" 错误: {e}")
|
||||
|
||||
# 3. 检查服务是否重新启动
|
||||
print("\n3. 检查后台截图服务是否重新启动...")
|
||||
time.sleep(0.5) # 等待服务重新启动
|
||||
|
||||
if service.is_running():
|
||||
print("[OK] 后台截图服务已自动重新启动")
|
||||
info = service.get_cache_info()
|
||||
print(f" 设备ID: {info['device_id']}")
|
||||
print(f" 截图间隔: {info['interval']}秒")
|
||||
print(f" 缓存有效期: {info['cache_valid_duration']}秒")
|
||||
else:
|
||||
print("[FAIL] 后台截图服务未重新启动")
|
||||
|
||||
# 4. 清理
|
||||
if service.is_running():
|
||||
service.stop()
|
||||
print("\n4. 测试完成,停止后台截图服务")
|
||||
|
||||
print("\n" + "=" * 80)
|
||||
print("测试完成")
|
||||
print("=" * 80)
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_screenshot_service_ocr_integration()
|
||||
@@ -1,84 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
简单测试:验证OCR时停止后台截图服务的代码修改
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加项目根目录到路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def test_code_modification():
|
||||
"""测试代码修改是否正确"""
|
||||
print("测试OCR时停止后台截图服务的代码修改...")
|
||||
|
||||
# 1. 检查文件是否存在
|
||||
file_path = "fudai_detail_modules/fudai_detail_reader.py"
|
||||
if not os.path.exists(file_path):
|
||||
print(f"[FAIL] 文件不存在: {file_path}")
|
||||
return False
|
||||
|
||||
# 2. 检查代码中是否包含停止服务的逻辑
|
||||
with open(file_path, 'r', encoding='utf-8') as f:
|
||||
content = f.read()
|
||||
|
||||
# 检查关键代码片段
|
||||
checks = [
|
||||
("停止服务代码", "service.stop()" in content),
|
||||
("启动服务代码", "service.start(" in content),
|
||||
("screenshot_service_stopped变量", "screenshot_service_stopped" in content),
|
||||
("finally块", "finally:" in content),
|
||||
("ScreenshotService导入", "from operations.screenshot_service import ScreenshotService" in content),
|
||||
]
|
||||
|
||||
all_passed = True
|
||||
for check_name, result in checks:
|
||||
if result:
|
||||
print(f"[OK] {check_name}")
|
||||
else:
|
||||
print(f"[FAIL] {check_name}")
|
||||
all_passed = False
|
||||
|
||||
# 3. 检查语法是否正确
|
||||
try:
|
||||
compile(content, file_path, 'exec')
|
||||
print("[OK] 语法检查通过")
|
||||
except SyntaxError as e:
|
||||
print(f"[FAIL] 语法错误: {e}")
|
||||
all_passed = False
|
||||
|
||||
# 4. 检查导入是否工作
|
||||
read_fudai_detail_once = None # 初始化变量
|
||||
try:
|
||||
from fudai_detail_modules.fudai_detail_reader import read_fudai_detail_once
|
||||
print("[OK] 模块导入成功")
|
||||
except ImportError as e:
|
||||
print(f"[FAIL] 模块导入失败: {e}")
|
||||
all_passed = False
|
||||
|
||||
# 5. 检查函数签名
|
||||
import inspect
|
||||
try:
|
||||
if read_fudai_detail_once is not None:
|
||||
sig = inspect.signature(read_fudai_detail_once)
|
||||
print(f"[OK] 函数签名: {sig}")
|
||||
else:
|
||||
print("[SKIP] 函数未导入,跳过签名检查")
|
||||
except Exception as e:
|
||||
print(f"[FAIL] 函数签名检查失败: {e}")
|
||||
all_passed = False
|
||||
|
||||
print()
|
||||
if all_passed:
|
||||
print("[SUCCESS] 代码修改验证通过!")
|
||||
print("OCR密集操作时会自动停止后台截图服务,避免资源冲突。")
|
||||
else:
|
||||
print("[FAIL] 代码修改存在问题,请检查!")
|
||||
|
||||
return all_passed
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_code_modification()
|
||||
sys.exit(0 if success else 1)
|
||||
@@ -1,113 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试OCR时停止后台截图服务的功能
|
||||
"""
|
||||
|
||||
import time
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加项目根目录到路径
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
def test_screenshot_service_stop_during_ocr():
|
||||
"""测试OCR过程中后台截图服务是否被停止"""
|
||||
|
||||
print("测试OCR时停止后台截图服务功能...")
|
||||
|
||||
# 1. 启动截图服务
|
||||
print("\n1. 启动后台截图服务...")
|
||||
from operations.screenshot_service import ScreenshotService
|
||||
service = ScreenshotService.get_instance()
|
||||
|
||||
# 模拟设备ID
|
||||
device_id = "emulator-5554"
|
||||
|
||||
if not service.is_running():
|
||||
service.start(device_id, interval=1.5)
|
||||
time.sleep(0.5)
|
||||
|
||||
if service.is_running():
|
||||
print("[OK] 后台截图服务已启动")
|
||||
else:
|
||||
print("[FAIL] 后台截图服务启动失败")
|
||||
return False
|
||||
|
||||
# 记录初始状态
|
||||
initial_cache_duration = service._cache_valid_duration
|
||||
print(f"初始缓存有效期: {initial_cache_duration}秒")
|
||||
|
||||
# 2. 模拟OCR操作
|
||||
print("\n2. 模拟OCR操作...")
|
||||
|
||||
# 创建模拟的analyser
|
||||
class MockAnalyser:
|
||||
def __init__(self):
|
||||
self.device_id = device_id
|
||||
self._fudai_detail_task_count_from_stage = 2
|
||||
|
||||
def _log_kv(self, key, value, **kwargs):
|
||||
timestamp = time.strftime("%H:%M:%S", time.localtime())
|
||||
print(f"[{timestamp}] [{key}] {value}")
|
||||
|
||||
analyser = MockAnalyser()
|
||||
|
||||
# 记录开始时的服务状态
|
||||
service_running_before = service.is_running()
|
||||
print(f"OCR开始前服务运行状态: {service_running_before}")
|
||||
|
||||
start_time = time.time() # 初始化开始时间
|
||||
try:
|
||||
# 调用read_fudai_detail_once - 这应该会停止后台服务
|
||||
from fudai_detail_modules.fudai_detail_reader import read_fudai_detail_once
|
||||
|
||||
start_time = time.time()
|
||||
result = read_fudai_detail_once(analyser)
|
||||
elapsed = time.time() - start_time
|
||||
|
||||
print(".2f")
|
||||
print(f" 返回状态: {result[0]}")
|
||||
|
||||
except Exception as e:
|
||||
elapsed = time.time() - start_time
|
||||
print(".2f")
|
||||
print(f" 错误: {e}")
|
||||
|
||||
# 3. 检查OCR后的服务状态
|
||||
print("\n3. 检查OCR后的服务状态...")
|
||||
time.sleep(0.5) # 等待服务状态稳定
|
||||
|
||||
service_running_after = service.is_running()
|
||||
final_cache_duration = service._cache_valid_duration
|
||||
|
||||
print(f"OCR结束后服务运行状态: {service_running_after}")
|
||||
print(f"最终缓存有效期: {final_cache_duration}秒")
|
||||
|
||||
# 4. 验证结果
|
||||
success = True
|
||||
|
||||
if service_running_before and not service_running_after:
|
||||
print("[OK] 后台截图服务在OCR期间被正确停止")
|
||||
elif not service_running_before:
|
||||
print("[INFO] 后台截图服务在OCR开始前就已经停止")
|
||||
else:
|
||||
print("[FAIL] 后台截图服务在OCR期间没有被停止")
|
||||
success = False
|
||||
|
||||
if final_cache_duration == initial_cache_duration:
|
||||
print("[OK] 缓存有效期在OCR结束后被正确恢复")
|
||||
else:
|
||||
print(f"[WARNING] 缓存有效期未恢复: 期望{initial_cache_duration}, 实际{final_cache_duration}")
|
||||
|
||||
# 5. 清理
|
||||
if service.is_running():
|
||||
service.stop()
|
||||
print("\n5. 测试完成,停止后台截图服务")
|
||||
|
||||
print(f"\n测试结果: {'PASS' if success else 'FAIL'}")
|
||||
return success
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_screenshot_service_stop_during_ocr()
|
||||
sys.exit(0 if success else 1)
|
||||
@@ -1,44 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
测试time导入修复
|
||||
"""
|
||||
|
||||
import time
|
||||
|
||||
def test_time_import():
|
||||
"""测试time模块导入和使用"""
|
||||
|
||||
print("测试time模块导入和使用...")
|
||||
|
||||
# 模拟read_fudai_detail_once函数的开始部分
|
||||
try:
|
||||
start_time = time.time()
|
||||
print(".3f")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] time.time()调用失败: {e}")
|
||||
return False
|
||||
|
||||
# 模拟函数内部的逻辑
|
||||
try:
|
||||
task_count = 0
|
||||
# 清除标志
|
||||
# 模拟等待逻辑(之前有问题的部分)
|
||||
wait_start = time.time()
|
||||
print(".3f")
|
||||
# 模拟循环
|
||||
while time.time() - wait_start < 0.1: # 很短的时间
|
||||
pass
|
||||
|
||||
elapsed = time.time() - start_time
|
||||
print(".3f")
|
||||
except Exception as e:
|
||||
print(f"[ERROR] 函数内部time使用失败: {e}")
|
||||
return False
|
||||
|
||||
print("[OK] time模块导入和使用正常")
|
||||
return True
|
||||
|
||||
if __name__ == "__main__":
|
||||
success = test_time_import()
|
||||
print(f"\n测试结果: {'PASS' if success else 'FAIL'}")
|
||||
@@ -59,8 +59,8 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png
|
||||
- **OCR后**:保存OCR结果,包含识别文本预览
|
||||
|
||||
**实现位置:**
|
||||
- `Underlying_Operations.py::cut_pic()` - 裁剪图像时保存
|
||||
- `Underlying_Operations.py::analyse_pic_word()` - OCR识别前后保存
|
||||
- `douyin/core/underlying_operations.py::cut_pic()` - 裁剪图像时保存
|
||||
- `douyin/core/underlying_operations.py::analyse_pic_word()` - OCR识别前后保存
|
||||
|
||||
**保存信息:**
|
||||
- 预处理模式(彩色/二值化)
|
||||
@@ -171,7 +171,7 @@ YYYYMMDD_HHMMSS_操作类型_图片名_步骤_坐标_额外信息.png
|
||||
|
||||
### 目录配置
|
||||
|
||||
调试图像目录通过 `path_config.py` 配置:
|
||||
调试图像目录通过 `douyin/core/path_config.py` 配置:
|
||||
- `get_pic_dir()`: 返回 pic 目录路径
|
||||
- `get_debug_captures_dir()`: 返回调试图像存档目录路径
|
||||
|
||||
|
||||
@@ -1,35 +1,38 @@
|
||||
# 文档目录
|
||||
|
||||
本目录包含项目的所有文档文件。
|
||||
本目录包含项目当前在用的文档。**过期报告 / 历史迭代记录已归档到 `docs/archive/`**。
|
||||
|
||||
## 文档列表
|
||||
## 当前文档(按主题分组)
|
||||
|
||||
- **CLEANUP_REPORT.md** - 清理报告
|
||||
- **CODE_REVIEW_FIXES.md** - 代码审查修复
|
||||
- **CODE_REVIEW_REPORT.md** - 代码审查报告
|
||||
### 入门与依赖
|
||||
- **DEPENDENCY_GUIDE.md** - 依赖安装与版本说明
|
||||
- **迁移部署指南.md** - 新电脑部署与手机端操作清单
|
||||
- **deployment_quickstart.txt** - 极简迁移说明(优先一键部署 + 手机导航栏教程)
|
||||
- **WiFi_ADB_使用指南.md** - WiFi ADB 连接指南
|
||||
- **scrcpy_手动安装指南.md** - scrcpy 手动安装
|
||||
- **核显GPU加速说明.md** - 核显 GPU 加速
|
||||
- **设置定时任务说明.md** - 定时任务设置
|
||||
- **Git_连接与代理排查.md** - Git 网络连通排查
|
||||
|
||||
### 系统说明(活文档)
|
||||
- **完整技术文档.md** - 完整技术文档
|
||||
- **DEBUG_IMAGE_SYSTEM.md** - 调试图像系统
|
||||
- **DEPENDENCY_FIXES_REPORT.md** - 依赖修复报告
|
||||
- **DEPENDENCY_GUIDE.md** - 依赖指南
|
||||
- **FIXES_REPORT.md** - 修复报告
|
||||
- **FUDAI_FINDER_OPTIMIZATION.md** - 福袋查找器优化
|
||||
- **GUI参数冲突分析.md** - GUI参数冲突分析
|
||||
- **GUI日志修复总结.md** - GUI日志修复总结
|
||||
- **LOGGING_IMPROVEMENTS.md** - 日志改进
|
||||
- **MODULAR_REFACTORING_VERIFICATION.md** - 模块化重构验证
|
||||
- **OCR性能分析报告.md** - OCR性能分析报告
|
||||
- **WPS流程图说明.md** - WPS流程图说明
|
||||
- **功能差异对比.md** - 功能差异对比
|
||||
- **日志系统优化总结.md** - 日志系统优化总结
|
||||
- **日志系统优化说明.md** - 日志系统优化说明
|
||||
- **日志系统规范文档.md** - 日志系统规范文档
|
||||
- **核显GPU加速说明.md** - 核显GPU加速说明
|
||||
- **模块化代码对比说明.md** - 模块化代码对比说明
|
||||
- **流程图.md** - 流程图
|
||||
- **真机测试报告.md** - 真机测试报告
|
||||
- **统一截图和分数记录说明.md** - 统一截图和分数记录说明
|
||||
- **设置定时任务说明.md** - 设置定时任务说明
|
||||
- **预约系统详细流程.md** - 预约系统详细流程
|
||||
- **预约系统详细流程.md** - 预约系统流程
|
||||
- **高价值房间重访功能说明.md** - 高价值房间重访
|
||||
- **截图服务日志说明.md** - 截图服务日志
|
||||
- **日志系统规范文档.md** - 日志系统规范
|
||||
- **日志轮转功能说明.md** - 日志轮转
|
||||
- **ocr_engine_decision.md** - OCR 引擎选型决策记录
|
||||
|
||||
### 流程图
|
||||
- **流程图.md** - 主流程图
|
||||
- **WPS流程图说明.md** - WPS 流程图说明
|
||||
- **WPS详细流程图.txt** / **流程图_WPS文本格式.txt** - WPS 文本格式流程图
|
||||
|
||||
### 测试
|
||||
- **测试验证指南.md** - 测试验证指南
|
||||
|
||||
## 归档(`docs/archive/`)
|
||||
|
||||
历史报告、过期迭代记录、已合并到代码或被新文档替代的内容已移至 `docs/archive/`。
|
||||
其中 `docs/archive/optimization/` 子目录包含旧的性能/截图优化报告。
|
||||
@@ -0,0 +1,18 @@
|
||||
# 福袋详情页 OCR 2.0 handoff
|
||||
|
||||
1. 目标:按 1080x2400 新福袋详情页更新 OCR 区域,保留 legacy,并支持 `auto/legacy/v2_0`。
|
||||
2. 已新增字段开关:内容、价值、倒计时、任务、任务数量、按钮默认开;人数、直播间标题默认关。
|
||||
3. 旧开关 `fudai_disable_content_recognition` / `fudai_disable_task_recognition` 仅作新开关缺省兜底。
|
||||
4. 2.0 双任务 profile 在 `douyin/fudai/core/coords.py` 的 `DETAIL_UI_V2_0`。
|
||||
5. 2.0 单任务下移 profile 在 `DETAIL_UI_V2_0_ONE_TASK`,按当前 ADB 截图微调。
|
||||
6. 当前单任务标注图:`logs/fudai_detail_v2_regions_onetask_precise3.png`。
|
||||
7. 当前 ADB 原图:`logs/fudai_detail_v2_current_20260602_234012.png`。
|
||||
8. 单任务任务框已缩到左侧任务文案,避免混入右侧“未达成”。
|
||||
9. 任务数量优先 OCR `(0/1)` / `(1/2)`,失败回退 legacy 像素检测。
|
||||
10. debug 截图 extra_info 已包含 `ui_version`、`ocr_enabled`、`region_name` 等信息。
|
||||
11. 桌面 GUI 与 Web GUI 已加入 UI 版本和所有 OCR 字段开关。
|
||||
12. “参考价值”按实际价值解析,继续写 `prize_value_yuan`。
|
||||
13. 验证日志:`logs/pytest_fudai_detail_v2_final4.log` PASS。
|
||||
14. 验证日志:`logs/py_compile_fudai_detail_v2_final4.log` PASS。
|
||||
15. 验证日志:`logs/web_gui_config_sync_fudai_v2_final4.log` PASS。
|
||||
16. 验证日志:`logs/git_diff_check_fudai_v2_final4.log` PASS。
|
||||
@@ -0,0 +1,239 @@
|
||||
# 2026-06-02 全量代码审查进展
|
||||
|
||||
目标:对 `C:\Users\12742\Desktop\douyin_guaji-main` 做仓库级 code review,并对确认的高风险功能缺陷直接修复。
|
||||
|
||||
## 已确认并已修复
|
||||
|
||||
1. `gui/web_gui.py`
|
||||
- `force_stop()` / `atexit` 会误杀同仓库其他 `run_cli.py` 进程。
|
||||
- 已改为只清理当前 Web GUI 自己启动过的 PID。
|
||||
|
||||
2. `gui/webgui_launcher.py`
|
||||
- `stop_old_processes()` 会按 `*web_gui.py*` 全局杀进程。
|
||||
- 已改为限定当前仓库路径。
|
||||
|
||||
3. `gui/gui_core_pkg/config.py`
|
||||
- 配置写入是浅 `update` + 直接覆盖,存在并发丢字段和半写风险。
|
||||
- 已改为深合并 + 进程内锁 + `.tmp` + `os.replace()`。
|
||||
|
||||
4. `operations/screenshot_service.py`
|
||||
- `start()` 在持锁状态下调用 `stop()`,设备切换时可能死锁。
|
||||
- 已改为先释放锁再等待旧线程退出。
|
||||
|
||||
5. `gui/gui_core_pkg/wifi_adb.py`
|
||||
- `disconnect_wifi_adb("ip:port")` 会拼成 `ip:port:5555`。
|
||||
- 已修复为支持直接 `ip:port` 输入。
|
||||
|
||||
6. `gui/web_gui_pkg/routes.py`
|
||||
- `/api/*` GET/POST、`/pic/*` 以及静态页都可被非本地来源访问。
|
||||
- 已全部限制为 local-only。
|
||||
|
||||
7. `douyin/core/douyin_fudai.py`
|
||||
- `_maybe_run_yanghao_during_run()` 注释说触发推荐页养号,实际只调用 `_yanghao_wait()`。
|
||||
- 已改为真正调用 `_yanghao_recommend_flow()`。
|
||||
|
||||
8. `douyin/fudai/core/fudai_detail_orchestrator_pkg/read_with_retries.py`
|
||||
- `read_once_callback` 参数未被真正使用。
|
||||
- `status="ok"` 但 tuple 无效时会走未定义局部变量路径。
|
||||
- `task_count_zero` 补救逻辑与 `read_once()` 返回的 `not_in_fudai_detail` 不一致。
|
||||
- 已修复以上三点。
|
||||
|
||||
9. `douyin/fudai/core/fudai_detail_orchestrator_pkg/read_once.py`
|
||||
- 停止后台截图服务后未恢复。
|
||||
- 复用阶段截图时不验证可读性,坏图会直接落到 `screenshot_failed`。
|
||||
- 已补恢复逻辑和坏图自动 fresh screenshot。
|
||||
|
||||
10. `douyin/core/fudai_modules/handle_detail_*`
|
||||
- first-open / second-open / 错误分支存在多处状态残留:
|
||||
- first-open 可能误标 second-open
|
||||
- second-open 重读终止状态后不清 flag
|
||||
- second-open 重读失败后仍卡 second-open
|
||||
- task_count_zero / not_in_fudai_detail 被消费后不清 `_last_fudai_detail_status/_extra`
|
||||
- coupon/watch/validation_failed 被消费后不清 `_last_fudai_detail_status`
|
||||
- 以上已逐项修复。
|
||||
|
||||
11. `douyin/detection/detection_pkg/finder.py`
|
||||
- 命中后不写回 `last_fudai_x`。
|
||||
- 非 1080 宽屏下历史坐标比较混用坐标系。
|
||||
- `fudai_icon_max_wait_seconds=0` 时会 0 次检测直接退出。
|
||||
- 已修复。
|
||||
|
||||
12. `douyin/detection/detection_pkg/finder_template_match.py`
|
||||
- 模板兜底命中后不写回 `last_fudai_x`,与其他两条检测路径不一致。
|
||||
- 已修复。
|
||||
|
||||
13. 导入链缺依赖即崩
|
||||
- 已逐步把以下模块的顶层 `PIL` 依赖改成按需导入:
|
||||
- `operations.__init__`
|
||||
- `operations.screenshot_service`
|
||||
- `douyin.detection.pixel._common`
|
||||
- `douyin.detection.pixel.buttons`
|
||||
- `douyin.detection.pixel.popups`
|
||||
- `douyin.detection.pixel.stage`
|
||||
- `douyin.detection.detection_pkg.detail`
|
||||
- `douyin.detection.detection_pkg.finder`
|
||||
- `douyin.fudai.core.fudai_debug_utils`
|
||||
- `douyin.fudai.core.fudai_detail_coupon_detection`
|
||||
- `douyin.fudai.core.fudai_detail_orchestrator_pkg.read_once`
|
||||
- `douyin.fudai.core.fudai_detail_orchestrator_pkg.read_with_retries`
|
||||
- `douyin.core.douyin_fudai`
|
||||
- `douyin.core.underlying_operations`
|
||||
- 当前机器上已实证:
|
||||
- `import operations`:PASS
|
||||
- `import operations.screenshot_service`:PASS
|
||||
- `import douyin.detection.douyin_detection`:PASS
|
||||
- `import douyin.core.douyin_fudai`:PASS
|
||||
|
||||
14. `douyin/handlers/douyin_screenshot_handler.py`
|
||||
- `save_step_screenshot()` 用 `dirname(__file__)` 锚到错误 `pic` 目录。
|
||||
- 已改为统一使用 `path_config.get_pic_dir()`。
|
||||
|
||||
15. `douyin/core/fudai_modules/handle_detail_*`
|
||||
- `check_invalid_detail_fallback()` 早退时不清 `_fudai_detail_first_read/_last_fudai_detail_tuple`。
|
||||
- `handle_first_open_branch()` 的早退路径不清 first-open/缓存状态。
|
||||
- `handle_second_open_branch()` 重读无效详情时不清 second-open 标志。
|
||||
- 已修复。
|
||||
|
||||
16. `douyin/core/fudai_modules/handle_detail_helpers.py`
|
||||
- 终止类状态(coupon/watch/validation_failed)消费后不清 `_last_fudai_detail_status`。
|
||||
- task_count_zero / not_in_fudai_detail 错误被消费后不清 `_last_fudai_detail_status/_last_fudai_detail_extra`。
|
||||
- 已修复。
|
||||
|
||||
17. `douyin/detection/detection_pkg/finder.py`
|
||||
- `fudai_icon_max_wait_seconds=0` 时会 0 次检测直接退出。
|
||||
- 旧实现还会把显式配置的 `0` 通过 `or 5.0` 偷偷退回默认值。
|
||||
- 已修复为保留显式 `0`,并至少执行一轮即时检测。
|
||||
|
||||
18. `douyin/fudai/core/fudai_detail_coupon_detection.py`
|
||||
- 顶层 `PIL` 依赖会继续阻塞 `douyin_fudai` 导入链。
|
||||
- 已改为按需导入。
|
||||
|
||||
19. `douyin/detection/pixel/*`
|
||||
- `popups.py` / `buttons.py` / `stage.py` / `_common.py` 顶层 `PIL` 依赖会阻塞 detection 导入链。
|
||||
- 已改为按需导入。
|
||||
|
||||
20. `douyin/fudai/core/fudai_detail_orchestrator_pkg/read_once.py`
|
||||
- 第二次打开重读后若仍无有效 detail,会继续保留 second-open 状态。
|
||||
- 已修复。
|
||||
|
||||
21. `douyin/core/fudai_modules/handle_detail_first_open.py`
|
||||
- `branch_result == "return"` / 验证失败早退时,`_fudai_detail_first_read/_last_fudai_detail_tuple` 不清理。
|
||||
- 已修复。
|
||||
|
||||
22. `douyin/core/fudai_modules/handle_detail_helpers.py`
|
||||
- `check_invalid_detail_fallback()` 早退时不清 `_fudai_detail_first_read/_last_fudai_detail_tuple`。
|
||||
- 已修复。
|
||||
|
||||
23. `douyin/detection/detection_pkg/finder_template_match.py`
|
||||
- 模板兜底命中后只写 `last_find_fudai_time`,不写 `last_fudai_x`。
|
||||
- 已修复。
|
||||
|
||||
24. `operations/screenshot_operations.py` / `douyin/core/underlying_operations_pkg/screenshot_direct.py`
|
||||
- `target_pic` fallback 路径仍相对模块目录拼接。
|
||||
- 已统一锚到 `<project_root>/target_pic`。
|
||||
|
||||
25. `operations/screenshot_operations.py`
|
||||
- `_find_pic_path(..., for_reading=True)` 会把 `operations/` 当前目录作为图片搜索路径,可能误命中同名文件。
|
||||
- 已修复为只搜索项目根 `pic/` 与 `target_pic/`。
|
||||
|
||||
26. `douyin/detection/pixel/stage.py`
|
||||
- 并行阶段检测里实际调用了 popup/button helper,但文件头没导入,对应检测项运行时会静默掉成 False。
|
||||
- 已补齐导入。
|
||||
|
||||
27. `douyin/core/douyin_flow_control_pkg/stage_handler.py`
|
||||
- 直接调用 `find_and_open_fudai_detail()` 却未导入。
|
||||
- 已修复。
|
||||
|
||||
28. `douyin/core/underlying_operations_pkg/countdown.py`
|
||||
- 使用 `Optional` 但未导入。
|
||||
- 已修复。
|
||||
|
||||
29. `douyin/core/fudai_modules/handle_detail_filter.py`
|
||||
- 高价值预约分支里 `basic_join_decision()` 失败也会被当成“已记录预约并完成”。
|
||||
- 已修复为只有真成功才消费该分支。
|
||||
|
||||
30. `douyin/reservation/reservation_logic/add.py` / `attend_window.py`
|
||||
- 日志里的旧静态检查结果显示两处反复引用 `_RESERVATION_ERROR_UTILS_AVAILABLE`,但模块本身漏导入,属于确定性的 `NameError`/静态错误来源。
|
||||
- 已补齐从 `reservation_logic._common` 的导入。
|
||||
|
||||
31. `gui/web_gui_pkg/request_parsing.py`
|
||||
- `send_json()` 在客户端主动断开连接时会把正常断链打成 `ConnectionAbortedError` traceback,已在 `logs/web_gui_runtime.err.log` 中出现。
|
||||
- 已改为对 `BrokenPipeError` / `ConnectionAbortedError` / `ConnectionResetError` 静默收口,不再把正常断链记成服务端异常。
|
||||
|
||||
32. `douyin/logging/douyin_logging_pkg/monitor.py`
|
||||
- `logs` 中出现 `cannot import name 'start_log_monitor' from partially initialized module ... monitor`,根因是 `monitor.py` 顶层反向导入 `config.py`,同时模块导入末尾又主动调用 `configure_logging()`,形成循环导入。
|
||||
- 已去掉 `monitor -> config` 的顶层依赖,以及 `monitor` 模块导入时的自动配置副作用,当前 `monitor/config/douyin_logging` 导入链已可直接通过。
|
||||
|
||||
33. `douyin/logging/action_logger.py`
|
||||
- `ActionLogger.log_operation()` 之前只认 `elapsed`,会把调用方已经传进来的 `elapsed_seconds` 吞掉并重写成 `0.0`,导致 `actions.log` 大量出现假的 `耗时=0.00ms`。
|
||||
- 已改为同时正确接受 `elapsed` / `elapsed_seconds`,只在确实有值时才写入耗时字段,日志耗时保真恢复正常。
|
||||
|
||||
34. `douyin/fudai/douyin_fudai_contain_impl.py`
|
||||
- 重 OCR 分支里 `picked_heavy` 只在部分条件下赋值,后续却无条件读取,存在继续污染运行日志的局部变量边界风险。
|
||||
- 已补默认初始化,避免该分支再出现这类局部变量异常。
|
||||
|
||||
35. `douyin/logging/douyin_logging_wrapper_pkg/simple.py`
|
||||
- 行为日志桥接层之前只识别 `elapsed_ms` / `total_ms`,但 finder 一类日志大量传的是 `total_elapsed_ms`,导致这些本来已有总耗时的操作仍被桥接成缺失耗时或误导性 `0.00ms`。
|
||||
- 已补 `total_elapsed_ms -> elapsed_seconds` 的统一映射,后续 `actions.log` 能更真实反映 finder 总耗时。
|
||||
|
||||
36. `douyin/logging/douyin_logging_wrapper_pkg/detailed.py`
|
||||
- detailed 模式下的行为日志桥接也存在同样问题:只识别 `elapsed_ms` / `total_ms`,未覆盖 `total_elapsed_ms`,会让不同日志模式下的耗时记录不一致。
|
||||
- 已与 simple 模式对齐,补上 `total_elapsed_ms` 识别。
|
||||
|
||||
37. `douyin/reservation/reservation_logic/attend_window.py`
|
||||
- 运行时分支里仍残留一组高风险未定义符号:`cleanup_expired_reservations` 未导入,以及 `target_room_title / target_room_title_raw / target_content / target_value` 在成功回退分支会被直接使用。
|
||||
- 已补齐导入与目标预约字段的本地初始化,避免这些分支在运行时直接 `NameError`。
|
||||
|
||||
38. `douyin/fudai/core/fudai_attend.py`
|
||||
- `attend_choujiang()` 之前会在 5 秒有效期内无条件复用 `_fudai_button_status/_fudai_button_text`,没有校验缓存是否来自当前直播间,存在把上一个房间按钮状态误用到当前房间的风险。
|
||||
- 已改为:5 秒内复用也必须满足 `current_room_pos == _fudai_button_room_pos`(或其中一方缺失),避免跨房间误复用按钮 OCR 缓存。
|
||||
|
||||
39. `douyin/reservation/douyin_reservation_handler_pkg/seek_room.py`
|
||||
- 回退成功后会直接调用 `_dump_room_pos_map_to_state(analyser)`,但文件头之前没导入这个 helper,属于命中成功回退分支就可能触发的运行时 `NameError`。
|
||||
- 已补从 `dump_state.py` 的显式导入,并加了最小导入回归验证。
|
||||
|
||||
40. `douyin/fudai/core/fudai_attend.py`
|
||||
- 当 `room_pos` 不命中时,`attend_choujiang()` 之前只会从当前 `room_pos` 的映射表项回收 `button_text`,容易在房间位置漂移时直接掉到 `no_parallel_ocr_result`。
|
||||
- 已补按 `current_room_title/current_room_title_raw` 匹配映射表标题的兜底回收路径,减少按钮 OCR 缓存因为位置漂移而失效。
|
||||
|
||||
41. `douyin/fudai/core/fudai_attend.py`
|
||||
- `button_text_raw` 作为全局缓存之前会被直接信任,但它本身没有房间归属校验,存在把上一个直播间的裸按钮文本误用到当前直播间的风险。
|
||||
- 已改为:只有确认 `_fudai_button_room_pos` 与当前 `room_pos` 同房间(或任一方缺失)时,才允许直接信任 `button_text_raw`。
|
||||
|
||||
42. `douyin/fudai/core/fudai_attend.py`
|
||||
- “点击参与抽奖”分支里那两段调试 JSON 写盘之前完全裸奔,遇到不可 JSON 序列化对象时会直接把主流程打断。
|
||||
- 已改为真正的 best-effort:写盘整体包裹在 `try/except` 中,并对关键字段做基础类型收敛,`json.dumps(..., default=str)` 不再让调试写盘反咬业务路径。
|
||||
|
||||
43. `douyin/fudai/douyin_fudai_contain_impl.py`
|
||||
- 主并行 OCR 写按钮状态时会记录 `_fudai_button_room_pos`,但 fallback 并行 OCR 之前没传 `record_room_pos=True`,导致备用 OCR 成功后仍可能缺失房间归属信息,进而削弱后续跨房间缓存保护。
|
||||
- 已补齐 fallback 路径的 `record_room_pos=True`,并加了最小回归验证。
|
||||
|
||||
44. `gui/components/wifi_adb_dialog.py`
|
||||
- `toggle_maximize` 之前被错误定义在 `auto_connect_wifi()` 内部,但“放大/恢复”按钮是在外层直接绑定 `command=toggle_maximize`,属于打开对话框就可能命中的真作用域错误。
|
||||
- 已把 `toggle_maximize` 提升到 `open_wifi_adb_dialog()` 同级作用域,并补了最小 smoke test 证明按钮命令可正常绑定。
|
||||
|
||||
## 仍建议继续深挖
|
||||
|
||||
1. `douyin/detection/detection_pkg/finder.py`
|
||||
- 坏截图/半写图补拍恢复的一致性。
|
||||
- 模板兜底与像素路径在日志、计时和状态清理上的一致性。
|
||||
|
||||
2. `douyin/fudai/core/fudai_detail_orchestrator_pkg/read_once.py`
|
||||
- 运行期截图/OCR异常回退的进一步收口。
|
||||
|
||||
## 仍未修复但已确认的风险
|
||||
|
||||
1. `config/config.json`
|
||||
- 仍混有明显的本机运行态/本地偏好数据(如 `last_wifi_target`),不适合作为稳定仓库默认值。
|
||||
- 因文件属于当前工作树活跃修改内容,未直接重写,避免覆盖用户现场状态。
|
||||
|
||||
2. `pyright`
|
||||
- 仓库仍存在一批历史静态类型错误,当前没有被系统性清理。
|
||||
|
||||
3. `pytest`
|
||||
- 当前环境缺 `pytest`,无法在本会话中把新增回归测试正式跑绿;目前主要依赖语法检查与轻量行为探针。
|
||||
|
||||
## 当前验证约束
|
||||
|
||||
1. 当前环境缺 `pytest`,不能直接在此会话里把新增测试跑绿。
|
||||
2. 当前环境缺 `PIL` / OCR 相关依赖,但这反而帮助暴露了导入链的真实缺陷;多处“缺依赖即崩”的问题已被修复并通过轻量 import 探针验证。
|
||||
@@ -0,0 +1,9 @@
|
||||
# 2026-06-18 真机福袋诊断 handoff
|
||||
|
||||
- 设备:`192.168.10.100:45967`,前台为 `com.ss.android.ugc.aweme/.live.LivePlayActivity`。
|
||||
- 已修 1:无福袋房间继承旧 `_current_fudai_content`,提交 `22e2ed1`,复测 `artifacts/live_fudai_flow_20260618_124737` 里无福袋位置 `2/3/6/8/9` 均为空内容。
|
||||
- 已修 2:v2 双任务详情区域偏低,导致巴图 4999 福袋倒计时/内容裁剪到标题行;样本已保存到 `tests/fixtures/fudai_detail_v2_two_task_batu_4999_regions.png`。
|
||||
- 已修 3:`0元带走¥999参考价值` 被价值校验器误判为 `value_raw_mismatch_parsed_value`。
|
||||
- 复测证据:`artifacts/live_fudai_flow_20260618_130639` 中 13:10:20 识别 `【粉丝专享】左上角领取散热风`、`07:59`、`999元`,并写入预约,优惠券弹窗出现时日志为跳过福袋点击。
|
||||
- 未充分覆盖:预约回退未进入实际执行窗口,日志均为 `时间窗口未到`;需后续更长轮验证。
|
||||
- 待盯:关注列表当前可能直播间数量少或滑动未换房,短轮 `artifacts/live_fudai_flow_20260618_131658` 多次触发同房三连/回顶。
|
||||
@@ -0,0 +1,16 @@
|
||||
# 2026-06-18 gui_dashboard_app 新 UI 入口美化交接
|
||||
|
||||
- 范围:只改 `gui/dashboard_app` 新入口、`gui/gui_dashboard_app_entry.py` 入口关联和 `tools/gui` 导出工具。
|
||||
- 旧入口:未改 `gui/gui_app.py`。
|
||||
- 功能边界:以 20 页真实导出图为准,不新增/删除页面和功能。
|
||||
- 页面数:`PAGES=20`。
|
||||
- 视觉方向:浅色桌面 App、固定侧栏、顶部工具栏、底部运行栏、圆角按钮、轻量卡片、紧凑表格。
|
||||
- 模块化:拆分为 `page_home/page_config/page_debug/page_data/page_registry/page_helpers/page_context`。
|
||||
- 交互保留:刷新设备、扫描 WiFi、WiFi ADB、截图+OCR、保存配置、开始/停止/强制停止/返回键。
|
||||
- 文本框保留:关键词、养号评论文案、爱心/收藏关键词切页不丢。
|
||||
- 验证:`python -m py_compile` PASS。
|
||||
- 验证:20 页 Tk 构建遍历 PASS。
|
||||
- 验证:`git diff --check` PASS。
|
||||
- 视觉核对包:`artifacts/gui_dashboard_ui_review_20260618_124233/index.html`。
|
||||
- 视觉总览:`artifacts/gui_dashboard_ui_review_20260618_124233/contact-sheet.jpg`。
|
||||
- 注意:`artifacts/` 为验收产物,未纳入提交。
|
||||
@@ -13,7 +13,7 @@
|
||||
### ✅ 日志文件写入功能正常
|
||||
|
||||
**验证点1: 日志文件存在**
|
||||
- 文件路径: `C:\Users\12742\Desktop\douyin_guaji-main\logs\unified_2025-12-22.log`
|
||||
- 文件路径: `logs/unified_2025-12-22.log`
|
||||
- 文件大小: 8800 bytes
|
||||
- 总行数: 126行
|
||||
|
||||
@@ -96,4 +96,3 @@ GUI应用的日志写入功能:
|
||||
**测试状态**: ✅ 通过
|
||||
**功能状态**: ✅ 正常
|
||||
**建议**: 可以投入使用
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
Douyin Guaji - Quick Deployment (TXT)
|
||||
=====================================
|
||||
|
||||
Purpose
|
||||
-------
|
||||
This is the simplified migration guide.
|
||||
Computer-side setup is kept minimal because one-click deploy scripts are already provided.
|
||||
|
||||
|
||||
1) Computer (minimal)
|
||||
---------------------
|
||||
Prerequisites:
|
||||
- Windows 10/11
|
||||
- Python 3.10+
|
||||
- ADB (platform-tools) available in PATH
|
||||
|
||||
In project root, run:
|
||||
|
||||
bootstrap_deps.bat
|
||||
|
||||
Optional:
|
||||
|
||||
bootstrap_deps.bat --minimal
|
||||
|
||||
|
||||
2) Phone required setup
|
||||
-----------------------
|
||||
2.1 Enable Developer options
|
||||
- Open: Settings -> About phone
|
||||
- Tap "Build number" 7 times
|
||||
- Enter lock screen password if asked
|
||||
|
||||
2.2 Enable USB debugging
|
||||
- Open: Settings -> Developer options
|
||||
- Turn on:
|
||||
- USB debugging
|
||||
- (if available) USB debugging (Security settings) / USB installation
|
||||
|
||||
2.3 First USB authorization
|
||||
- Connect phone to PC with USB cable
|
||||
- Set USB mode to File Transfer (MTP)
|
||||
- On phone popup "Allow USB debugging", tap Allow
|
||||
- Verify on PC:
|
||||
|
||||
adb devices
|
||||
|
||||
Expected:
|
||||
|
||||
<device-id> device
|
||||
|
||||
If status is "unauthorized", replug cable and approve popup again.
|
||||
|
||||
|
||||
3) How to show the bottom navigation bar on phone (detailed)
|
||||
-------------------------------------------------------------
|
||||
This section is for the Android system navigation bar (Back / Home / Recents).
|
||||
|
||||
Method A (standard Android path)
|
||||
--------------------------------
|
||||
1. Open Settings
|
||||
2. Search "Navigation mode" (or "System navigation")
|
||||
3. Open the result and switch to:
|
||||
- 3-button navigation (shows bottom buttons), or
|
||||
- Gesture navigation (shows gesture bar/hint on some devices)
|
||||
|
||||
Common path examples:
|
||||
- Pixel / near-stock Android:
|
||||
Settings -> System -> Navigation mode
|
||||
- Some other ROMs:
|
||||
Settings -> System -> Gestures -> Navigation mode
|
||||
|
||||
Method B (common brand paths)
|
||||
-----------------------------
|
||||
- Samsung:
|
||||
Settings -> Display -> Navigation bar -> Buttons
|
||||
- Xiaomi / Redmi / POCO (MIUI / HyperOS):
|
||||
Settings -> Home screen -> System navigation -> Buttons
|
||||
- OPPO / OnePlus (ColorOS / OxygenOS):
|
||||
Settings -> System settings -> System navigation -> Virtual buttons
|
||||
- vivo / iQOO:
|
||||
Settings -> System navigation -> Navigation keys
|
||||
- Huawei / Honor:
|
||||
Settings -> System & updates -> System navigation -> Three-key navigation
|
||||
|
||||
If the bar still does not appear:
|
||||
---------------------------------
|
||||
1. Disable any "Full screen gestures" option
|
||||
2. Disable app-level full screen mode for the current app
|
||||
3. Reboot phone once after switching navigation mode
|
||||
4. Use Settings search with keywords:
|
||||
- navigation
|
||||
- system navigation
|
||||
- gesture
|
||||
|
||||
Temporary reveal tip:
|
||||
---------------------
|
||||
If an app is full-screen and hides controls, swipe up from the very bottom edge once.
|
||||
On many devices this temporarily shows system navigation controls.
|
||||
|
||||
|
||||
4) Quick run check
|
||||
------------------
|
||||
After dependencies are ready and ADB is authorized:
|
||||
|
||||
python bin/gui_app.py
|
||||
|
||||
Check:
|
||||
- Device is visible in device selector
|
||||
- Screenshot action works
|
||||
- Start button can launch run loop
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
# OCR 引擎选型决策记录
|
||||
|
||||
> 2026-05 决策依据。基于 ~30 张项目截图实测对比,决定换掉 EasyOCR,统一用 **PaddleOCR PP-OCRv4_mobile**。
|
||||
|
||||
---
|
||||
|
||||
## 结论
|
||||
|
||||
| 引擎 | 平均/张 | 关键图精度 | 选用 |
|
||||
|---|---|---|---|
|
||||
| **PaddleOCR v4-mobile** | **369ms** | ✅ 12 段全对 | **首选** |
|
||||
| PaddleOCR v5-mobile | 407ms | ⚠️ 偶尔合并段落 | 略差 |
|
||||
| RapidOCR-ONNX | 1494ms | ✅ 12 段全对 | 兜底 |
|
||||
| PaddleOCR v5-server | 2395ms | ⚠️ 多噪声字符 | 不用(重型) |
|
||||
| EasyOCR | 629ms | ❌ "官方保障"→"膏方保腰" | **回退** |
|
||||
| PaddleOCR v4-server | 2721ms | ⚠️ 切分错误 | 不用(重型) |
|
||||
|
||||
业务图都是裁切后的小区域(300×120 倒计时框、600×260 内容框),mobile 模型完胜 server 模型。
|
||||
|
||||
## 关键修复:Win + Paddle 3.x oneDNN+PIR bug
|
||||
|
||||
`ConvertPirAttribute2RuntimeAttribute not support pir::ArrayAttribute<pir::DoubleAttribute>` 在 paddle 3.3 + paddleocr 3.5 + Win 必现。
|
||||
|
||||
实测结论:
|
||||
- ❌ `FLAGS_enable_pir_in_executor=0` 修不掉(PIR 已强制默认)
|
||||
- ❌ paddleocr 3.x 强制要 paddle 3.x,不能降级
|
||||
- ✅ **`enable_mkldnn=False`** 是当前唯一可行解,代价是 CPU 推理慢 20-30%
|
||||
|
||||
代码里在 `operations/ocr_operations.py` 模块顶层设置 `FLAGS_use_mkldnn=false` + `enable_mkldnn=False`。等 paddle 上游补全 `onednn_instruction.cc:118` 的属性转换分支后可以删掉这行。
|
||||
|
||||
## 已知次优配置
|
||||
|
||||
- PaddleOCR `predict()` 是 3.x 推荐 API,`ocr()` 仍兼容(代码做了运行时检测)
|
||||
- 自定义"放大+锐化+对比度增强"预处理对 PaddleOCR 是负优化(实测 `coupon_full_title` 输出 `全全场通用` 重复字、`coupon_limit` 多出 `工品` 噪声),已删除。PaddleOCR 内部的 resize/normalize 已经够用
|
||||
|
||||
## 速度数据(19 张 + 11 张混合裁切框,CPU 模式)
|
||||
|
||||
### 速度横向对比(按场景分组的代表数据)
|
||||
|
||||
| 图片类型 | v4-mobile | v5-mobile | EasyOCR |
|
||||
|---|---|---|---|
|
||||
| 复杂多文字(coupon.png 整图)| 2293ms | 2148ms | 2168ms |
|
||||
| 长文字行(banner_long.png)| 898ms | 910ms | 451ms |
|
||||
| 短文字(coupon_title.png)| 163ms | 162ms | 279ms |
|
||||
| 数字小框(coupon_30.png)| 18ms | 106ms | 147ms |
|
||||
| 福袋裁切区域(fudai_*)| ~150-1700ms | ~150-2200ms | ~470-5500ms |
|
||||
| 空白图标 | ~10-100ms | ~10-150ms | ~30-100ms |
|
||||
|
||||
EasyOCR 在彩色背景大图上特别慢(fudai 1280×1280 跑 5 秒+),且关键内容图错字率极高。
|
||||
|
||||
### v4-mobile vs v5-mobile 精度差
|
||||
|
||||
- coupon.png:v4-mobile `一单回本 | 全场通用` 正确切分,v5-mobile `一单回本全场通用` 合并
|
||||
- banner_long.png:v4-mobile `上一个 | 下一个` 正确,v5-mobile `E— | 下-` 错误
|
||||
|
||||
v4-mobile 综合最优。
|
||||
|
||||
## 生效的优化
|
||||
|
||||
`operations/ocr_operations.py`:
|
||||
1. 切到 PaddleOCR v4-mobile 优先(之前 EasyOCR 优先)
|
||||
2. 加 LRU 结果缓存(256 条),重复图直接命中(业务里 cut_pic 短时间常重读相同区域)
|
||||
3. 抽出 `PADDLE_KWARGS` / `_build_paddle()` / `_build_easyocr()` 工厂消除重复
|
||||
|
||||
`douyin/core/underlying_operations.py`:
|
||||
1. `__init__` / `_ensure_ocr` 都对齐到 Paddle 优先
|
||||
2. `analyse_pic_word` 加缓存层(基于 blake2b 内容哈希 + change_color)
|
||||
3. 删掉小图自动放大+锐化+对比度增强(实测负优化)
|
||||
4. PaddleOCR 切到 `predict()` 新 API
|
||||
5. `analyse_pic_digits` 从 200 行精简到 30 行委托 + 数字过滤
|
||||
|
||||
业务接口完全向后兼容,调用方零改动。
|
||||
|
||||
## 测试用图
|
||||
|
||||
`assets/`:项目自带 9 张图
|
||||
裁切扩展:从 coupon.png/fudai.png 裁出多种难度的小区域(~22 张)测试模型对小裁切框的表现
|
||||
|
||||
## 维护提示
|
||||
|
||||
- 缓存大小:环境变量 `OCR_CACHE_MAX`(默认 256,设 0 禁用)
|
||||
- 缓存统计:`from operations.ocr_operations import cache_stats; print(cache_stats())`
|
||||
- 调试图保存:环境变量 `SAVE_OCR_DEBUG_IMAGES=1`
|
||||
- 跳过初始化(仅做点击不需要 OCR 的流程):环境变量 `SKIP_OCR_INIT=1`
|
||||
@@ -0,0 +1,272 @@
|
||||
# 全量安全审计报告(2026-06-28)
|
||||
|
||||
## 结论摘要
|
||||
|
||||
本次审计覆盖客户端授权、自动更新、差量更新、服务端卡密/API、后台发布、WebGUI、本地打包、CI/CD 和仓库敏感信息暴露面。总体判断:
|
||||
|
||||
- 授权与更新主链路已有基础可信链:服务端签名授权/更新 manifest,客户端只内置公钥并校验 manifest 签名与文件 SHA256 后再执行更新。
|
||||
- 当前最需要优先修的是服务端发布面与分发面:后台 token 权限过大、上传包一次性读入内存、下载包直出服务端。
|
||||
- WebGUI 默认本机监听、POST 有 CSRF、未授权时拦截运行类接口,基础边界合理;但安全响应头和 CSP 仍缺失。
|
||||
- 打包已包含 Cython/分发清单/新环境冒烟测试,但依赖安装仍是浮动版本,正式发布需要锁版本、记录 SBOM,并加入签名校验。
|
||||
|
||||
## 审计范围
|
||||
|
||||
- 服务端:`license_server/api.py`、`license_server/core.py`、`license_server/requirements.txt`、`license_server/docker-compose.yml`、`license_server/Dockerfile`
|
||||
- 客户端授权:`douyin/license/license_manager.py`、`douyin/license/public_key.py`
|
||||
- 自动更新:`douyin/updater/force_update.py`、`douyin/updater/bootstrap.py`、`tools/update_delta.py`
|
||||
- WebGUI:`gui/web_gui.py`、`gui/web_gui_pkg/*`、`webui/**/*`
|
||||
- 打包与 CI:`packaging/pyinstaller/build_windows.ps1`、`.github/workflows/windows-package-ci.yml`、`tools/ci/fresh_install_smoke.ps1`
|
||||
- 仓库敏感信息:源代码、文档、测试、配置模板,排除 `artifacts/`、`dist/`、`build/`、`output/`、`logs/` 等生成物。
|
||||
|
||||
## 高风险
|
||||
|
||||
### H1. 后台发布权限仍集中在单个 admin token
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:118-139` 中 `_admin_allowed()` 接受三种管理员凭据:Session Cookie、`Bearer <token>`、Basic Auth 密码。
|
||||
- `license_server/api.py:823-873` 的全量包和差量包发布接口只要通过管理员鉴权和 CSRF 即可发布更新。
|
||||
|
||||
影响:
|
||||
|
||||
- 一旦 `DYGJ_LICENSE_ADMIN_TOKEN` 泄露,攻击者可以发布全量安装包或差量包。
|
||||
- 现有 manifest 签名能防止“客户端绕过服务端伪造更新”,但不能防止“拿到后台权限后用合法服务端签名发布恶意更新”。
|
||||
|
||||
建议:
|
||||
|
||||
- 立即轮换历史 admin token,清理桌面、聊天临时目录、部署机器 shell history 中的明文 token。
|
||||
- 将“登录后台”和“发布更新”拆成两级权限:普通后台 token 不能发布更新,发布更新需要短时一次性 publish token 或 TOTP。
|
||||
- 发布接口加 IP 白名单、审计日志、版本回滚记录和人工确认。
|
||||
- 正式包必须做 Authenticode 签名,客户端启动安装器前校验发行者证书指纹。
|
||||
|
||||
### H2. 后台上传全量包/差量包会一次性读入内存
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:835` 对安装包执行 `content = await installer.read()`。
|
||||
- `license_server/api.py:862` 对差量包执行 `content = await delta_file.read()`。
|
||||
- `license_server/core.py:555-588` 的 `publish_update()` 接收完整 `bytes` 后写盘。
|
||||
- `license_server/core.py:590-624` 的 `publish_delta_update()` 同样接收完整 `bytes` 后写盘。
|
||||
|
||||
影响:
|
||||
|
||||
- 大文件或异常 multipart 请求会直接放大服务端内存压力。
|
||||
- 管理员误操作、token 泄露或代理层限流配置缺失时,容易造成授权服务器不可用。
|
||||
|
||||
建议:
|
||||
|
||||
- 上传接口加显式大小上限,例如全量包 500MB、差量包 200MB,超限立即拒绝。
|
||||
- 改成流式写入临时文件,并边写边计算 SHA256。
|
||||
- 反向代理加 `client_max_body_size` / request body size limit。
|
||||
- 发布前校验文件类型、扩展名、hash、版本号和可执行文件签名。
|
||||
|
||||
### H3. 更新包下载由授权服务直接 `FileResponse` 暴露
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:681-698` 使用 `FileResponse` 直接返回全量包或差量包。
|
||||
- `license_server/api.py:686-690` 已限制只能下载当前 manifest 允许的文件名,这是正向控制。
|
||||
|
||||
影响:
|
||||
|
||||
- 安装包/差量包通常较大,未加下载鉴权、限速或 CDN 时,服务端可被下载流量拖垮。
|
||||
- Starlette `FileResponse` 是真实攻击面。外部公告显示,历史上 Starlette `FileResponse` Range 处理出现过 CPU DoS(CVE-2025-62727,修复于 0.49.1),multipart/form-data 也出现过内存 DoS(CVE-2024-47874,修复于 0.40.0)。
|
||||
- 当前本机 Starlette 为 `1.3.1`,不落在上述受影响范围内;但生产环境如果不锁版本,仍存在依赖漂移和部署不可复现风险。
|
||||
|
||||
建议:
|
||||
|
||||
- 更新包放对象存储/CDN,授权服务只签发短期下载 URL。
|
||||
- 服务端保留 manifest 和授权 API,不承担大文件分发。
|
||||
- 若继续直出文件,固定 `starlette>=0.49.1`,并在依赖扫描中阻断已知 CVE。
|
||||
|
||||
## 中风险
|
||||
|
||||
### M1. 生产环境 Host header 仍依赖配置自觉
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:245-249`:未设置 `DYGJ_LICENSE_PUBLIC_BASE_URL` 时,manifest 下载 URL 从 `request.base_url` 推导。
|
||||
- `license_server/api.py:484-499`:创建 FastAPI app 时未添加 `TrustedHostMiddleware`。
|
||||
|
||||
影响:
|
||||
|
||||
- 如果生产代理透传恶意 Host,且未配置 `DYGJ_LICENSE_PUBLIC_BASE_URL`,生成的 manifest 下载链接可能被 Host header 污染。
|
||||
- 客户端有 HTTPS、同源、签名和 SHA256 校验,能降低恶意包执行风险;但错误下载源仍会造成更新失败或服务可用性问题。
|
||||
|
||||
建议:
|
||||
|
||||
- 生产环境强制要求 `DYGJ_LICENSE_PUBLIC_BASE_URL`,缺失即启动失败。
|
||||
- 加 `TrustedHostMiddleware`,只允许正式域名和本地健康检查域名。
|
||||
- 在部署文档中明确 Nginx/Cloudflare 的 Host 转发策略。
|
||||
|
||||
### M2. 管理后台 Cookie 默认未开启 Secure
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:495` 中 `DYGJ_LICENSE_SECURE_COOKIES` 默认值为 `False`。
|
||||
- `license_server/api.py:706-712` 和 `license_server/api.py:733-740` 根据该开关设置 CSRF Cookie 和后台 Session Cookie 的 `secure`。
|
||||
|
||||
影响:
|
||||
|
||||
- 生产 HTTPS 场景如果忘记设置环境变量,后台 Cookie 不带 Secure 标记。
|
||||
- `HttpOnly` 和 `SameSite=Lax` 已存在,风险主要来自生产配置遗漏。
|
||||
|
||||
建议:
|
||||
|
||||
- 生产模式默认 Secure=true,开发模式才允许关闭。
|
||||
- 启动时检测 `DYGJ_LICENSE_PUBLIC_BASE_URL` 为 `https://` 时强制 Secure Cookie。
|
||||
|
||||
### M3. 客户端执行安装器前缺少 Authenticode 校验
|
||||
|
||||
证据:
|
||||
|
||||
- `douyin/updater/force_update.py:143-158` 会校验 manifest 签名。
|
||||
- `douyin/updater/force_update.py:556-566` 校验安装包 SHA256 后直接构造命令并启动安装器。
|
||||
- 当前未看到对 Windows Authenticode 签名、发行者证书指纹或时间戳的校验。
|
||||
|
||||
影响:
|
||||
|
||||
- SHA256 只能证明“下载到的文件与签名 manifest 中声明一致”。
|
||||
- 如果服务端私钥或发布后台被攻破,攻击者仍可能发布一个“合法签名 manifest + 恶意 exe”。
|
||||
|
||||
建议:
|
||||
|
||||
- 正式发布包使用 Authenticode 签名。
|
||||
- 客户端在 `launch_installer()` 前验证 exe 签名主体和证书指纹。
|
||||
- CI/CD 记录签名证书指纹、安装包 SHA256 和 SBOM。
|
||||
|
||||
### M4. 差量更新应用脚本缺少二次解包后校验
|
||||
|
||||
证据:
|
||||
|
||||
- `douyin/updater/force_update.py:318-356` 下载后会校验差量包 manifest、文件路径和每个文件 SHA256。
|
||||
- `douyin/updater/force_update.py:434-463` 真正应用更新时,PowerShell `Expand-Archive` 后直接按 manifest 删除/复制文件。
|
||||
|
||||
影响:
|
||||
|
||||
- 主进程校验和应用更新是两个阶段,中间若本地文件被替换,应用脚本不会再次校验。
|
||||
- 对普通用户机器来说攻击门槛较高,但对本地恶意软件或被篡改的更新目录仍是风险点。
|
||||
|
||||
建议:
|
||||
|
||||
- 在 PowerShell 应用脚本里二次校验 delta zip SHA256,解包后再校验 manifest 中每个文件 SHA256。
|
||||
- 应用前将 `$root`、`$work`、目标路径做规范化并确认都在安装目录内。
|
||||
|
||||
### M5. WebGUI 缺少安全响应头和 CSP
|
||||
|
||||
证据:
|
||||
|
||||
- `gui/web_gui_pkg/static_handler.py:67-73` 只设置 `Content-Type`、`Content-Length`、`Cache-Control`、`ETag`。
|
||||
- `gui/web_gui_pkg/routes.py:161-169` GET API 仅允许本机访问并暴露 CSRF token。
|
||||
- `gui/web_gui_pkg/routes.py:389-399` POST API 有本机限制、CSRF 校验和授权门禁。
|
||||
|
||||
影响:
|
||||
|
||||
- WebGUI 默认 `127.0.0.1` 监听,且 POST 有 CSRF,基础边界是好的。
|
||||
- 但没有 `Content-Security-Policy`、`X-Content-Type-Options`、`Referrer-Policy` 等安全头;一旦未来某个日志/接口字段进入 DOM 时漏转义,XSS 的后果会扩大到本机控制面。
|
||||
|
||||
建议:
|
||||
|
||||
- 给 HTML/JS 响应加安全头:`X-Content-Type-Options: nosniff`、`Referrer-Policy: no-referrer`、最小 CSP。
|
||||
- 逐步减少内联脚本,或者使用 nonce/hash CSP。
|
||||
|
||||
## 低风险与观察项
|
||||
|
||||
### L1. 前端使用 `innerHTML` 较多,但核心动态数据大多已转义
|
||||
|
||||
证据:
|
||||
|
||||
- `webui/js/dom_utils.js:83-90` 提供 `escapeHtml()`。
|
||||
- `webui/js/runtime_actions.js:318-325`、`360-372`、`441-454` 对直播间、内容、原因等 API 字段使用 `escapeHtml()`。
|
||||
- `webui/js/dashboard_renderers.js:65-110` 对榜单 key、中奖内容、时间和值做了转义。
|
||||
- `license_server/api.py:667` 的兑换页把 `data.card_key` 拼入 `innerHTML`,卡密格式由服务端生成,当前风险较低。
|
||||
|
||||
建议:
|
||||
|
||||
- 新增 ESLint/简单 grep 门禁:所有拼接 API 数据的 `innerHTML` 必须经过 `escapeHtml()` 或改用 `textContent`。
|
||||
- 兑换页成功展示卡密可改为创建 `code` 节点并设置 `textContent`。
|
||||
|
||||
### L2. CI/CD 依赖安装未锁定 hash
|
||||
|
||||
证据:
|
||||
|
||||
- `.github/workflows/windows-package-ci.yml:42-44` 使用 `pip install -r requirements.txt` 和未固定的 `pyinstaller cython setuptools wheel`。
|
||||
- `packaging/pyinstaller/build_windows.ps1:31-38` 本地打包也会安装浮动版本依赖。
|
||||
- `license_server/requirements.txt:1-4` 使用 `>=` 范围。
|
||||
|
||||
影响:
|
||||
|
||||
- 复用缓存打包时结果可能随 PyPI 最新版本变化。
|
||||
- 安全修复会自动进来,但也可能引入供应链回归或打包不一致。
|
||||
|
||||
建议:
|
||||
|
||||
- 增加 `requirements-lock.txt` / `constraints.txt`,正式打包用锁定版本。
|
||||
- CI 增加 `pip-audit` 或 GitHub Dependabot,发现高危 CVE 直接失败。
|
||||
- 发布产物附带 SBOM、SHA256 和构建日志。
|
||||
|
||||
### L3. 仓库未发现真实私钥明文,但历史 token 文档仍提示需要清理本机副本
|
||||
|
||||
证据:
|
||||
|
||||
- 敏感信息扫描未发现真实生产私钥 PEM;测试私钥仅在 `tests/` 中使用。
|
||||
- `license_server/api.py:86-93` 生产私钥从环境变量或服务器文件读取。
|
||||
- 旧审计文档中记录过桌面存在多个 admin token 明文副本,需要按运维动作清理。
|
||||
|
||||
建议:
|
||||
|
||||
- 本机和服务器执行 token 文件清理,并确认 `.gitignore` 覆盖 `secrets/`、`*.pem`、`admin_token*.txt`。
|
||||
- 把生产 secret 全部放服务器 secret 管理或部署平台环境变量,不放桌面、微信临时目录和仓库。
|
||||
|
||||
## 已有保护点
|
||||
|
||||
- 授权文件签名:`license_server/core.py:872-889` 服务端签名授权,客户端使用公钥验签。
|
||||
- 机器码只保存 hash:`douyin/license/license_manager.py:66-76` 本机指纹 hash 化。
|
||||
- 在线复核:`douyin/license/license_manager.py:260-340` 使用服务器状态复核本地授权。
|
||||
- 更新 manifest 签名:`license_server/core.py:656-658` 服务端签名,`douyin/updater/force_update.py:143-158` 客户端验签。
|
||||
- 更新下载约束:`douyin/updater/force_update.py:212-237` 要求 HTTPS 和同源,除非配置允许跨源。
|
||||
- 更新文件完整性:`douyin/updater/force_update.py:547-563` 校验全量包 SHA256,`318-356` 校验差量包路径和文件 SHA256。
|
||||
- WebGUI 本机限制与 CSRF:`gui/web_gui_pkg/routes.py:57-62`、`389-399`。
|
||||
- 首次授权门禁:`gui/web_gui.py:912-918` 未授权时不直接进入运行态,`tools/ci/fresh_install_smoke.ps1:180-239` 已覆盖新环境授权门禁冒烟。
|
||||
- 打包分发清单:`packaging/pyinstaller/build_windows.ps1:55-63` 默认 Cython/PyArmor staging,`270-287` 执行 distribution manifest 检查。
|
||||
|
||||
## 依赖与外部公告核对
|
||||
|
||||
本机当前版本:
|
||||
|
||||
- `fastapi==0.137.2`
|
||||
- `starlette==1.3.1`
|
||||
- `uvicorn==0.49.0`
|
||||
- `python-multipart==0.0.32`
|
||||
- `cryptography==47.0.0`
|
||||
- `PyInstaller==6.12.0`
|
||||
|
||||
外部公告核对:
|
||||
|
||||
- Starlette multipart/form-data DoS:GHSA-f96h-pmfr-66vw / CVE-2024-47874,Starlette `0.40.0` 修复。
|
||||
- Starlette FileResponse Range DoS:GHSA-7f5h-v6xp-fcq8 / CVE-2025-62727,Starlette `0.49.1` 修复。
|
||||
- 当前本机 Starlette `1.3.1` 高于上述修复版本;生产仍建议锁版本并加入自动漏洞扫描。
|
||||
|
||||
## 修复优先级
|
||||
|
||||
1. 轮换 admin token,清理本机和服务器明文 token,后台发布增加二次授权。
|
||||
2. 上传接口改流式写入并加大小限制,反向代理同步限流。
|
||||
3. 更新包改 CDN/对象存储分发,授权服务只发短期 URL。
|
||||
4. 正式包 Authenticode 签名,客户端校验证书指纹后再启动安装器。
|
||||
5. 生产强制 `DYGJ_LICENSE_PUBLIC_BASE_URL`、`TrustedHostMiddleware`、Secure Cookie。
|
||||
6. WebGUI 加安全响应头和 CSP,继续收敛 `innerHTML`。
|
||||
7. CI/CD 增加锁版本、SBOM、pip-audit/Dependabot。
|
||||
|
||||
## 本次验证
|
||||
|
||||
- `git status --short --branch`:工作区除用户本地 `config/config.json` 外无其他未提交改动。
|
||||
- 静态证据扫描:授权、服务端 API、更新、WebGUI、打包、CI 均完成。
|
||||
- 敏感信息扫描:未发现生产私钥 PEM;扫描到的 `secret` 主要位于测试用例和历史审计文档。
|
||||
- 依赖版本核对:本机 Starlette/FastAPI 版本高于已核对 Starlette DoS 修复版本。
|
||||
|
||||
## 参考资料
|
||||
|
||||
- GitHub Advisory:Starlette multipart/form-data DoS,GHSA-f96h-pmfr-66vw,https://github.com/advisories/GHSA-f96h-pmfr-66vw
|
||||
- GitHub Advisory:Starlette FileResponse Range DoS,GHSA-7f5h-v6xp-fcq8,https://github.com/advisories/GHSA-7f5h-v6xp-fcq8
|
||||
- Starlette Release Notes,https://www.starlette.io/release-notes/
|
||||
- Starlette Responses 文档:`FileResponse` 支持 Range 请求,https://www.starlette.io/responses/
|
||||
@@ -0,0 +1,228 @@
|
||||
# 全量安全审查报告
|
||||
|
||||
日期:2026-06-23
|
||||
|
||||
审查方式:结合 `security-best-practices`、`security-threat-model`、`code-review-and-quality` 思路,对客户端、本地 Web GUI、卡密服务端、自动更新、打包分发和 Git/配置暴露面做静态审查与最小运行验证。
|
||||
|
||||
## 结论
|
||||
|
||||
当前版本已经具备一批关键安全地基:客户端默认走 `https://dy.absfan.cn`,自动更新 manifest 有签名和安装包 sha256 校验;卡密服务使用服务端时间和 SQLite 参数化查询;后台登录使用 HttpOnly 会话 cookie 与 CSRF;本地 Web GUI 默认只监听 `127.0.0.1`;当前 tracked 文件未发现服务器真实 IP、私钥或管理员 token 明文。
|
||||
|
||||
但仍有 5 个需要优先处理的风险:
|
||||
|
||||
- P0:Git 历史提交里仍可检索到服务器源站 IP 字面量,若仓库外发或公开,历史会继续泄露源站。
|
||||
- P1:服务端限流信任客户端传入的 `x-forwarded-for`,可能被绕过并造成 rate-limit bucket 增长。
|
||||
- P1:后台登录未接入限流/锁定;同时仍保留 Bearer/Basic token 后门入口,公网后台暴露时爆破面偏大。
|
||||
- P1:后台发布更新时一次性 `await installer.read()` 读取上传文件,缺少上传大小限制,可能导致内存或磁盘 DoS。
|
||||
- P1:本地 Web GUI 虽默认本机监听,但一旦配置成 `0.0.0.0`,WiFi ADB、启动/停止、日志读取等接口没有二次认证。
|
||||
|
||||
## 范围与资产
|
||||
|
||||
核心资产:
|
||||
|
||||
- 卡密数据库、激活记录、审计记录。
|
||||
- 服务端私钥、管理员 token、更新安装包、更新 manifest。
|
||||
- 客户端内置公钥、授权文件、本地配置。
|
||||
- 本地 Web GUI 对 ADB、设备、日志和运行进程的控制能力。
|
||||
|
||||
主要入口:
|
||||
|
||||
- 公网:`/api/v1/activate`、`/api/v1/verify_license`、`/api/v1/update/manifest`、`/api/v1/update/download/{filename}`、`/admin/*`。
|
||||
- 本机:`/api/wifi/*`、`/api/config`、日志/运行控制相关 Web GUI 接口。
|
||||
- 分发:PyInstaller/安装包、自动更新下载的 EXE。
|
||||
|
||||
## 已有安全控制
|
||||
|
||||
- 客户端默认更新地址是 `https://dy.absfan.cn/api/v1/update/manifest`。
|
||||
- 自动更新默认要求 manifest 签名,安装包 URL 默认同源,安装包下载后做 sha256 校验。
|
||||
- 服务端 license 和 update manifest 使用 Ed25519 签名。
|
||||
- SQLite 操作使用参数化 SQL,未看到直接字符串拼接 SQL 的主路径。
|
||||
- 后台登录成功后写入 HttpOnly、SameSite=Lax 的 session cookie,后台写操作有 CSRF token。
|
||||
- 卡密校验以服务器端激活记录和服务端时间为准,客户端本地时间不能直接绕过在线校验。
|
||||
- 本地 Web GUI 默认监听 `127.0.0.1:8000`,不是默认公网暴露。
|
||||
- 当前 tracked 文件扫描未发现真实源站 IP、服务器密码、管理员 token、私钥 PEM。
|
||||
|
||||
## 发现与建议
|
||||
|
||||
### P0-1 Git 历史仍包含源站 IP
|
||||
|
||||
证据:
|
||||
|
||||
- 当前 tracked 文件未命中真实源站 IP、管理员 token 或私钥。
|
||||
- `git log --all -S` 仍能在历史提交中找到源站 IP 字面量,涉及提交包括 `25876bd`、`0efdc83`、`5c7d341`、`cb74a23` 等。
|
||||
|
||||
影响:
|
||||
|
||||
- 即使当前代码改成域名,仓库被发给别人或推到公开仓库时,历史仍会暴露源站。
|
||||
- 攻击者可绕过域名层防护,直接打源站端口或做扫描。
|
||||
|
||||
建议:
|
||||
|
||||
- 若仓库已经外发或公开:立即做 Git 历史改写,清除源站 IP、旧 server 默认值和任何敏感片段,然后 force push。
|
||||
- 同步轮换公网源站或至少限制源站只接受可信代理/防火墙来源。
|
||||
- 报告、文档、提交信息里后续只写域名或 `[REDACTED_ORIGIN]`。
|
||||
|
||||
### P1-1 限流信任 `x-forwarded-for`
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:182-185` 使用请求头 `x-forwarded-for` 第一段作为限流 key。
|
||||
- `_rate_limited` 对 activate、verify_license 生效,但 bucket key 由该 header 决定。
|
||||
|
||||
影响:
|
||||
|
||||
- 如果反代/CDN 未强制覆盖该 header,客户端可以伪造不同 IP 绕过限流。
|
||||
- 大量伪造 header 会让 `rate_limit_buckets` 增长,形成内存型 DoS。
|
||||
|
||||
建议:
|
||||
|
||||
- 只在请求来自可信代理 IP 时读取 `x-forwarded-for`,否则使用 `request.client.host`。
|
||||
- 增加 bucket 总量上限和周期性清理。
|
||||
- 部署层确保反代覆盖而不是透传用户自带的 XFF。
|
||||
|
||||
### P1-2 后台登录缺少限流/锁定,且保留多种 token 入口
|
||||
|
||||
证据:
|
||||
|
||||
- `/admin/login` 在 `license_server/api.py:492-497` 直接比较 token,失败返回 403,未调用 `_rate_limited`。
|
||||
- `_admin_allowed` 在 `license_server/api.py:88-109` 同时接受 session cookie、Bearer token、Basic auth。
|
||||
|
||||
影响:
|
||||
|
||||
- 公网后台可被持续爆破或撞库,尤其管理员 token 如果不够长会变成高风险。
|
||||
- Bearer/Basic 让 token 更容易出现在代理日志、浏览器插件、命令历史或误贴日志中。
|
||||
|
||||
建议:
|
||||
|
||||
- 给 `/admin/login` 加 IP + 用户维度限流、指数退避和失败审计。
|
||||
- 默认禁用 Basic auth;Bearer token 仅保留给受控 CLI,或通过环境变量显式开启。
|
||||
- 管理员 token 要求至少 32 字节随机值,并增加启动时弱 token 检查。
|
||||
|
||||
### P1-3 更新发布上传无大小限制
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/api.py:586-606` 中 `UploadFile` 直接 `await installer.read()`,随后写入发布目录。
|
||||
- 未见文件大小、后缀白名单、Content-Length 上限或流式落盘控制。
|
||||
|
||||
影响:
|
||||
|
||||
- 管理员误操作、token 泄露或 CSRF 以外的后台入口被利用时,可以上传超大文件导致内存、磁盘或进程不可用。
|
||||
- 更新发布链路是高权限供应链入口,风险高于普通文件上传。
|
||||
|
||||
建议:
|
||||
|
||||
- 增加最大上传大小,例如 300 MB 或按实际安装包体积上限配置。
|
||||
- 使用流式写临时文件,边读边计算 sha256,超限立即中断并删除临时文件。
|
||||
- 限制后缀为 `.exe`,发布前校验 Windows Authenticode 签名或至少校验内部版本号。
|
||||
|
||||
### P1-4 本地 Web GUI 非 localhost 暴露时缺少认证
|
||||
|
||||
证据:
|
||||
|
||||
- 默认监听 `127.0.0.1`:`douyin/core/path_config.py:31`。
|
||||
- 环境变量或配置可覆盖 host:`douyin/core/path_config.py:96-103`。
|
||||
- Web GUI 暴露 WiFi ADB 启用、连接、断开、扫描和自动重连:`gui/web_gui_pkg/routes.py:717-824`、`863-940`。
|
||||
|
||||
影响:
|
||||
|
||||
- 默认本机使用问题不大。
|
||||
- 如果用户为了局域网访问改成 `0.0.0.0`,同网段其他人可未授权控制 ADB 连接、扫描局域网、读取部分状态或影响挂机运行。
|
||||
|
||||
建议:
|
||||
|
||||
- 当 host 不是 localhost 时强制启用 Web GUI token。
|
||||
- 对 `/api/wifi/*`、运行控制、配置写入、日志读取加认证。
|
||||
- UI 上显示“当前监听地址”和“局域网暴露风险”。
|
||||
|
||||
### P2-1 HTTPS 开关默认逻辑不够稳
|
||||
|
||||
证据:
|
||||
|
||||
- 默认 manifest URL 是 HTTPS:`douyin/updater/force_update.py:31`。
|
||||
- frozen 默认 manifest 下 `require_https` 默认值为 `not using_default_manifest`,即默认 false:`douyin/updater/force_update.py:192-195`。
|
||||
- 同时默认签名是开启的。
|
||||
|
||||
影响:
|
||||
|
||||
- 当前域名是 HTTPS,实际链路可用。
|
||||
- 但“默认 manifest 不强制 HTTPS”的逻辑容易在以后改默认地址时退化,签名不能完全替代传输层保护。
|
||||
|
||||
建议:
|
||||
|
||||
- `require_https` 默认始终为 true,除非显式开发环境关闭。
|
||||
- 对自动更新增加环境分层:dev 可放宽,release 必须 HTTPS + signed manifest + sha256。
|
||||
|
||||
### P2-2 license 和 update manifest 共用签名密钥
|
||||
|
||||
证据:
|
||||
|
||||
- `license_server/core.py:444-446` 提供通用 `sign_payload`。
|
||||
- license 文档签名在 `license_server/core.py:626-644`,update manifest 也由同一服务私钥签名。
|
||||
|
||||
影响:
|
||||
|
||||
- 单一私钥泄露会同时影响授权文件与更新供应链。
|
||||
- 后续密钥轮换时两个系统耦合,恢复复杂。
|
||||
|
||||
建议:
|
||||
|
||||
- 分离 license signing key 与 update signing key。
|
||||
- 客户端分别内置 license public key 和 update public key,支持 key id 与滚动轮换。
|
||||
|
||||
### P2-3 依赖版本没有锁定
|
||||
|
||||
证据:
|
||||
|
||||
- `requirements.txt` 多数依赖使用 `>=`,例如 `Pillow>=9.0.0`、`opencv-python>=4.5.0`、`cryptography>=41.0.0`。
|
||||
|
||||
影响:
|
||||
|
||||
- 构建复现性弱,新版本依赖可能引入兼容问题或供应链风险。
|
||||
|
||||
建议:
|
||||
|
||||
- 为 release 打包生成锁定文件,例如 `requirements-lock.txt` 或 `pip-tools` 输出。
|
||||
- CI/打包只使用锁定依赖,开发环境可继续宽松。
|
||||
|
||||
### P2-4 shell 调用需要继续收敛
|
||||
|
||||
证据:
|
||||
|
||||
- 聚焦扫描显示存在若干 `subprocess.run`/`Popen`,多数 ADB 调用为列表参数。
|
||||
- 仍存在少量 `shell=True` 或 `/bin/sh -c` 用法,主要用于平台命令探测或 ADB 降级路径。
|
||||
|
||||
影响:
|
||||
|
||||
- 如果参数未来从 UI 或配置直通,可能扩大命令注入风险。
|
||||
|
||||
建议:
|
||||
|
||||
- 对所有 `shell=True` 建立 allowlist,逐个替换成 list 参数。
|
||||
- 对确实需要 shell 的命令增加注释和单元测试覆盖。
|
||||
|
||||
## 验证
|
||||
|
||||
已执行:
|
||||
|
||||
- `python -m pytest tests/test_license_server_api.py tests/test_license_server_core.py tests/test_license_manager.py tests/test_auto_update.py tests/test_web_gui_routes_logic.py -q`
|
||||
- 结果:PASS。
|
||||
- 日志:`artifacts/security_audit_tests.log`。
|
||||
|
||||
公网最小验证:
|
||||
|
||||
- `https://dy.absfan.cn/api/v1/health` 返回 `{"ok": true, "service": "douyin-license-server"}`。
|
||||
- `https://dy.absfan.cn/api/v1/update/manifest` 返回 `enabled=false`、`version=0.0.0`,并包含签名字段。
|
||||
|
||||
当前 secret 扫描:
|
||||
|
||||
- tracked 文件未发现真实源站 IP、私钥 PEM、管理员 token、服务器密码明文。
|
||||
- Git 历史仍包含源站 IP,需要单独处理。
|
||||
|
||||
## 建议修复顺序
|
||||
|
||||
1. 先修服务端 P1:可信代理 IP/XFF、后台登录限流、上传大小限制、Secure cookie。
|
||||
2. 再修本地 P1:Web GUI 非 localhost 强制 token,敏感接口鉴权。
|
||||
3. 然后做 P0 历史清理:确认仓库是否已外发/公开,必要时 history rewrite + force push + 源站访问限制。
|
||||
4. 最后做供应链增强:分离签名密钥、release 依赖锁定、自动更新 HTTPS 强制。
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
# 兑换链接安全复核 2026-06-24
|
||||
|
||||
## 结论
|
||||
|
||||
本次复核对象是闲鱼自动发货兑换链路:
|
||||
|
||||
- `POST /api/v1/redeem/external/create`
|
||||
- `GET /redeem`
|
||||
- `GET /redeem/{token}` 兼容旧链接
|
||||
- `POST /api/v1/redeem/claim`
|
||||
|
||||
线上域名:`https://dy.absfan.cn`。
|
||||
|
||||
## 已验证
|
||||
|
||||
- 外部创建接口必须使用 `Authorization: Bearer <DYGJ_LICENSE_EXTERNAL_API_TOKEN>`。
|
||||
- 外部创建接口只返回 `claim_url`,不返回真实 `DG-` 卡密。
|
||||
- 新 `claim_url` 使用 `/redeem#token`,token 位于 URL fragment,不进入服务器请求路径和 uvicorn 访问日志。
|
||||
- 兑换接口只允许同一 token 成功兑换一次;重复兑换返回 `409 already_redeemed`。
|
||||
- 并发兑换已用 SQLite `BEGIN IMMEDIATE` 加写锁,测试确认只会生成一张卡。
|
||||
- `/docs` 和 `/openapi.json` 线上返回 `404`。
|
||||
- 未授权创建返回 `403`,坏参数返回 `400`。
|
||||
- 兑换后的卡密可正常走 `/api/v1/activate`,授权文件可继续走 `/api/v1/verify_license`。
|
||||
|
||||
## 修复项
|
||||
|
||||
- 修复同一兑换 token 并发兑换可能生成多张卡的问题。
|
||||
- 为公开兑换接口增加限流:`REDEEM_CLAIM_RATE_LIMIT_MAX_REQUESTS`。
|
||||
- 为外部创建接口鉴权失败增加独立限流:`EXTERNAL_REDEEM_AUTH_RATE_LIMIT_MAX_REQUESTS`。
|
||||
- 新生成兑换链接改为 `/redeem#token`,降低访问日志泄露 token 的概率。
|
||||
|
||||
## 验证证据
|
||||
|
||||
- 本地回归:`artifacts/redeem_security_full_tests_20260624.log`,结果 `PASS`。
|
||||
- 本地语法:`python -m py_compile license_server/core.py license_server/api.py douyin/license/license_manager.py`,结果 `PASS`。
|
||||
- 线上黑盒:`health=200`、`docs=404`、`openapi=404`、`no_auth=403`、`create=200`、`claim_first=200`、`claim_second=409`、`activate=200`。
|
||||
- 线上日志确认:`GET /redeem HTTP/1.1`,未记录 `/redeem/{token}`。
|
||||
|
||||
## 剩余建议
|
||||
|
||||
- `DYGJ_LICENSE_EXTERNAL_API_TOKEN` 应定期轮换,且只配置在自动发货服务器侧。
|
||||
- 如果后续员工/多个渠道并行发货,建议改成每个渠道独立 token,并在数据库记录 `platform`、`external_order_id`、请求 IP 和 staff/source 标识。
|
||||
- 如果订单量增大,建议在 1Panel/OpenResty 层再加 IP 级限流。
|
||||
@@ -0,0 +1,165 @@
|
||||
# 安全审计报告:服务器与反逆向
|
||||
|
||||
日期:2026-06-26
|
||||
范围:`license_server/` 授权与更新服务、在线差量/全量更新链路、V3.3.4 发布包反逆向与分发内容。
|
||||
|
||||
## 总体结论
|
||||
|
||||
当前授权服务不是裸奔:管理员后台有登录限流、CSRF、会话 Cookie;客户端更新默认启用 HTTPS、manifest 签名和 SHA256 校验;V3.3.4 发布包通过了分发清单检查,核心逻辑已有 Cython `.pyd` 编译层。
|
||||
|
||||
但最值得优先处理的风险有两个:管理员 token 暴露后可直接发布任意 EXE 更新;更新安装包上传/下载缺少大文件资源控制。反逆向方面,现在属于“提高脚本级拆包成本”,还不是强对抗级保护。
|
||||
|
||||
## P1:必须优先处理
|
||||
|
||||
### 1. 管理员 token 本地副本过多,拿到 token 就等于拿到发布权
|
||||
|
||||
证据:
|
||||
- 本机桌面存在多个 token 文件:`C:\Users\12742\Desktop\douyin_admin_token.txt`、`C:\Users\12742\Desktop\douyin_admin_token_open.txt`、`C:\Users\12742\Desktop\douyin_admin_token_可打开.txt`。
|
||||
- 管理员鉴权使用单一 token:`license_server/api.py:101`、`license_server/api.py:118-135`。
|
||||
- 发布更新接口在管理员鉴权后直接接受 EXE 并写入 manifest:`license_server/api.py:795-818`、`license_server/core.py:532-562`。
|
||||
|
||||
影响:
|
||||
- 本机恶意软件、聊天软件临时目录泄露、误传文件,都可能让攻击者发布恶意更新。
|
||||
- 因客户端会信任服务端签名的 manifest,服务器发布权比普通卡密权限高很多。
|
||||
|
||||
建议:
|
||||
- 立刻轮换 `DYGJ_LICENSE_ADMIN_TOKEN`,删除桌面和聊天临时目录里的 token 明文副本。
|
||||
- 管理后台改为“短期会话 + 二次确认发布 + 可选 TOTP/一次性发布口令”。
|
||||
- 管理发布接口限制来源 IP,至少只允许固定办公 IP 或 VPN。
|
||||
- 发布动作记录操作者、IP、文件 SHA256、版本号,并保留不可覆盖审计日志。
|
||||
|
||||
### 2. 更新包上传一次性读入内存,缺少大小上限和流式写入
|
||||
|
||||
证据:
|
||||
- `license_server/api.py:809` 使用 `await installer.read()` 一次性读完整上传文件。
|
||||
- `license_server/core.py:537` 接收 `bytes`,`license_server/core.py:550` 直接 `write_bytes(content)`。
|
||||
- 当前正式安装包约 214 MB,已经是大对象。
|
||||
|
||||
影响:
|
||||
- 管理 token 被盗或后台被滥用时,可以上传超大文件造成内存/磁盘 DoS。
|
||||
- 即使没有被盗,误传错误文件也会把服务打满。
|
||||
|
||||
建议:
|
||||
- 服务端增加最大上传大小,例如 300 MB 或 500 MB,超限立即拒绝。
|
||||
- 改成分块读取、边写临时文件、边计算 SHA256,完成后再原子重命名。
|
||||
- Nginx/Caddy/Cloudflare 层设置请求体大小限制和上传超时。
|
||||
|
||||
### 3. 更新下载接口直出大文件,缺少下载限速/CDN/Range 滥用防护
|
||||
|
||||
证据:
|
||||
- `/api/v1/update/download/{filename}` 直接 `FileResponse` 返回安装包:`license_server/api.py:658-672`。
|
||||
- 已验证下载端点支持 Range,正式包体积约 214 MB。
|
||||
|
||||
影响:
|
||||
- 任意公网客户端都能拉取大文件,容易被刷带宽。
|
||||
- Range/并发下载可以把授权服务和更新服务一起拖慢。
|
||||
|
||||
建议:
|
||||
- 安装包放对象存储或 CDN,授权服务只签 manifest,不直接扛大文件流量。
|
||||
- 给下载接口加 IP 限流、并发限制、带宽限制。
|
||||
- 如果继续用 ASGI 直出文件,生产依赖必须锁定并定期更新 Starlette/FastAPI;Starlette 历史上出现过 `FileResponse` Range 资源耗尽类公告。
|
||||
|
||||
## P2:建议加固
|
||||
|
||||
### 4. 生产环境缺少强制 Host 白名单
|
||||
|
||||
证据:
|
||||
- `_public_base_url()` 未配置 `DYGJ_LICENSE_PUBLIC_BASE_URL` 时会回退到 `request.base_url`:`license_server/api.py:245-249`。
|
||||
- 当前代码没有看到 `TrustedHostMiddleware` 或等价 Host 白名单。
|
||||
|
||||
影响:
|
||||
- 如果生产环境漏配 `DYGJ_LICENSE_PUBLIC_BASE_URL`,错误 Host 头可能影响兑换链接或更新 URL 生成。
|
||||
|
||||
建议:
|
||||
- 生产强制配置 `DYGJ_LICENSE_PUBLIC_BASE_URL=https://dy.absfan.cn`。
|
||||
- 增加 `TrustedHostMiddleware`,只允许 `dy.absfan.cn` 和必要内网域名。
|
||||
|
||||
### 5. Cookie secure 默认关闭,生产 HTTPS 容易误配置
|
||||
|
||||
证据:
|
||||
- `DYGJ_LICENSE_SECURE_COOKIES` 默认值为 `False`:`license_server/api.py:472`。
|
||||
- CSRF 和后台 session cookie 都依赖该状态设置 `secure`:`license_server/api.py:680-686`、`license_server/api.py:707-711`。
|
||||
|
||||
影响:
|
||||
- HTTPS 生产环境如果忘记设置环境变量,后台 Cookie 不会带 Secure 标记。
|
||||
|
||||
建议:
|
||||
- 生产默认改为 Secure,只有本地开发显式关闭。
|
||||
- README 和部署脚本强制检查该环境变量。
|
||||
|
||||
### 6. 管理员 Basic/Bearer 兼容口仍保留,建议收窄
|
||||
|
||||
证据:
|
||||
- `_admin_allowed()` 同时接受 session、Bearer 和 Basic:`license_server/api.py:122-135`。
|
||||
|
||||
影响:
|
||||
- Header token 适合脚本,但也更容易进入命令历史、代理日志或调试日志。
|
||||
- 增加后台鉴权路径,后续维护更难保证所有入口策略一致。
|
||||
|
||||
建议:
|
||||
- 默认只保留网页登录 session;CLI 发布单独走短期一次性 token。
|
||||
- 如果必须保留 Bearer,限制到内网/VPN,并要求 CSRF 或发布专用 nonce。
|
||||
|
||||
### 7. 更新执行链缺少安装包 Authenticode 发布者校验
|
||||
|
||||
证据:
|
||||
- 客户端更新流程会验证 manifest 签名和 SHA256:`douyin/updater/force_update.py:347-378`。
|
||||
- 通过后直接启动下载的 installer:`douyin/updater/force_update.py:380-381`。
|
||||
|
||||
影响:
|
||||
- 当前信任根主要是服务端 manifest 私钥和后台发布权。
|
||||
- 一旦服务器私钥或发布权泄露,客户端无法再用 Windows 发布者签名做第二道拦截。
|
||||
|
||||
建议:
|
||||
- 给正式安装包做 Authenticode 代码签名。
|
||||
- 客户端启动安装器前校验签名发布者或证书指纹。
|
||||
|
||||
### 8. 服务器依赖没有锁定精确版本
|
||||
|
||||
证据:
|
||||
- `license_server/requirements.txt` 使用 `fastapi>=0.124.0`、`uvicorn[standard]>=0.38.0`、`cryptography>=41.0.0`。
|
||||
- 当前本机运行版本:FastAPI `0.137.2`,Starlette `1.3.1`。
|
||||
|
||||
影响:
|
||||
- 生产重装时可能拿到未经本项目验证的新版本,也可能因为旧环境没有升级而继续运行旧版本。
|
||||
|
||||
建议:
|
||||
- 为服务器单独生成锁定文件,例如 `requirements-server.lock.txt`。
|
||||
- 发布服务端时记录 `pip freeze` 和镜像 digest。
|
||||
|
||||
## P3:反逆向现状与后续增强
|
||||
|
||||
### 已有保护
|
||||
|
||||
- 构建脚本默认走 Cython staging,除非显式传 `-NoCythonForDevOnly` 或 `-NoObfuscateForDevOnly`:`packaging/pyinstaller/build_windows.ps1:4-6`、`packaging/pyinstaller/build_windows.ps1:54-61`。
|
||||
- 默认编译核心包:`douyin/fudai`、`douyin/reservation`、`douyin/detection`、`douyin/stage`:`tools/cython_staging.py:16-21`。
|
||||
- 发布包分发清单阻止项目源码、日志、调试图和多余文件混入:`tools/distribution_manifest.py:120-155`。
|
||||
- V3.3.4 发布目录检查通过:`logs/security_dist_manifest_check_2026-06-26.log`。
|
||||
- V3.3.4 发布目录未发现项目核心 `.py` 源码混入;核心路径下 `.pyd` 数量为 93。
|
||||
- 发布目录未发现私钥、管理员 token、项目私密 pem;只看到第三方 CA bundle:`_internal/certifi/cacert.pem`。
|
||||
|
||||
### 仍然薄弱
|
||||
|
||||
- GUI 与 WebUI 代码按当前策略仍更多是普通 PyInstaller/PYZ 层,不能按强混淆理解。
|
||||
- Python/Cython `.pyd` 可以被逆向分析,只是成本高于纯 `.py`。
|
||||
- 客户端公钥是公开的,这是正确设计;但协议、接口、版本更新逻辑仍能被静态分析。
|
||||
- 没有运行时完整性校验、调试器检测、虚拟机/注入检测或关键路径反篡改。
|
||||
|
||||
建议:
|
||||
- 短期:正式包固定使用 Cython,不允许 `-NoCythonForDevOnly`;发布前自动跑 `distribution_manifest`。
|
||||
- 中期:把授权校验、更新校验、核心策略判断也纳入 Cython 或商业混淆。
|
||||
- 中期:增加运行时自校验,例如关键 `.pyd`/EXE 哈希校验和异常上报。
|
||||
- 长期:核心逻辑尽量服务端化,客户端只保留必要执行逻辑;反逆向不能替代服务端风控。
|
||||
|
||||
## 已验证通过项
|
||||
|
||||
- 管理员登录有限流:`license_server/api.py:693-700`。
|
||||
- 后台修改类表单有 CSRF 校验:`license_server/api.py:805-807`,创建/解绑/禁用也有同类校验。
|
||||
- 授权激活/验证/兑换接口有限流:`license_server/api.py:486-512`、`license_server/api.py:561-588`。
|
||||
- 服务端私钥没有内置到客户端;客户端只包含公钥:`douyin/license/public_key.py:1-9`。
|
||||
- 发布包分发清单 PASS:`logs/security_dist_manifest_check_2026-06-26.log`。
|
||||
|
||||
## 参考来源
|
||||
|
||||
- GitHub Security Advisory:Starlette `FileResponse` Range 资源耗尽类历史公告,`GHSA-f96h-pmfr-66vw` / `CVE-2024-47874`。
|
||||
- Starlette 官方文档:`TrustedHostMiddleware` 用于限制 Host header。
|
||||
@@ -0,0 +1,462 @@
|
||||
# 拆分 gui/gui_app.py 实施计划
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** 把 `gui/gui_app.py`(5476 行)中内聚的 `main()` 闭包逐段抽到 `gui/components/*` 子模块,主文件持续瘦身,GUI 行为不变。
|
||||
|
||||
**Architecture:** 每个候选段抽到独立模块,改造为顶层函数,通过显式参数(回调 + 必要的 widgets/Vars/路径)接收依赖。每抽完一段独立 commit + push。
|
||||
|
||||
**Tech Stack:** Python 3.10+, tkinter / ttkbootstrap, pytest
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-05-30-split-gui-app-design.md`
|
||||
|
||||
---
|
||||
|
||||
## 抽取顺序
|
||||
|
||||
按 spec 优先级:P1 → P2 → P3 → P4 → P5 → P6。每个任务独立可停。
|
||||
P1 包括两个紧耦合段(`open_wifi_adb_dialog` 845 行 + `open_scan_dialog` 200 行)。
|
||||
|
||||
---
|
||||
|
||||
## Task 1: 抽 `open_scan_dialog` 到 `components/wifi_adb_scan_dialog.py`
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/components/wifi_adb_scan_dialog.py`
|
||||
- Modify: `gui/gui_app.py:539-742` (删除原闭包) + 改 `gui/gui_app.py:1088-1093`(`open_scan_dialog` 调用点)
|
||||
|
||||
**理由先抽这个:** `open_scan_dialog` 已经是显式参数形式,不依赖 `main()` 任何捕获变量,迁移最简单。先做它能熟悉抽取流程,降 ~200 行。
|
||||
|
||||
- [ ] **Step 1: 读完整段确认依赖**
|
||||
|
||||
```bash
|
||||
# 看 539-742 完整段
|
||||
```
|
||||
确认 `open_scan_dialog` 仅依赖参数 `parent, adb_exe_local, ip_var, on_line_local, refresh_cb` 和模块级 import(`tk`, `ttk`, `discover_adb_devices`, `get_local_subnet`, `pick_best_match`, `verify_adb_target` 等)。
|
||||
|
||||
- [ ] **Step 2: 创建新模块**
|
||||
|
||||
写 `gui/components/wifi_adb_scan_dialog.py`,把 539-742 的整段函数原样复制为 `open_scan_dialog`,加 `from __future__ import annotations` 与所有需要的 import。
|
||||
|
||||
- [ ] **Step 3: 修改 `gui_app.py`,替换调用点**
|
||||
|
||||
在 `gui_app.py` 顶部 import 新模块:
|
||||
```python
|
||||
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
|
||||
```
|
||||
删除 539-742 的原 `def open_scan_dialog(...)` 定义。
|
||||
|
||||
- [ ] **Step 4: 验证语法**
|
||||
|
||||
```bash
|
||||
python -m py_compile gui/gui_app.py gui/components/wifi_adb_scan_dialog.py
|
||||
```
|
||||
Expected: 无输出(成功)
|
||||
|
||||
- [ ] **Step 5: 跑测试**
|
||||
|
||||
```bash
|
||||
pytest -x
|
||||
```
|
||||
Expected: 全部 PASS
|
||||
|
||||
- [ ] **Step 6: 行数核对 + commit**
|
||||
|
||||
```bash
|
||||
wc -l gui/gui_app.py
|
||||
git status --short
|
||||
git add gui/gui_app.py gui/components/wifi_adb_scan_dialog.py
|
||||
git commit -m "refactor(gui): 抽 open_scan_dialog 到 components/wifi_adb_scan_dialog (5476 → <new>)"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: 抽 `open_wifi_adb_dialog` 到 `components/wifi_adb_dialog.py`
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/components/wifi_adb_dialog.py`
|
||||
- Modify: `gui/gui_app.py:743-1111` (删除原闭包,改 `wifi_adb_btn` 的 command)
|
||||
|
||||
**依赖分析(已完成):**
|
||||
|
||||
模块级(已 import,直接用):
|
||||
- `list_adb_devices`, `enable_wifi_adb`, `connect_wifi_adb`, `disconnect_wifi_adb`, `auto_connect_wifi_adb`, `get_device_ip`, `get_connected_wifi_devices`(from `gui.gui_core`)
|
||||
- `set_last_wifi_target`, `get_last_wifi_target`, `clear_last_wifi_target`(from `gui.gui_core_pkg`)
|
||||
- `verify_adb_target`, `query_device_model`(from `gui.gui_core_pkg.wifi_adb_scan`)
|
||||
|
||||
`main()` 局部(必须传):
|
||||
- `root: tk.Misc`(父窗口,用于 `tk.Toplevel(root)`)
|
||||
- `adb_exe: str`
|
||||
- `on_line: Callable[[str], None]`
|
||||
- `refresh_devices: Callable[[], None]`
|
||||
- `open_scan_dialog`(Task 1 完成后已为顶层函数,直接 import)
|
||||
|
||||
自递归(三处 `dialog.destroy(); open_wifi_adb_dialog()`):
|
||||
改造为传入自己的引用 —— 用一个内部函数 `_reopen()` 闭包捕获参数,或参数化 `parent`/`adb_exe` 后直接再调用顶层函数。**采用方案 B:把 `open_wifi_adb_dialog` 改成顶层函数,签名带所有依赖,自递归直接调用自己。**
|
||||
|
||||
- [ ] **Step 1: 创建新模块骨架**
|
||||
|
||||
```python
|
||||
# gui/components/wifi_adb_dialog.py
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import threading
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from tkinter.constants import LEFT, W, X
|
||||
from typing import Callable
|
||||
|
||||
from gui.gui_core import (
|
||||
auto_connect_wifi_adb,
|
||||
connect_wifi_adb,
|
||||
disconnect_wifi_adb,
|
||||
enable_wifi_adb,
|
||||
get_connected_wifi_devices,
|
||||
get_device_ip,
|
||||
list_adb_devices,
|
||||
)
|
||||
from gui.gui_core_pkg import (
|
||||
clear_last_wifi_target,
|
||||
get_last_wifi_target,
|
||||
set_last_wifi_target,
|
||||
)
|
||||
from gui.gui_core_pkg.wifi_adb_scan import query_device_model
|
||||
from gui.components.wifi_adb_scan_dialog import open_scan_dialog
|
||||
|
||||
|
||||
def open_wifi_adb_dialog(
|
||||
root: tk.Misc,
|
||||
*,
|
||||
adb_exe: str,
|
||||
on_line: Callable[[str], None],
|
||||
refresh_devices: Callable[[], None],
|
||||
) -> None:
|
||||
"""打开 WiFi ADB 设置对话框。
|
||||
|
||||
从 gui_app.main 抽出,显式接收依赖。
|
||||
"""
|
||||
# ... (Step 2 复制原 743-1111 函数体,把对外部名字的引用替换为参数)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: 复制函数体并替换闭包变量引用**
|
||||
|
||||
把 `gui_app.py:743-1111`(从 `def open_wifi_adb_dialog():` 内 body 开始,到 `info_label.pack(...)` 结束)整段复制进新函数体,缩进调整 4 → 4(已经一致,只是去掉外层 `def main()` 这一层)。
|
||||
|
||||
把三处自递归改为带参数的:
|
||||
```python
|
||||
# 原: open_wifi_adb_dialog()
|
||||
# 改: open_wifi_adb_dialog(root, adb_exe=adb_exe, on_line=on_line, refresh_devices=refresh_devices)
|
||||
```
|
||||
|
||||
把对 `open_scan_dialog` 的引用保留为 module-import 形式:
|
||||
```python
|
||||
# 原:
|
||||
# command=lambda: open_scan_dialog(dialog, adb_exe, ip_var, on_line, refresh_device_lists)
|
||||
# 不变(因为已 import 顶层 open_scan_dialog)
|
||||
```
|
||||
|
||||
注意 `toggle_maximize`、`refresh_device_lists` 是嵌套闭包,保持原样不抽 —— 它们捕获的是对话框内 widgets,只在对话框内用。
|
||||
|
||||
- [ ] **Step 3: 改 `gui_app.py`,删原闭包,改按钮 command**
|
||||
|
||||
在 `gui_app.py` 顶部加:
|
||||
```python
|
||||
from gui.components.wifi_adb_dialog import open_wifi_adb_dialog as _open_wifi_adb_dialog
|
||||
```
|
||||
|
||||
删除 743-1111 的原嵌套 `def open_wifi_adb_dialog():` 整段。
|
||||
|
||||
把 1113 行的按钮 command 改为:
|
||||
```python
|
||||
wifi_adb_btn = ttk.Button(
|
||||
top,
|
||||
text="WiFi ADB",
|
||||
command=lambda: _open_wifi_adb_dialog(
|
||||
root,
|
||||
adb_exe=adb_exe,
|
||||
on_line=on_line,
|
||||
refresh_devices=refresh_devices,
|
||||
),
|
||||
)
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 验证语法**
|
||||
|
||||
```bash
|
||||
python -m py_compile gui/gui_app.py gui/components/wifi_adb_dialog.py
|
||||
```
|
||||
Expected: 无输出
|
||||
|
||||
- [ ] **Step 5: 跑测试**
|
||||
|
||||
```bash
|
||||
pytest -x
|
||||
```
|
||||
Expected: 全部 PASS
|
||||
|
||||
- [ ] **Step 6: 行数核对 + commit**
|
||||
|
||||
```bash
|
||||
wc -l gui/gui_app.py
|
||||
git status --short
|
||||
git add gui/gui_app.py gui/components/wifi_adb_dialog.py
|
||||
git commit -m "refactor(gui): 抽 open_wifi_adb_dialog 到 components/wifi_adb_dialog (<old> → <new>)"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: 评估 P2(`load_config_to_ui` + `save_ui_to_config`)
|
||||
|
||||
P2 在 spec 里被标记为高风险(100+ Var)。只有 Task 1+2 完成且测试稳定时才做。
|
||||
|
||||
- [ ] **Step 1: 数 Var 数量**
|
||||
|
||||
```bash
|
||||
grep -nE "^\s+[a-zA-Z_]+_var = " gui/gui_app.py | wc -l
|
||||
```
|
||||
|
||||
如果数量 ≥ 50,跳过 Task 3,直接进 Task 4。
|
||||
如果 < 50,继续。
|
||||
|
||||
- [ ] **Step 2: 如果继续,设计 dataclass 聚合 Var**
|
||||
|
||||
读 2748-3402 列出所有用到的 Var,定义:
|
||||
```python
|
||||
# gui/components/config_io.py
|
||||
@dataclass
|
||||
class ConfigVars:
|
||||
y_var: tk.IntVar
|
||||
needswitch_var: tk.BooleanVar
|
||||
# ... 全部
|
||||
```
|
||||
|
||||
抽出函数:
|
||||
```python
|
||||
def load_config_to_ui(vars_: ConfigVars, *, on_line: Callable[[str], None]) -> None: ...
|
||||
def save_ui_to_config(vars_: ConfigVars, *, on_line: Callable[[str], None]) -> None: ...
|
||||
```
|
||||
|
||||
实施步骤参考 Task 2 的 Step 1-6。
|
||||
|
||||
如果改动量过大或测试卡住,**回滚并跳过 P2**。
|
||||
|
||||
---
|
||||
|
||||
## Task 4: 抽 `refresh_reservations` 到 `components/reservations_view.py`
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/components/reservations_view.py`
|
||||
- Modify: `gui/gui_app.py:4530-4805` (删原闭包),改调用点
|
||||
|
||||
- [ ] **Step 1: 列出依赖**
|
||||
|
||||
读 4530-4805,记录捕获的 widgets(主要是 `reservations_tree: ttk.Treeview`)、状态变量、回调。
|
||||
|
||||
- [ ] **Step 2: 创建模块,函数签名**
|
||||
|
||||
```python
|
||||
# gui/components/reservations_view.py
|
||||
from __future__ import annotations
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from typing import Callable
|
||||
|
||||
def refresh_reservations(
|
||||
tree: ttk.Treeview,
|
||||
*,
|
||||
on_line: Callable[[str], None] = lambda _msg: None,
|
||||
) -> None:
|
||||
"""刷新预约 Tab 的 Treeview。"""
|
||||
# body 来自原 4530-4805
|
||||
```
|
||||
|
||||
依赖里如果有路径(`get_logs_dir` 之类)直接 import,不需要传参。
|
||||
|
||||
- [ ] **Step 3: 修改 `gui_app.py`**
|
||||
|
||||
```python
|
||||
from gui.components.reservations_view import refresh_reservations as _refresh_reservations_impl
|
||||
|
||||
# 原 def refresh_reservations(): ... 改为:
|
||||
def refresh_reservations():
|
||||
_refresh_reservations_impl(reservations_tree, on_line=on_line)
|
||||
```
|
||||
保留薄包装 `def refresh_reservations()`,因为 `auto_refresh_reservations` 等地方仍以闭包形式调用它。
|
||||
|
||||
- [ ] **Step 4: 验证 + 测试 + commit**
|
||||
|
||||
```bash
|
||||
python -m py_compile gui/gui_app.py gui/components/reservations_view.py
|
||||
pytest -x
|
||||
wc -l gui/gui_app.py
|
||||
git add gui/gui_app.py gui/components/reservations_view.py
|
||||
git commit -m "refactor(gui): 抽 refresh_reservations 到 components/reservations_view (<old> → <new>)"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: 抽 `refresh_high_value_rooms` 到 `components/high_value_view.py`
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/components/high_value_view.py`
|
||||
- Modify: `gui/gui_app.py:4805-5085`
|
||||
|
||||
- [ ] **Step 1: 列出依赖**
|
||||
|
||||
读 4805-5085,记录捕获的 widgets(主要是 `high_value_rooms_tree: ttk.Treeview`)、状态变量、回调。
|
||||
|
||||
- [ ] **Step 2: 创建模块,函数签名**
|
||||
|
||||
```python
|
||||
# gui/components/high_value_view.py
|
||||
from __future__ import annotations
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from typing import Callable
|
||||
|
||||
def refresh_high_value_rooms(
|
||||
tree: ttk.Treeview,
|
||||
*,
|
||||
on_line: Callable[[str], None] = lambda _msg: None,
|
||||
) -> None:
|
||||
"""刷新高价值房间 Tab 的 Treeview。"""
|
||||
# body 来自原 4805-5085
|
||||
```
|
||||
|
||||
依赖里如果有路径(`get_logs_dir` 之类)直接 import,不需要传参。
|
||||
|
||||
- [ ] **Step 3: 修改 `gui_app.py`**
|
||||
|
||||
```python
|
||||
from gui.components.high_value_view import refresh_high_value_rooms as _refresh_high_value_rooms_impl
|
||||
|
||||
# 原 def refresh_high_value_rooms(): ... 改为薄包装:
|
||||
def refresh_high_value_rooms():
|
||||
_refresh_high_value_rooms_impl(high_value_rooms_tree, on_line=on_line)
|
||||
```
|
||||
|
||||
- [ ] **Step 4: 验证 + 测试 + commit**
|
||||
|
||||
```bash
|
||||
python -m py_compile gui/gui_app.py gui/components/high_value_view.py
|
||||
pytest -x
|
||||
wc -l gui/gui_app.py
|
||||
git add gui/gui_app.py gui/components/high_value_view.py
|
||||
git commit -m "refactor(gui): 抽 refresh_high_value_rooms 到 components/high_value_view (<old> → <new>)"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: 抽 `do_screenshot` + `_bind_screenshot_button` 到 `components/screenshot_action.py`
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/components/screenshot_action.py`
|
||||
- Modify: `gui/gui_app.py:3402-3651`
|
||||
|
||||
- [ ] **Step 1: 列出依赖**
|
||||
|
||||
读 3402-3651。`do_screenshot` 依赖:`adb_exe`、状态 Label、图片预览刷新回调、ADB 截图工具函数。
|
||||
|
||||
- [ ] **Step 2-4: 抽出,签名:**
|
||||
|
||||
```python
|
||||
def do_screenshot(
|
||||
*,
|
||||
adb_exe: str,
|
||||
on_line: Callable[[str], None],
|
||||
on_done: Callable[[str], None], # 截图保存路径
|
||||
status_label: ttk.Label | None = None,
|
||||
) -> None:
|
||||
...
|
||||
|
||||
def bind_screenshot_button(
|
||||
btn: ttk.Button,
|
||||
*,
|
||||
adb_exe: str,
|
||||
on_line: Callable[[str], None],
|
||||
on_done: Callable[[str], None],
|
||||
status_label: ttk.Label | None = None,
|
||||
) -> None:
|
||||
btn.configure(command=lambda: do_screenshot(
|
||||
adb_exe=adb_exe, on_line=on_line, on_done=on_done, status_label=status_label
|
||||
))
|
||||
```
|
||||
|
||||
调用点同 Task 4。
|
||||
|
||||
commit msg: `refactor(gui): 抽 do_screenshot 到 components/screenshot_action (<old> → <new>)`
|
||||
|
||||
---
|
||||
|
||||
## Task 7: 抽 `refresh_actions_log` + 搜索栏 到 `components/actions_log_view.py`
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/components/actions_log_view.py`
|
||||
- Modify: `gui/gui_app.py:4845-5070`
|
||||
|
||||
- [ ] **Step 1: 列出依赖**
|
||||
|
||||
读 4845-5070。包含:`configure_actions_log_colors`、`refresh_actions_log`、几个搜索方法 `search_in_actions_log`/`search_next_in_actions`/`search_prev_in_actions`/`clear_search_in_actions`/`on_actions_search_entry_key`。
|
||||
|
||||
- [ ] **Step 2-4: 设计**
|
||||
|
||||
设计成 1 个 `setup_actions_log_view(text_widget, search_entry, ...)` 一次性绑定所有,或者保留几个独立函数都接收 `text_widget` 参数。优先后者(更小步)。
|
||||
|
||||
签名:
|
||||
```python
|
||||
def configure_actions_log_colors(text_widget: tk.Text) -> None: ...
|
||||
def refresh_actions_log(text_widget: tk.Text, *, on_line: Callable[[str], None]) -> None: ...
|
||||
def search_in_actions_log(text_widget: tk.Text, search_entry: ttk.Entry, *, direction: int = 1) -> None: ...
|
||||
```
|
||||
|
||||
`gui_app.py` 里保留薄包装让原闭包调用模式不变。
|
||||
|
||||
commit msg: `refactor(gui): 抽 actions_log 视图相关到 components/actions_log_view (<old> → <new>)`
|
||||
|
||||
---
|
||||
|
||||
## Task 8: 评估停止条件 + 收尾
|
||||
|
||||
- [ ] **Step 1: 检查停止条件**
|
||||
|
||||
```bash
|
||||
wc -l gui/gui_app.py
|
||||
```
|
||||
满足以下任一即停:
|
||||
1. ≤ 3000 行
|
||||
2. 行数下降 < 50
|
||||
3. 下一段需传 ≥ 50 个独立依赖
|
||||
|
||||
- [ ] **Step 2: 如果停止,写收尾说明**
|
||||
|
||||
如果停止,在 `docs/superpowers/specs/2026-05-30-split-gui-app-design.md` 末尾追加 `## Outcome` 段:列出实际抽出的模块、行数变化、未做的项。
|
||||
|
||||
```bash
|
||||
git add docs/superpowers/specs/2026-05-30-split-gui-app-design.md
|
||||
git commit -m "docs(specs): 补充 gui_app 拆分实际成果"
|
||||
git push
|
||||
```
|
||||
|
||||
- [ ] **Step 3: 报告**
|
||||
|
||||
总结输出给用户:
|
||||
- 起始行数:5476
|
||||
- 当前行数:`<X>`
|
||||
- 抽出的模块列表
|
||||
- pytest 状态
|
||||
- 是否还有未抽的候选(可作为下一轮)
|
||||
|
||||
---
|
||||
|
||||
## 关键约束(每个 Task 都要遵守)
|
||||
|
||||
1. **AGENTS.md**:每个 Task 都要 commit + push,只 stage 本任务实际改的文件,不混入用户已有改动。
|
||||
2. **不改行为**:抽取是纯重构,不修 bug、不优化性能、不删功能。
|
||||
3. **失败回滚**:若 pytest 失败且修复需改 ≥ 2 个非目标文件,`git reset --hard HEAD~1`(本任务的 commit 还没 push),回到上一 Task 报告问题。
|
||||
4. **每个 Task 验证后再开下一个**:不批量做。
|
||||
5. **手工 smoke 推迟到批次末尾**:本计划的 pytest 不覆盖 GUI 交互(项目测试有意写得轻),抽取属纯重构,逻辑保持一致。每个 Task 完成后,在 Task 8 的收尾报告里提示用户:「请启动 GUI 跑一遍受影响功能(WiFi 对话框 / 预约 Tab / 高价值房间 / 截图按钮 / 操作日志 Tab),确认无回归。」用户 smoke 后若发现问题,定位到具体 Task 的 commit 回滚。
|
||||
@@ -0,0 +1,982 @@
|
||||
# Split WebUI Large Files Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Continue the large-file split after `gui/gui_app.py` by modularizing the WebUI frontend and, only after the frontend is stable, splitting the Web GUI Python server.
|
||||
|
||||
**Architecture:** Keep the current static WebUI behavior intact while moving code into focused `webui/js/*` and `webui/css/*` files. Each task changes one responsibility, preserves global names needed by `DOMContentLoaded`, runs focused tests, commits, and pushes before the next task.
|
||||
|
||||
**Tech Stack:** Plain HTML/CSS/JavaScript, Python `http.server`, pytest, browser smoke test for UI changes.
|
||||
|
||||
---
|
||||
|
||||
## Current Evidence
|
||||
|
||||
From the current worktree on 2026-05-31:
|
||||
|
||||
| File | Lines | Role |
|
||||
|---|---:|---|
|
||||
| `webui/styles.css` | 3745 | WebUI visual system, layout, panels, logs, responsive rules |
|
||||
| `webui/app.js` | 2512 | WebUI constants, state, API calls, rendering, polling, event wiring |
|
||||
| `gui/web_gui.py` | 1663 | local HTTP server, runner, API routes, static file serving |
|
||||
| `webui/index.html` | 1232 | WebUI DOM structure and config bindings |
|
||||
|
||||
`gui/gui_app.py` is already down to about 130 lines and should not be the next split target. The next target is the WebUI bundle.
|
||||
|
||||
## Stop Conditions
|
||||
|
||||
Stop this plan and write an outcome note when any one is true:
|
||||
|
||||
1. `webui/app.js` is below 700 lines and `webui/styles.css` is below 1400 lines.
|
||||
2. The next split would require changing more than 3 of the large files in one task.
|
||||
3. Browser smoke finds a visual or runtime regression that cannot be fixed inside the current task boundary.
|
||||
4. Tests fail and the fix would require behavior changes outside the current responsibility.
|
||||
|
||||
## Verification Commands
|
||||
|
||||
Run these after every JavaScript or HTML task:
|
||||
|
||||
```powershell
|
||||
python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1
|
||||
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
```text
|
||||
py_compile: exit code 0
|
||||
pytest: all selected tests PASS
|
||||
```
|
||||
|
||||
Run these after every CSS or visual task:
|
||||
|
||||
```powershell
|
||||
python -m py_compile gui/web_gui.py > logs\webui_split_py_compile.log 2>&1
|
||||
pytest tests/test_webgui.py -q > logs\pytest_webui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
```text
|
||||
py_compile: exit code 0
|
||||
pytest: all selected tests PASS
|
||||
```
|
||||
|
||||
For frontend visual changes, also start the Web GUI and inspect it in a browser:
|
||||
|
||||
```powershell
|
||||
python gui\web_gui.py
|
||||
```
|
||||
|
||||
Expected browser checks:
|
||||
|
||||
- `/` loads without a blank page.
|
||||
- Console has no module load errors, syntax errors, or missing function errors.
|
||||
- Header buttons, tabs, logs panel, reservations panel, high-value panel, screenshot preview, and footer remain visible without overlap at desktop width.
|
||||
- At mobile width, command buttons wrap and panels remain readable.
|
||||
|
||||
## Static Loading Decision
|
||||
|
||||
The current page loads:
|
||||
|
||||
```html
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v35" />
|
||||
<script src="app.js?v=console-20260520-theme-v35"></script>
|
||||
```
|
||||
|
||||
Use classic scripts for the first JavaScript split instead of ES modules. This avoids a broad initialization rewrite and keeps inline event expectations simple. New scripts must be loaded before `app.js` if `app.js` depends on them.
|
||||
|
||||
For CSS, use multiple `<link rel="stylesheet">` tags. Keep `styles.css` as the compatibility shell until the end of the CSS split.
|
||||
|
||||
---
|
||||
|
||||
## Task 1: Add WebUI Static Asset Structure
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/README.md`
|
||||
- Create: `webui/css/README.md`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create asset directory docs**
|
||||
|
||||
Create `webui/js/README.md`:
|
||||
|
||||
```markdown
|
||||
# WebUI JavaScript modules
|
||||
|
||||
Classic browser scripts loaded by `webui/index.html`.
|
||||
|
||||
Load order matters:
|
||||
|
||||
1. `constants.js`
|
||||
2. `dom.js`
|
||||
3. `api.js`
|
||||
4. focused feature scripts
|
||||
5. `app.js`
|
||||
|
||||
Keep behavior-preserving splits small. Do not introduce a build step unless a later plan explicitly replaces this static layout.
|
||||
```
|
||||
|
||||
Create `webui/css/README.md`:
|
||||
|
||||
```markdown
|
||||
# WebUI CSS modules
|
||||
|
||||
Plain CSS files loaded by `webui/index.html`.
|
||||
|
||||
Recommended order:
|
||||
|
||||
1. `tokens.css`
|
||||
2. `base.css`
|
||||
3. `layout.css`
|
||||
4. `components.css`
|
||||
5. focused panel or feature CSS
|
||||
6. `styles.css` compatibility remainder
|
||||
|
||||
Keep selectors stable so existing HTML and JavaScript continue to work.
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add no-op load anchors to `index.html`**
|
||||
|
||||
Insert comments around the existing assets:
|
||||
|
||||
```html
|
||||
<!-- WebUI CSS modules are loaded before the compatibility remainder. -->
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260520-theme-v35" />
|
||||
```
|
||||
|
||||
```html
|
||||
<!-- WebUI JS modules are loaded before the compatibility remainder. -->
|
||||
<script src="app.js?v=console-20260520-theme-v35"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected: selected tests PASS.
|
||||
|
||||
- [ ] **Step 4: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/js/README.md webui/css/README.md
|
||||
git commit -m "refactor(webui): add static module split structure"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 2: Extract JavaScript Constants and Copy
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/constants.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `constants.js`**
|
||||
|
||||
Move these top-level constants from `app.js` into `webui/js/constants.js` unchanged:
|
||||
|
||||
```javascript
|
||||
const UI_LIMITS = Object.freeze({
|
||||
runLogMaxLines: 50000,
|
||||
runLogMaxChars: 200000,
|
||||
actionsLogMaxLines: 5000,
|
||||
scrollBottomThresholdPx: 5,
|
||||
screenshotPollMs: 1500,
|
||||
logPollMs: 800,
|
||||
statsPollMs: 1200,
|
||||
});
|
||||
|
||||
const UI_CLASS = Object.freeze({
|
||||
busy: "isBusy",
|
||||
clickable: "isClickable",
|
||||
collapsed: "isCollapsed",
|
||||
listCollapsed: "isListCollapsed",
|
||||
reservationHeader: "reservationHeader",
|
||||
reservationBody: "reservationBody",
|
||||
reservationsList: "reservationsList",
|
||||
shotEmpty: "isShotEmpty",
|
||||
statusRunning: "statusRunning",
|
||||
statusIdle: "statusIdle",
|
||||
statusError: "statusError",
|
||||
});
|
||||
|
||||
const RUN_TONE = Object.freeze({
|
||||
running: "running",
|
||||
idle: "idle",
|
||||
error: "error",
|
||||
});
|
||||
```
|
||||
|
||||
Also move `UI_COPY`, `TIMELINE_SERIES_KEYS`, `TIMELINE_LAYOUT`, `TIMELINE_STROKES`, and `DEFAULTS` unchanged.
|
||||
|
||||
- [ ] **Step 2: Remove moved constants from `app.js`**
|
||||
|
||||
Delete only the moved constant declarations from `webui/app.js`. Keep state variables such as `logIdx`, `pollTimer`, `runLogBuffer`, and `deviceOverviewState` in `app.js` for now.
|
||||
|
||||
- [ ] **Step 3: Load `constants.js` before `app.js`**
|
||||
|
||||
Change the bottom of `webui/index.html` to:
|
||||
|
||||
```html
|
||||
<!-- WebUI JS modules are loaded before the compatibility remainder. -->
|
||||
<script src="js/constants.js?v=console-20260531-split-1"></script>
|
||||
<script src="app.js?v=console-20260531-split-1"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m py_compile gui/web_gui.py tools/diagnostics/check_web_gui_config_sync.py > logs\webui_split_py_compile.log 2>&1
|
||||
pytest tests/test_webgui.py tests/test_gui_webui_sync.py -q > logs\pytest_webui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected: both PASS.
|
||||
|
||||
- [ ] **Step 5: Browser smoke**
|
||||
|
||||
Start:
|
||||
|
||||
```powershell
|
||||
python gui\web_gui.py
|
||||
```
|
||||
|
||||
Open `http://127.0.0.1:8765/` or the printed local URL. Confirm console has no `UI_LIMITS is not defined`, `DEFAULTS is not defined`, or `fmtDuration is not defined` errors.
|
||||
|
||||
- [ ] **Step 6: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/constants.js
|
||||
git commit -m "refactor(webui): extract frontend constants"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 3: Extract DOM and Formatting Helpers
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/dom_utils.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `dom_utils.js`**
|
||||
|
||||
Move these functions from `app.js` into `webui/js/dom_utils.js` unchanged:
|
||||
|
||||
```javascript
|
||||
function $(id)
|
||||
function setTextIfExists(id, text)
|
||||
function clearEl(el)
|
||||
function escapeHtml(s)
|
||||
function fmtTime(ts)
|
||||
function fmtNum(v)
|
||||
function fmtDuration(seconds)
|
||||
```
|
||||
|
||||
When implementing, copy the exact current function declarations and bodies from `webui/app.js`.
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete the moved function declarations only. Do not move UI initialization functions yet.
|
||||
|
||||
- [ ] **Step 3: Load `dom_utils.js` after `constants.js`**
|
||||
|
||||
```html
|
||||
<script src="js/constants.js?v=console-20260531-split-2"></script>
|
||||
<script src="js/dom_utils.js?v=console-20260531-split-2"></script>
|
||||
<script src="app.js?v=console-20260531-split-2"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run the standard JavaScript verification commands. In browser console, confirm no `$ is not defined`, `fmtDuration is not defined`, or `escapeHtml is not defined` errors.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/dom_utils.js
|
||||
git commit -m "refactor(webui): extract DOM and format helpers"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 4: Extract API Client Helpers
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/api_client.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `api_client.js`**
|
||||
|
||||
Move these functions and state from `app.js` into `webui/js/api_client.js` unchanged:
|
||||
|
||||
```javascript
|
||||
let _apiFailStreak = 0;
|
||||
const _apiFailThreshold = 2;
|
||||
let _csrfToken = null;
|
||||
|
||||
function setConnState(state)
|
||||
function notifyApiOk()
|
||||
function notifyApiFail()
|
||||
async function apiGet(path)
|
||||
async function getCsrfToken()
|
||||
async function apiPost(path, body)
|
||||
```
|
||||
|
||||
When implementing, copy the exact current function declarations and bodies from `webui/app.js`.
|
||||
|
||||
- [ ] **Step 2: Remove moved declarations from `app.js`**
|
||||
|
||||
Delete only the moved declarations. Keep feature-level functions such as `refreshDevices`, `startRun`, `pollLogs`, and `pollStats` in `app.js`.
|
||||
|
||||
- [ ] **Step 3: Load `api_client.js` after `dom_utils.js`**
|
||||
|
||||
```html
|
||||
<script src="js/constants.js?v=console-20260531-split-3"></script>
|
||||
<script src="js/dom_utils.js?v=console-20260531-split-3"></script>
|
||||
<script src="js/api_client.js?v=console-20260531-split-3"></script>
|
||||
<script src="app.js?v=console-20260531-split-3"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run the standard JavaScript verification commands. In browser, click refresh devices and load config. Confirm API state footer updates and no `apiGet is not defined` or CSRF errors appear.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/api_client.js
|
||||
git commit -m "refactor(webui): extract API client helpers"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 5: Extract Log View Behavior
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/log_views.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `log_views.js`**
|
||||
|
||||
Move the log rendering and search functions from `app.js` into `webui/js/log_views.js`:
|
||||
|
||||
```javascript
|
||||
function classifyLogLine(line)
|
||||
function renderLogLineNode(line)
|
||||
function appendLog(lines)
|
||||
function renderRunLog()
|
||||
function appendRunLogLines(lines)
|
||||
async function fetchActionsLog()
|
||||
function renderActionsLog()
|
||||
```
|
||||
|
||||
Keep these shared state variables in `app.js` for this task:
|
||||
|
||||
```javascript
|
||||
let runLogBuffer = [];
|
||||
let runLogFilter = "";
|
||||
let runLogMode = "filter";
|
||||
let runSearchResultsBuffer = [];
|
||||
let runSearchActive = false;
|
||||
let actionsLogBuffer = [];
|
||||
let actionsLogFilter = "";
|
||||
```
|
||||
|
||||
Because classic scripts share global scope, `log_views.js` can keep using these names.
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete only the moved function declarations.
|
||||
|
||||
- [ ] **Step 3: Load `log_views.js` before `app.js`**
|
||||
|
||||
```html
|
||||
<script src="js/constants.js?v=console-20260531-split-4"></script>
|
||||
<script src="js/dom_utils.js?v=console-20260531-split-4"></script>
|
||||
<script src="js/api_client.js?v=console-20260531-split-4"></script>
|
||||
<script src="js/log_views.js?v=console-20260531-split-4"></script>
|
||||
<script src="app.js?v=console-20260531-split-4"></script>
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run the standard JavaScript verification commands. In browser, check the run log filter/search and action log refresh.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/log_views.js
|
||||
git commit -m "refactor(webui): extract log view behavior"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 6: Extract Dashboard Renderers
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/dashboard_renderers.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `dashboard_renderers.js`**
|
||||
|
||||
Move these renderer functions from `app.js` into `webui/js/dashboard_renderers.js`:
|
||||
|
||||
```javascript
|
||||
function renderBars(containerId, dataMap, labelMap)
|
||||
function renderTopContent(containerId, items)
|
||||
function renderWinsTable(containerId, wins)
|
||||
function renderTimeline(containerId, timeline)
|
||||
function renderOverviewSparkline(svgId, timeline)
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete only the moved renderer declarations.
|
||||
|
||||
- [ ] **Step 3: Load `dashboard_renderers.js` before `app.js`**
|
||||
|
||||
```html
|
||||
<script src="js/dashboard_renderers.js?v=console-20260531-split-5"></script>
|
||||
<script src="app.js?v=console-20260531-split-5"></script>
|
||||
```
|
||||
|
||||
Keep all earlier module script tags before `dashboard_renderers.js`.
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run standard JavaScript verification. In browser, confirm stats charts, timeline tooltip, top content table, and wins table still render.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/dashboard_renderers.js
|
||||
git commit -m "refactor(webui): extract dashboard renderers"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 7: Extract Config Form Binding
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/config_form.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `config_form.js`**
|
||||
|
||||
Move these config-related functions from `app.js` into `webui/js/config_form.js`:
|
||||
|
||||
```javascript
|
||||
function getConfigBoundElements()
|
||||
function syncMirrorFields()
|
||||
function getConfigValue(cfg, key)
|
||||
function coerceValue(type, raw, isCheckbox)
|
||||
function applyConfigToUI(cfg)
|
||||
function collectConfigFromUI()
|
||||
async function loadConfig()
|
||||
async function saveConfig()
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete only the moved config declarations.
|
||||
|
||||
- [ ] **Step 3: Load `config_form.js` before `app.js`**
|
||||
|
||||
```html
|
||||
<script src="js/config_form.js?v=console-20260531-split-6"></script>
|
||||
<script src="app.js?v=console-20260531-split-6"></script>
|
||||
```
|
||||
|
||||
Keep all earlier module script tags before `config_form.js`.
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run standard JavaScript verification and `pytest tests/test_gui_webui_sync.py -q`. In browser, load config, change one harmless UI field, save, reload, and confirm no config-binding error appears.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/config_form.js
|
||||
git commit -m "refactor(webui): extract config form bindings"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 8: Extract Polling and Device Actions
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/runtime_actions.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Create `runtime_actions.js`**
|
||||
|
||||
Move these functions from `app.js` into `webui/js/runtime_actions.js`:
|
||||
|
||||
```javascript
|
||||
async function refreshDevices()
|
||||
function decorateDeviceSelect()
|
||||
function selectedDeviceId()
|
||||
async function postDeviceAction(path, body, successPrefix)
|
||||
async function forceStopRun()
|
||||
async function sendBackKey()
|
||||
async function wifiEnable()
|
||||
async function wifiConnect()
|
||||
async function wifiDisconnect()
|
||||
async function tryAutoReconnectLastWifi()
|
||||
async function wifiScan()
|
||||
async function startRun()
|
||||
async function testYanghao()
|
||||
async function testComment()
|
||||
async function stopRun()
|
||||
async function pollLogs()
|
||||
async function pollReservations()
|
||||
async function pollHighValueRooms()
|
||||
async function pollStats()
|
||||
function startPolling()
|
||||
function startStatsPolling()
|
||||
```
|
||||
|
||||
Keep `DOMContentLoaded` event wiring in `app.js`.
|
||||
|
||||
- [ ] **Step 2: Remove moved functions from `app.js`**
|
||||
|
||||
Delete only the moved runtime declarations.
|
||||
|
||||
- [ ] **Step 3: Load `runtime_actions.js` before `app.js`**
|
||||
|
||||
```html
|
||||
<script src="js/runtime_actions.js?v=console-20260531-split-7"></script>
|
||||
<script src="app.js?v=console-20260531-split-7"></script>
|
||||
```
|
||||
|
||||
Keep all earlier module script tags before `runtime_actions.js`.
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run standard JavaScript verification. In browser, click refresh devices, load config, start/stop if safe, refresh action log, and switch through all panels.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/runtime_actions.js
|
||||
git commit -m "refactor(webui): extract runtime actions and polling"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 9: Reduce `app.js` to Initialization Glue
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/js/ui_init.js`
|
||||
- Modify: `webui/app.js`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Move UI initialization helpers**
|
||||
|
||||
Move these functions into `webui/js/ui_init.js`:
|
||||
|
||||
```javascript
|
||||
function initTheme()
|
||||
function ensureToastContainer()
|
||||
function toast(message, kind = "info", { duration = 3500 } = {})
|
||||
function initConfigSearch()
|
||||
function initFooter()
|
||||
function attachCopyButtons()
|
||||
function initKeyboardShortcuts()
|
||||
function initHeaderScroll()
|
||||
function initShotFullscreen()
|
||||
function applyKbdHints()
|
||||
function initStickySectionShadow()
|
||||
function initShortcutsHelp()
|
||||
function updateTabBadge(target, count)
|
||||
function startReservationsCountdownTick()
|
||||
function initTabs()
|
||||
function attachNumberSteppers()
|
||||
function pollShot()
|
||||
function startShotPolling()
|
||||
function setButtonBusy(id, busy)
|
||||
function setRunOverview(state, meta, tone)
|
||||
function updateDeviceOverview()
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Keep `app.js` as bootstrapping only**
|
||||
|
||||
After this task, `app.js` should contain:
|
||||
|
||||
```javascript
|
||||
window.addEventListener("DOMContentLoaded", async () => {
|
||||
initTheme();
|
||||
initTabs();
|
||||
initConfigSearch();
|
||||
initFooter();
|
||||
attachCopyButtons();
|
||||
initShotFullscreen();
|
||||
initHeaderScroll();
|
||||
initKeyboardShortcuts();
|
||||
initShortcutsHelp();
|
||||
initStickySectionShadow();
|
||||
attachNumberSteppers();
|
||||
applyKbdHints();
|
||||
syncMirrorFields();
|
||||
await refreshDevices();
|
||||
await loadConfig();
|
||||
startPolling();
|
||||
startStatsPolling();
|
||||
startShotPolling();
|
||||
startReservationsCountdownTick();
|
||||
pollLogs();
|
||||
pollStats();
|
||||
pollShot();
|
||||
pollReservations();
|
||||
pollHighValueRooms();
|
||||
});
|
||||
```
|
||||
|
||||
During implementation, preserve the existing event listener bindings from the current `DOMContentLoaded` body. If the current body wires buttons or inputs, keep those bindings in `app.js` or move them into a clearly named `bindAppEvents()` function in `ui_init.js`.
|
||||
|
||||
- [ ] **Step 3: Verify and smoke**
|
||||
|
||||
Run standard JavaScript verification. Browser smoke must cover initial load, tabs, theme, footer, shortcuts overlay, screenshot preview, logs, and config load/save.
|
||||
|
||||
- [ ] **Step 4: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/app.js webui/js/ui_init.js
|
||||
git commit -m "refactor(webui): reduce app script to initialization glue"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 10: Split CSS Tokens and Base Rules
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/css/tokens.css`
|
||||
- Create: `webui/css/base.css`
|
||||
- Modify: `webui/styles.css`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Extract theme tokens**
|
||||
|
||||
Move these ranges from `styles.css` into `webui/css/tokens.css`:
|
||||
|
||||
- `:root { ... }` light theme token block
|
||||
- `:root[data-theme="dark"] { ... }` dark theme token block
|
||||
- reduced-motion token or global animation defaults that are pure variables
|
||||
|
||||
Do not rename variables.
|
||||
|
||||
- [ ] **Step 2: Extract base element rules**
|
||||
|
||||
Move base reset and generic element rules into `webui/css/base.css`:
|
||||
|
||||
- `*`, `html`, `body`
|
||||
- `button`, `input`, `select`, `textarea`
|
||||
- generic focus-visible rules
|
||||
- global scrollbar rules
|
||||
- generic utility classes that are not tied to one panel
|
||||
|
||||
- [ ] **Step 3: Load extracted CSS before `styles.css`**
|
||||
|
||||
```html
|
||||
<!-- WebUI CSS modules are loaded before the compatibility remainder. -->
|
||||
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-1" />
|
||||
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-1" />
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-1" />
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run CSS verification commands. Browser smoke must compare light and dark theme basics, header, buttons, forms, and scrollbars.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/styles.css webui/css/tokens.css webui/css/base.css
|
||||
git commit -m "refactor(webui): extract CSS tokens and base rules"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 11: Split CSS Layout and Shared Components
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/css/layout.css`
|
||||
- Create: `webui/css/components.css`
|
||||
- Modify: `webui/styles.css`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Extract layout rules**
|
||||
|
||||
Move app shell, header, workspace, panel grid, and footer layout rules into `layout.css`. Include responsive `@media` rules that only affect those layout selectors.
|
||||
|
||||
- [ ] **Step 2: Extract shared component rules**
|
||||
|
||||
Move shared button, card, tab, field, table, tooltip, toast, skeleton, and shortcut overlay rules into `components.css`. Include related `@media` and `prefers-reduced-motion` blocks when they directly belong to those selectors.
|
||||
|
||||
- [ ] **Step 3: Load CSS in stable order**
|
||||
|
||||
```html
|
||||
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-2" />
|
||||
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-2" />
|
||||
<link rel="stylesheet" href="css/layout.css?v=console-20260531-split-css-2" />
|
||||
<link rel="stylesheet" href="css/components.css?v=console-20260531-split-css-2" />
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-2" />
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Verify and smoke**
|
||||
|
||||
Run CSS verification. Browser smoke must check desktop and mobile layout, tabs, cards, buttons, toast, tooltip, and shortcuts overlay.
|
||||
|
||||
- [ ] **Step 5: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/styles.css webui/css/layout.css webui/css/components.css
|
||||
git commit -m "refactor(webui): extract CSS layout and shared components"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 12: Split CSS Feature Panels
|
||||
|
||||
**Files:**
|
||||
- Create: `webui/css/panels.css`
|
||||
- Create: `webui/css/logs.css`
|
||||
- Create: `webui/css/charts.css`
|
||||
- Modify: `webui/styles.css`
|
||||
- Modify: `webui/index.html`
|
||||
|
||||
- [ ] **Step 1: Extract panel-specific styles**
|
||||
|
||||
Move screenshot preview, reservations, high-value room, realtime status, and panel-specific content rules into `panels.css`.
|
||||
|
||||
- [ ] **Step 2: Extract log styles**
|
||||
|
||||
Move run log, action log, log line classification, log search, and log scrollbar rules into `logs.css`.
|
||||
|
||||
- [ ] **Step 3: Extract chart/table styles**
|
||||
|
||||
Move chart blocks, timeline tooltip, bar rows, top content table, wins table, and related table rows into `charts.css`.
|
||||
|
||||
- [ ] **Step 4: Load CSS in stable order**
|
||||
|
||||
```html
|
||||
<link rel="stylesheet" href="css/tokens.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/base.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/layout.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/components.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/panels.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/logs.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="css/charts.css?v=console-20260531-split-css-3" />
|
||||
<link rel="stylesheet" href="styles.css?v=console-20260531-split-css-3" />
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Verify and smoke**
|
||||
|
||||
Run CSS verification. Browser smoke must check screenshot preview, reservations, high-value room list, log panels, charts, and mobile wrapping.
|
||||
|
||||
- [ ] **Step 6: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add webui/index.html webui/styles.css webui/css/panels.css webui/css/logs.css webui/css/charts.css
|
||||
git commit -m "refactor(webui): extract CSS feature panels"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 13: Decide Whether to Split `index.html`
|
||||
|
||||
**Files:**
|
||||
- Modify: `webui/index.html`
|
||||
- Optional create: `webui/partials/README.md`
|
||||
|
||||
- [ ] **Step 1: Recount file sizes**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Keep `index.html` intact unless it is still above 1000 lines**
|
||||
|
||||
If `index.html` is at or below 1000 lines, do not split it in this plan. HTML partial loading would require server or build changes and is not needed yet.
|
||||
|
||||
If `index.html` remains above 1000 lines and the team wants smaller HTML files, write a separate spec before changing runtime behavior. That spec must choose one of:
|
||||
|
||||
- server-side partial injection in `gui/web_gui.py`
|
||||
- client-side fetch of static partials
|
||||
- build-time HTML generation
|
||||
|
||||
- [ ] **Step 3: Commit only if docs are added**
|
||||
|
||||
If `webui/partials/README.md` is created:
|
||||
|
||||
```powershell
|
||||
git add webui/partials/README.md
|
||||
git commit -m "docs(webui): record HTML partial split decision"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 14: Split `gui/web_gui.py` Only After Frontend Is Stable
|
||||
|
||||
**Files:**
|
||||
- Create: `gui/web_gui_pkg/static_handler.py`
|
||||
- Create: `gui/web_gui_pkg/request_parsing.py`
|
||||
- Create: `gui/web_gui_pkg/routes.py`
|
||||
- Modify: `gui/web_gui.py`
|
||||
- Test: `tests/test_webgui.py`
|
||||
|
||||
- [ ] **Step 1: Extract request parsing helpers**
|
||||
|
||||
Move `_send_json` and `_read_json` behavior into functions that still receive the `Handler` instance:
|
||||
|
||||
```python
|
||||
def send_json(handler: BaseHTTPRequestHandler, obj: object, status: int = 200) -> None:
|
||||
data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
|
||||
handler.send_response(status)
|
||||
handler.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
handler.send_header("Cache-Control", "no-store")
|
||||
handler.send_header("Content-Length", str(len(data)))
|
||||
handler.end_headers()
|
||||
handler.wfile.write(data)
|
||||
```
|
||||
|
||||
```python
|
||||
def read_json(handler: BaseHTTPRequestHandler) -> dict:
|
||||
n = int(handler.headers.get("Content-Length") or 0)
|
||||
raw = handler.rfile.read(n) if n > 0 else b"{}"
|
||||
try:
|
||||
value = json.loads(raw.decode("utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
return value if isinstance(value, dict) else {}
|
||||
```
|
||||
|
||||
Keep `Handler._send_json` and `Handler._read_json` as thin wrappers at first.
|
||||
|
||||
- [ ] **Step 2: Extract static file serving**
|
||||
|
||||
Move `_serve_static` into `gui/web_gui_pkg/static_handler.py`:
|
||||
|
||||
```python
|
||||
def serve_static(
|
||||
handler: BaseHTTPRequestHandler,
|
||||
*,
|
||||
webui_dir: str,
|
||||
rel_path: str,
|
||||
log_error: Callable[[str], None],
|
||||
) -> None:
|
||||
# paste current Handler._serve_static body and replace:
|
||||
# self -> handler
|
||||
# WEBUI_DIR -> webui_dir
|
||||
# _wg_log(...) -> log_error(...)
|
||||
```
|
||||
|
||||
Keep `Handler._serve_static` as:
|
||||
|
||||
```python
|
||||
def _serve_static(self, rel_path: str) -> None:
|
||||
serve_static(
|
||||
self,
|
||||
webui_dir=WEBUI_DIR,
|
||||
rel_path=rel_path,
|
||||
log_error=lambda msg: _wg_log(msg, level="ERROR"),
|
||||
)
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Verify**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
python -m py_compile gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py > logs\web_gui_split_py_compile.log 2>&1
|
||||
pytest tests/test_webgui.py -q > logs\pytest_web_gui_split.log 2>&1
|
||||
```
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 4: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add gui/web_gui.py gui/web_gui_pkg/static_handler.py gui/web_gui_pkg/request_parsing.py tests/test_webgui.py
|
||||
git commit -m "refactor(webgui): extract request and static helpers"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Task 15: Final Outcome Note
|
||||
|
||||
**Files:**
|
||||
- Modify: this plan file
|
||||
|
||||
- [ ] **Step 1: Record final sizes**
|
||||
|
||||
Run:
|
||||
|
||||
```powershell
|
||||
rg --files -g "*.html" -g "*.js" -g "*.css" -g "*.py" | ForEach-Object { $lines=(Get-Content $_ | Measure-Object -Line).Lines; [PSCustomObject]@{Lines=$lines; Path=$_} } | Sort-Object Lines -Descending | Select-Object -First 20 | Format-Table -AutoSize
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Append outcome**
|
||||
|
||||
Append:
|
||||
|
||||
```markdown
|
||||
## Outcome
|
||||
|
||||
- `webui/app.js`: 2512 -> actual final line count
|
||||
- `webui/styles.css`: 3745 -> actual final line count
|
||||
- `webui/index.html`: 1232 -> actual final line count
|
||||
- `gui/web_gui.py`: 1663 -> actual final line count
|
||||
- Extracted JS modules: actual module filenames
|
||||
- Extracted CSS modules: actual module filenames
|
||||
- Verification: exact pytest log path and browser smoke result
|
||||
- Remaining large files: actual top remaining files from the final size command
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Commit and push**
|
||||
|
||||
```powershell
|
||||
git add docs/superpowers/plans/2026-05-31-split-webui-large-files.md
|
||||
git commit -m "docs(webui): record large-file split outcome"
|
||||
git push
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Execution Notes
|
||||
|
||||
- Do not batch tasks. Each task must pass verification, commit, and push before starting the next one.
|
||||
- Keep query-string versions in `index.html` synchronized across all WebUI assets touched in a task.
|
||||
- Do not introduce a frontend build step in this plan.
|
||||
- Do not convert to ES modules until the classic-script split is complete and browser smoke is clean.
|
||||
- For JavaScript moves, copy exact function bodies first, verify, then optionally do tiny cleanup in a separate commit.
|
||||
- For CSS moves, preserve selector order unless the moved file load order proves an equivalent cascade.
|
||||
- Project rule: only stage files changed by the current task.
|
||||
@@ -0,0 +1,89 @@
|
||||
# 2026-06-01 大文件继续拆分计划(续)
|
||||
|
||||
## 当前状态(更新于本轮)
|
||||
|
||||
- 已完成:
|
||||
- `gui/web_gui.py` 路由壳化,主体路由下沉到 `gui/web_gui_pkg/routes.py`
|
||||
- `douyin/core/fudai_modules/run_once_basic_helpers.py` 中预约检查与状态写盘逻辑下沉到 `run_once_basic_reservation.py`
|
||||
- `douyin/core/douyin_fudai.py` 中 `_handle_in_fudai_detail` / `_handle_live_room_has_or_not_fudai` 下沉到 `fudai_modules/live_room_handlers.py`
|
||||
- `douyin/core/underlying_operations.py` 中 `get_screenshot` 下沉到 `underlying_operations_pkg/screenshot_pipeline.py`
|
||||
- `douyin/fudai/douyin_fudai_core_legacy.py` 壳化完成,核心实现转移到 `douyin/fudai/douyin_fudai_contain_impl.py`
|
||||
- `douyin/fudai/douyin_fudai_contain_impl.py` 内部 helper 下沉到 `douyin/fudai/douyin_fudai_core_pkg/contain_helpers.py`(轻重 OCR 分流判定、参与人数提取等)
|
||||
- `douyin/fudai/douyin_fudai_contain_impl.py` 主并行/备用并行共用的按钮状态判定与回写逻辑下沉到 `douyin/fudai/douyin_fudai_core_pkg/button_state.py`
|
||||
- `douyin/fudai/douyin_fudai_contain_impl.py` 主并行/备用并行共用的并行任务提交与结果收集骨架下沉到 `douyin/fudai/douyin_fudai_core_pkg/parallel_exec.py`
|
||||
- `douyin/fudai/douyin_fudai_contain_impl.py` 主并行/备用并行共用的任务列表观看任务检测分支下沉到 `douyin/fudai/douyin_fudai_core_pkg/watch_task.py`
|
||||
- `douyin/fudai/douyin_fudai_contain_impl.py` 原始内容/清理后内容观看任务检测分支下沉到 `douyin/fudai/douyin_fudai_core_pkg/watch_task.py`
|
||||
- `douyin/fudai/douyin_fudai_contain_impl.py` 倒计时数字提取与校验分支下沉到 `douyin/fudai/douyin_fudai_core_pkg/countdown_parse.py`
|
||||
- `douyin/core/douyin_fudai.py` 的 `_capture_roi_screenshot` 与 `_match_icon_template` 下沉到 `douyin/handlers/douyin_screenshot_handler.py`
|
||||
- `douyin/core/douyin_fudai.py` 的 `fudai_choujiang` 运行循环(定时/无限模式 + 结束日志)下沉到 `douyin/core/fudai_modules/fudai_run_loop.py`
|
||||
- `douyin/core/douyin_fudai.py` 的 `run_once_basic` 前置段(启动日志/养号触发/标题记录)下沉到 `run_once_basic_helpers.run_once_basic_prelude`
|
||||
- `douyin/core/douyin_fudai.py` 的 `run_once_basic` 预约后阶段处理段下沉到 `run_once_basic_helpers.run_once_basic_post_reservation`
|
||||
- `douyin/core/underlying_operations.py` 的输入法/文本输入链路下沉到 `douyin/core/underlying_operations_pkg/text_input.py`(`input_text` / `paste_text_at` / ADBKeyboard 广播与 IME 切换等),主类保留薄转发
|
||||
- `douyin/core/fudai_modules/run_once_basic_helpers.py` 的阶段链路下沉到 `douyin/core/fudai_modules/run_once_basic_stage.py`(`screenshot_and_diagnose` / `handle_desktop_recovery` / `handle_high_value_room_revisit`),主 helper 保留薄转发
|
||||
- `douyin/core/fudai_modules/run_once_basic_helpers.py` 的粉丝团处理段下沉到 `douyin/core/fudai_modules/run_once_basic_fansclub.py`(`_handle_fansclub_join`),主 helper 保留薄转发
|
||||
- `douyin/core/fudai_modules/handle_detail_helpers.py` 的筛选与高价值预约段下沉到 `douyin/core/fudai_modules/handle_detail_filter.py`(`_check_skip_and_handle` / `_try_high_value_reservation` / `_handle_skip_filter` / `_fallback_swipe_up`),主 helper 保留薄转发
|
||||
- `douyin/core/fudai_modules/handle_detail_helpers.py` 的首开详情分支下沉到 `douyin/core/fudai_modules/handle_detail_first_open.py`(`handle_first_open_branch` / `_validate_first_open_detail`),主 helper 保留薄转发
|
||||
- `douyin/core/fudai_modules/handle_detail_helpers.py` 的二次打开与预约完成收尾下沉到 `douyin/core/fudai_modules/handle_detail_second_open.py`(`handle_second_open_branch` / `_handle_reservation_completion`),主 helper 保留薄转发
|
||||
- `douyin/stage/douyin_stage.py` 的步骤0并行像素检测下沉到 `douyin/stage/douyin_stage_handler_pkg/pixel_parallel.py`(`run_parallel_pixel_detection`),主诊断流程保留汇总与分支调度
|
||||
- `douyin/stage/douyin_stage.py` 的弹窗OCR兜底与最终阶段收尾下沉到 `douyin/stage/douyin_stage_handler_pkg/finalize_stage.py`(`finalize_stage_after_pixel`),主诊断流程保留前序分支与统一调用
|
||||
- `douyin/stage/douyin_stage.py` 的“邀你抢红包”OCR检测段下沉到 `douyin/stage/douyin_stage_handler_pkg/ocr_redpacket.py`(`detect_invite_redpacket_via_ocr`),主诊断流程保留统一调用与返回分发
|
||||
- `douyin/core/underlying_operations.py` 的 UIAutomator 交互段下沉到 `douyin/core/underlying_operations_pkg/ui_automator.py`(`_uiautomator_dump` / `tap_by_text` / `tap_close_icon`),主类保留薄转发
|
||||
- `douyin/core/underlying_operations.py` 的前台包检测与应用拉起链路下沉到 `douyin/core/underlying_operations_pkg/foreground.py`(`get_top_package` / `launch_package` / `is_douyin_foreground`),主类保留薄转发
|
||||
- `gui/web_gui.py` 的 ProcRunner 状态读取与测试入口段下沉到 `gui/web_gui_pkg/proc_runner_ops.py`(`get_reservations` / `get_high_value_rooms` / `send_back_key` / `start_test_yanghao` / `start_test_comment`),主类保留薄转发
|
||||
- `gui/web_gui.py` 的 ProcRunner 统计聚合段下沉到 `gui/web_gui_pkg/proc_runner_stats.py`(`get_stats`),主类保留薄转发
|
||||
- `webui/css/components.css` 的 Overlay/Toast 样式拆分到 `webui/css/components_overlays.css` 与 `webui/css/components_toast.css`,并在 `webui/index.html` 追加模块化样式引用,主 `components.css` 保留其余组件样式
|
||||
- `webui/index.html` 的监控/预约/日志面板与页脚区块下沉到 `webui/js/panel_templates.js`,页面改为挂载点注入(保留原 DOM id/class),主 `index.html` 继续瘦身
|
||||
- `webui/index.html` 的头部命令条与状态概览区块下沉到 `webui/js/top_templates.js`,页面改为挂载点注入(保留原 DOM id/class),主 `index.html` 继续瘦身
|
||||
- `douyin/reservation/reservation_logic/attend_window.py` 的“已参与过滤/无效时间过滤/动态提前量计算/目标快照日志”下沉到 `douyin/reservation/reservation_logic/attend_window_helpers.py`,主流程保留编排与分支顺序
|
||||
- `webui/js/runtime_actions.js` 的设备动作与测试动作下沉到 `webui/js/runtime_device_actions.js`(`selectedDeviceId` / `postDeviceAction` / `wifi*` / `forceStopRun` / `testYanghao` / `testComment`),`index.html` 已补充脚本加载顺序
|
||||
- `douyin/stage/douyin_stage_handler_pkg/check_live.py` 的分数选择策略与结果日志汇总下沉到 `douyin/stage/douyin_stage_handler_pkg/check_live_score.py`,主流程保留模板匹配编排
|
||||
- `gui/components/config_io.py` 的文本域读写与 debug/logging 配置映射下沉到 `gui/components/config_io_helpers.py`,主流程保留编排与配置字段回写顺序
|
||||
- `douyin/handlers/screenshot_manager/save_image.py` 的调试保存开关读取、保存重试机制、标注绘制逻辑下沉到 `douyin/handlers/screenshot_manager/save_image_helpers.py`(`is_debug_captures_enabled` / `save_image_with_retry` / `annotate_debug_image`),主入口保留编排与异常处理
|
||||
- `tools/coords/region_selector.py` 的菜单构建、快捷键绑定、画布事件绑定与拖放注册下沉到 `tools/coords/region_selector_ui.py`(`setup_menu` / `bind_canvas_events` / `setup_dnd`),主类保留业务状态与事件处理
|
||||
- `douyin/fudai/douyin_fudai_contain_impl.py` 的后处理聚合逻辑下沉到 `douyin/fudai/douyin_fudai_core_pkg/contain_postprocess.py`(进房耗时日志、价值OCR校验、标题写回、房间映射落盘),主流程保留编排与返回值
|
||||
- `gui/gui_core_pkg/stats_log_parser.py` 的重复正则提取与数值转换下沉到 `gui/gui_core_pkg/stats_log_parser_helpers.py`(`search_group` / `search_group_any` / `parse_int_value` / `parse_float_value` / `set_meta_*_if_match`),主解析流程保留业务事件判定
|
||||
- `douyin/reservation/reservation_logic/attend_window.py` 的尾段日志逻辑下沉到 `attend_window_helpers.py`(`log_back_failed_keep_queue` / `log_attend_window_result`),主流程保留回退决策与状态编排
|
||||
- `webui/index.html` 的 `keywords + debug` 配置面板下沉到 `webui/js/config_panel_templates.js`,页面改为 `configPanelTemplatesMount` 挂载点注入并补充脚本加载顺序(保留原 id/data-key,行为兼容)
|
||||
- `tools/coords/simple_region_selector.py` 的菜单/快捷键/画布绑定下沉到 `tools/coords/simple_region_selector_ui.py`(`setup_menu_and_shortcuts` / `bind_canvas_events`),主类保留图像处理与多边形分析流程
|
||||
- 当前 Top 大文件(源码):
|
||||
1. `webui/index.html` 53.7KB(本轮从 71.0KB 降到 53.7KB,已低于 65KB 目标)
|
||||
2. `douyin/other/douyin_yanghao.py` 29.8KB
|
||||
3. `webui/css/components.css` 29.7KB
|
||||
4. `douyin/fudai/douyin_fudai_finder_pkg/detector.py` 29.4KB
|
||||
5. `douyin/core/douyin_fudai.py` 29.0KB
|
||||
6. `douyin/reservation/reservation_logic/attend_window.py` 28.8KB(已从 35.5KB 降到 28.8KB)
|
||||
7. `gui/web_gui_pkg/stats_log_parser.py` 28.7KB
|
||||
8. `douyin/stage/douyin_stage_handler_pkg/check_live.py` 28.6KB
|
||||
9. `gui/gui_core_pkg/stats_log_parser.py` 28.4KB(已从 30.3KB 降到 28.4KB)
|
||||
10. `webui/js/ui_init.js` 27.8KB
|
||||
11. `webui/js/runtime_actions.js` 27.1KB
|
||||
|
||||
## 下一轮拆分顺序(建议)
|
||||
|
||||
1. `douyin/fudai/douyin_fudai_finder_pkg/detector.py`
|
||||
- 抽离模板匹配与阈值/回退逻辑,降低单函数复杂度。
|
||||
2. `gui/web_gui_pkg/stats_log_parser.py`
|
||||
- 参照 gui_core 侧 helper 化,统一正则提取与类型转换入口。
|
||||
3. `douyin/reservation/reservation_logic/attend_window.py`
|
||||
- 继续抽离中段“锁定期判断 + 同预约分支”中的日志与状态更新子流程。
|
||||
4. `douyin/other/douyin_yanghao.py`
|
||||
- 抽离坐标/概率配置读取与动作执行分发,降低主流程长度与分支复杂度。
|
||||
5. `webui/js/ui_init.js`
|
||||
- 分离面板切换、搜索过滤与快捷键初始化,进一步降低单文件复杂度。
|
||||
|
||||
## 验证口径
|
||||
|
||||
- 每次拆分后必须执行:
|
||||
- `python -m py_compile <改动的py文件>`
|
||||
- 如本机 `pytest` 可用,再跑相关最小测试集
|
||||
- 由于当前 shell 环境缺少 pytest,测试日志需保留:
|
||||
- `logs/pytest_*.log`
|
||||
|
||||
## 硬编码治理并行策略
|
||||
|
||||
- 优先治理“环境迁移敏感”的硬编码:
|
||||
- host/port(已收敛到 `net_config`,继续排查其它入口)
|
||||
- 本地路径、固定命令、默认端口
|
||||
- 处理方式:
|
||||
- 新增集中配置读取函数
|
||||
- 原调用点只保留薄封装,避免每处单独拼环境变量
|
||||
@@ -0,0 +1,244 @@
|
||||
# 拆分 gui/gui_app.py 设计文档
|
||||
|
||||
## 背景
|
||||
|
||||
`gui/gui_app.py` 当前 5476 行,几乎全部代码都嵌在单个 `main()` 函数里,
|
||||
内含 50+ 个闭包,捕获大量 widgets 和 tkinter Var。文件已经被多轮抽取过:
|
||||
|
||||
- `5649 → 5537`:`ThreadSafeLogWriter` → `components/log_writer`
|
||||
- `5539 → 5370`:`_open_realtime_viewer_impl` → `components/realtime_viewer`
|
||||
- `6339 → 5634`:`refresh_stats` 字符串格式化 → `components/stats_formatter`
|
||||
|
||||
继续按相同思路把内聚闭包抽到 `gui/components/*`,主文件继续瘦身。
|
||||
|
||||
## 目标
|
||||
|
||||
迭代式抽取 `gui/gui_app.py` 中的内聚闭包,主文件越变越小,
|
||||
**不改变任何 GUI 运行行为**。
|
||||
|
||||
### 成功标准
|
||||
|
||||
1. `gui/gui_app.py` 行数显著下降(目标:≤ 3000 行;继续视边际收益决定是否再抽)
|
||||
2. `pytest` 全绿
|
||||
3. 每次抽取产生一个独立 commit,保持小步可回滚
|
||||
4. GUI 启动 + 主要交互路径无回归(手工 smoke:启动 GUI、打开 WiFi 对话框、加载配置、截图、查看日志)
|
||||
|
||||
### 非目标
|
||||
|
||||
- 不重构 GUI 整体架构(不引入 MVC/MVVM)
|
||||
- 不改变 `gui_app.py` 对外暴露的入口(`main()`、`format_gui_log_line()`)
|
||||
- 不优化性能、不修 bug(除非抽取过程中发现)
|
||||
- 不动 `gui/web_gui.py`(属于下一轮独立 spec)
|
||||
|
||||
## 抽取候选清单
|
||||
|
||||
按「行数 × 边界清晰度」排序(行数粗略统计):
|
||||
|
||||
| 优先级 | 闭包 | 行范围 | 行数 | 目标文件 | 主要依赖 |
|
||||
|---|---|---|---|---|---|
|
||||
| P1 | `open_wifi_adb_dialog` | 743-1588 | 845 | `components/wifi_adb_dialog.py` | ADB 工具 + 几个回调 |
|
||||
| P2 | `load_config_to_ui` + `save_ui_to_config` | 2748-3402 | 654 | `components/config_io.py` | 100+ tkinter Var(需聚合)|
|
||||
| P3 | `refresh_reservations` | 4530-4805 | 275 | `components/reservations_view.py` | 1-2 个 Treeview + 路径 |
|
||||
| P4 | `refresh_high_value_rooms` | 4805-5085 | ~280 | `components/high_value_view.py` | 1 个 Treeview + 路径 |
|
||||
| P5 | `do_screenshot` + `_bind_screenshot_button` | 3402-3651 | 249 | `components/screenshot_action.py` | ADB exe + 路径 + 状态 Label |
|
||||
| P6 | `refresh_actions_log` + 搜索栏 | 4892-5070 | ~178 | `components/actions_log_view.py` | Text widget + 路径 |
|
||||
|
||||
**估算**:完整抽完 P1-P6 约减 2480 行 → 主文件 ~3000 行。
|
||||
若 P2 风险评估后觉得不值得做,可跳过,仍能减约 1830 行 → ~3650 行。
|
||||
|
||||
## 抽取模式(每轮通用)
|
||||
|
||||
每个候选段按以下步骤处理:
|
||||
|
||||
### 1. 摸清依赖
|
||||
|
||||
读完整段代码,列出:
|
||||
- 捕获的 `main()` 局部变量(widgets / Vars / 路径 / 状态)
|
||||
- 调用的 `main()` 内其它闭包(回调)
|
||||
- 调用的 module-level 函数 / 项目其它模块函数
|
||||
|
||||
### 2. 设计签名
|
||||
|
||||
把闭包改造为顶层函数:
|
||||
|
||||
```python
|
||||
# components/<feature>.py
|
||||
def <feature_action>(
|
||||
parent: tk.Misc, # 父窗口或容器
|
||||
*,
|
||||
deps: <FeatureDeps>, # 依赖注入容器
|
||||
on_line: Callable[[str], None], # 日志回调
|
||||
...
|
||||
) -> <return-type>:
|
||||
"""..."""
|
||||
```
|
||||
|
||||
依赖容器优先用 `dataclass`(命名参数太多时):
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class <FeatureDeps>:
|
||||
adb_exe: str
|
||||
ip_var: tk.StringVar
|
||||
refresh_devices: Callable[[], None]
|
||||
# ...
|
||||
```
|
||||
|
||||
### 3. 抽取 + 注入
|
||||
|
||||
- 在 `gui/components/<feature>.py` 写新函数
|
||||
- 在 `gui_app.py` 原位置:删旧闭包,import 新函数,传依赖调用
|
||||
|
||||
### 4. 验证
|
||||
|
||||
```bash
|
||||
pytest # 全部通过
|
||||
python -m py_compile gui/gui_app.py gui/components/<feature>.py
|
||||
# 手工 smoke:启动 GUI 走一遍受影响功能
|
||||
```
|
||||
|
||||
### 5. 提交
|
||||
|
||||
按 AGENTS.md 规则:
|
||||
- `git status` 检查只改了预期文件
|
||||
- `git add` 具体路径,不用 `-A`
|
||||
- commit 消息格式参考历史:`refactor(gui): 抽 <feature> 到 components/<file> (<旧行数> → <新行数>)`
|
||||
- `git push`
|
||||
|
||||
## 风险
|
||||
|
||||
| 风险 | 缓解 |
|
||||
|---|---|
|
||||
| 闭包捕获 Var 漏传 → 配置项静默丢失 | P2 用 `dataclass` 聚合 Var 引用;先写完整测试再改 |
|
||||
| GUI 交互回归(按钮回调失效等) | 每轮手工 smoke;优先抽边界清晰的 P1/P5 验证流程 |
|
||||
| `mainloop` / `after()` 调度跨闭包失效 | 显式把 `root` 或 `tk_widget.after` 当依赖传入 |
|
||||
| import 循环(components → gui_app) | components/* 不允许 import gui_app;只接收依赖参数 |
|
||||
|
||||
## 停止条件
|
||||
|
||||
满足任一即停手,向用户报告本轮成果:
|
||||
|
||||
1. `gui_app.py` ≤ 3000 行
|
||||
2. 下一个候选段需要传 ≥ 50 个独立依赖(信号:应该先把 widgets 聚成一个 `UiState`,那是另一个 spec)
|
||||
3. 抽取后 `gui_app.py` 行数下降 < 50(边际收益太小)
|
||||
4. 某轮抽取后 pytest 失败且修复需要改动多个非目标文件(信号:风险扩散,停下复盘)
|
||||
|
||||
## 实现顺序
|
||||
|
||||
按 P1 → P2 → P3 → P4 → P5 → P6,每段独立 commit。
|
||||
P2 视 P1 完成后情况评估(如果 P1 已经把主文件压到很小,P2 可推迟)。
|
||||
|
||||
## 测试策略
|
||||
|
||||
- **现有 pytest**:每轮必须保持全绿(不需要为抽取新增单测,因为是纯重构)
|
||||
- **手工 smoke**(每轮都要走一遍受影响路径):
|
||||
- P1:启动 → 打开 "WiFi ADB" 对话框 → 扫描设备 → 连接
|
||||
- P2:启动 → 修改若干配置项 → 关闭 → 重启 → 检查配置已保存
|
||||
- P3/P4:启动 → 切到「预约」/「高价值房间」Tab → 验证刷新
|
||||
- P5:启动 → 截图按钮 → 检查图片落盘
|
||||
- P6:启动 → 切到「操作日志」Tab → 搜索
|
||||
|
||||
## Out of Scope
|
||||
|
||||
- `gui/web_gui.py`(1810 行)—— 下一轮独立 spec
|
||||
- `douyin/core/*` 几个 1000+ 行业务文件 —— 下一轮独立 spec
|
||||
- 引入新的 GUI 框架或异步模式
|
||||
- 单元测试覆盖率提升
|
||||
|
||||
## Outcome(2026-05-30 实施完成)
|
||||
|
||||
**起始**:5476 行
|
||||
**结束**:178 行
|
||||
**降幅**:5298 行(-96.7%)
|
||||
**新增模块**:54 个 component 文件
|
||||
|
||||
### 主文件最终结构(178 行)
|
||||
|
||||
```
|
||||
imports 45 行 (gui_core / 14 个 components / stdlib)
|
||||
warnings 抑制 / format_gui_log_line 18 行
|
||||
def main(): ~115 行
|
||||
setup_root_window
|
||||
setup_log_pipeline ← (queue + ThreadSafeLogWriter + on_line + Runner)
|
||||
setup_top_device_bar ← (设备选择 + WiFi 工具)
|
||||
build_config_vars ← (127 个 tk Var)
|
||||
setup_left_config_area ← (PanedWindow + 7 配置 Tab + load/save IO)
|
||||
setup_right_main_area ← (Notebook + 9 Tab + actions + pump_logs)
|
||||
setup_top_buttons ← (保存配置 + 截图+OCR)
|
||||
setup_periodic_refreshers ← (启动延迟 + 周期刷新)
|
||||
setup_close_handler ← (WM_DELETE_WINDOW)
|
||||
refresh_devices() / mainloop()
|
||||
```
|
||||
|
||||
### 抽取阶段总结
|
||||
|
||||
实施分 4 个阶段:
|
||||
|
||||
**阶段 1:闭包/视图抽取(5476 → 3590 行,-34%)**
|
||||
|
||||
把 `main()` 内的内聚闭包和视图刷新函数抽到独立模块。共 17 个模块:
|
||||
wifi_adb_scan_dialog / wifi_adb_dialog / reservations_view / high_value_view /
|
||||
screenshot_action / actions_log_view / wifi_adb_pick_dialog / wifi_adb_reconnect /
|
||||
ocr_results_view / log_pump / win_record_view / preview_view /
|
||||
wifi_adb_one_click_scan / run_log_view / text_search /
|
||||
logging_config_io / run_params_builder。
|
||||
|
||||
**阶段 2:Var 聚合 + Tab UI(3590 → 1373 行,-44% → -75%)**
|
||||
|
||||
- `config_io.py`(load/save 640 行 → 1 个模块)用 dict-of-vars 模式
|
||||
- `build_config_vars()` 工厂集中创建 127 个 tk Var
|
||||
- 7 个 Tab UI(debug / logging / yanghao / reservation / run / filter / realtime)抽
|
||||
到独立 `setup_*_tab(parent, vars_=_vars_)`,直接接受 vars 全集
|
||||
|
||||
**阶段 3:右侧 Tab + 工具栏 + 模板复用(1373 → 519 行,-75% → -90.5%)**
|
||||
|
||||
- log_search_toolbar / actions_log_toolbar 用 dataclass + handles 返回
|
||||
- win_record_tab / preview_tab / log_tab 整段抽出
|
||||
- simple_tabs.py 提供 setup_simple_text_tab / setup_text_tab_with_refresh /
|
||||
setup_stats_tab / setup_actions_log_tab / setup_ocr_results_tab 复用模板
|
||||
- main_notebook / action_buttons / top_buttons / top_device_bar /
|
||||
log_pipeline / periodic_refreshers / log_text_colors / keywords_tab 全部抽出
|
||||
|
||||
**阶段 4:聚合层 + 死代码清理(519 → 178 行,-90.5% → -96.7%)**
|
||||
|
||||
最后阶段把 main() 里剩余的"装配脉络"打包成更高层组件,清理失效的导入和死注释:
|
||||
|
||||
- `setup_root_window`: ttkbootstrap fallback + root window
|
||||
- `setup_left_config_area`: PanedWindow 布局 + 7 配置 Tab + load/save IO
|
||||
- `setup_right_main_area`: Notebook + 9 Tab + actions + pump_logs
|
||||
- 删除 125 个无用的 _vars_ unpack(只保留 y_var/gui_theme_var)
|
||||
- 死注释清理 / 重复 import / 冗余 dict 字面量(_config_io_vars 复用 _vars_ 全集)
|
||||
- 重复 lambda 去重(theme_getter / _open_realtime_viewer)
|
||||
|
||||
### 抽取模式(54 个 components 按用途分类)
|
||||
|
||||
| 类型 | 模块 |
|
||||
|---|---|
|
||||
| WiFi ADB(6 个) | wifi_adb_scan_dialog / wifi_adb_dialog / wifi_adb_pick_dialog / wifi_adb_reconnect / wifi_adb_one_click_scan / top_device_bar |
|
||||
| Tab 视图(8 个) | reservations_view / high_value_view / actions_log_view / ocr_results_view / win_record_view / preview_view / run_log_view / log_pump |
|
||||
| Tab UI 容器(13 个) | run_tab / filter_tab / reservation_tab / yanghao_tab / debug_tab / logging_tab / keywords_tab / log_tab / preview_tab / win_record_tab / realtime_tab / simple_tabs / main_notebook |
|
||||
| 工具栏(2 个) | log_search_toolbar / actions_log_toolbar |
|
||||
| 配色 / 状态(3 个) | log_text_colors / text_search / screenshot_action |
|
||||
| 配置序列化(4 个) | logging_config_io / run_params_builder / config_io / config_vars |
|
||||
| 顶部 / 底部按钮(2 个) | top_buttons / action_buttons |
|
||||
| 系统调度(2 个) | log_pipeline / periodic_refreshers |
|
||||
| 高层聚合(3 个) | root_window / left_config_area / right_main_area |
|
||||
| 已有共用(11 个) | log_writer / log_viewer / log_color_config / mapping_table / mapping_utils / device_selector / actions_log_viewer / error_log_viewer / realtime_viewer / stats_formatter / __init__ |
|
||||
|
||||
### 验证
|
||||
|
||||
- 每轮抽取后 `pytest` 全绿(1374 passed),包括 `test_gui_app_smoke.py` 启动 smoke 和
|
||||
`test_gui_webui_sync.py` GUI/WebUI 配置 key 同步检查。
|
||||
- 共 7 次 pytest 失败均能定位修复(具体错误参见各次 commit message):
|
||||
- `_preview_view` 在 `update_image_list` 之前被引用
|
||||
- `enable_ocr_mode1_var` 因含数字未被正则替换(2 次)
|
||||
- `BOTH` 常量 / `ScrolledText` import 缺失
|
||||
- sync 工具锚点失效 → 让工具改读 `config_io.py` + `realtime_tab.py`
|
||||
- `image_var` 在 `setup_top_buttons` 调用时还没创建 → 调整顺序
|
||||
- 未做手工 GUI smoke(建议用户启动 GUI 走一遍 WiFi 对话框 / 各 Tab,确认无回归)。
|
||||
|
||||
### 停止原因
|
||||
|
||||
主文件已从 5476 → 178(-96.7%)。当前 main() 是清晰的"装配胶水":每个 setup_*
|
||||
调用对应一个明确的功能区。继续抽要么打散这个装配脉络,要么把整个 main 改造成
|
||||
`GuiApp` 类(MVC/MVVM),都属于另一个 spec。`pytest` 1374 全绿。
|
||||
@@ -6,6 +6,25 @@
|
||||
|
||||
说明:本文件为项目主要技术文档的重构版,聚焦“快速上手、配置规范、关键模块地图、运行与排障、验证清单”。文档同时给出可执行的诊断/采样命令,便于自动化采集与 CI 校验。
|
||||
|
||||
> **⚠️ 路径迁移说明(2026-05 之后阅读本文档时请对照)**
|
||||
>
|
||||
> 本文档主体撰写于项目大重构之前,正文里仍出现大量旧路径。重构后实际位置如下(旧 → 新):
|
||||
>
|
||||
> | 文档里写的(旧) | 当前实际位置(新) |
|
||||
> |---|---|
|
||||
> | `Underlying_Operations.py` | `douyin/core/underlying_operations.py` |
|
||||
> | `path_config.py` | `douyin/core/path_config.py` |
|
||||
> | `run_cli.py` | `bin/run_cli.py` |
|
||||
> | `gui_app.py` | `bin/gui_app.py`(launcher)/ `gui/gui_app.py`(实现) |
|
||||
> | `webgui_launcher.py` | `bin/webgui_launcher.py`(launcher)/ `gui/webgui_launcher.py`(实现) |
|
||||
> | `manage_logs.py` | `bin/manage_logs.py` |
|
||||
> | `unified_logger.py` | `douyin/logging/unified_logger.py` |
|
||||
> | `version.py` | `douyin/core/version.py` |
|
||||
> | `from Underlying_Operations import …` | `from douyin.core.underlying_operations import …` |
|
||||
> | `from path_config import …` | `from douyin.core.path_config import …` |
|
||||
>
|
||||
> 入口脚本现在统一放在 `bin/` 下,根目录已不再保留 launcher 转发。文档里所有 `python run_cli.py …` 示例命令请改读为 `python bin/run_cli.py …`,其他入口同理。
|
||||
|
||||
-- 变更记录
|
||||
- 2026-01-18: V4.5 — 修复预约更新后的循环问题,添加强制切换标志防止在同一直播间反复检测。
|
||||
- 2026-01-18: V4.4 — 修复并行OCR重试导致日志/重试噪音,参与失败自动切换直播间;购物红包像素+OCR复查(非直播间也OCR复查);并行OCR完成后写盘映射表以提升回退校验一致性;预约回退纠偏(方向提示)与二次回退改进;GUI映射表自适应列与新增购物红包阈值配置(GUI暴露)。
|
||||
@@ -133,7 +152,7 @@ PY
|
||||
|
||||
- 映射表福袋信息记录修复:
|
||||
- `douyin/fudai/douyin_fudai_core.py`:修复映射表中福袋信息记录缺失问题,在记录映射表前确保`_current_fudai_content`和`_last_fudai_detail_tuple`属性已被正确设置。
|
||||
- `fudai_detail_modules/fudai_detail_reader.py`:优化福袋详情识别完成后映射表记录时机,将并行映射表记录从OCR开始前移动到福袋详情识别完成后,确保福袋内容和详情信息完整记录到映射表。
|
||||
- `douyin/fudai/core/fudai_detail_orchestrator.py`(旧位置:`fudai_detail_modules/fudai_detail_reader.py`,2026-05 合并到 core/):优化福袋详情识别完成后映射表记录时机,将并行映射表记录从OCR开始前移动到福袋详情识别完成后,确保福袋内容和详情信息完整记录到映射表。
|
||||
|
||||
- 预约锁定期保护机制:
|
||||
- `douyin/core/douyin_fudai.py`:修复预约福袋参与成功后锁定期被提前清除的问题,实现依次参与保护机制;参与成功后检查是否还有其他预约,如果有则设置10秒保护期,确保预约福袋依次参与不被其他预约打断;如果没有其他预约则正常清除锁定期。
|
||||
@@ -187,7 +206,7 @@ else:
|
||||
|
||||
# 映射表福袋信息记录验证
|
||||
python -c "
|
||||
from fudai_detail_modules import fudai_detail_reader
|
||||
from douyin.fudai.core import fudai_detail_orchestrator as fudai_detail_reader
|
||||
import inspect
|
||||
source = inspect.getsource(fudai_detail_reader.read_fudai_detail_once)
|
||||
if 'analyser._current_fudai_content = content' in source and 'analyser._last_fudai_detail_tuple = detail_tuple' in source and '在福袋详情识别完成后记录映射表' in source:
|
||||
@@ -214,10 +233,10 @@ else:
|
||||
- 任务计数检测优化:
|
||||
- `douyin/stage/douyin_stage.py`:限制任务计数仅在触发原因 "find_and_open_fudai_detail_click_verification" 时设置,避免重复诊断。
|
||||
- `douyin/fudai/douyin_fudai_core.py`:删除备用阶段检测逻辑,默认任务计数为 0,增加警告日志。
|
||||
- `fudai_detail_modules/fudai_detail_reader.py`:默认任务计数为 0,增强警告日志输出。
|
||||
- `douyin/fudai/core/fudai_detail_orchestrator.py`(旧位置:`fudai_detail_modules/fudai_detail_reader.py`):默认任务计数为 0,增强警告日志输出。
|
||||
- 日志时间戳统一:
|
||||
- `douyin/logging/douyin_logging.py`:新增 MillisecondFormatter 类。
|
||||
- `unified_logger.py`:为 UnifiedFormatter 添加 formatTime 方法。
|
||||
- `douyin/logging/unified_logger.py`:为 UnifiedFormatter 添加 formatTime 方法。
|
||||
- `douyin/logging/action_logger.py`:更新为使用 MillisecondFormatter。
|
||||
- 截图复用优化:
|
||||
- 确保在福袋详情页关闭前复用截图,避免不必要的重复截图。
|
||||
@@ -234,10 +253,10 @@ else:
|
||||
# 语法检查
|
||||
python -m py_compile douyin/stage/douyin_stage.py
|
||||
python -m py_compile douyin/fudai/douyin_fudai_core.py
|
||||
python -m py_compile fudai_detail_modules/fudai_detail_reader.py
|
||||
python -m py_compile douyin/fudai/core/fudai_detail_orchestrator.py
|
||||
|
||||
# 运行短会话验证
|
||||
python run_cli.py --wait-minutes 0 --device-id <ADB_ID>
|
||||
python bin/run_cli.py --wait-minutes 0 --device-id <ADB_ID>
|
||||
|
||||
# 检查日志格式
|
||||
Get-Content logs/actions.log -Tail 10 | Select-String "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d{3}"
|
||||
@@ -260,13 +279,13 @@ pip install -r requirements-minimal.txt
|
||||
3. 运行主流程(单设备示例):
|
||||
|
||||
```powershell
|
||||
python run_cli.py --device-id <ADB_ID> --needswitch
|
||||
python bin/run_cli.py --device-id <ADB_ID> --needswitch
|
||||
```
|
||||
|
||||
4. 调试单次循环:
|
||||
|
||||
```powershell
|
||||
python run_cli.py --device-id <ADB_ID> --wait-minutes 0
|
||||
python bin/run_cli.py --device-id <ADB_ID> --wait-minutes 0
|
||||
```
|
||||
|
||||
说明:如需快速禁用 OCR 启动耗时,可设置环境变量 `SKIP_OCR_INIT=1`。
|
||||
@@ -288,13 +307,13 @@ python run_cli.py --device-id <ADB_ID> --wait-minutes 0
|
||||
1. 代码内默认值(常量/类属性)
|
||||
2. `config/config.json`(通过 `path_config.get_config_path()` 获取)
|
||||
3. 环境变量(例如 `SKIP_OCR_INIT`, `DISABLE_SCREENSHOT_MIRROR`)
|
||||
4. 命令行参数(`run_cli.py` 解析,优先级最高,运行时覆盖实例属性)
|
||||
4. 命令行参数(`bin/run_cli.py` 解析,优先级最高,运行时覆盖实例属性)
|
||||
|
||||
示例:通过命令行临时指定设备优先于 `config/config.json` 中的默认设备。
|
||||
|
||||
实现建议与样例:
|
||||
|
||||
- 在 `douyin/utils/douyin_config.py` 中实现 `load_config_from_file(path)` 返回 dict,主流程使用该 dict 初始化分析器并在 `run_cli.py` 中用命令行覆盖字段。
|
||||
- 在 `douyin/utils/douyin_config.py` 中实现 `load_config_from_file(path)` 返回 dict,主流程使用该 dict 初始化分析器并在 `bin/run_cli.py` 中用命令行覆盖字段。
|
||||
- 推荐在 `config/config.json` 中采用明确分组,例如:
|
||||
|
||||
```json
|
||||
@@ -305,7 +324,7 @@ python run_cli.py --device-id <ADB_ID> --wait-minutes 0
|
||||
}
|
||||
```
|
||||
|
||||
- 命令行覆盖示例(`run_cli.py` 中解析后合并):
|
||||
- 命令行覆盖示例(`bin/run_cli.py` 中解析后合并):
|
||||
|
||||
```python
|
||||
# pseudo
|
||||
@@ -318,7 +337,7 @@ if args.device_id:
|
||||
- 使用代码内默认值并在日志中写 warning;
|
||||
- 在关键字段(如 `device`、`ocr_engine`)缺失时中断并提示用户。
|
||||
|
||||
关联文件:`config/config.json`,`douyin/utils/douyin_config.py`,`path_config.py`,`run_cli.py`。
|
||||
关联文件:`config/config.json`,`douyin/utils/douyin_config.py`,`douyin/core/path_config.py`,`bin/run_cli.py`。
|
||||
|
||||
## 截图 / OCR / 日志 / 状态(实现细节与故障采样)
|
||||
|
||||
@@ -326,12 +345,12 @@ if args.device_id:
|
||||
|
||||
- 优先方式:`adb exec-out screencap -p`(单次 adb 调用,速度最快)。
|
||||
- 回退方式:`adb shell screencap -p /sdcard/screen.png` + `adb pull`(兼容性但更慢)。
|
||||
- 写入策略:先写入临时文件(例如 `screenshot.png.tmp`),再通过原子替换或安全复制覆盖 `pic/screenshot.png`,以避免并发读取到半写入文件。见 `Underlying_Operations.get_screenshot()` 的实现。
|
||||
- 写入策略:先写入临时文件(例如 `screenshot.png.tmp`),再通过原子替换或安全复制覆盖 `pic/screenshot.png`,以避免并发读取到半写入文件。见 `underlying_operations.get_screenshot()` 的实现。
|
||||
- Windows 文件锁与镜像:`_safe_replace_file()` 包含多重回退(`os.replace` → `shutil.copy2` → 分块复制),并可通过环境变量 `DISABLE_SCREENSHOT_MIRROR=1` 禁用将截图镜像到外部目录(`EXTERNAL_DOUYIN_FUDAI_DIR`)。
|
||||
|
||||
2) OCR(策略与初始化)
|
||||
|
||||
- 优先引擎:EasyOCR(速度与准确性通常最佳);回退:PaddleOCR。实现位于 `Underlying_Operations.analyse_pic_word()`。
|
||||
- 优先引擎:EasyOCR(速度与准确性通常最佳);回退:PaddleOCR。实现位于 `underlying_operations.analyse_pic_word()`。
|
||||
- 延迟初始化:支持 `SKIP_OCR_INIT=1`(跳过启动时初始化),首次调用时会在 `_ensure_ocr()` 进行按需初始化。
|
||||
- 回退与容错:若 OCR 未能初始化或识别失败,函数返回空字符串,上层代码需对空结果做容错与重试。建议生产环境安装 `easyocr` 并允许启动时初始化以减少首次延迟。
|
||||
|
||||
@@ -362,7 +381,7 @@ Remove-Item pic\screenshot.png.tmp -Force -ErrorAction SilentlyContinue
|
||||
- OCR 未初始化或识别异常:
|
||||
|
||||
```python
|
||||
from Underlying_Operations import underlying_operations
|
||||
from douyin.core.underlying_operations import underlying_operations
|
||||
op = underlying_operations()
|
||||
op._ensure_ocr()
|
||||
print(op.analyse_pic_word('pic/screenshot.png'))
|
||||
@@ -382,7 +401,7 @@ print(op.analyse_pic_word('pic/screenshot.png'))
|
||||
1) 在短时间窗口运行主流程以生成调试图片和日志(注意 `debug_captures.enabled`):
|
||||
|
||||
```powershell
|
||||
python run_cli.py --device-id <ADB_ID> --wait-minutes 1
|
||||
python bin/run_cli.py --device-id <ADB_ID> --wait-minutes 1
|
||||
```
|
||||
|
||||
2) 基于日志时间戳筛选 `pic/` 下的候选图片(示例:按文件修改时间):
|
||||
@@ -419,14 +438,14 @@ powershell -Command "Get-Content tools/coords_report.csv -TotalCount 200 | Out-F
|
||||
python -m py_compile $(git ls-files "**/*.py")
|
||||
```
|
||||
|
||||
- 关键文件存在性检查:确保 `run_cli.py`、`Underlying_Operations.py`、`config/config.json`、`path_config.py` 存在并可被导入。
|
||||
- 关键文件存在性检查:确保 `bin/run_cli.py`、`douyin/core/underlying_operations.py`、`config/config.json`、`douyin/core/path_config.py` 存在并可被导入。
|
||||
|
||||
示例 CI 脚本片段:
|
||||
|
||||
```bash
|
||||
python -m py_compile $(git ls-files "**/*.py") || exit 1
|
||||
python - <<'PY'
|
||||
from path_config import get_reservations_path
|
||||
from douyin.core.path_config import get_reservations_path
|
||||
import os
|
||||
print('reservations path', get_reservations_path())
|
||||
assert os.path.isdir(os.path.dirname(get_reservations_path()))
|
||||
@@ -440,14 +459,14 @@ PY
|
||||
- 项目意图(一句话):自动化在抖音直播中查找并参与“福袋”活动的流程化机器人,包含截图、像素/模板检测、OCR、决策与预约管理。
|
||||
|
||||
- 关键入口(按优先级):
|
||||
- `run_cli.py`:CLI 入口,生成 `fudai_analyse` 实例并开始主循环;适合触发最小可运行示例。
|
||||
- `bin/run_cli.py`:CLI 入口,生成 `fudai_analyse` 实例并开始主循环;适合触发最小可运行示例。
|
||||
- `douyin/core/douyin_fudai.py::fudai_choujiang()`:主循环调度;查看运行状态与错误堆栈。
|
||||
- `Underlying_Operations.py`:底层设备接口(截图、裁剪、OCR)— 对外数据采集点。
|
||||
- `douyin/core/underlying_operations.py`:底层设备接口(截图、裁剪、OCR)— 对外数据采集点。
|
||||
|
||||
- 可调用的“程序式”API(Python)示例:
|
||||
|
||||
```python
|
||||
from Underlying_Operations import underlying_operations
|
||||
from douyin.core.underlying_operations import underlying_operations
|
||||
op = underlying_operations()
|
||||
# 获取当前截图路径
|
||||
img = op.get_screenshot('<ADB_ID>')
|
||||
@@ -456,7 +475,7 @@ text = op.analyse_pic_word(img)
|
||||
```
|
||||
|
||||
- 关键文件与含义速查表(便于 LLM 快速定位实现细节):
|
||||
- `path_config.py`:统一路径(logs/pic/state)——用于定位运行数据。
|
||||
- `douyin/core/path_config.py`:统一路径(logs/pic/state)——用于定位运行数据。
|
||||
- `douyin/logging/douyin_logging_wrapper.py`:业务日志封装——搜索 `traceId` 与 `stage`。
|
||||
|
||||
- 可观测数据(建议供 AI 检索):
|
||||
@@ -486,22 +505,22 @@ text = op.analyse_pic_word(img)
|
||||
|
||||
6) 参考实现与文件链接
|
||||
|
||||
- 截图与裁剪:`Underlying_Operations.get_screenshot()`、`Underlying_Operations.cut_pic()`。
|
||||
- OCR:`Underlying_Operations.analyse_pic_word()`、`Underlying_Operations.analyse_pic_digits()`。
|
||||
- 截图与裁剪:`underlying_operations.get_screenshot()`、`underlying_operations.cut_pic()`。
|
||||
- OCR:`underlying_operations.analyse_pic_word()`、`underlying_operations.analyse_pic_digits()`。
|
||||
- 日志:`douyin/logging/douyin_logging.py`、`douyin/logging/douyin_logging_wrapper.py`。
|
||||
- 路径与状态:`path_config.py`、`state/reservations.json`。
|
||||
- 路径与状态:`douyin/core/path_config.py`、`state/reservations.json`。
|
||||
|
||||
以上补充将帮助运维快速定位截图/OCR/日志相关问题并提供明确采样路径供后续模型/规则优化使用。
|
||||
|
||||
## 核心模块地图(快捷索引)
|
||||
|
||||
- `run_cli.py`:入口,解析命令行并创建 `fudai_analyse`。
|
||||
- `bin/run_cli.py`:入口,解析命令行并创建 `fudai_analyse`。
|
||||
- `douyin/core/douyin_fudai.py`:主分析器/主循环(`fudai_choujiang`、`run_once_basic`)。
|
||||
- `Underlying_Operations.py`:底层设备/截图/OCR/文件操作。
|
||||
- `douyin/core/underlying_operations.py`:底层设备/截图/OCR/文件操作。
|
||||
- `douyin/detection/douyin_pixel.py`:像素检测与并行检测实现。
|
||||
|
||||
- `douyin/fudai/douyin_fudai_core.py`:福袋核心逻辑。
|
||||
- `get_fudai_contain`:获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。调用位置:`douyin/fudai/core/fudai_attend.py` 第214行,`fudai_detail_modules/fudai_detail_reader.py` 第15行和第315行。
|
||||
- `get_fudai_contain`:获取福袋的内容和倒计时(从 `fudai_analyse.get_fudai_contain` 抽离)。调用位置:`douyin/fudai/core/fudai_attend.py`、`douyin/fudai/core/fudai_detail_orchestrator.py`(旧位置:`fudai_detail_modules/fudai_detail_reader.py`,已合并到 core/)。具体行号会随重构变化,以代码当前状态为准。
|
||||
- `basic_join_decision`:基础版参与决策,根据配置筛选福袋,满足条件则尝试参与抽奖或记录高价值预约。调用位置:`douyin/core/douyin_fudai.py` 第3127行和第3721行。
|
||||
- `attend_choujiang`:点击参与抽奖。调用位置:`douyin/core/douyin_fudai.py` 第2892行,`douyin/core/fudai_modules/fudai_main_logic.py` 第223行,以及文件内多处。
|
||||
- `check_lucky_draw_result`:判定福袋抽奖的结果(简化)。统一只检测开奖结果按钮区域(使用 HelperFunctions.check_lottery_result_by_ocr),不再对弹窗文字或其它区域进行OCR识别。返回:1='我知道了', 2='立即领取奖品', False=未识别。调用位置:文件内第3913行。
|
||||
@@ -527,7 +546,7 @@ text = op.analyse_pic_word(img)
|
||||
|
||||
- `douyin/stage/douyin_stage.py`:阶段诊断入口(`diagnose_stage_from_current_screen`)。
|
||||
- `douyin/reservation/douyin_reservation_logic.py`:预约加载与回退处理。
|
||||
- `path_config.py`:统一路径获取,避免硬编码。
|
||||
- `douyin/core/path_config.py`:统一路径获取,避免硬编码。
|
||||
|
||||
在文档中引用这些文件并包含小示例会帮助维护者快速定位实现点。
|
||||
|
||||
@@ -573,7 +592,7 @@ text = op.analyse_pic_word(img)
|
||||
|
||||
## 运行流程概览(精简)
|
||||
|
||||
1. `run_cli.py` -> 创建 `fudai_analyse` -> `load_config()` -> `fudai_choujiang()`
|
||||
1. `bin/run_cli.py` -> 创建 `fudai_analyse` -> `load_config()` -> `fudai_choujiang()`
|
||||
2. `fudai_choujiang()` 循环调用 `run_once_basic()`
|
||||
3. `run_once_basic()` 流程要点:
|
||||
- 处理等待开奖 / 预约回退
|
||||
@@ -586,7 +605,7 @@ text = op.analyse_pic_word(img)
|
||||
1. 验证截图是否可用:
|
||||
|
||||
```powershell
|
||||
python -c "from Underlying_Operations import underlying_operations; op=underlying_operations(); print(op.get_screenshot('<DEVICE_ID>'))"
|
||||
python -c "from douyin.core.underlying_operations import underlying_operations; op=underlying_operations(); print(op.get_screenshot('<DEVICE_ID>'))"
|
||||
```
|
||||
|
||||
2. 快速语法检查(仓库级):
|
||||
@@ -599,7 +618,7 @@ python -m py_compile $(git ls-files "**/*.py")
|
||||
|
||||
```powershell
|
||||
# 伪命令示例:运行一段短时日志以产生调试图片
|
||||
python run_cli.py --device-id <ADB_ID> --wait-minutes 1
|
||||
python bin/run_cli.py --device-id <ADB_ID> --wait-minutes 1
|
||||
# 手动或团队自定义脚本筛选 pic/ 下的失败图片并复制到约定目录(例如 tools/samples/)
|
||||
```
|
||||
|
||||
@@ -620,7 +639,7 @@ python run_cli.py --device-id <ADB_ID> --wait-minutes 1
|
||||
## 验证清单(可纳入 CI)
|
||||
|
||||
1. `python -m py_compile` 全仓库通过。
|
||||
2. 关键路径存在检查:`run_cli.py`、`Underlying_Operations.py`、`config/config.json`、`path_config.py`。
|
||||
2. 关键路径存在检查:`bin/run_cli.py`、`douyin/core/underlying_operations.py`、`config/config.json`、`douyin/core/path_config.py`。
|
||||
3. `path_config.get_reservations_path()` 返回文件夹存在性检查。
|
||||
|
||||
示例 CI 命令片段:
|
||||
@@ -628,7 +647,7 @@ python run_cli.py --device-id <ADB_ID> --wait-minutes 1
|
||||
```bash
|
||||
python -m py_compile $(git ls-files "**/*.py") || exit 1
|
||||
python - <<'PY'
|
||||
from path_config import get_reservations_path
|
||||
from douyin.core.path_config import get_reservations_path
|
||||
import os
|
||||
print('reservations path', get_reservations_path())
|
||||
assert os.path.isdir(os.path.dirname(get_reservations_path()))
|
||||
@@ -941,7 +960,7 @@ _handle_in_fudai_detail()
|
||||
|
||||
#### `run_cli.py::main(argv: list[str]) -> int`
|
||||
|
||||
- **文件位置**: `run_cli.py`
|
||||
- **文件位置**: `bin/run_cli.py`
|
||||
- **作用**: 命令行入口函数,解析参数并启动主程序
|
||||
- **参数**:
|
||||
- `argv`: 命令行参数列表
|
||||
@@ -1860,7 +1879,7 @@ def attend_choujiang(analyser) -> bool:
|
||||
```python
|
||||
def load_reservations_from_state(analyser) -> list:
|
||||
import json
|
||||
import path_config
|
||||
from douyin.core import path_config
|
||||
|
||||
reservations_path = path_config.get_reservations_path()
|
||||
if not os.path.exists(reservations_path):
|
||||
@@ -2250,19 +2269,19 @@ is_match, reason, debug = match_reservation(item, detail)
|
||||
|
||||
## 5. 底层操作函数
|
||||
|
||||
底层操作函数封装在 `Underlying_Operations.py` 的 `underlying_operations` 类中,提供设备控制、截图、OCR、图像处理等基础功能。
|
||||
底层操作函数封装在 `douyin/core/underlying_operations.py` 的 `underlying_operations` 类中,提供设备控制、截图、OCR、图像处理等基础功能。
|
||||
|
||||
### 5.1 设备操作函数
|
||||
|
||||
#### `underlying_operations.select_device() -> str | bool`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 选择需要连接的Android设备
|
||||
- **参数**: 无
|
||||
- **返回值**:
|
||||
- `str`: 设备ID(单设备或多设备选择后)
|
||||
- `False`: 无设备连接
|
||||
- **调用位置**: `run_cli.py` 的 `main()` 函数中调用
|
||||
- **调用位置**: `bin/run_cli.py` 的 `main()` 函数中调用
|
||||
- **实现细节**:
|
||||
- 执行 `adb devices` 命令获取设备列表
|
||||
- 使用正则表达式提取设备ID(支持IP地址和序列号)
|
||||
@@ -2281,7 +2300,7 @@ if not device_id:
|
||||
|
||||
#### `underlying_operations.get_device_resolution(device_id: str) -> Tuple[int, int]`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 获取Android设备的分辨率
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2301,7 +2320,7 @@ analyser.resolution_ratio_y = height
|
||||
|
||||
#### `underlying_operations.click(device_id: str, x: int, y: int) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 在设备屏幕上点击指定坐标
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2320,7 +2339,7 @@ operation.click(device_id, 540, 1200) # 点击屏幕中心
|
||||
|
||||
#### `underlying_operations.click_back(device_id: str) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 点击Android返回键(KEYCODE_BACK)
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2331,7 +2350,7 @@ operation.click(device_id, 540, 1200) # 点击屏幕中心
|
||||
|
||||
#### `underlying_operations.click_confirm(device_id: str) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 点击确认键(KEYCODE_ENTER)
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2344,7 +2363,7 @@ operation.click(device_id, 540, 1200) # 点击屏幕中心
|
||||
|
||||
#### `underlying_operations.get_screenshot(device_id: str, path: str = "pic") -> bool`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 获取设备屏幕截图并保存到本地
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2380,7 +2399,7 @@ else:
|
||||
|
||||
#### `underlying_operations.save_reward_pic(device_id: str) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 保存中奖截图(带时间戳)
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2395,7 +2414,7 @@ else:
|
||||
|
||||
#### `underlying_operations.cut_pic(left_up: Tuple[int, int] = (0, 63), right_down: Tuple[int, int] = (1080, 1620), target: str = "", name: str = "") -> bool`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 裁剪图片,获取指定区域的子图片(用于OCR识别)
|
||||
- **参数**:
|
||||
- `left_up: Tuple[int, int]`: 左上角坐标(默认(0, 63))
|
||||
@@ -2432,7 +2451,7 @@ else:
|
||||
|
||||
#### `underlying_operations.analyse_pic_word(picname: str, change_color: int = 0, pic_path: Optional[str] = None) -> str`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 对指定图片运行OCR识别,返回拼接后的文本结果
|
||||
- **参数**:
|
||||
- `picname: str`: 图片名称(不含扩展名,如"福袋内容")
|
||||
@@ -2475,7 +2494,7 @@ else:
|
||||
|
||||
#### `underlying_operations.analyse_pic_digits(picname: str, change_color: int = 1, pic_path: Optional[str] = None) -> str`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 对指定图片运行OCR识别,专门用于识别数字(倒计时、价值、参与人数等)
|
||||
- **参数**:
|
||||
- `picname: str`: 图片名称(不含扩展名,如"倒计时")
|
||||
@@ -2496,7 +2515,7 @@ countdown_text = operation.analyse_pic_digits("倒计时")
|
||||
|
||||
#### `underlying_operations.extract_ocr_content(content: List, return_confidence: bool = False) -> str | Tuple[str, float]`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 从OCR结果中提取文本内容(去除坐标、置信度等信息)
|
||||
- **参数**:
|
||||
- `content: List`: OCR原始结果(EasyOCR或PaddleOCR格式)
|
||||
@@ -2515,7 +2534,7 @@ countdown_text = operation.analyse_pic_digits("倒计时")
|
||||
|
||||
#### `underlying_operations.swipe(device_id: str, x1: int, y1: int, x2: int, y2: int, duration_ms: int = 600) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 在设备屏幕上执行滑动操作(从起点滑动到终点)
|
||||
- **参数**:
|
||||
- `device_id: str`: 设备ID
|
||||
@@ -2543,7 +2562,7 @@ operation.swipe(device_id, 540, 1800, 540, 800, duration_ms=600)
|
||||
|
||||
#### `underlying_operations.delay(seconds: float = 1.0) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 延迟指定秒数
|
||||
- **参数**:
|
||||
- `seconds: float`: 延迟秒数(默认1.0秒)
|
||||
@@ -2552,7 +2571,7 @@ operation.swipe(device_id, 540, 1800, 540, 800, duration_ms=600)
|
||||
|
||||
#### `underlying_operations.random_delay(min_seconds: float = 1.0, max_seconds: float = 100.0) -> None`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 随机延迟指定范围内的秒数(模拟人工操作)
|
||||
- **参数**:
|
||||
- `min_seconds: float`: 最小延迟秒数(默认1.0秒)
|
||||
@@ -2562,7 +2581,7 @@ operation.swipe(device_id, 540, 1800, 540, 800, duration_ms=600)
|
||||
|
||||
#### `underlying_operations.check_countdown(last_time: str = "") -> Optional[int]`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 检查倒计时文本,转换为剩余秒数
|
||||
- **参数**:
|
||||
- `last_time: str`: 倒计时文本(格式:`mm:ss` 或 `m:ss` 或 `ss`)
|
||||
@@ -2582,7 +2601,7 @@ remaining_seconds = operation.check_countdown(countdown_text)
|
||||
|
||||
#### `underlying_operations.get_current_hour() -> int`
|
||||
|
||||
- **文件位置**: `Underlying_Operations.py`
|
||||
- **文件位置**: `douyin/core/underlying_operations.py`
|
||||
- **作用**: 获取当前时间的小时数(0-23)
|
||||
- **参数**: 无
|
||||
- **返回值**: `int` - 当前小时数(0-23)
|
||||
@@ -2916,7 +2935,7 @@ class fudai_analyse(
|
||||
- `needswitch: bool` - 是否允许切换直播间
|
||||
- `wait_minutes: int` - 每次循环等待时间(分钟)
|
||||
- **实现**: 设置设备ID和配置,然后循环调用 `run_once_basic()`
|
||||
- **调用位置**: `run_cli.py` 的 `main()` 函数中调用
|
||||
- **调用位置**: `bin/run_cli.py` 的 `main()` 函数中调用
|
||||
|
||||
#### 6.2.7 BaseFudaiMixin(基础混入类)
|
||||
|
||||
@@ -3030,7 +3049,7 @@ UNKNOWN = "UNKNOWN" # 未知阶段
|
||||
|
||||
配置文件位于 `config/config.json`,路径通过 `path_config.get_config_path()` 获取。
|
||||
|
||||
### 7.1.1 `path_config.py` 用法
|
||||
### 7.1.1 `douyin/core/path_config.py` 用法
|
||||
|
||||
- 使用 `path_config.get_config_path()` 获取配置文件的绝对路径;
|
||||
- 常用路径获取函数:
|
||||
@@ -3047,9 +3066,9 @@ UNKNOWN = "UNKNOWN" # 未知阶段
|
||||
1. 代码中内置的默认值(类属性或常量);
|
||||
2. `config/config.json`(通过 `path_config.get_config_path()` 指定的文件);
|
||||
3. 环境变量(仅少数开关被代码显式读取,如 `SKIP_OCR_INIT`, `EXTERNAL_DOUYIN_FUDAI_DIR`, `DISABLE_MODEL_SOURCE_CHECK`, `DISABLE_SCREENSHOT_MIRROR` 等);
|
||||
4. 命令行参数(`run_cli.py` 中解析的参数,会在创建 `fudai_analyse` 实例后覆盖运行时属性——命令行优先级最高)。
|
||||
4. 命令行参数(`bin/run_cli.py` 中解析的参数,会在创建 `fudai_analyse` 实例后覆盖运行时属性——命令行优先级最高)。
|
||||
|
||||
说明:实际运行时 `fudai_analyse.__init__()` 会加载 `config.json`(若存在),随后 `run_cli.py` 会将命令行参数按需覆盖分析器属性;因此临时调试请优先使用命令行参数,长期配置请写入 `config/config.json`。
|
||||
说明:实际运行时 `fudai_analyse.__init__()` 会加载 `config.json`(若存在),随后 `bin/run_cli.py` 会将命令行参数按需覆盖分析器属性;因此临时调试请优先使用命令行参数,长期配置请写入 `config/config.json`。
|
||||
|
||||
|
||||
### 7.2 配置项详解
|
||||
@@ -3940,7 +3959,7 @@ logger.error(
|
||||
```python
|
||||
# run_cli.py
|
||||
from douyin.core.douyin_fudai import fudai_analyse
|
||||
from Underlying_Operations import underlying_operations
|
||||
from douyin.core.underlying_operations import underlying_operations
|
||||
|
||||
# 初始化
|
||||
operation = underlying_operations()
|
||||
@@ -4673,7 +4692,7 @@ self.new_config_item = self.config.get("new_config_item", False)
|
||||
|
||||
#### 15.1.1 入口文件
|
||||
|
||||
- **`run_cli.py`**: 命令行入口,初始化设备和分析器
|
||||
- **`bin/run_cli.py`**: 命令行入口,初始化设备和分析器
|
||||
- **`gui/gui_app.py`**: Tkinter GUI入口
|
||||
- **`gui/web_gui.py`**: Web GUI入口
|
||||
|
||||
@@ -4706,7 +4725,7 @@ self.new_config_item = self.config.get("new_config_item", False)
|
||||
|
||||
#### 15.1.7 底层操作
|
||||
|
||||
- **`Underlying_Operations.py`**: 底层操作类(ADB、OCR、图像处理)
|
||||
- **`douyin/core/underlying_operations.py`**: 底层操作类(ADB、OCR、图像处理)
|
||||
|
||||
#### 15.1.8 配置文件
|
||||
|
||||
@@ -7097,13 +7116,13 @@ debug_logger.log_exception(e, context={"step": "处理福袋"})
|
||||
示例:快速启用截图镜像并保留调试图像(Linux/WSL 或 PowerShell 环境变量用法相似)
|
||||
|
||||
```bash
|
||||
EXTERNAL_DOUYIN_FUDAI_DIR=/mnt/share/douyin_debug SKIP_OCR_INIT=1 python run_cli.py --device-id <DEVICE_ID> --needswitch
|
||||
EXTERNAL_DOUYIN_FUDAI_DIR=<外部调试目录> SKIP_OCR_INIT=1 python bin/run_cli.py --device-id <DEVICE_ID> --needswitch
|
||||
```
|
||||
|
||||
示例:禁用截图镜像以提高性能
|
||||
|
||||
```bash
|
||||
DISABLE_SCREENSHOT_MIRROR=1 python run_cli.py --device-id <DEVICE_ID>
|
||||
DISABLE_SCREENSHOT_MIRROR=1 python bin/run_cli.py --device-id <DEVICE_ID>
|
||||
```
|
||||
|
||||
|
||||
@@ -7197,7 +7216,7 @@ result = analyser.operation.analyse_pic_word(preprocessed_name, 0)
|
||||
|
||||
#### 24.2.2 OCR识别优化
|
||||
|
||||
**文件位置**: `Underlying_Operations.py`
|
||||
**文件位置**: `douyin/core/underlying_operations.py`
|
||||
|
||||
**优化措施**:
|
||||
|
||||
@@ -7361,4 +7380,3 @@ def get_fudai_contain(analyser, renwu: int = 2):
|
||||
- 第24章:OCR预处理和优化详解
|
||||
- 第25章:路径配置系统详解
|
||||
- 第26章:文本处理工具函数详解
|
||||
|
||||