-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
208 lines (170 loc) · 6.9 KB
/
utils.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
import asyncio
import json
import time
from pathlib import Path
import httpx
import requests
from pathvalidate import sanitize_filename
from sclib import SoundcloudAPI
def get_sanitized_filename(title):
filename = sanitize_filename(f"{title}".replace(" ", "_"))
if len(filename) > 150:
filename = filename[:150]
filename = filename + ".zip"
return filename
# Beatsage download functions
def get_soundcloud_playlist(playlist_url):
api = SoundcloudAPI()
print(playlist_url)
rp = api.resolve(playlist_url)
if "track" in str(type(rp)).lower():
return [rp.permalink_url]
else:
soundcloud_urls = [track.permalink_url for track in rp.tracks]
return soundcloud_urls
def get_song_url(url):
if "youtube.com" in url:
return [url]
else:
return get_soundcloud_playlist(url)
async def download_url(sess, url, save_path, chunk_size=128):
async with sess.stream("get", url) as r:
print(r, "Beginning download")
assert r.status_code == 200
with save_path.open("wb") as fd:
async for chunk in r.aiter_bytes():
if not chunk:
break
fd.write(chunk)
print(f"Level saved at: {save_path}")
async def get_details(sess, url):
print(f"Getting details of: {url}")
data = {"youtube_url": url}
for i in range(3):
rp = await sess.post("https://beatsage.com/youtube_metadata", data=json.dumps(data))
if rp.status_code == 429:
seconds_to_wait = 60
print(f"Too many requests detected, waiting {seconds_to_wait} seconds")
time.sleep(seconds_to_wait)
rp = await sess.post("https://beatsage.com/youtube_metadata", data=json.dumps(data))
if rp.status_code != 200:
continue
else:
break
video_metadata = json.loads(rp.text)
video_metadata.get("title")
return video_metadata
async def get_level(sess, video_data, upload=False):
url = video_data[0]
video_metadata = video_data[1]
fields = {"youtube_url": url,
"cover_art": "(binary)",
"audio_metadata_title": video_metadata.get("title"),
"audio_metadata_artist": video_metadata.get("artist"),
"difficulties": "Hard,Expert,ExpertPlus,Normal",
"modes": "Standard,90Degree,OneSaber",
"events": "DotBlocks,Obstacles",
"environment": "DefaultEnvironment",
"system_tag": "v2"}
data = fields
# data = aiohttp.FormData()
# for key in fields.keys():
# data.add_field(name=key, value=fields.get(key))
rp = await sess.post("https://beatsage.com/beatsaber_custom_level_create", data=data)
assert rp.status_code == 200
content = json.loads(rp.text)
download_id = content.get("id")
still_pending = True
print("Pending level download")
while still_pending:
await asyncio.sleep(30)
rp = await sess.get(f"https://beatsage.com/beatsaber_custom_level_heartbeat/{download_id}")
assert rp.status_code == 200
content = json.loads(rp.text)
status = content.get("status")
if status.lower() == "done":
break
filename = get_sanitized_filename(video_metadata.get('title'))
download_path = Path("levels", filename)
level_folder = Path("levels")
if not level_folder.exists():
level_folder.mkdir()
await download_url(sess, f"https://beatsage.com/beatsaber_custom_level_download/{download_id}", download_path)
if upload:
file_path = Path(download_path)
await upload_to_quest(sess, file_path)
return {video_metadata.get("title"): download_path}
async def upload_to_quest(sess, file_path, quest_local_ip):
assert file_path.exists() and file_path.is_file()
client_exceptions = (
asyncio.TimeoutError,
httpx.ConnectTimeout
)
while True:
try:
await sess.get(f"http://{quest_local_ip}:50000/main/upload")
break
except client_exceptions:
print("Trying to find Quest to upload to")
await asyncio.sleep(10)
files = {"name": "file", "filename": file_path.name, "file": file_path.open("rb")}
rp = await sess.post(f"http://{quest_local_ip}:50000/host/beatsaber/upload", files=files)
assert rp.status_code == 204
# options = Options()
# options.headless = True
# driver = webdriver.Chrome(executable_path="/usr/bin/chromedriver", options=options)
#
# driver.get(f"http://{quest_local_ip}:50000/main/upload")
# driver.find_element(By.CSS_SELECTOR, "input").send_keys(file_path.absolute().__str__())
# WebDriverWait(driver, 300).until(EC.presence_of_element_located((By.CSS_SELECTOR, ".toast-message")))
# driver.find_element(By.CSS_SELECTOR, ".toast-message").click()
# print("Finished upload")
# driver.quit()
# Quest upload functions
def commit_to_quest(quest_local_ip):
print("Starting commit")
rp = requests.post(f"http://{quest_local_ip}:50000/host/beatsaber/commitconfig")
assert rp.ok
async def run_tasks(todo, function, **kwargs):
# connector = aiohttp.TCPConnector(limit_per_host=2, limit=3)
# sess = aiohttp.ClientSession(connector=connector)
sess = httpx.AsyncClient(timeout=600)
semaphore = asyncio.Semaphore(5)
async with semaphore:
tasks = [function(sess, elem, **kwargs) for elem in todo]
for task in tasks:
print(task)
results = await asyncio.gather(*tasks)
# await sess.close()
return results
def get_song_urls(urls=None):
if urls is None:
urls = Path("urls.txt").read_text().split("\n")
song_urls = [get_song_url(url) for url in urls]
song_urls = [y for x in song_urls for y in x]
for url in song_urls:
print(url)
return song_urls
def async_get_details(song_urls):
# asyncio.set_event_loop(asyncio.new_event_loop())
# loop = asyncio.get_event_loop()
loop = asyncio.new_event_loop()
video_metadatas = loop.run_until_complete(run_tasks(song_urls, get_details))
return video_metadatas
def async_get_levels(song_urls, video_metadatas):
loop = asyncio.new_event_loop()
video_data_list = list(zip(song_urls, video_metadatas))
download_paths = loop.run_until_complete(run_tasks(video_data_list, get_level, upload=False))
return download_paths
def async_upload_levels_to_quest(level_paths, quest_local_ip):
loop = asyncio.new_event_loop()
loop.run_until_complete(run_tasks(level_paths, upload_to_quest, quest_local_ip=quest_local_ip))
def main():
file_path = Path(
"/home/sam/PycharmProjects/auto_beatsage/levels/Echo_(feat._Tauren_Wells)__Live__Elevation_Worship.zip")
quest_local_ip = "192.168.1.38"
files = {"name": "file", "filename": file_path.name, "file": file_path.open("rb")}
rp = httpx.post(f"http://{quest_local_ip}:50000/host/beatsaber/upload", files=files)
print(rp)
if __name__ == "__main__":
main()