Added osu/osz converter and importer

This commit is contained in:
UnitedAirforce
2026-06-09 22:45:46 +08:00
parent b190479d88
commit 4b08430cf4
18 changed files with 3017 additions and 0 deletions
+368
View File
@@ -0,0 +1,368 @@
import os
import zipfile
import json
import shutil
import hashlib
from PIL import Image
def calculate_md5_and_size(file_path):
md5_hash = hashlib.md5()
file_size = 0
with open(file_path, "rb") as file:
for byte_block in iter(lambda: file.read(4096), b""):
md5_hash.update(byte_block)
file_size += len(byte_block)
return md5_hash.hexdigest(), file_size
def process_folder(folder_path):
md5_checksum_dict = {}
size_dict = {}
for root, dirs, files in os.walk(folder_path):
for file_name in files:
file_path = os.path.join(root, file_name)
relative_path = os.path.relpath(file_path, folder_path)
md5_checksum, file_size = calculate_md5_and_size(file_path)
md5_checksum_dict[relative_path.replace("\\", "/")] = md5_checksum
size_dict[relative_path.replace("\\", "/")] = file_size
return md5_checksum_dict, size_dict
def write_to_file(file_name, data):
with open(file_name, "w") as file:
file.write(json.dumps(data, separators=(',', ':')))
def get_unique_song_file(existing_songs, song_file):
counter = 1
unique_song_file = song_file
while unique_song_file in existing_songs:
unique_song_file = f"{song_file}{counter}"
counter += 1
return unique_song_file
def get_chart_list(dir, manifest):
chart_6k = manifest.get("diff_6k").split('/')
chart_4k = manifest.get("diff_4k").split('/')
dir_list = []
all_chart = chart_6k + chart_4k
diff_table = ["_EL.bms", "_EX.bms", "_LPR.bms", "_PR.bms", "_EL4.bms", "_EX4.bms", "_PR4.bms"]
for i in range(len(all_chart)):
if all_chart[i] != "0":
path = os.path.join(dir, "note", manifest.get("mp3") + diff_table[i])
dir_list.append(path)
return dir_list
def deleteChart(song_id):
# Find the song manifest to remove.
playmanifest_path = "OverRide/playmanifest.json"
with open(playmanifest_path, 'r', encoding="utf-8") as f:
playmanifest = json.load(f)
manifest_to_remove = None
for manifest in playmanifest:
if manifest[0].get("id") == song_id:
manifest_to_remove = manifest
break
# We now have the manifest to remove, which is aquired after looping through the main manifest.
if manifest_to_remove is None:
print("That song ID not found. 没有找到此歌曲ID。")
return
# Confirm with the user one last time by printing out some useful data.
song_title = manifest_to_remove[0].get("title")
diff_str = manifest_to_remove[0].get("diff_6k") + "/" + manifest_to_remove[0].get("diff_4k")
charter = manifest_to_remove[0].get("charter_6k") + "/" + manifest_to_remove[0].get("charter_4k")
print(f"Are you sure you want to delete the song '{song_title}', difficulty '{diff_str}', charted by '{charter}'?")
print(f"你确定要删除这首歌吗?名为 '{song_title}',难度 '{diff_str}',谱师为 '{charter}'?")
confirm = input("(y/n): ")
if confirm.lower() != 'y':
print("Deletion cancelled. 删除终止。")
return
song_name = manifest_to_remove[0].get("mp3")
# Remove everything but the chart.
paths_to_check = [
(os.path.join("OverRide", "bga", f"{song_name}.zip"), False),
(os.path.join("OverRide", "music", f"{song_name}"), False),
(os.path.join("Resources", "data_fm", f"{song_name}.jpg"), False),
(os.path.join("Resources", "data_fm", f"255{song_name}.jpg"), False),
]
for path, _ in paths_to_check:
if os.path.exists(path):
os.remove(path)
# Remove charts
charts = get_chart_list(os.path.join("OverRide"), manifest_to_remove[0])
for chart in charts:
chart = chart.replace(".bms", "")
if os.path.exists(chart):
os.remove(chart)
# Remove the charts from the zip.
note_zip_path = os.path.join("OverRide", "Note.zip")
if os.path.exists(note_zip_path):
temp_zip_path = os.path.join("OverRide", "temp_Note.zip")
with zipfile.ZipFile(note_zip_path, 'r') as note_zip:
with zipfile.ZipFile(temp_zip_path, 'w') as temp_zip:
for item in note_zip.infolist():
check_name = "offlineNote_" + song_name + "_"
file_name = item.filename
if not file_name.startswith(check_name):
# write file
temp_zip.writestr(item, note_zip.read(item.filename))
os.remove(note_zip_path)
os.rename(temp_zip_path, note_zip_path)
# Remove the manifest, and refresh the metadata.
playmanifest.remove(manifest_to_remove)
with open(playmanifest_path, 'w', encoding="utf-8") as f:
json.dump(playmanifest, f, indent=4)
# Correct the main sync and metadata.
update_metadata()
print("Song has been deleted from the server. 歌曲已从服务器删除。")
def importChart(name):
# Create a temp directory for unzipping the provided zip file.
extract_to = "_temp"
if os.path.exists(extract_to):
shutil.rmtree(extract_to)
os.makedirs(extract_to)
if not os.path.isfile(name):
print(f"Error: The file '{name}' does not exist.")
return
# Safely opens the zip file.
try:
with zipfile.ZipFile(name, 'r') as zip_ref:
zip_ref.extractall(extract_to)
except zipfile.BadZipFile:
print(f"Error: '{name}' is not a valid zip file.")
return
except PermissionError:
print(f"Error: Permission denied. Check your permissions for '{extract_to}'.")
return
except Exception as e:
print(f"An unexpected error occurred when unzipping: {e}")
return
# Safely read the song manifest
manifest_path = os.path.join(extract_to, "manifest.json")
if not os.path.isfile(manifest_path):
print(f"Error: The file '{manifest_path}' does not exist.")
return
try:
with open(manifest_path, 'r', encoding='utf-8') as f:
manifest = json.load(f)
except Exception as e:
print(f"JSON parse failed for manifest failed: {e}")
return
for song in manifest:
song_file = song.get("mp3")
# get list of charts
charts = get_chart_list(extract_to, song)
# Sanity check everything
# (0): at least one chart should be present in the config.
standard_check = True
reason_fail = ""
if charts == []:
standard_check = False
reason_fail += "\nNo charts found in the chart config this song (all zeroes). "
bga_data = song.get("bga")
# (1): either the jpg and png version of the thumbnail should exist.
img1_path = os.path.join(os.path.join(extract_to, "thumbs"), f"{song_file}.jpg")
img2_path = os.path.join(os.path.join(extract_to, "thumbs"), f"{song_file}.png")
is_png = False
if os.path.exists(img1_path) == False:
if os.path.exists(img2_path) == False:
standard_check = False
reason_fail += "\nSong thumbnail (music_name.jpg or music_name.png) is missing from the thumbs folder. "
else:
is_png = True
# (2): The correct mp3 file should be there.
song_path = os.path.join(os.path.join(extract_to, "music"), f"{song_file}.mp3")
if os.path.exists(song_path) == False:
standard_check = False
reason_fail += "\nMusic file (music_name.mp3) is missing from the Music folder. "
# (3): If bga data is present, bga file should be there.
bga_path = os.path.join(os.path.join(extract_to, "bga"), f"{song_file}.zip")
if bga_data != None and os.path.exists(bga_path) == False:
standard_check = False
reason_fail += "\nSince manifest specified BGA, there should be a music_name.zip in the bga folder. "
# (4): If bga data is not present but there is a song_name.zip in bga folder.
if bga_data == None and os.path.exists(bga_path):
standard_check = False
reason_fail += "\nManifest did not specify BGA, but there is a music_name.zip in the bga folder. While this is not a breaking issue, if you wish to use the BGA please specify it in the manifest. "
# (5): All the charts specified in the manifest should exist
for chart in charts:
if os.path.exists(chart) == False:
standard_check = False
reason_fail += "\nA chart that is specified in manifest is missing from the note folder: " + chart + ". "
# That is it!
if standard_check == False:
print("The song contains issues and is not imported. 此曲目存在问题,没有导入。")
print("The reasons are as follows. 原因如下。")
print(reason_fail)
shutil.rmtree(extract_to)
continue
playmanifest_path = "OverRide/playmanifest.json"
with open(playmanifest_path, 'r', encoding="utf-8") as f:
playmanifest = json.load(f)
existing_song_files = [item[0].get("mp3") for item in playmanifest]
unique_song_file = get_unique_song_file(existing_song_files, song_file)
# Copy bga zip file if bga is specified
if bga_data != None:
new_bga_name = unique_song_file + ".zip"
new_bga_path = os.path.join("OverRide", "bga", new_bga_name)
os.makedirs(os.path.dirname(new_bga_path), exist_ok=True)
shutil.move(bga_path, new_bga_path)
# Copy music file
new_song_name = unique_song_file
new_song_path = os.path.join("OverRide", "Music", new_song_name)
os.makedirs(os.path.dirname(new_song_path), exist_ok=True)
shutil.move(song_path, new_song_path)
# Copy the thumbnails
new_img_name = unique_song_file + ".jpg"
new_img_path = os.path.join("Resources", "data_fm", new_img_name)
os.makedirs(os.path.dirname(new_img_path), exist_ok=True)
if is_png:
with Image.open(img2_path) as img:
rgb_img = img.convert("RGB")
rgb_img.save(new_img_path, "JPEG")
else:
shutil.move(img1_path, new_img_path)
# Save a resized 255x255 version of the image
resized_img_name = "255" + unique_song_file + ".jpg"
resized_img_path = os.path.join("Resources", "data_fm", resized_img_name)
with Image.open(new_img_path) as img:
img = img.resize((255, 255), Image.Resampling.LANCZOS)
img.save(resized_img_path, "JPEG")
# Copy all the charts
for chart in charts:
new_chart_name = os.path.basename(chart).replace(".bms", "")
new_chart_name = new_chart_name.replace(song_file, unique_song_file)
new_chart_path = os.path.join("OverRide", "Note", new_chart_name)
os.makedirs(os.path.dirname(new_chart_path), exist_ok=True)
shutil.copy(chart, new_chart_path)
# Add charts to zip
note_zip_path = os.path.join("OverRide", "Note.zip")
new_charts = []
for chart in charts:
new_chart_name = chart.replace(song_file, f"offlineNote_{unique_song_file}")
new_chart_name = new_chart_name.replace(".bms", "")
os.rename(chart, new_chart_name)
new_charts.append(new_chart_name)
with zipfile.ZipFile(note_zip_path, 'a') as note_zip:
for chart in new_charts:
note_zip.write(chart, arcname=os.path.basename(chart))
# Merge the manifest
if playmanifest:
last_id = playmanifest[-1][0].get("id", 0)
else:
last_id = 0
song["id"] = last_id + 1
song["mp3"] = unique_song_file
playmanifest.append([song])
with open(playmanifest_path, 'w', encoding="utf-8") as f:
json.dump(playmanifest, f, indent=4)
print(f"Song added: 歌曲已添加:{unique_song_file}")
# Refresh the metadata and we are done!
update_metadata()
shutil.rmtree(extract_to)
def update_metadata():
resources_folder = "Resources"
md5_checksum_dict, size_dict = process_folder(resources_folder)
md5_file_name = "OverRapid/Md5ListChecksum.json"
size_file_name = "OverRapid/SizeList.json"
write_to_file(md5_file_name, md5_checksum_dict)
write_to_file(size_file_name, size_dict)
print(f"MD5 and size checksums saved.")
def main():
print("Override Concierge - 您的Override管家")
print("For music import, simply enter the zip file's path. For music deletion, simply enter its SID as displayed in-game.")
print("曲目导入请输入zip文件的目录。曲目删除请输入游戏内显示的SID。")
user_input = input("Input 输入: ")
if user_input.isdigit():
deleteChart(int(user_input))
elif not user_input.endswith(".zip"):
print("The file is not zip. 文件不是zip。")
else:
importChart(user_input)
if __name__ == "__main__":
main()
@@ -0,0 +1,2 @@
**/__pycache__/
**/input/
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
@@ -0,0 +1,117 @@
# o!m2bms
[Original Repo](https://github.com/mashimycota/om2bms)
Program that converts osu!mania maps to BMS maps. (**currently only supports 2k to 8k**)
Supports fully keysounded maps and bpm changes.
**If you come across any Errors, please report them in the issues!**
## Installation
Written on Python 3.6+.
You can download the required libraries by running:
```
pip install -r requirements.txt
```
Requires an instance of ffmpeg in your system PATH. Here's an [ffmpeg installtion tutorial](https://phoenixnap.com/kb/ffmpeg-windows) if you don't have it already. (To check it if works, type `ffmpeg` in your terminal, and it should not return an error)
Set the default output directory by running,
```
python om2bms_osz.py -sdo [OUTPUT DIRECTORY]
```
or go to `default_outdir.ini` and paste the path to a subdirectory in a BMS songfolder directory.
## Running
Run
```
python om2bms_osz.py -i sample_osz_file.osz
```
to convert all 2k-8k files in `sample_osz_file.osz` and output them to `[OUTPUT DIRECTORY]/sample_osz_file`
To convert individual .osu files run
```
python om2bms_osu.py -i sample_osu_file.osu
```
#### Batch Converting
Run
```
python commandUI.py
```
To access the Command Line User Interface that allows some settings customisation and batch conversion of `.osz` files that are in the input folder (not compatible with single `.osu` files for now)
(I personally think always converting `.osz` files is best anyway)
### To view help, run
```
python om2bms_osz.py -h
```
```
python om2bms_osu.py -h
```
## Key Mapping
(note: I will make images for this section in the future | will also make the layouts customizable)
Lets define the columns like this = `|1|2|3|4|5|6|7|8|`.
If a column is used for the key count in question, it will have it's corresponding number inside it.
### 2k
`|1| | | |5| | | |` (so 1k + scratch with controller)
### 3k
`| | | |4|5|6| | |`
### 4k
`| | |3|4| |6|7| |`
### 5k
`| |2|3|4|5|6| | |`
### 6k
`|1|2|3|4|5|6| | |` (so 5k + scratch if controller)
## To-do List
- [ ] Slider Velocity
- [ ] Difficulty calculation when converting
- [x] *Background Videos* **(Needs to find fix for offset)**
- [x] Persistent settings file for UI
- [x] Support other keycounts then just 7k and 8k **(Supports 2k - 8k)**
- [ ] Improved background image resize/processing when converting
- [x] Adapt to be used without command line, aka a general run function for the arguments (necessary for GUI and improving command line UI)
- [ ] Make GUI
- [ ] Drag-and-drop for GUI
- [ ] Change output file format from `.bms` to `.bmson` (will allow easier feature implementation). Not to be done for a while. Will require big rewrite.
## Notes
- Tested with LR2
- Does not currently support SV changes
- Uses first timing point to estimate the first measure
- Assumes timing points are always the start of a new measure
- If there are >1 hitsounds played in one note, only plays the hitsound with the highest bit
[.osu file documentation](https://osu.ppy.sh/help/wiki/osu!_File_Formats/Osu_(file_format)).
[BMS file documentation](https://hitkey.nekokan.dyndns.info/cmds.htm).
## License
This project is licensed under the GPLv3 license, refer to LICENSE for details.
@@ -0,0 +1,148 @@
import om2bms_osz
import os
import json
if __name__ == "__main__":
clear = lambda: os.system("cls")
end = False
curr_page = "main"
# curr_opts = {
# "in_file": "input",
# "set_default_out": open("./default_outdir.ini", "r").read().strip(),
# "hitsound": None,
# "bg": True,
# "video": True,
# "offset": -235,
# "judge": 2
# }
if not os.path.exists("./settings.json"):
# incase someone for some reason deletes the settings file
default_settings = {
"in_file": "input",
"set_default_out": "output",
"hitsound": None,
"bg": True,
"video": True,
"offset": -235,
"judge": 2
}
json.dump({"custom":default_settings, "default": default_settings}, open("./settings.json", "w"))
curr_opts = json.load(open("./settings.json", "r"))["custom"]
if not os.path.isdir(curr_opts["in_file"]):
os.mkdir(curr_opts["in_file"])
print(f"The missing input directory \"{curr_opts['in_file']}\" has been created. You can put your .osz files in there to convert.")
input("Press ENTER to continue...")
while not end:
# updates options with whatever changes were made in previous iteration
settings_file = json.load(open("./settings.json", "r"))
settings_file["custom"] = curr_opts
json.dump(settings_file, open("./settings.json", "w"))
# ugly format that shows the value of every setting at the beginning of each loop
main_page_options = """Input Folder: {}\t\t Output Folder: {}\t\t\t Use Hitsounds: {}
Background Image: {}\t\t Default Map Offset: {}ms\t\t Judgement: {}
Background Video: {}""".format(curr_opts["in_file"], curr_opts["set_default_out"], "False" if curr_opts["hitsound"] is None else curr_opts["hitsound"],
curr_opts["bg"], curr_opts["offset"], curr_opts["judge"], curr_opts["video"])
clear()
print("\n")
print(main_page_options)
print()
# initial page display
print("="*20 + "OPTIONS" + "="*20)
if curr_page == "main":
print("(1) Run Converter")
print("(2) Edit Settings")
print("(3) List Files To Convert")
print("(4) Exit Program")
elif curr_page == "settings":
print("(1) Change Input Folder \t\t (2) Change Output Folder")
print("(3) Toggle hitsounds \t\t\t (4) Toggle Convert Background Image")
print("(5) Change Offset\t\t\t (6) Change Map Judgement")
print("(7) Toggle Convert Background Video")
print("\n(RESET): Reset these settings back to the system defaults")
print("\n(0) Back to main page")
print("")
option = input("Choose option number: ").lower().strip()
if curr_page == "main": # functionality for each option of main page
if option == "1":
# input_dir_scan = list(os.scandir(curr_opts["in_file"]))
for file in os.scandir(curr_opts["in_file"]): # we loop across the path of every .osz file and convert them
if file.is_file() and file.path.endswith(".osz"):
curr_opts["in_file"] = file.path
om2bms_osz.convert(**curr_opts)
print("\nConversion Complete\n")
end = True
elif option == "2":
curr_page = "settings"
clear()
elif option == "3": # we just iterate over and display the filename of all .osz files in input file
for file in os.scandir(curr_opts["in_file"]):
if file.is_file() and file.path.endswith(".osz"):
print(os.path.basename(file.path))
input("(Enter to clear)")
elif option == "4":
end = True
else:
input("ERROR: That option number does not exist!")
elif curr_page == "settings": # functionality for each option of settings page
if option == "1":
new_input = input("Enter new input folder: ").strip()
if new_input:
curr_opts["in_file"] = new_input
else:
input("ERROR: the input folder must be a none empty name.")
elif option == "2":
new_output = input("Enter new output folder: ").strip()
if new_output:
curr_opts["set_default_out"] = new_output
else:
input("ERROR: the output folder must be a none empty name.")
elif option == "3":
curr_opts["hitsound"] = not curr_opts["hitsound"]
elif option == "4":
curr_opts["bg"] = not curr_opts["bg"]
elif option == "5":
new_offset = input("Enter a new Offset (ms): ").strip()
if all([num in map(str, range(10)) for num in (new_offset[1:] if new_offset[0] == "-" else new_offset)]):
curr_opts["offset"] = int(new_offset)
else:
input("ERROR: you must enter a whole number for the offset!")
elif option == "6":
new_judgement = input("Enter a number for the map judgement: ").strip()
if all([num in map(str, range(10)) for num in new_judgement]):
curr_opts["judge"] = int(new_judgement)
else:
input("ERROR: Judgement number must be a positive whole number!")
elif option == "7":
curr_opts["video"] = not curr_opts["video"]
elif option == "reset":
settings_file = json.load(open("./settings.json", "r"))
curr_opts = settings_file["default"]
# will update the "settings.json" on next iteration of the while loop
elif option == "0":
curr_page = "main"
else:
input("ERROR: That option number does not exist!")
@@ -0,0 +1 @@
output
@@ -0,0 +1 @@
@@ -0,0 +1,351 @@
from typing import Union, List, Tuple, Dict
from om2bms.exceptions import BMSHitSoundException
class OsuMania:
"""Class containing information from .osu file"""
def __init__(self):
# general
self.audio_filename = None
self.audio_lead_in = None
self.video_filename = None
self.video_start_time = None
self.special_style = None # o!m scrollkey y/n
self.sample_set = None
# metadata
self.title = None
self.title_unicode = None
self.artist = None
self.artist_unicode = None
self.creator = None
self.version = None
self.source = None
self.beatmap_id = None
self.stagebg = None
self.key_count = None # originally circle size
self.od = None
self.float_bpm = []
self.timing_points = []
self.hit_objects = []
self.sample_objects = []
self.objects = []
self.sample_filenames = []
self.filename_to_sample = {}
self.noninherited_tp = []
self.hitsounds = {}
self.hitsound_names = []
def parse_float_bpm(self, bpm: float):
"""
Parse float bpm into (INDEX, BPM)
"""
for e in self.float_bpm:
if e[1] == bpm:
return
self.float_bpm.append((get_current_hs_count(len(self.float_bpm) + 1), bpm))
class OsuTimingPoint:
"""Contains information for a particular timing point"""
def __init__(self):
self.time = None
self.ms_per_beat = None
self.meter = None
self.sample_set = None
self.sample_index = None
self.volume = None # not supported in lr2
self.inherited = None
self.kiai_mode = None # not needed
self.ms_per_measure = None
self.sort_type = 0 # for sorting
def __repr__(self):
return str(self.time) + "ms at " + str(self.ms_per_beat) + "ms_per_beat"
def __eq__(self, other):
return self.ms_per_beat == other.ms_per_beat and self.meter == other.meter and \
self.sample_set == other.sample_set and self.sample_index == other.sample_index
class SoundEvent:
"""Just to contain build_filename"""
_hit_sound_key = {
0: "none",
1: "normal",
2: "whistle",
4: "finish",
8: "clap"}
_sample_set_key = {
1: "normal",
2: "soft",
3: "drum"}
def __init__(self):
self.index = None
self.sort_type = 1 # for sorting
def build_filename(self, custom_index: int, sample_set: int, hitsound: int) -> str:
"""
filename = {sample set}-hit{sound}{index}.wav
"""
index = "" if custom_index == 1 else str(custom_index)
return str(HitSound._sample_set_key[sample_set]) + "-hit" + str(HitSound._hit_sound_key[hitsound]) \
+ index + ".wav"
def get_info(self):
"""
For list iterating purposes
"""
return (self.index, self)
class OsuBGSoundEvent(SoundEvent):
"""
For when sample plays in the background that is not the audiofile
"""
def __init__(self, time, filename, sample_num):
super().__init__()
self.time = time
self.filename = filename
self.index = get_current_hs_count(sample_num)
def __str__(self):
return self.filename
class HitSound(SoundEvent):
"""
hit_sound key
"""
def __init__(self, hitsound: int, tp: Union[OsuTimingPoint, None], sample_set: int, custom_index:
int, filename: str, sample_num: int):
super().__init__()
self.timing_point = tp
self.hitsound = hitsound
self.sample_set = sample_set
self.custom_index = custom_index if custom_index != 0 else self.timing_point.sample_index
self.filename = filename if filename != "" else self.build_filename(self.custom_index, self.sample_set,
self.hitsound)
self.addition_set = self.sample_set # needed?
self.index = get_current_hs_count(sample_num)
def __str__(self):
return self.filename
class OsuHitObject:
"""
Hitobject class
mania_column:
scroll = 0
key1 = 1
key2 = 2
...
key7 = 7
"""
def __init__(self):
self.time = None
self.time_value = None
self.new_combo = False
self.hit_sound = None
self.mania_column = None
self.timing_point = None
self.sort_type = 1 # for sorting
class OsuManiaNote(OsuHitObject):
"""Single o!m note"""
def __init__(self):
super().__init__()
def get_type_value(self):
"""
Returns type value of note
"""
return 5 if self.new_combo else 1
def __str__(self):
return "NOTE: t=" + str(self.time) + "|c=" + str(self.mania_column)
def __repr__(self):
return "NOTE: t=" + str(self.time) + "|c=" + str(self.mania_column)
class OsuManiaLongNote(OsuHitObject):
"""o!m noodle"""
def __init__(self, end_time=None):
super().__init__()
self.end_time = end_time
def get_type_value(self):
"""
Returns type value of note
"""
return 132 if self.new_combo else 128
def __str__(self):
return "LN: t=" + str(self.time) + "|t2=" + str(self.end_time) + "|c=" + str(self.mania_column)
def __repr__(self):
return "LN: t=" + str(self.time) + "|t2=" + str(self.end_time) + "|c=" + str(self.mania_column)
class BMSMeasure:
"""
Contains info for all lines in the same measure
"""
_hit_sounds = True
def __init__(self, measure_number: str):
self.measure_number = measure_number
self.lines = []
def __str__(self):
"""
Returns in format XXXYY:NN
"""
ret = ""
for line in self.lines:
ret += ("#" + str(self.measure_number) + str(line.channel) + ":" + str(line.data) + "\n")
return str(ret)
def create_data_line(self, channel: str, bits: int,
locations: List[Tuple[List[int], Union[OsuHitObject, OsuBGSoundEvent, str]]]):
"""
Wrapper for creating data_line
"""
chars = {}
locations_ = []
for e in locations:
locations_.append(e[0])
if isinstance(e[1], OsuHitObject):
if e[1].hit_sound is not None and BMSMeasure._hit_sounds:
chars[e[0]] = e[1].hit_sound.index
if chars[e[0]] == "":
chars[e[0]] = "ZZ"
else:
chars[e[0]] = "ZZ"
elif isinstance(e[1], OsuBGSoundEvent):
chars[e[0]] = e[1].index
else:
chars[e[0]] = e[1]
self.lines.append(BMSMainDataLine(channel, bits, chars, locations_, self.measure_number))
def create_measure_length_change(self, num_of_beats):
"""
Channel 2 measure length change
"""
# beats_over_four = float(num_of_beats / 4)
self.lines.append(BMSMainDataLine("02", 1, {0: str(num_of_beats)}, [0], self.measure_number))
def create_bpm_change_line(self, bpm: int):
"""
Channel 3 bpm change (ints only), 01 - FF(255)
"""
self.lines.append(BMSMainDataLine("03", 1, {0: str(hex(bpm))[2:4].upper().zfill(2)}, [0], self.measure_number))
def create_bpm_extended_change_line(self, bpm: Union[int, float], float_bpm_arr):
"""
Channel 8 bpm change. Takes real number.
"""
tup = (None, None)
for e in float_bpm_arr:
if e[1] == bpm:
tup = e
self.lines.append(BMSMainDataLine("08", 1, {0: str(tup[0])}, [0], self.measure_number))
class BMSMainDataLine:
"""
Single line within the
"""
def __init__(self, channel: str, bits: int, chars: Dict[int, str], locations: List[int], measure_number: str):
self.channel = channel
self.data = self._build_data(bits, chars, locations)
self.measure_number = measure_number
def _build_data(self, bits: int, chars: Dict[int, str], locations: List[int]) -> str:
"""
Builds the components of line
"""
ret = ""
location_index = 0
for i in range(bits):
if i == locations[location_index]:
ret += chars[i]
if not location_index >= len(locations) - 1:
location_index += 1
else:
ret += "00"
return ret
def __str__(self):
"""
Returns in format XXXYY:NN
"""
ret = "#" + str(self.measure_number) + str(self.channel) + ":" + str(self.data) + "\n"
return str(ret)
def get_current_hs_count(sample_num: int) -> str:
"""
Returns the HitSound instance's base36 hitsound identifier.
"""
def base36encode(number, alphabet='0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ') -> str:
"""Converts an integer to a base36 string.
Adapted from Wikipedia.
"""
base36 = ''
if 0 <= number < len(alphabet):
return alphabet[number]
while number != 0:
number, i = divmod(number, len(alphabet))
base36 = alphabet[i] + base36
return base36
ret = base36encode(sample_num)
if len(ret) == 1:
ret = "0" + ret
elif len(ret) > 2 or ret == "ZZ":
# raise BMSHitSoundException("Too many hitsounds.")
print("Too many hitsounds - continuing")
return ""
return ret
def calculate_bpm(timing_point: OsuTimingPoint) -> Union[int, float]:
"""
Calculates bpm and rounds if decimals 1-4 are 0 or 9
"""
def get_nth_decimal(number, n):
"""
Returns nth decimal of number
"""
return int(number * (10 ** n)) % 10
bpm_float = 1 / ((timing_point.ms_per_beat / 1000) / 60)
ncount = count = 0
for i in range(1, 5):
if get_nth_decimal(bpm_float, i) == 0:
count += 1
elif get_nth_decimal(bpm_float, i) == 9:
ncount += 1
if count == 4:
return int(bpm_float)
elif ncount == 4:
return round(bpm_float)
else:
return int(bpm_float * (10 ** 4)) / 10000
@@ -0,0 +1,23 @@
"""
For exceptions
"""
class OsuParseException(Exception):
"""Excpetion class for osu parsing excpetions"""
pass
class OsuGameTypeException(Exception):
"""For non-osumania maps """
pass
class BMSHitSoundException(Exception):
"""When there are too many sound files (~1293)"""
pass
class BMSMaxMeasuresException(Exception):
"""BMS files only support up to 999 measures."""
pass
@@ -0,0 +1,107 @@
from PIL import Image, ImageFilter, ImageEnhance, ImageOps, ImageFont, ImageDraw
import os
from pydub import AudioSegment
from om2bms.data_structures import OsuTimingPoint
def appratio(t: int,b: int, val: float) -> int:
"""
calculates a fixed ratio with t and b to then convert val according to that ratio.
"""
return int((t/b)*val)
def cut_save_preview_audio(path_to_audio: str, preview_time: int, timing_points: list[OsuTimingPoint]) -> None:
"""
Retrives a segment of an audio file and saves as preview_{filename}.mp3
"""
filename = os.path.basename(path_to_audio)
extention = filename.split(".")[-1]
file_dir = os.path.dirname(path_to_audio)
audio = AudioSegment.from_file(path_to_audio, format=extention)
segment_length = 20000 # in milliseconds
interval = [0,0]
if preview_time >= 0: # if there was already a preview starting point defined in the osu map
preview_time_end = preview_time + segment_length
if len(audio) < preview_time_end:
interval = [preview_time, len(audio)]
else:
interval = [preview_time, preview_time_end]
elif timing_points != [] and any([tp.kiai_mode for tp in timing_points]): # if no defined preview point, take first kiai section
i = 0
while not timing_points[i].kiai_mode:
i += 1
start = timing_points[i].time
end = start + segment_length
if end > len(audio):
end = len(audio)
interval = [start, end]
else: # if neither of the above, take default preview point that starts at 40% of the song
start = int(len(audio)*0.4)
end = len(audio) if (start+segment_length) > len(audio) else start + segment_length
interval = [start, end]
preview_audio = audio[interval[0]:interval[1]]
new_filename = "preview_"+filename
preview_audio.export(os.path.join(file_dir, new_filename), format=extention)
def size_bg_thumbnail(path_to_image: str, creator: str, beatmapid: str, thumbnail_size = (1000, 750)) -> None:
"""
Resizes image to 700x700. Add black borders if image is widescreen.
"""
source_image = Image.open(path_to_image).convert("RGB")
background = source_image
(sw, sh) = source_image.size
thumbnail_w, thumbnail_h = thumbnail_size
thumbnail_aspect = round(thumbnail_w/thumbnail_h, 3)
source_aspect = round(sw/sh, 3)
# print(thumbnail_aspect, source_aspect)
if thumbnail_aspect == source_aspect or source_aspect < 1.333:
# if it's already the desired aspect, we'll only resize it and do no more processing on it.
background.thumbnail((thumbnail_w, thumbnail_h))
# background.show()
background.save(path_to_image)
background.close()
else:
# if it's not the desired aspect ratio, we fit it to an image with that aspect ratio (we also add text to the image in this case)
zoomed_w, zoomed_h = round((sw/sh)*thumbnail_w), thumbnail_h
# print(w, zoomed_w, h, zoomed_h)
background.resize((zoomed_h, zoomed_w)) # resizes to h=700 aspect ratio
background = ImageEnhance.Brightness(background).enhance(0.5) # dims image to 40% brightness
background = background.filter(ImageFilter.GaussianBlur(6)) # blurs image
background = ImageOps.fit(background, thumbnail_size) # fits/crops background image to the desired size
source_image.thumbnail(thumbnail_size) # resizes source image
paste_start_y = (thumbnail_h-source_image.height) // 2
background.paste(source_image, (0, paste_start_y)) # places source image centered into the background
curr_path = os.path.dirname(__file__) #because of some weird fucking path issue that the code is too dumb to understand (I spent an hour finding out this was the issue)
font = ImageFont.truetype(os.path.join(curr_path, "allerregular.ttf"), appratio(22,700,thumbnail_w))
draw = ImageDraw.Draw(background)
# mapper
text_offset = appratio(10,700, thumbnail_w)
draw.text((text_offset ,paste_start_y-text_offset), "mapped by "+creator, (255,255,255), anchor="lb", font=font)
# map uid
draw.text((thumbnail_w-text_offset, paste_start_y + source_image.height + text_offset), "uid: /"+str(beatmapid), anchor="rt", font=font)
# background.show()
background.save(path_to_image)
background.close()
# black_background_thumbnail("./lol.jpg", "Thor", "236", (700, 525))
@@ -0,0 +1,534 @@
import codecs
import os
import re
from typing import Union, List, Tuple, Dict
from fractions import Fraction
from math import gcd
from functools import reduce
# import om2bms.image_resizer
from om2bms.data_structures import OsuMania
from om2bms.data_structures import OsuTimingPoint
from om2bms.data_structures import OsuManiaNote
from om2bms.data_structures import OsuManiaLongNote
from om2bms.data_structures import OsuBGSoundEvent
from om2bms.data_structures import BMSMeasure
from om2bms.data_structures import calculate_bpm
from om2bms.osu import OsuBeatmapReader
from om2bms.exceptions import OsuGameTypeException
from om2bms.exceptions import OsuParseException
from om2bms.exceptions import BMSMaxMeasuresException
class OsuManiaToBMSParser:
"""
in_file: path to osu file to convert
out_dir: directory to output the converted bms file
filename: the name to print to console when converting
"""
_ms_to_inverse_note_values = {}
_mania_note_to_channel = {
0: 16,
1: 11,
2: 12,
3: 13,
4: 14,
5: 15,
6: 18,
7: 19
}
_mania_ln_to_channel = {
0: 56,
1: 51,
2: 52,
3: 53,
4: 54,
5: 55,
6: 58,
7: 59
}
_convertion_options = {}
_out_file = None
def __init__(self, in_file, out_dir, filename):
self.reset()
self.bg_filename = None
self.audio_filepath = None
self.failed = False
try:
self.beatmap = OsuBeatmapReader(in_file)
except OsuGameTypeException:
self.failed = True
return
except OsuParseException as e:
self.failed = True
print(e)
return
print("\tConverting " + filename)
self.beatmap = self.beatmap.get_parsed_beatmap()
bms_filename = self.beatmap.title + " " + self.beatmap.version + ".bms"
bms_filename = re.sub('[\\/:"*?<>|]+', "", bms_filename)
output = os.path.join(out_dir, bms_filename)
OsuManiaToBMSParser._out_file = codecs.open(output, "w", "shiftjis", errors="replace")
self.write_buffer(self.create_header())
music_start_param = self.music_start_time(self.beatmap)
self.get_next_measure(music_start_param[0], music_start_param[1], self.beatmap)
OsuManiaToBMSParser._out_file.close()
file = os.path.dirname(in_file)
if OsuManiaToBMSParser._convertion_options["BG"] and self.beatmap.stagebg is not None and \
os.path.isfile(os.path.join(file, self.beatmap.stagebg)):
# om2bms.image_resizer.black_background_thumbnail(os.path.join(file, self.beatmap.stagebg))
self.bg_filename = os.path.join(file, self.beatmap.stagebg)
if self.beatmap.audio_filename is not None and os.path.isfile(os.path.join(file, self.beatmap.audio_filename)):
self.audio_filepath = os.path.join(file, self.beatmap.audio_filename)
if self.beatmap.video_filename is not None and os.path.isfile(os.path.join(file, self.beatmap.video_filename)):
self.video_filename = os.path.join(file, self.beatmap.video_filename)
def get_bg(self):
"""
Returns bg filename
"""
return self.bg_filename
def get_audio_path(self):
"""
Returns path to map audio
"""
return self.audio_filepath
def get_video_name(self):
"""
Returns filename to map video
"""
return self.video_filename
def reset(self):
"""
Resets class variables
"""
OsuManiaToBMSParser._out_file = None
OsuBeatmapReader._latest_tp_index = 0
OsuBeatmapReader._latest_noninherited_tp_index = 0
OsuBeatmapReader._sample_index = 1
BMSMeasure._hit_sounds = OsuManiaToBMSParser._convertion_options["HITSOUND"]
def write_buffer(self, buffer: Union[BMSMeasure, List[str]]):
"""
Writes to file. \n between each element in buffer if list
"""
if buffer is None:
return
elif isinstance(buffer, BMSMeasure):
for line in buffer.lines:
OsuManiaToBMSParser._out_file.write(str(line))
else:
for line in buffer:
OsuManiaToBMSParser._out_file.write(line)
OsuManiaToBMSParser._out_file.write("\n")
OsuManiaToBMSParser._out_file.write("\n")
def expansion_wrapper(self, n, ms_per_measure) -> Fraction:
"""
Approximates n, where 0 < n < 1, to p/q where q=2^i or 3 * 2^i up to q=192.
"""
def expander(n, ms_per_measure, meter, end):
"""
Generalized expander for non upper number of 3 or 4 measures.
"""
def within_offset(num, sum__, offset):
"""
return true if within
"""
return int(ms_per_measure * num) - 1 < ms_per_measure * (sum__ + offset) < int(ms_per_measure * num) + 2
done = False
denominator = meter
sum_ = Fraction(1, meter)
while sum_ + Fraction(1, denominator) < n:
sum_ += Fraction(1, denominator)
iterations = 0
while iterations < 6:
if within_offset(n, sum_, 0) or round(n, 5) == round(float(sum_), 5):
done = True
break
if float(sum_) > n:
sum_ -= Fraction(1, denominator)
denominator *= 2
elif float(sum_) < n:
sum_ += Fraction(1, denominator)
denominator *= 2
iterations += 1
# pad with maxs
while not done:
if within_offset(n, sum_, 0):
break
prev_error = abs(n - sum_)
if sum_ > n:
if within_offset(n, sum_, -Fraction(1, end)):
sum_ -= Fraction(1, end)
break
elif abs(n - (prev_error - Fraction(1, end))) > sum_ - Fraction(1, end):
break
sum_ -= Fraction(1, end)
elif sum_ < n:
if within_offset(n, sum_, Fraction(1, end)):
sum_ += Fraction(1, end)
break
elif abs(n - (prev_error + Fraction(1, end))) < sum_ - Fraction(1, end):
break
sum_ += Fraction(1, end)
return (abs(n - sum_), sum_)
error2 = expander(n, ms_per_measure, 4, 128)
error3 = expander(n, ms_per_measure, 3, 192)
error = error2 if error2[0] < error3[0] else error3
time_value = error[1]
if time_value == 1:
return Fraction(0, 1)
if time_value != 0:
self.add_to_mtnv(time_value * ms_per_measure, time_value)
return error[1]
def music_start_time(self, beatmap: OsuMania):
"""
Returns the measure offset and ms of first measure. Calls BMSMeasure and BMSMainDataLine on the BGM start line.
"""
first_object = beatmap.objects[0]
first_timing = beatmap.timing_points[0]
ms_per_measure = first_timing.meter * first_timing.ms_per_beat
use_obj = False
if first_object.time < first_timing.time:
start_time = first_object.time
use_obj = True
else:
start_time = first_timing.time
# find first obj on down beat
if use_obj:
i = 0
while beatmap.objects[i].time < first_timing.time:
i += 1
start_time = beatmap.objects[i].time
while start_time - ms_per_measure > 0:
start_time -= ms_per_measure
# start_time_offset is the time from 0 ms to the first obj
start_time_offset = ms_per_measure - start_time if start_time > 0 else abs(start_time)
start_time_offset += OsuManiaToBMSParser._convertion_options["OFFSET"]
mus_start_at_001 = True if first_object.time + ms_per_measure < ms_per_measure else False
sto_fraction = start_time_offset / ms_per_measure
time_value_ratio = self.expansion_wrapper(sto_fraction, ms_per_measure)
if time_value_ratio == 0 and mus_start_at_001:
bms_measure = BMSMeasure("001")
measure_start = 1
bms_measure.create_data_line("01", time_value_ratio.denominator, [(time_value_ratio.numerator, "01")])
else:
if mus_start_at_001:
bms_measure = BMSMeasure("001")
measure_start = 1
else:
bms_measure = BMSMeasure("000")
if time_value_ratio == 0:
measure_start = 0
else:
measure_start = 1
bms_measure.create_data_line("01", time_value_ratio.denominator, [(time_value_ratio.numerator, "01")])
measure_offset = measure_start
if beatmap.objects[0].time > start_time:
while not start_time >= beatmap.objects[0].time:
start_time += ms_per_measure
measure_offset += 1
else:
measure_offset = 0 if measure_start == 0 else 1
if first_timing.meter != 4:
if bms_measure.measure_number == "000":
bms_measure.create_measure_length_change(first_timing.meter / 4)
elif bms_measure.measure_number == "001":
bms_measure0 = BMSMeasure("000")
bms_measure0.create_measure_length_change(first_timing.meter / 4)
self.write_buffer(bms_measure0)
bms_measure.create_measure_length_change(first_timing.meter / 4)
self.write_buffer(bms_measure)
if first_timing.meter != 4:
for i in range(1, measure_offset):
bms_measure = BMSMeasure(str(i).zfill(3))
bms_measure.create_measure_length_change(first_timing.meter / 4)
self.write_buffer(bms_measure)
first_measure_time = int(start_time)
if first_object.time < first_measure_time - 1:
measure_offset -= 1
first_measure_time -= ms_per_measure
if time_value_ratio == 0 and not mus_start_at_001:
while not self.within_2_ms(start_time, measure_offset * ms_per_measure):
measure_offset += 1
self.initialize_mtnv()
return (measure_offset, first_measure_time)
def get_next_measure(self, starting_measure: int, starting_ms: int, beatmap: OsuMania):
"""
Retrieves information for each measure.
"""
def add_to_measure(current_measure_, hitobjj_):
"""
Adds hitobj to measure
"""
if isinstance(hitobjj_, OsuManiaNote):
column = hitobjj_.mania_column
bmscolumn = OsuManiaToBMSParser._mania_note_to_channel[column]
if bmscolumn not in current_measure_:
current_measure_[OsuManiaToBMSParser._mania_note_to_channel[column]] = [hitobjj_]
else:
current_measure_[OsuManiaToBMSParser._mania_note_to_channel[column]].append(hitobjj_)
elif isinstance(hitobjj_, OsuManiaLongNote):
column = hitobjj_.mania_column
bmscolumn = OsuManiaToBMSParser._mania_ln_to_channel[column]
if bmscolumn not in current_measure_:
current_measure_[OsuManiaToBMSParser._mania_ln_to_channel[column]] = [hitobjj_]
else:
current_measure_[OsuManiaToBMSParser._mania_ln_to_channel[column]].append(hitobjj_)
elif isinstance(hitobjj_, OsuBGSoundEvent):
column = 1
if column not in current_measure_:
current_measure_[column] = [hitobjj_]
else:
current_measure_[column].append(hitobjj_)
elif isinstance(hitobjj_, OsuTimingPoint):
if 0 not in current_measure_:
current_measure_[0] = [hitobjj_]
else:
current_measure_[0] = [hitobjj_]
current_measure = {}
current_time_in_ms = starting_ms
truncate_measure = False
first_timing = beatmap.noninherited_tp[0]
ms_per_measure = first_timing.ms_per_beat * first_timing.meter
measure_number = starting_measure
most_recent_tp = first_timing
i = 0
while i < len(beatmap.objects):
hitobj = beatmap.objects[i]
if hitobj.time < int(current_time_in_ms + ms_per_measure) - 1 and not truncate_measure:
if not isinstance(hitobj, OsuTimingPoint):
add_to_measure(current_measure, hitobj)
elif isinstance(hitobj, OsuTimingPoint) and self.within_2_ms(current_time_in_ms, hitobj.time):
most_recent_tp = hitobj
ms_per_measure = hitobj.ms_per_beat * hitobj.meter
current_time_in_ms = hitobj.time
add_to_measure(current_measure, hitobj)
else:
truncate_measure = True
else: # hitobj.starttime >= current_time_in_ms + ms_per_measure:
if truncate_measure:
if hitobj.time - current_time_in_ms < 0:
truncation_frac = (hitobj.time - (current_time_in_ms - ms_per_measure)) / ms_per_measure
else:
truncation_frac = (hitobj.time - current_time_in_ms) / ms_per_measure
truncation_float = float(self.expansion_wrapper(truncation_frac, ms_per_measure))
bmsmeasure = self.create_measure(current_measure, most_recent_tp, current_time_in_ms,
str(measure_number).zfill(3),
truncation_float)
truncate_measure = False
self.write_buffer(bmsmeasure)
self.initialize_mtnv()
measure_number += 1
most_recent_tp = hitobj
ms_per_measure = hitobj.ms_per_beat * hitobj.meter
current_time_in_ms = hitobj.time
current_measure = {}
add_to_measure(current_measure, hitobj)
i += 1
continue
else:
bmsmeasure = self.create_measure(current_measure, most_recent_tp, current_time_in_ms,
str(measure_number).zfill(3), 0)
self.write_buffer(bmsmeasure)
# move to next measure with hitnotes
while not self.within_2_ms(current_time_in_ms, hitobj.time):
measure_number += 1
current_time_in_ms += ms_per_measure
if hitobj.time < int(current_time_in_ms + ms_per_measure) - 1:
if isinstance(hitobj, OsuTimingPoint) and not self.within_2_ms(current_time_in_ms, hitobj.time):
truncate_measure = True
elif isinstance(hitobj, OsuTimingPoint) and self.within_2_ms(current_time_in_ms, hitobj.time):
most_recent_tp = hitobj
self.initialize_mtnv()
ms_per_measure = hitobj.ms_per_beat * hitobj.meter
current_time_in_ms = hitobj.time
current_measure = {}
add_to_measure(current_measure, hitobj)
break
if measure_number > 999:
raise BMSMaxMeasuresException("Exceeded 999 measures")
if not truncate_measure:
i += 1
# for the last measure (outside loop)
bmsmeasure = self.create_measure(current_measure, most_recent_tp, current_time_in_ms,
str(measure_number).zfill(3), 0)
self.write_buffer(bmsmeasure)
def initialize_mtnv(self) -> None:
"""
Reset _ms_to_inverse_note_values (bpm changes)
"""
OsuManiaToBMSParser._ms_to_inverse_note_values = {}
def add_to_mtnv(self, key: int, value: Fraction):
"""
Wrapper to add into mtnv
"""
OsuManiaToBMSParser._ms_to_inverse_note_values[key] = value
OsuManiaToBMSParser._ms_to_inverse_note_values[key - 1] = value
OsuManiaToBMSParser._ms_to_inverse_note_values[key + 1] = value
def within_2_ms(self, base, n) -> bool:
"""
True if n is close enough to base
"""
return base - 2 <= n <= base + 2
def create_measure(self, current_measure, timing_point: OsuTimingPoint, measure_start: float,
measure_number: str, measure_truncation: float):
"""
Creates a BMSMeasure containing linedata
"""
def get_numerator_with_gcd(fraction, gcd_) -> int:
"""
Returns numerator of fraction with denom of gcd
"""
if fraction[1] == gcd_:
return fraction[0]
elif fraction[1] < gcd_:
fraction[0] *= 2
fraction[1] *= 2
return get_numerator_with_gcd(fraction, gcd_)
else: # fraction[1] > gcd: (switch from
if fraction[1] % 3 == 0:
fraction[0] //= 3
fraction[1] //= 3
else:
fraction[0] //= 4
fraction[0] *= 3
fraction[1] //= 4
fraction[1] *= 3
return get_numerator_with_gcd(fraction, gcd_)
# if the measure is empty skip
if len(current_measure) == 0:
return
bms_measure = BMSMeasure(measure_number)
if timing_point.meter != 4:
bms_measure.create_measure_length_change(timing_point.meter / 4)
self.initialize_mtnv()
elif measure_truncation != 0:
bms_measure.create_measure_length_change(measure_truncation)
ms_per_measure = timing_point.meter * timing_point.ms_per_beat
if len(current_measure) != 0:
for key in sorted(current_measure.keys()):
# get notes from column/key and put them into a line
denoms = []
locations = [] # temp
locations_ = [] # to be passed into bmsmaindataline
for note in current_measure[key]:
# if first_note:
time_value_ms = round(abs(measure_start - note.time), 5)
if self.within_2_ms(time_value_ms, 0):
time_value_ratio = Fraction(0, 1)
elif int(time_value_ms) in OsuManiaToBMSParser._ms_to_inverse_note_values:
time_value_ratio = OsuManiaToBMSParser._ms_to_inverse_note_values[int(time_value_ms)]
else:
time_value_ratio = self.expansion_wrapper(time_value_ms / ms_per_measure, ms_per_measure)
denoms.append(time_value_ratio.denominator)
locations.append(([time_value_ratio.numerator, time_value_ratio.denominator], note))
if key == 0 and not current_measure[key][0].inherited:
new_bpm = calculate_bpm(current_measure[key][0])
if new_bpm <= 255 and isinstance(new_bpm, int):
bms_measure.create_bpm_change_line(new_bpm)
else:
bms_measure.create_bpm_extended_change_line(new_bpm, self.beatmap.float_bpm)
elif key == 1:
locations_ = sorted(locations, key=lambda x: x[0])
for i in range(len(locations)):
bms_measure.create_data_line(str(key).zfill(2), locations_[i][0][1],
[(locations_[i][0][0], locations_[i][1])])
else:
# make all denomaintors = to gcd
gcd_ = reduce(lambda a, b: a * b // gcd(a, b), denoms)
for list_ in locations:
locations_.append((get_numerator_with_gcd(list_[0], gcd_), list_[1]))
bms_measure.create_data_line(str(key).zfill(2), gcd_, sorted(locations_, key=lambda x: x[0]))
return bms_measure
def create_header(self) -> List[str]:
"""
Makes everything before maindata field
"""
# HEADER FIELD
buffer = list([""])
buffer.append("*---------------------- HEADER FIELD")
buffer.append("")
buffer.append("#PLAYER 1")
buffer.append("#GENRE " + self.beatmap.creator)
buffer.append("#TITLE " + self.beatmap.title_unicode)
if str(self.beatmap.key_count) + "k" not in self.beatmap.version.lower(): # addes [nk] prefix to the diff name
diff_key_count = "[" + str(self.beatmap.key_count) + "K] "
buffer.append("#SUBTITLE " + diff_key_count + self.beatmap.version)
else:
buffer.append("#SUBTITLE " + self.beatmap.version)
buffer.append("#ARTIST " + self.beatmap.artist_unicode)
# buffer.append("#SUBARTIST " + beatmap.artist)
buffer.append("#BPM " + str(int(calculate_bpm(self.beatmap.timing_points[0]))))
buffer.append("#PLAYLEVEL " + "0") # initially 5
buffer.append("#RANK " + str(OsuManiaToBMSParser._convertion_options["JUDGE"]))
buffer.append("")
for hs in self.beatmap.hitsound_names:
buffer.append("#WAV" + hs[0] + " " + str(hs[1]))
buffer.append("")
if self.beatmap.audio_filename is not None: # is for preview audio
buffer.append("#PREVIEW " + "preview_" + self.beatmap.audio_filename)
if self.beatmap.video_filename is not None and OsuManiaToBMSParser._convertion_options["VIDEO"]: #TODO add to _conversion_options so that it isn't added by default => adding to cmd UI also
buffer.append("#VIDEOFILE " + self.beatmap.video_filename)
if self.beatmap.stagebg is not None and OsuManiaToBMSParser._convertion_options["BG"]:
buffer.append("#BMP01 " + self.beatmap.stagebg)
buffer.append("#STAGEFILE " + self.beatmap.stagebg) # allows you to preview the map bg in song select
buffer.append("")
if len(self.beatmap.float_bpm) > 0:
for e in self.beatmap.float_bpm:
buffer.append("#BPM" + str(e[0]) + " " + str(e[1]))
buffer.append("")
# BGM FIELD
buffer.append("*---------------------- EXPANSION FIELD")
buffer.append("")
buffer.append("*---------------------- MAIN DATA FIELD")
buffer.append("")
buffer.append("")
if self.beatmap.stagebg is not None and OsuManiaToBMSParser._convertion_options["BG"]:
buffer.append("#00004:01")
return buffer
@@ -0,0 +1,399 @@
import copy
import codecs
from om2bms.data_structures import OsuMania
from om2bms.data_structures import OsuTimingPoint
from om2bms.data_structures import OsuBGSoundEvent
from om2bms.data_structures import HitSound
from om2bms.data_structures import OsuManiaNote
from om2bms.data_structures import OsuManiaLongNote
from om2bms.data_structures import calculate_bpm
from om2bms.exceptions import OsuGameTypeException
from om2bms.exceptions import OsuParseException
class OsuBeatmapReader:
"""Parses information from .osu file to OsuMania class. """
_latest_tp_index = 0
_latest_noninherited_tp_index = 0
_sample_index = 1
def __init__(self, input_file):
self.osumania_beatmap = OsuMania()
self.parse(input_file, self.osumania_beatmap)
def get_parsed_beatmap(self):
"""
Returns the parsed beatmap.
"""
return self.osumania_beatmap
def parse(self, input_file, osumania_beatmap):
"""
Parses beatmap
"""
def header_hitobjects(line, beatmap):
"""
Parses header HitObjects
"""
def decode_bits(num: int) -> int:
"""
For when sample_set plays > 1 hitsound at the same time. Take only the largest
"""
if num > 8:
return 8
elif num > 4:
return 4
elif num > 2:
return 2
else:
return 1
ln_buffer = None
type_ln = False
line_separated = parse_symbol_separated(line, ',')
if len(line_separated) < 4:
OsuParseException("HitObject Error: Invalid Syntax")
hit_object_type = line_separated[3]
hit_object_arg = parse_symbol_separated(line_separated[-1], ':')
hit_object = None
if hit_object_type == "1" or hit_object_type == "5": # single note
hit_object = OsuManiaNote()
if hit_object_type == "5":
hit_object.new_combo = True
elif hit_object_type == "2" or hit_object_type == "6": # o!std slider
return
elif hit_object_type == "8" or hit_object_type == "12": # o!std spinner
return
elif hit_object_type == "132" or hit_object_type == "128": # o!m longnote
type_ln = True
hit_object = OsuManiaLongNote(int(hit_object_arg[0]))
ln_buffer = OsuManiaLongNote(int(hit_object_arg[0]))
if hit_object_type == "128":
hit_object.new_combo = True
else:
raise OsuParseException("HitObject Error: type " + hit_object_type + " not found in " + line)
#! This is where the column conversion will be done for lower key counts.
# column index = floor(x*y/512) = floor(x/512/y)
# x = index * 512/y
lt7keys = {
6: {0:0, 1:1, 2:2,
3:3, 4:4, 5:5},
5: {0:1, 1:2, 2:3,
3:4, 4:5},
4: {0:2, 1:3,
2:5, 3:6},
3: {0:3, 1:4, 2:5},
2: {0:0, 2:4},
}
if beatmap.key_count == 7:
hit_object.mania_column = (int(line_separated[0]) // (512 // beatmap.key_count)) + 1 \
if line_separated[0] != "0" else 0
elif beatmap.key_count in range(2, 9):
hit_object.mania_column = (int(line_separated[0]) // (512 // beatmap.key_count))
if beatmap.key_count != 8:
# uses dictionary to redefine which column it's in depending on keycount
hit_object.mania_column = lt7keys[beatmap.key_count][hit_object.mania_column]
hit_object.hit_sound = int(line_separated[4])
hit_object.time = int(line_separated[2])
if OsuBeatmapReader._latest_tp_index < len(beatmap.timing_points) - 1 and \
beatmap.timing_points[OsuBeatmapReader._latest_tp_index + 1].time <= hit_object.time:
OsuBeatmapReader._latest_tp_index += 1
hitsound_int = int(line_separated[4]) if int(line_separated[4]) in [0, 1, 2, 4, 8] else \
decode_bits(int(line_separated[4]))
timing_point = beatmap.timing_points[OsuBeatmapReader._latest_tp_index]
if type_ln:
filename = "" if len(hit_object_arg) < 5 else hit_object_arg[5].strip()
sample_set = int(hit_object_arg[1])
else:
filename = "" if len(hit_object_arg) < 4 else hit_object_arg[4].strip()
sample_set = int(hit_object_arg[0])
if filename == "" and hitsound_int == 0:
hitsound = None
else:
if sample_set == 0:
sample_set = timing_point.sample_set
custom_index = int(hit_object_arg[3]) if type_ln else int(hit_object_arg[2])
hs_id = (hitsound_int, sample_set, custom_index, filename)
if hs_id not in beatmap.hitsounds:
hitsound = HitSound(hitsound_int, timing_point, sample_set, custom_index, filename, OsuBeatmapReader._sample_index)
OsuBeatmapReader._sample_index += 1
beatmap.hitsounds[hs_id] = hitsound
beatmap.hitsound_names.append(hitsound.get_info())
else:
hitsound = beatmap.hitsounds[hs_id]
hit_object.hit_sound = hitsound
hit_object.timing_point = timing_point
beatmap.hit_objects.append(hit_object)
if ln_buffer is not None:
ln_buffer.time = hit_object.end_time
ln_buffer.end_time = hit_object.end_time
ln_buffer.mania_column = hit_object.mania_column
beatmap.hit_objects.append(ln_buffer)
def header_timingpoints(line, beatmap):
"""
Parses header TimingPoints:
"""
def get_ms_per_beat(ms, _beatmap):
"""
Takes care of negative values found in Timing Points
"""
if ms >= 0:
return ms
else:
for _tp in reversed(_beatmap.timing_points):
if not _tp.inherited:
return (abs(ms) / 100) * _tp.ms_per_beat
raise OsuParseException("Non inherited BPM not found. Timing points are broken")
line_separated = parse_symbol_separated(line, ',')
if len(line_separated) != 8:
raise OsuParseException("TimingPoint Error: Invalid Syntax")
tp = OsuTimingPoint()
tp.time = int(float(line_separated[0]))
tp.inherited = True if int(line_separated[6]) == 0 else False
tp.meter = int(line_separated[2])
tp.sample_set = int(line_separated[3])
tp.sample_index = int(line_separated[4])
tp.volume = int(line_separated[5])
tp.kiai_mode = False if line_separated[7] == 0 else True
# delete previous tp if new tp causes old tp to last only a few ms
if len(beatmap.timing_points) > 0 and tp.time <= beatmap.timing_points[-1].time + 2 and not tp.inherited:
del beatmap.timing_points[-1]
if tp.inherited:
tp.ms_per_beat = get_ms_per_beat(float(line_separated[1]), beatmap)
prev_tp = beatmap.timing_points[-1]
if len(beatmap.timing_points) > 0 and tp.time <= prev_tp.time + 1 and \
tp.sample_set != prev_tp.sample_set and tp.sample_index != prev_tp.sample_index:
del beatmap.timing_points[-1]
else:
tp.ms_per_beat = float(line_separated[1])
bpm = calculate_bpm(tp)
if isinstance(bpm, float) or bpm > 255:
beatmap.parse_float_bpm(bpm)
if len(beatmap.timing_points) > 0 and tp.time <= beatmap.noninherited_tp[-1].time + 1:
del beatmap.noninherited_tp[-1]
beatmap.noninherited_tp.append(tp)
beatmap.timing_points.append(tp)
def header_events(line, beatmap):
"""
Parses header Events
"""
line_separated = parse_symbol_separated(line, ',')
if len(line_separated) < 1:
OsuParseException("Events Error: Invalid Syntax")
event = {}
if line_separated[0] == "Sample":
if len(line_separated) != 5:
raise OsuParseException("Events Error: Invalid Syntax")
time = int(line_separated[1])
filename = str(line_separated[3][1:-1])
if filename not in beatmap.filename_to_sample.keys():
beatmap.sample_filenames.append(filename)
sample = OsuBGSoundEvent(time, filename, OsuBeatmapReader._sample_index)
OsuBeatmapReader._sample_index += 1
beatmap.filename_to_sample[filename] = sample
beatmap.sample_objects.append(sample)
beatmap.hitsound_names.append(sample.get_info())
else:
sample = beatmap.filename_to_sample[filename]
new_sample = copy.deepcopy(sample)
new_sample.time = time
beatmap.sample_objects.append(new_sample)
elif line_separated[0] == "Video":
if len(line_separated) != 3:
OsuParseException("Events Error: Invalid Syntax")
else:
beatmap.video_start_time = int(line_separated[1])
beatmap.video_filename = line_separated[2].strip("\n").strip("\r")[1:-1]
elif len(line_separated) <= 5 and line_separated[0] == "0":
temp = line_separated[2]
temp = temp.replace('"', '').strip()
sep = temp.split('.')
if len(sep) == 2:
beatmap.stagebg = sep[0] + "." + sep[1]
def header_difficulty(line, beatmap):
"""
Parses the header Difficulty
"""
line_property = get_line_property(line)
if line_property[0] == "CircleSize":
keycount = int(line_property[1])
if keycount in range(2,9):
beatmap.key_count = keycount
else:
raise OsuParseException("Only 2k-8k files are supported!")
elif line_property[0] == "HPDrainRate":
pass
elif line_property[0] == "OverallDifficulty":
beatmap.od = float(line_property[1])
elif line_property[0] == "ApproachRate":
pass
else:
OsuParseException("Attribute Error: " + line_property[0] + " not found")
def header_general(line, beatmap):
"""
Parses the header General
"""
line_property = get_line_property(line)
if line_property[0] == "AudioFilename":
audio_filename = line_property[1].strip()
beatmap.audio_filename = audio_filename
audio = HitSound(0, None, 0, 1, audio_filename, OsuBeatmapReader._sample_index)
OsuBeatmapReader._sample_index += 1
beatmap.hitsound_names.append(audio.get_info())
elif line_property[0] == "AudioLeadIn":
beatmap.audio_lead_in = int(line_property[1])
elif line_property[0] == "PreviewTime":
beatmap.preview_time = int(line_property[1])
elif line_property[0] == "Countdown":
pass
elif line_property[0] == "SampleSet":
beatmap.sample_set = str(line_property[1])
pass
elif line_property[0] == "StackLeniency":
pass
elif line_property[0] == "Mode":
if not int(line_property[1]) == 3:
raise OsuGameTypeException("Beatmap is not an o!m beatmap!")
elif line_property[0] == "LetterboxInBreaks":
pass
elif line_property[0] == "SpecialStyle":
if line_property[1] == 1:
beatmap.special_style = True
elif line_property[0] == "WidescreenStoryboard":
pass
def header_metadata(line, beatmap):
"""
Parses the header Metadata
"""
line_property = get_line_property(line)
if line_property[0] == "Title":
beatmap.title = line_property[1].strip().replace("/", "").replace("\\", "")
elif line_property[0] == "TitleUnicode":
try:
beatmap.title_unicode = line_property[1].strip().encode("shiftjis")
beatmap.title_unicode = line_property[1].strip()
except UnicodeEncodeError:
beatmap.title_unicode = beatmap.title
elif line_property[0] == "Artist":
beatmap.artist = line_property[1].strip()
elif line_property[0] == "ArtistUnicode":
try:
beatmap.artist_unicode = line_property[1].strip().encode("shiftjis")
beatmap.artist_unicode = line_property[1].strip()
except UnicodeEncodeError:
beatmap.artist_unicode = beatmap.artist
elif line_property[0] == "Creator":
beatmap.creator = line_property[1].strip()
elif line_property[0] == "Version":
beatmap.version = line_property[1].strip()
elif line_property[0] == "Source":
beatmap.source = line_property[1].strip()
elif line_property[0] == "Tags":
pass
elif line_property[0] == "BeatmapID":
beatmap.beatmap_id = line_property[1].strip()
elif line_property[0] == "BeatmapSetID":
pass
def is_empty(line):
"""
Returns True iff line is empty
"""
return len(line.strip()) == 0
def is_comment(line):
"""
Returns True iff line is a comment line
"""
return len(line) >= 2 and line[0:1] == "//"
def is_section_header(line):
"""
Return True iff line is section header.
"""
return len(line) >= 2 and line[0] == '[' and line[-2] == ']'
def get_section(line):
"""
Return section header
"""
return line[1:-2]
def get_line_property(line):
"""
Returns tuple of (Attribute, Value)
"""
split = line.split(":")
return (split[0], split[1])
def parse_symbol_separated(line, symbol):
"""
Returns list of elements in line separated by symbol.
"""
return line.split(symbol)
file = codecs.open(input_file, 'r', "utf-8")
section = "FileFormat"
for line in file.readlines():
if is_empty(line) or is_comment(line):
continue
elif is_section_header(line):
section = get_section(line)
continue
if line[0] == '[':
section = line[1:-3]
continue
if section == "FileFormat":
continue
elif section == "General":
header_general(line, osumania_beatmap)
elif section == "Editor":
continue
elif section == "Metadata":
header_metadata(line, osumania_beatmap)
elif section == "Difficulty":
header_difficulty(line, osumania_beatmap)
elif section == "Events":
header_events(line, osumania_beatmap)
elif section == "TimingPoints":
header_timingpoints(line, osumania_beatmap)
elif section == "Colours":
continue
elif section == "HitObjects":
header_hitobjects(line, osumania_beatmap)
else:
OsuParseException("Header Error: " + section + " not found")
osumania_beatmap.objects = sorted(osumania_beatmap.hit_objects +
osumania_beatmap.sample_objects +
osumania_beatmap.noninherited_tp,
key=lambda x: (x.time, x.sort_type))
# for i in range(len(osumania_beatmap.objects)):
# if isinstance(osumania_beatmap.objects[i], OsuTimingPoint):
# j = i
# while osumania_beatmap.objects[j].time == osumania_beatmap.objects[i].time:
# j -= 1
# j += 1
# osumania_beatmap.objects[j], osumania_beatmap.objects[i], = \
# osumania_beatmap.objects[i], osumania_beatmap.objects[j]
file.close()
@@ -0,0 +1,55 @@
import os
from argparse import ArgumentParser
import om2bms.om_to_bms
if __name__ == '__main__':
parser = ArgumentParser(description='Convert a .osu osu!mania file to a BMS file. '
'Outputs to directory of om2bms.py',
add_help=True,
allow_abbrev=True)
parser.add_argument('-i', '--in_file',
action='store',
help='Path to file to be converted.',
type=str)
parser.add_argument('-hs', '--hitsound',
action='store_false',
default=False,
help='Disables hitsounds.')
parser.add_argument('-b', '--bg',
action='store_false',
default=True,
help='Disables background conversion.')
parser.add_argument('-o', '--offset',
default=0,
type=int,
help="Adjusts music start time by [offset] ms.")
parser.add_argument('-j', '--judge',
default=2,
type=int,
help="Judge difficulty. Defaults to EASY. "
"(3: EASY), (2: NORMAL), (1: HARD), (0: VERY HARD)")
args = parser.parse_args()
cwd = os.getcwd()
om2bms.om_to_bms.OsuManiaToBMSParser._convertion_options = {
"HITSOUND": args.hitsound,
"VIDEO": False,
"BG": args.bg,
"OFFSET": args.offset,
"JUDGE": args.judge
}
convert = om2bms.om_to_bms.OsuManiaToBMSParser(
args.in_file, os.getcwd(), args.in_file)
print("Done")
exit(0)
@@ -0,0 +1,233 @@
import zipfile
import os
import json
import shutil
from argparse import ArgumentParser
from om2bms.exceptions import BMSMaxMeasuresException
from om2bms.extra_file_processing import size_bg_thumbnail, cut_save_preview_audio
from types import SimpleNamespace
import om2bms.om_to_bms
import multiprocessing
def convert(in_file: str, set_default_out: str = None, hitsound: bool = None, bg: bool = True, video: bool = True, foldername: str = None, offset: int = -235, judge: int = 2):
args = SimpleNamespace(**{ # Allows simpler use of the paramaters
"in_file": in_file,
"set_default_out": set_default_out,
"hitsound": hitsound,
"bg": bg,
"video": video,
"foldername": foldername,
"offset": offset,
"judge": judge
})
cwd = os.getcwd()
cfg_file = os.path.join(cwd, 'settings.json')
if not os.path.exists(cfg_file):
default_settings = {
"in_file": "input",
"set_default_out": "output",
"hitsound": None,
"bg": True,
"video": True,
"offset": -235,
"judge": 2
}
json.dump({"custom":default_settings, "default": default_settings}, open(cfg_file, "w"))
# I know this whole if statement is weird, but I don't want to risk breaking anything any more
if args.set_default_out is not None and args.set_default_out:
# modifies output dir in json settings
settings_obj = json.load(open(cfg_file, "r"))
settings_obj["custom"]["set_default_out"] = args.set_default_out.strip()
json.dump(settings_obj, open(cfg_file, "w"))
outdir = args.set_default_out.strip()
else:
outdir = json.load(open(cfg_file, "r"))["custom"]["set_default_out"]
if args.in_file is None:
exit(0)
if args.foldername is None:
foldername = os.path.basename(args.in_file)[:-4]
out_foldername = foldername
else:
out_foldername = args.foldername
unzip_dir = os.path.join(cwd, "unzip_dir")
if not os.path.isdir(unzip_dir):
os.makedirs(unzip_dir)
try:
if not os.path.isdir(unzip_dir):
os.makedirs(unzip_dir)
filename = os.path.basename(args.in_file)
shutil.copy2(args.in_file, unzip_dir)
osz_dir = os.path.join(unzip_dir, filename)
base = os.path.splitext(osz_dir)[0]
os.rename(osz_dir, base + ".zip")
osz_file_dir = base + ".zip"
print("Unzipping...")
with zipfile.ZipFile(osz_file_dir, 'r') as zipf:
zipf.extractall(unzip_dir)
output_file_dir = os.path.join(outdir, out_foldername)
print("Output directory is " + output_file_dir)
if not os.path.isdir(output_file_dir):
os.makedirs(output_file_dir)
processes = []
manager = multiprocessing.Manager()
bg_list = manager.list()
audio_list = manager.list()
for file in os.listdir(unzip_dir):
if file.endswith(".osu"):
filedir = os.path.join(unzip_dir, file)
p = multiprocessing.Process(target=start_convertion,
args=(filedir, output_file_dir, file, args, bg_list, audio_list))
processes.append(p)
for p in processes:
p.start()
for p in processes:
p.join()
if args.bg:
print("Converting BG...")
convert_bg_list(bg_list)
print("Snipping preview audio...")
make_preview_audio(audio_list)
# move files to output directory
for f in os.listdir(unzip_dir):
if not os.path.isdir(os.path.join(unzip_dir, f)):
if not f.split(".")[-1] == "zip" and not f.split(".")[-1] == "osu":
full_path = os.path.join(unzip_dir, f)
try:
shutil.copy2(full_path, output_file_dir)
except PermissionError as e:
print(e)
continue
print("Done")
# exit(0)
except Exception as e:
print(e)
exit(1)
finally:
shutil.rmtree(unzip_dir)
def start_convertion(filedir_, output_file_dir_, file_, args, bg_list_, audio_list_):
"""
Returns bg filename
"""
try:
om2bms.om_to_bms.OsuManiaToBMSParser._convertion_options = {
"HITSOUND": None if args.hitsound == False else args.hitsound,
"BG": args.bg,
"VIDEO": args.video,
"OFFSET": args.offset,
"JUDGE": args.judge
}
converted_file = om2bms.om_to_bms.OsuManiaToBMSParser(filedir_, output_file_dir_, file_)
if not converted_file.failed:
if args.bg:
bg_list_.append((converted_file.get_bg(), converted_file.beatmap.creator, converted_file.beatmap.beatmap_id))
audio_list_.append((converted_file.get_audio_path(), converted_file.beatmap.preview_time, converted_file.beatmap.timing_points))
except BMSMaxMeasuresException as e:
print(e)
def make_preview_audio(audio_list_) -> None:
"""
Creates a second audio file that we will use in the om2bms preview section
(From osu map, uses either PreviewTime + 20s, first kiai section + 20s, 40% song + 20s)
"""
seen = []
for audio_info in audio_list_:
audio_path, map_preview_time, map_timing_poins = audio_info
if audio_path is not None and audio_path not in seen:
cut_save_preview_audio(audio_path, map_preview_time, map_timing_poins)
seen.append(audio_path)
def convert_bg_list(bg_list_) -> None:
"""
Converts all images in img_list
"""
seen = []
for bg_info in bg_list_:
bg, creator, beatmapid = bg_info
if bg is not None and bg not in seen:
size_bg_thumbnail(bg, creator, beatmapid)
seen.append(bg)
if __name__ == "__main__":
parser = ArgumentParser(description='Convert all .osu osu!mania files in a .osz to BMS files',
add_help=True,
allow_abbrev=True)
parser.add_argument('-i', '--in_file',
action='store',
default=None,
help='Path to .osz to be converted.',
type=str)
parser.add_argument('-sdo', '--set_default_out',
action='store',
default=None,
help='Sets the default output directory',
type=str)
parser.add_argument('-hs', '--hitsound',
action='store_false',
default=None,
help='Disables hitsounds.')
parser.add_argument('-b', '--bg',
action='store_false',
default=True,
help='Disables background image conversion.')
parser.add_argument("-v", "--video",
action="store_false",
default=True,
help="Disables video conversion.")
parser.add_argument('-f', '--foldername',
action='store',
default=None,
help='Directory name to store output files in output path. '
'Default value is the .osz filename')
parser.add_argument('-o', '--offset',
default=-235,
type=int,
help="Adjusts music start time by [offset] ms.")
parser.add_argument('-j', '--judge',
default=2,
type=int,
help="Judge difficulty. Defaults to EASY. "
"(3: EASY), (2: NORMAL), (1: HARD), (0: VERY HARD)")
args = parser.parse_args()
convert(**vars(args)) # because this function takes actual arguments instead of kwargs
@@ -0,0 +1 @@
holds no info, it's just so that ./output/ uploads to github
@@ -0,0 +1,2 @@
pillow
pydub
@@ -0,0 +1 @@
{"custom": {"in_file": "input", "set_default_out": "output", "hitsound": null, "bg": true, "video": true, "offset": -235, "judge": 2}, "default": {"in_file": "input", "set_default_out": "output", "hitsound": null, "bg": true, "video": true, "offset": -235, "judge": 2}}