shethjenil commited on
Commit
68004d8
·
verified ·
1 Parent(s): 90e08c1

Upload 3 files

Browse files
SONGRECOGNIZER.py CHANGED
@@ -1,151 +1,88 @@
1
- # from cv2 import imdecode,IMREAD_GRAYSCALE ,TM_CCOEFF_NORMED , matchTemplate
2
- # from numpy import frombuffer,uint8,where
3
- # from io import BytesIO
4
- # from requests import get
5
- # def find_element_coordinatesofmic():
6
- # template = imdecode(frombuffer(BytesIO(get("https://shethjenil-automatic-song-rec.static.hf.space/voiceelement.jpg").content).read(), uint8), IMREAD_GRAYSCALE)
7
- # screen_image = imdecode(frombuffer(device.screencap(), uint8), IMREAD_GRAYSCALE)
8
- # w, h = template.shape[::-1]
9
- # loc = where(matchTemplate(screen_image, template, TM_CCOEFF_NORMED) >= 0.8)
10
- # return [loc[1][0] + w // 2, loc[0][0] + h // 2]
11
- from os import getenv, path, remove, makedirs
12
- import winshell
13
- import sys
14
- from shutil import copyfile , rmtree
15
-
16
- def add_to_startmenu(target, shortcut_name):
17
- shortcut = winshell.shortcut(path.join(winshell.start_menu(), f"{shortcut_name}.lnk"))
18
- shortcut.path = target
19
- print(shortcut.show_cmd)
20
- shortcut.write()
21
-
22
- def remove_from_startmenu(shortcut_name):
23
- remove(path.join(winshell.start_menu(), f"{shortcut_name}.lnk"))
24
- if len(sys.argv) == 2:
25
- if sys.argv[1] == "--uninstall":
26
- if path.exists(path.join(getenv("LOCALAPPDATA"), "JENILSOFTWARESONGREC")):
27
- rmtree(path.join(getenv("LOCALAPPDATA"), "JENILSOFTWARESONGREC"))
28
- remove_from_startmenu("Song Recognizer")
29
- sys.exit()
30
- if not path.exists(path.join(getenv("LOCALAPPDATA"), "JENILSOFTWARESONGREC")) or (len(sys.argv) == 2 and sys.argv[1] == "--install"):
31
- try:
32
- # Create directory if it doesn't exist
33
- makedirs(path.join(getenv("LOCALAPPDATA"), "JENILSOFTWARESONGREC"))
34
- except OSError as e:
35
- print("Error creating directory:", e)
36
- sys.exit(1)
37
-
38
- try:
39
- # Copy file to the created directory
40
- copyfile(sys.argv[0], path.join(getenv("LOCALAPPDATA"), "JENILSOFTWARESONGREC", sys.argv[0].split("\\")[-1]))
41
- add_to_startmenu(path.join(getenv("LOCALAPPDATA"), "JENILSOFTWARESONGREC", sys.argv[0].split("\\")[-1]), "Song Recognizer")
42
- except IOError as e:
43
- print("Error copying file:", e)
44
- sys.exit(1)
45
-
46
- sys.exit()
47
-
48
-
49
-
50
- from subprocess import Popen , DEVNULL
51
- from time import sleep
52
- from ppadb.client import Client
53
- from os import remove,chdir
54
- from pytube import Search
55
- from xml.etree.ElementTree import parse
56
- from json import dump ,load
57
- from tkinter import messagebox
58
- from tkinter.simpledialog import askstring
59
- chdir(getattr(sys, '_MEIPASS', path.abspath(path.dirname(__file__))))
60
- #change a path to your project folder
61
- try:
62
- messagebox.showinfo(message="this program is made by Vicky,varshil,jeet(leader),preet to dedicating SCIENCE FEST 2024")
63
- messagebox.showinfo(message="in mobile in setting in system build number tap 7 times to open developer options Enable USB debugging and then connect your mobile to pc and tap ok")
64
- Popen(r"data\adb kill-server", shell=True, stdout=DEVNULL, stderr=DEVNULL)
65
- Popen(r"data\adb start-server", shell=True, stdout=DEVNULL, stderr=DEVNULL)
66
- while True:
67
- global device
68
- try:
69
- device = Client(host="127.0.0.1", port=5037).devices()[0]
70
- break
71
- except:
72
- messagebox.showwarning(message="waiting for device")
73
- pass
74
- messagebox.showwarning(message="please unlock and open your mobile during project")
75
- global screentimeout
76
-
77
- while True:
78
- password = askstring("password","enter password")
79
- if password.strip() != "":
80
- if device.shell(f"locksettings clear --old {password}").strip() == "Lock credential cleared":
81
- device.shell(f"#locksettings set-disabled 1")
82
- break
83
- else:
84
- messagebox.showwarning(message="wrong password")
85
- messagebox.showwarning(message="""IF YOU HAVE A PATTERN LOCK THEN ENTER A POINT NUMBER INSTEAD OF PASSWORD LIKE FOR
86
- UPPER LEFT POINT IS 1 AND LAST BOTTOM RIGHT IS 9 MIDDLE POINT IS 5 AND LAST BOTTOM LEFT IS 7""")
87
-
88
- else:
89
- if device.shell("locksettings clear").strip() == "Lock credential cleared":
90
- device.shell(f"#locksettings set-disabled 1")
91
- break
92
- else:
93
- messagebox.showwarning(message="wrong password")
94
- messagebox.showwarning(message="""IF YOU HAVE A PATTERN LOCK THEN ENTER A POINT NUMBER INSTEAD OF PASSWORD LIKE FOR
95
- UPPER LEFT POINT IS 1 AND LAST BOTTOM RIGHT IS 9 MIDDLE POINT IS 5 AND LAST BOTTOM LEFT IS 7""")
96
- device.shell("input keyevent KEYCODE_SLEEP")
97
- screentimeout=device.shell("settings get system screen_off_timeout")
98
- device.shell("settings put system screen_off_timeout 1800000")
99
- if device.shell(f"ls /sdcard/cfg.json").strip() != "/sdcard/cfg.json":
100
- device.shell("am start -n com.google.android.googlequicksearchbox/com.google.android.apps.search.googleapp.activity.GoogleAppActivity")
101
- device.shell("uiautomator dump")
102
- device.pull("/sdcard/window_dump.xml", "window_dump.xml")
103
- a = [node.attrib['bounds'] for node in parse('window_dump.xml').getroot().iter() if "text" in node.attrib and node.attrib["content-desc"] == "Voice search"][0].split("][")[0].replace("[","").split(",")
104
- mic = [int(a[0]), int(a[1])]
105
- device.input_tap(mic[0], mic[1])
106
- sleep(1)
107
- device.shell("uiautomator dump")
108
- device.pull("/sdcard/window_dump.xml", "window_dump.xml")
109
- a = [node.attrib['bounds'] for node in parse('window_dump.xml').getroot().iter() if "text" in node.attrib and node.attrib["text"] == "Search for a song"][0].split("][")[0].replace("[","").split(",")
110
- songbutton=[int(a[0]), int(a[1])]
111
- dump({"mic": mic, "songbutton": songbutton}, open("cfg.json", "w+"))
112
-
113
- device.push("cfg.json", "/sdcard/cfg.json")
114
- device.shell("am force-stop com.google.android.googlequicksearchbox")
115
- device.shell("rm /sdcard/window_dump.xml")
116
- remove("cfg.json")
117
- remove("window_dump.xml")
118
- else:
119
- device.pull("/sdcard/cfg.json", "cfg.json")
120
- cfg = load(open("cfg.json", "r"))
121
- cfg = load(open("cfg.json", "r"))
122
- mic = cfg["mic"]
123
- songbutton = cfg["songbutton"]
124
-
125
- def get_song_artist():
126
- device.shell("svc data enable")
127
- device.shell("input keyevent KEYCODE_WAKEUP")
128
- global mic , songbutton
129
- device.shell("am start -n com.google.android.googlequicksearchbox/com.google.android.apps.search.googleapp.activity.GoogleAppActivity")
130
- sleep(2)
131
- device.input_tap(mic[0],mic[1]) #mic
132
- device.input_tap(songbutton[0],songbutton[1]) #songbutton
133
- sleep(20)
134
- device.shell("uiautomator dump")
135
- device.pull("/sdcard/window_dump.xml", "window_dump.xml")
136
- song, artist = [node.attrib["text"] for node in parse('window_dump.xml').getroot().iter() if "text" in node.attrib and (text := node.attrib["text"].strip()) != ""][1:3]
137
- remove("window_dump.xml")
138
- device.shell("am force-stop com.google.android.googlequicksearchbox")
139
- device.shell("input keyevent KEYCODE_HOME")
140
- device.shell("svc data disable")
141
- device.shell("input keyevent KEYCODE_SLEEP")
142
- Popen(rf'data\vlc -f --audio-visual=goom --no-video-title-show --no-qt-fs-controller "{list(filter(lambda x: x.itag == 251, Search(f"{song} by {artist}").results[0].streams))[0].url}"', shell=True, stdout=DEVNULL, stderr=DEVNULL).communicate()
143
- while messagebox.askretrycancel(message="RECORD START"):
144
- get_song_artist()
145
- device.shell("settings put system screen_off_timeout " + screentimeout)
146
- Popen(r"data\adb kill-server", shell=True)
147
- except Exception as e:
148
- device.shell("settings put system screen_off_timeout " + screentimeout)
149
- Popen(r"data\adb kill-server", shell=True)
150
-
151
-
 
