This repository has been archived by the owner on Nov 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path__init__.py
2276 lines (2025 loc) · 67.8 KB
/
__init__.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import inspect
import os
import random
import re
import subprocess
from copy import deepcopy
from typing import Any, Union
import psutil
import regex
from flatten_everything import flatten_everything
import keyboard as keyboard__
from generate_random_values_in_range import randomize_number
from sendevent_touch import SendEventTouch
from PrettyColorPrinter import add_printer
import pandas as pd
from a_pandas_ex_string_to_dtypes import pd_add_string_to_dtypes
import cv2
from a_cv_imwrite_imread_plus import add_imwrite_plus_imread_plus_to_cv2
add_imwrite_plus_imread_plus_to_cv2()
from a_cv2_imshow_thread import add_imshow_thread_to_cv2
add_imshow_thread_to_cv2()
from a_pandas_ex_plode_tool import qq_s_isnan
from shapely.geometry import Polygon
pd_add_string_to_dtypes()
add_printer(True)
from time import strftime
timest = lambda: strftime("%Y_%m_%d_%H_%M_%S")
from a_pandas_ex_xml2df import pd_add_read_xml_files
import numpy as np
pd_add_read_xml_files()
def copy_func(f):
if callable(f):
if inspect.ismethod(f) or inspect.isfunction(f):
g = lambda *args, **kwargs: f(*args, **kwargs)
t = list(filter(lambda prop: not ("__" in prop), dir(f)))
i = 0
while i < len(t):
setattr(g, t[i], getattr(f, t[i]))
i += 1
return g
dcoi = deepcopy([f])
return dcoi[0]
class FlexiblePartial:
def __init__(self, func: Any, this_args_first: bool = True, *args, **kwargs):
self.this_args_first = this_args_first
try:
self.f = copy_func(func)
except Exception:
self.f = func
try:
self.args = copy_func(list(args))
except Exception:
self.args = args
try:
self.kwargs = copy_func(kwargs)
except Exception:
try:
self.kwargs = kwargs.copy()
except Exception:
self.kwargs = kwargs
def __call__(self, *args, **kwargs):
newdic = {}
newdic.update(self.kwargs)
newdic.update(kwargs)
if self.this_args_first:
return self.f(*self.args, *args, **newdic)
else:
return self.f(*args, *self.args, **newdic)
def __str__(self):
return "()"
def __repr__(self):
return "()"
def cropimage(img, coords):
return img[coords[1] : coords[3], coords[0] : coords[2]].copy()
def get_screenshot_adb(
adb_executable, deviceserial,
):
with subprocess.Popen(
f"{adb_executable} -s {deviceserial} shell screencap -p", stdout=subprocess.PIPE
) as p:
output = p.stdout.read()
png_screenshot_data = output.replace(b"\r\n", b"\n")
images = cv2.imdecode(
np.frombuffer(png_screenshot_data, np.uint8), cv2.IMREAD_COLOR
)
images = cv2.imread_plus(images, channels_in_output=3)
return images
def connect_to_adb(adb_path, deviceserial):
_ = subprocess.run(f"{adb_path} start-server", capture_output=True, shell=False)
_ = subprocess.run(
f"{adb_path} connect {deviceserial}", capture_output=True, shell=False
)
def get_label(va):
try:
stripped = va.strip("#")
return pd.Series([stripped, int(stripped, base=16)])
except Exception:
return pd.Series([pd.NA, pd.NA])
def get_label_1(va):
try:
stripped = va.strip("#")
return int(stripped, base=16)
except Exception:
return pd.NA
def execute_adb_command(
cmd: str, subcommands: list, exit_keys: str = "ctrl+x", end_of_printline: str = ""
) -> list:
if isinstance(subcommands, str):
subcommands = [subcommands]
elif isinstance(subcommands, tuple):
subcommands = list(subcommands)
popen = None
def run_subprocess(cmd):
nonlocal popen
def kill_process():
nonlocal popen
try:
print("Killing the process")
p = psutil.Process(popen.pid)
p.kill()
try:
if exit_keys in keyboard__.__dict__["_hotkeys"]:
keyboard__.remove_hotkey(exit_keys)
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
if exit_keys not in keyboard__.__dict__["_hotkeys"]:
keyboard__.add_hotkey(exit_keys, kill_process)
DEVNULL = open(os.devnull, "wb")
try:
popen = subprocess.Popen(
cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
universal_newlines=True,
stderr=DEVNULL,
shell=False,
)
for subcommand in subcommands:
if isinstance(subcommand, bytes):
subcommand = subcommand.rstrip(b"\n") + b"\n"
subcommand = subcommand.decode("utf-8", "replace")
else:
subcommand = subcommand.rstrip("\n") + "\n"
popen.stdin.write(subcommand)
popen.stdin.close()
for stdout_line in iter(popen.stdout.readline, ""):
try:
yield stdout_line
except Exception as Fehler:
continue
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
# print(Fehler)
try:
popen.stdout.close()
return_code = popen.wait()
except Exception as Fehler:
yield ""
proxyresults = []
try:
for proxyresult in run_subprocess(cmd):
proxyresults.append(proxyresult)
print(proxyresult, end=end_of_printline)
except KeyboardInterrupt:
try:
p = psutil.Process(popen.pid)
p.kill()
popen = None
except Exception as da:
pass
# print(da)
try:
if popen is not None:
p = psutil.Process(popen.pid)
p.kill()
except Exception as da:
pass
try:
if exit_keys in keyboard__.__dict__["_hotkeys"]:
keyboard__.remove_hotkey(exit_keys)
except Exception:
try:
keyboard__.unhook_all_hotkeys()
except Exception:
pass
return proxyresults
def get_screenwidth(adb_path, deviceserial):
try:
screenwidth, screenheight = (
subprocess.run(
fr'{adb_path} -s {deviceserial} shell dumpsys window | grep cur= |tr -s " " | cut -d " " -f 4|cut -d "=" -f 2',
shell=True,
capture_output=True,
)
.stdout.decode("utf-8", "ignore")
.strip()
.split("x")
)
screenwidth, screenheight = int(screenwidth), int(screenheight)
return screenwidth, screenheight
except Exception:
vax = subprocess.run(f'{adb_path} -s {deviceserial} shell dumpsys display', capture_output=True, shell=True)
vax = vax.stdout.splitlines()
vaxre = re.compile(rb'mBaseDisplayInfo.*width=\b(\d+)\b.*height=\b(\d+)\b', flags=re.I)
scw, sch = 1280, 720
for v in vax:
fd = (vaxre.findall(v))
if fd:
try:
print(v)
scw, sch = int(fd[0][0]), int(fd[0][1])
break
except Exception:
continue
return scw, sch
def dumpsys_to_df(adb_path, deviceserial):
activ = execute_adb_command(
f"{adb_path} -s {deviceserial} shell", subcommands=["dumpsys activity top -c"]
)
activewinow = "\n".join(activ)
activewinow2 = list(
flatten_everything(
[
k.splitlines()
for k in flatten_everything(
[
(
regex.findall(
r"View Hierarchy:.*[\r\n]\s{4}Looper",
activewinow,
flags=regex.DOTALL,
)
)
]
)
]
)
)
if not any(activewinow2):
activewinow2 = list(
flatten_everything(
[
k.splitlines()
for k in flatten_everything(
[
(
regex.findall(
r"View Hierarchy:.*\{[^\}]+\}\s*[\r\n]+",
activewinow,
flags=regex.DOTALL,
)
)
]
)
]
)
)
activewinow3 = [x for x in activewinow2 if regex.search(r"\}\s*$", x) is not None]
df = pd.DataFrame(activewinow3)
df.columns = ["hiera"]
spaces = df.hiera.str.extract(r"^(\s+)")[0]
abslen = spaces.str.len()
abslenwithoutmen = abslen - abslen.min()
level = abslenwithoutmen // 2
df = pd.concat([df, level], ignore_index=True, axis=1)
df.columns = ["hiera", "level"]
widgettype = df.hiera.str.extractall(r"^\s+([^{]+)").reset_index(drop=True)
df = pd.concat([df, widgettype], axis=1).rename(columns={0: "widget_type"}).copy()
return df, activewinow
def get_detailed_info_sep(df):
detailedinformationtogether = df.hiera.str.extractall(
r"^\s+[^{]+\{([^\}]+)"
).reset_index(drop=True)
detailedinformationsep = (
detailedinformationtogether[0].str.split(n=5, regex=False, expand=True).copy()
)
detailedinformationsep[1] = detailedinformationsep[1].apply(
lambda x: (str(x).replace('None', '') + "..........")[:9]
)
detailedinformationsep[2] = detailedinformationsep[2].apply(
lambda x: (str(x).replace('None', '') + "..........")[:8]
)
return detailedinformationsep
def get_widget_coords(detailedinformationsep):
widgetcoords = (
detailedinformationsep[3]
.str.strip()
.str.extractall(r"^(-?\d+),(-?\d+)-?(-?\d+),(-?\d+)")
.reset_index(drop=True)
.astype("string")
.astype("Int64")
.rename(columns={0: "x_start", 1: "y_start", 2: "x_end", 3: "y_end"})
.copy()
)
return widgetcoords
def concat_df_widget_coords(df, widgetcoords):
df = pd.concat([df, widgetcoords], axis=1).copy()
df.columns = [
"aa_complete_dump",
"aa_depth",
"aa_class_name",
"aa_x_start",
"aa_y_start",
"aa_x_end",
"aa_y_end",
]
return df
def get_details(detailedinformationsep):
details = (detailedinformationsep[1] + detailedinformationsep[2]).apply(
lambda x: pd.Series(list(x))
)
details = details.replace(".", False)
for col in details.columns[1:]:
details.loc[(details[col].astype("string").str.len() == 1), col] = True
flacol = [
"visibility",
"focusable",
"enabled",
"drawn",
"scrollbars_horizontal",
"scrollbars_vertical",
"clickable",
"long_clickable",
"context_clickable",
"pflag_is_root_namespace",
"pflag_focused",
"pflag_selected",
"pflag_prepressed",
"pflag_hovered",
"pflag_activated",
"pflag_invalidated",
"pflag_dirty_mask",
]
details.columns = flacol
return details
def concat_df_details(df, details):
df = pd.concat([df, details], axis=1).copy()
return df
def calculate_center(df):
df.loc[:, "aa_width"] = df["aa_x_end"] - df["aa_x_start"]
df.loc[:, "aa_height"] = df["aa_y_end"] - df["aa_y_start"]
df.loc[:, "aa_center_x"] = df["aa_x_start"] + (df["aa_width"] // 2)
df.loc[:, "aa_center_y"] = df["aa_y_start"] + (df["aa_height"] // 2)
df.loc[:, "aa_area"] = df["aa_width"] * df["aa_height"]
return df
def hashcodes_ids_to_int(df, detailedinformationsep):
int1 = detailedinformationsep[0].map(lambda x: get_label_1(x)).copy()
hex1 = detailedinformationsep[0].copy()
int1hex = (
pd.concat([int1, hex1], axis=1, ignore_index=True)
.rename(columns={0: "aa_hashcode_int", 1: "aa_hashcode_hex"})
.copy()
)
df = pd.concat([df, int1hex], axis=1).copy()
labeldf = (
detailedinformationsep[4]
.apply(get_label)
.rename(columns={0: "aa_mID_hex", 1: "aa_mID_int"})
.copy()
)
df = pd.concat([df, labeldf], axis=1).copy()
return df
def fill_missing_ids_with_na(df, detailedinformationsep):
idstuff = detailedinformationsep[5].fillna(pd.NA).copy()
df = (
pd.concat([df, idstuff], axis=1).rename(columns={5: "aa_id_information"}).copy()
)
return df
def remove_spaces(df):
spaces = df["aa_complete_dump"].str.extract(r"^(\s+)")[0]
abslen = spaces.str.len().min()
df.loc[:, "aa_complete_dump"] = df["aa_complete_dump"].str.slice(abslen)
pureid = (
df["aa_id_information"]
.fillna("")
.str.split(":")
.apply(lambda x: x[1] if len(x) == 2 else pd.NA)
.copy()
)
df.loc[pureid.index, "pure_id"] = pureid.copy()
for col_ in [x for x in df.columns if regex.search(r"^detail_[^0]\d*$", str(x))]:
df.loc[~df[col_].isna(), col_] = True
df.loc[df[col_].isna(), col_] = False
df.columns = [
"aa_" + regex.sub("^aa_", "", y) for y in df.columns.to_list()[:-1]
] + [df.columns.to_list()[-1]]
return df
def reset_index_and_backup(df):
df["old_index"] = df.index.__array__().copy()
df = df.reset_index(drop=True)
return df
def dump_uiautomator(adb_path, deviceserial):
dumpstring2 = subprocess.run(
fr"{adb_path} -s {deviceserial} shell uiautomator dump",
shell=False,
capture_output=True,
)
dumpstring3 = b""
tempfile = os.path.join(os.getcwd(), "____window_dump.xml")
if b"ERROR" not in dumpstring2.stderr:
dumpstring3 = subprocess.run(
f"{adb_path} -s {deviceserial} pull /sdcard/window_dump.xml {tempfile}",
capture_output=True,
)
with open(tempfile, mode="r", encoding="utf-8") as f:
dumpstring4 = f.read()
dumpstring5 = regex.findall(r"<\?xml.*</hierarchy>", dumpstring4)[0]
return dumpstring2, dumpstring3, dumpstring4, dumpstring5
def uiautomator_to_df(dumpstring):
if isinstance(dumpstring, bytes):
dumpstring = dumpstring.decode("utf-8", "replace")
if not dumpstring.strip().startswith("<?xml"):
dumpstring = "\n".join(dumpstring.splitlines()[1:])
df2 = pd.Q_Xml2df(dumpstring).reset_index()
df2 = df2.fillna(pd.NA).copy()
df2["aa_all_keys_len"] = df2["aa_all_keys"].apply(lambda x: len(x))
df = df2.copy()
df3 = df.copy()
df3 = df3.loc[~(df3["level_0"] == "rotation")]
allpossiblecolumns = [
"bounds",
"checkable",
"checked",
"class",
"clickable",
"content-desc",
"enabled",
"focusable",
"focused",
"index",
"long-clickable",
"package",
"password",
"resource-id",
"scrollable",
"selected",
"text",
]
allgooddataf = []
for col in df3.columns:
if not "level_" in col:
continue
df4 = df3.loc[df3[col].isin(allpossiblecolumns)].copy()
df4["keys_hierarchy"] = df4["aa_all_keys"].apply(lambda x: (x[:-1]))
try:
col_for_index = f"level_{df4.aa_all_keys_len.iloc[0] - 1}"
except Exception:
continue
for name, group in df4.groupby("keys_hierarchy"):
df5 = group[[col_for_index, "aa_value"]].copy()
df5.columns = ["indi", "aa_value"]
df5.index = df5["indi"].__array__().copy()
df5 = df5.drop(columns="indi")
df6 = df5.T.copy()
df6 = df6.reset_index(drop=True)
df6["keys_hierarchy"] = [name]
allgooddataf.append(df6.copy())
df = (
pd.concat(allgooddataf, ignore_index=True)
.reset_index(drop=True)
.drop_duplicates()
.reset_index(drop=True)
)
coords_ = (
df.bounds.str.extractall(r"(\d+)\W+(\d+)\W+(\d+)\W+(\d+)")
.reset_index(drop=True)
.rename(columns={0: "start_x", 1: "start_y", 2: "end_x", 3: "end_y"})
.astype(np.uint16)
.copy()
)
df = pd.concat([coords_, df], axis=1).copy()
df.loc[:, "aa_width"] = df.end_x - df.start_x
df.loc[:, "aa_height"] = df.end_y - df.start_y
df["aa_center_x"] = df["start_x"] + (df["aa_width"] // 2)
df["aa_center_y"] = df["start_y"] + (df["aa_height"] // 2)
df["aa_area"] = df["aa_width"] * df["aa_height"]
for col in df.columns:
if col == "keys_hierarchy":
continue
try:
df[col] = df[col].str.replace(r"^false$", "False", regex=True)
except Exception as fe:
pass
# print(fe)
for col in df.columns:
if col == "keys_hierarchy":
continue
try:
df[col] = df[col].str.replace(r"^true$", "True", regex=True)
except Exception as fe:
# print(fe)
continue
for col in df.columns:
if col == "bounds":
continue
try:
try:
df.loc[:, col] = df.loc[:, col].ds_string_to_best_dtype()
except Exception:
pass
df.loc[:, col] = df.loc[:, col].ds_reduce_memory_size(verbose=False)
except Exception:
pass
df.bounds = list(zip(df.start_x, df.start_y, df.end_x, df.end_y))
df = df.rename(
columns={
"start_x": "aa_start_x",
"start_y": "aa_start_y",
"end_x": "aa_end_x",
"end_y": "aa_end_y",
}
)
df = df.filter(list(sorted(df.columns))).copy()
return df
def split_ui_columns_rename_cols(dfu):
pureid = (
dfu["resource-id"]
.str.split(":")
.apply(lambda x: x[1] if len(x) == 2 else pd.NA)
.copy()
)
dfu.loc[pureid.index, "pure_id"] = pureid.copy()
dfu.columns = [
"bb_" + regex.sub("^aa_", "", y).replace("-", "_")
for y in dfu.columns.to_list()[:-1]
] + [dfu.columns.to_list()[-1]]
return dfu
def get_empty_dfu(df):
allco = [
"bb_area",
"bb_center_x",
"bb_center_y",
"bb_x_end",
"bb_y_end",
"bb_height",
"bb_x_start",
"bb_y_start",
"bb_width",
"bb_bounds",
"bb_checkable",
"bb_checked",
"bb_class",
"bb_clickable",
"bb_content_desc",
"bb_enabled",
"bb_focusable",
"bb_focused",
"bb_index",
"bb_keys_hierarchy",
"bb_long_clickable",
"bb_package",
"bb_password",
"bb_resource_id",
"bb_scrollable",
"bb_selected",
"bb_text",
"pure_id",
]
dfu = pd.DataFrame([[None] * len(allco)] * df.shape[0]).fillna(pd.NA) # ?????
dfu.columns = allco
return dfu
def rename_dfu_cols(dfu):
dfu = dfu.rename(
columns={
"bb_start_x": "bb_x_start",
"bb_start_y": "bb_y_start",
"bb_end_x": "bb_x_end",
"bb_end_y": "bb_y_end",
}
)
dfu["bb_screenshot"] = pd.NA
return dfu
def screenshotcrop(img, x00, y00, x01, y01):
try:
cropa = cropimage(img=img, coords=(x00, y00, x01, y01))
if qq_s_isnan(cropa, include_empty_iters=True):
cropa = pd.NA
except Exception:
cropa = pd.NA
return cropa
def take_screenshot(adb_path, deviceserial, channels_in_output=3):
screens = get_screenshot_adb(adb_executable=adb_path, deviceserial=deviceserial,)
screens = cv2.imread_plus(screens, channels_in_output=channels_in_output)
return screens
def get_all_children(df, screenshot=pd.NA):
if not qq_s_isnan(screenshot):
screens = screenshot.copy()
else:
screens = pd.NA
cropcoords = []
group2 = df.copy()
alldepths = group2.aa_depth.unique()
alldepths = list(reversed(sorted(alldepths)))
for ini, depth in enumerate(alldepths):
subgroup = group2.loc[group2.aa_depth == depth]
for key, item in subgroup.iterrows():
oldrunvalue = depth
goodstuff = []
for ra in reversed(range(0, key)):
if df.at[ra, "aa_depth"] < oldrunvalue:
goodstuff.append(df.loc[ra].to_frame().T)
oldrunvalue = df.at[ra, "aa_depth"]
try:
subdf = pd.concat(goodstuff).copy()
except Exception as fe:
continue
singleitem = item.to_frame().T.copy()
x00 = subdf.aa_x_start.sum() + item.aa_x_start
y00 = subdf.aa_y_start.sum() + item.aa_y_start
x01 = subdf.aa_x_start.sum() + item.aa_x_end
y01 = subdf.aa_y_start.sum() + item.aa_y_end
singleitem.loc[:, "aa_x_start_relative"] = singleitem.loc[:, "aa_x_start"]
singleitem.loc[:, "aa_y_start_relative"] = singleitem.loc[:, "aa_y_start"]
singleitem.loc[:, "aa_x_end_relative"] = singleitem.loc[:, "aa_x_end"]
singleitem.loc[:, "aa_y_end_relative"] = singleitem.loc[:, "aa_y_end"]
singleitem.loc[:, "aa_x_start"] = x00
singleitem.loc[:, "aa_y_start"] = y00
singleitem.loc[:, "aa_x_end"] = x01
singleitem.loc[:, "aa_y_end"] = y01
singleitem.loc[:, "aa_width"] = (
singleitem["aa_x_end"] - singleitem["aa_x_start"]
)
singleitem.loc[:, "aa_height"] = (
singleitem["aa_y_end"] - singleitem["aa_y_start"]
)
singleitem.loc[:, "aa_center_x"] = singleitem["aa_x_start"] + (
singleitem["aa_width"] // 2
)
singleitem.loc[:, "aa_center_y"] = singleitem["aa_y_start"] + (
singleitem["aa_height"] // 2
)
cropa = screenshotcrop(screens, x00, y00, x01, y01)
singleitem.loc[:, "aa_is_child"] = True
if qq_s_isnan(cropa, include_empty_iters=True):
singleitem.loc[:, "aa_screenshot"] = pd.NA
singleitem.loc[:, "aa_has_screenshot"] = False
else:
singleitem.loc[:, "aa_screenshot"] = [cropa]
singleitem.loc[:, "aa_has_screenshot"] = True
for ini_pa, pa_id in enumerate(subdf.old_index):
singleitem.loc[:, f"parent_{str(ini_pa).zfill(3)}"] = pa_id
cropcoords.append(singleitem.copy())
df = pd.concat(cropcoords).reset_index(drop=True)
return df
def shapely_poly_from4_coords(rect):
try:
X1, Y1, X2, Y2 = rect
polygon = [(X1, Y1), (X2, Y1), (X2, Y2), (X1, Y2)]
p = Polygon(polygon)
if p.area > 0:
return pd.Series([True, p])
return pd.Series([False, p])
except Exception:
X1, Y1, X2, Y2 = 50000, 50000, 50000, 50000
polygon = [(X1, Y1), (X2, Y1), (X2, Y2), (X1, Y2)]
p = Polygon(polygon)
return pd.Series([False, p])
def add_shapely_to_dataframes(df=None, dfu=None):
d1, d2 = None, None
if not qq_s_isnan(df):
square1 = df.apply(
lambda x: shapely_poly_from4_coords(
(x.aa_x_start, x.aa_y_start, x.aa_x_end, x.aa_y_end)
),
axis=1,
)
square1.columns = ["aa_valid_square", "aa_shapely"]
d1 = pd.concat([df, square1], axis=1)
if not qq_s_isnan(dfu):
square2 = dfu["bb_bounds"].apply(lambda x: shapely_poly_from4_coords(x))
square2.columns = ["bb_valid_square", "bb_shapely"]
d2 = pd.concat([dfu, square2], axis=1)
return d1, d2
def update_area(df=None, dfu=None):
if not qq_s_isnan(dfu):
dfu["bb_area"] = dfu["bb_shapely"].apply(lambda x: x.area)
if not qq_s_isnan(df):
df["aa_area"] = df["aa_shapely"].apply(lambda x: x.area)
return df, dfu
def add_bounds_to_df(df):
df["aa_bounds"] = df.apply(
lambda x: tuple(
(x["aa_x_start"], x["aa_y_start"], x["aa_x_end"], x["aa_y_end"])
),
axis=1,
)
return df
def get_cropped_coords(max_x, max_y, df, pref="aa"):
# pref = 'aa'
df[f"{pref}_cropped_x_start"] = df[f"{pref}_x_start"]
df[f"{pref}_cropped_y_start"] = df[f"{pref}_y_start"]
df[f"{pref}_cropped_x_end"] = df[f"{pref}_x_end"]
df[f"{pref}_cropped_y_end"] = df[f"{pref}_y_end"]
df.loc[(df[f"{pref}_cropped_x_start"] <= 0), f"{pref}_cropped_x_start"] = 0
df.loc[(df[f"{pref}_cropped_y_start"] <= 0), f"{pref}_cropped_y_start"] = 0
df.loc[(df[f"{pref}_cropped_x_end"] <= 0), f"{pref}_cropped_x_end"] = 0
df.loc[(df[f"{pref}_cropped_y_end"] <= 0), f"{pref}_cropped_y_end"] = 0
df.loc[(df[f"{pref}_cropped_x_start"] >= max_x), f"{pref}_cropped_x_start"] = max_x
df.loc[(df[f"{pref}_cropped_y_start"] >= max_y), f"{pref}_cropped_y_start"] = max_y
df.loc[(df[f"{pref}_cropped_x_end"] >= max_x), f"{pref}_cropped_x_end"] = max_x
df.loc[(df[f"{pref}_cropped_y_end"] >= max_y), f"{pref}_cropped_y_end"] = max_y
df.loc[:, f"{pref}_width_cropped"] = (
df[f"{pref}_cropped_x_end"] - df[f"{pref}_cropped_x_start"]
)
df.loc[:, f"{pref}_height_cropped"] = (
df[f"{pref}_cropped_y_end"] - df[f"{pref}_cropped_y_start"]
)
df.loc[:, f"{pref}_center_x_cropped"] = df[f"{pref}_cropped_x_start"] + (
df[f"{pref}_width_cropped"] // 2
)
df.loc[:, f"{pref}_center_y_cropped"] = df[f"{pref}_cropped_y_start"] + (
df[f"{pref}_height_cropped"] // 2
)
return df
def get_activity_df(max_x, max_y, adb_path, deviceserial, screens=pd.NA):
df, activewinow = dumpsys_to_df(adb_path, deviceserial)
# print(df)
detailedinformationsep = get_detailed_info_sep(df)
# print(detailedinformationsep)
widgetcoords = get_widget_coords(detailedinformationsep)
# print(widgetcoords)
df = concat_df_widget_coords(df, widgetcoords)
# print(df)
details = get_details(detailedinformationsep)
# print(details)
df = concat_df_details(df, details)
# print(df)
df = calculate_center(df)
# print(df)
df = hashcodes_ids_to_int(df, detailedinformationsep)
# print(df)
df = fill_missing_ids_with_na(df, detailedinformationsep)
# print(df)
df = remove_spaces(df)
# print(df)
df2 = reset_index_and_backup(df)
# print(df2)
df = get_all_children(df=df2, screenshot=screens)
df, _ = add_shapely_to_dataframes(df=df)
df, _ = update_area(df=df)
df = add_bounds_to_df(df)
df = df.rename(columns={"pure_id": "aa_pure_id", "old_index": "aa_old_index"})
df = get_cropped_coords(max_x, max_y, df, pref="aa")
return df
def get_view_df(
adb_path, deviceserial, max_x, max_y, merge_it=False, df=None, screens=pd.NA
):
dfu = pd.DataFrame()
try:
dumpstring2, dumpstring3, dumpstring4, dumpstring5 = dump_uiautomator(
adb_path, deviceserial
)
# print(dumpstring2, dumpstring3, dumpstring4, dumpstring5)
dfu = uiautomator_to_df(dumpstring=dumpstring5)
# print(dfu)
dfu = split_ui_columns_rename_cols(dfu)
except Exception:
if dfu.empty:
if merge_it:
dfu = get_empty_dfu(df)
dfu = rename_dfu_cols(dfu)
dfu = reset_index_and_backup(df=dfu)
dfu["bb_screenshot"] = pd.NA
if not qq_s_isnan(screens):
try:
dfu["bb_screenshot"] = dfu["bb_bounds"].apply(
lambda x: screenshotcrop(screens, *x)
)
except Exception:
pass
_, dfu = add_shapely_to_dataframes(dfu=dfu)
_, dfu = update_area(dfu=dfu)
dfu = dfu.rename(columns={"pure_id": "bb_pure_id", "old_index": "bb_old_index"})
dfu = get_cropped_coords(max_x, max_y, dfu, pref="bb")
return dfu
def _get_show_parent_function(df, item):
return FlexiblePartial(_execute_function_to_df_show_parents, True, df, item)
def _execute_function_to_df_show_parents(df, item):
itemf = item.to_frame().T.dropna(axis=1)
sortedcols = [
x
for x in list(reversed(sorted(itemf.columns.to_list())))
if str(x).startswith("parent_")
]
allparentscols = [
df.loc[df.aa_old_index == int(itemf[x])]
for x in sortedcols
if str(x).startswith("parent")
]
return pd.concat(allparentscols).sort_values(by="aa_depth", ascending=False)
def add_function_to_df_show_parents(df):
df.loc[:, "ff_show_parents"] = df.apply(
lambda item: _get_show_parent_function(df, item), axis=1
)
return df
def execute_function_df_dfu_show_screenshot(screenshot):
if not qq_s_isnan(screenshot, include_empty_iters=True):
cv2.imshow_thread(screenshot)
def get_function_df_dfu_show_screenshot(screenshot):
return FlexiblePartial(execute_function_df_dfu_show_screenshot, True, screenshot)
def add_function_df_dfu_show_screenshot(
df, column="aa_screenshot", new_column_name="ff_show_screenshot"
):
df.loc[:, new_column_name] = df[column].apply(
lambda item: get_function_df_dfu_show_screenshot(item)
)
return df
def execute_function_df_dfu_save_screenshot(screenshot):
if not qq_s_isnan(screenshot, include_empty_iters=True):
cv2.imshow_thread(screenshot)
def get_function_df_dfu_save_screenshot(screenshot, folder, filename):
if qq_s_isnan(screenshot):
return pd.NA
return FlexiblePartial(
cv2.imwrite_plus, True, os.path.join(folder, filename + ".png"), screenshot
)
def add_function_df_dfu_save_screenshot(
df, column="aa_screenshot", folder=None, new_column_name="ff_save_screenshot"
):
if folder is None:
folder = os.path.join(os.getcwd(), timest())
df.loc[:, new_column_name] = df.apply(
lambda item: get_function_df_dfu_save_screenshot(
screenshot=item[column], folder=folder, filename=str(item.name).zfill(5)
),
axis=1,
)
return df
def execute_df_tap_middle_offset(
adb_path, deviceserial, x, columnx, columny, offset_x, offset_y
):
execute_adb_command(
f"{adb_path} -s {deviceserial} shell",
[f"input tap {x[columnx]+offset_x} {x[columny]+offset_y}"],
)
def execute_df_tap_middle(
adb_path, deviceserial, x, columnx, columny, offset_x=0, offset_y=0
):
try:
return FlexiblePartial(
execute_adb_command,
True,
f"{adb_path} -s {deviceserial} shell",