1
+ ### SCANING AND CONNECT WIFI ADB
2
+
3
+ # import qrcode
4
+ # qr = qrcode.QRCode(border=1, box_size=10, version=1)
5
+ # qr.add_data("WIFI:T:ADB;S:ADB_WIFI_songrecproject;P:songrec;;")
6
+ # qr.print_ascii(invert=True)
7
+ from subprocess import run as sbprun
8
+ from time import sleep as time_sleep
9
+ from _thread import interrupt_main
10
+ from zeroconf import IPVersion, ServiceBrowser, ServiceStateChange, Zeroconf
11
+ device_ports = []
12
+ def on_service_state_change(zeroconf: Zeroconf,service_type: str,name: str,state_change: ServiceStateChange):
13
+ if state_change is ServiceStateChange.Added:
14
+ info = zeroconf.get_service_info(service_type, name)
15
+ addr = info.parsed_addresses()[0]
16
+ if service_type == "_adb-tls-pairing._tcp.local.":
17
+ sbprun(["adb", "pair", f"{addr}:{info.port or 5555}", "songrec"])
18
+ sbprun(["adb", "connect", f"{addr}:{device_ports[0]}"])
19
+ interrupt_main()
20
+ elif service_type == "_adb-tls-connect._tcp.local.":
21
+ device_ports.append(info.port)
22
+ print(open("qr.txt",encoding='utf-8').read())
23
+ zc = Zeroconf(ip_version=IPVersion.V4Only)
24
+ ServiceBrowser(zc,["_adb-tls-connect._tcp.local.", "_adb-tls-pairing._tcp.local."],[on_service_state_change])
25
+ try:
26
+ while True:
27
+ time_sleep(0.1)
28
+ except KeyboardInterrupt:
29
+ pass
30
+ zc.close()
31
+
32
+
33
+
34
+
35
+
36
+ from pytubefix import Search
37
+ from os import remove as os_remove
38
+ from lxml.etree import fromstring as xmlfromstr
39
+ from ppadb.client import Client as AdbClient
40
+ from ppadb.device import Device
41
+ def exist(src,xpath:str):
42
+ return len(src.xpath(xpath)) > 0
43
+ def get_text(src,xpath:str):
44
+ return src.xpath(xpath)[0].attrib.get("text")
45
+
46
+ time_sleep(1) # for refresing adb
47
+ client = AdbClient()
48
+ device:Device = client.devices()[0]
49
+ wm = device.wm_size()
50
+ conf = {"start_x":wm.width // 2,"start_y":int(wm.height * 0.9),"end_x":wm.width // 2,"end_y":int(wm.height * 0.2),"duration":1000}
51
+ resulttrack = '//*[@resource-id="com.google.android.googlequicksearchbox:id/soundsearch_track_name"]'
52
+ resultartist = '//*[@resource-id="com.google.android.googlequicksearchbox:id/soundsearch_artist"]'
53
+ def mobile_off():
54
+ device.shell("rm /sdcard/ui_layout.xml")
55
+ os_remove("ui_layout.xml")
56
+ device.shell("svc power stayon false")
57
+ device.input_keyevent("SLEEP")
58
+ def searchmusic():
59
+ device.input_keyevent("WAKEUP")
60
+ device.input_swipe(**conf)
61
+ device.shell("svc power stayon true")
62
+ device.shell("am start -a com.google.android.googlequicksearchbox.MUSIC_SEARCH")
63
+ while True:
64
+ try:
65
+ device.shell("uiautomator dump /sdcard/ui_layout.xml")
66
+ device.pull("/sdcard/ui_layout.xml","ui_layout.xml")
67
+ ui = xmlfromstr(open("ui_layout.xml", "rb").read())
68
+ if exist(ui,'//*[@text="Try again"]') and exist(ui,'//*[@text="Results from Google Search"]'):
69
+ mobile_off()
70
+ Search(get_text(ui,resulttrack) +" by "+ get_text(ui,resultartist)).videos[0].streams.filter(only_audio=True).first().download(filename="Temp",mp3=True)
71
+ sbprun("vlc -f --audio-visual=goom --no-video-title-show --no-qt-fs-controller Temp.mp3")
72
+ os_remove("Temp.mp3")
73
+ break
74
+ elif exist(ui,'//*[@text="Try again"]') and not exist(ui,'//*[@text="Results from Google Search"]'):
75
+ mobile_off()
76
+ print("no song found")
77
+ break
78
+ time_sleep(4)
79
+ except KeyboardInterrupt:
80
+ mobile_off()
81
+ break
82
+ except:
83
+ break
84
+ while True:
85
+ searchmusic()
86
+ if input("Do You Want Search Again ('Enter' for yes/'N' for No)").strip().upper() == "N":
87
+ client.kill()
88
+ break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
SONGRECOGNIZER.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:de4c5bc7f88128c256f8f8f98d58d15a8b415a2e7b445e6c3562f13c4bf80b46
3
+ size 101125813
SONGRECOGNIZER_ERR_SOLVING.png ADDED