Repository: Frikallo/MISST Branch: main Commit: c7ea17f94a78 Files: 32 Total size: 217.0 KB Directory structure: gitextract_qrb8u6kc/ ├── .gitignore ├── Build/ │ ├── build-CPU.json │ ├── build-CUDA.json │ └── build-INNO.iss ├── Installation Guide - MacOS.md ├── LICENSE ├── MISST/ │ ├── Assets/ │ │ ├── Themes/ │ │ │ ├── MISST.json │ │ │ └── maluableJSON │ │ ├── config_base.json │ │ └── silent/ │ │ └── silence.flac │ ├── MISSTSetup.py │ ├── MISSTapp.py │ ├── MISSThelpers.py │ ├── MISSTlogger.py │ ├── MISSTplayer.py │ ├── MISSTpreprocess.py │ ├── MISSTsettings.py │ ├── Pretrained/ │ │ ├── files.txt │ │ ├── hdemucs_mmi.yaml │ │ ├── htdemucs.yaml │ │ ├── htdemucs_ft.yaml │ │ ├── mdx.yaml │ │ ├── mdx_extra.yaml │ │ ├── mdx_extra_q.yaml │ │ ├── mdx_q.yaml │ │ ├── repro_mdx_a.yaml │ │ ├── repro_mdx_a_hybrid_only.yaml │ │ └── repro_mdx_a_time_only.yaml │ └── __version__.py ├── README.md ├── requirements-minimal.txt └── requirements.txt ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ venv/* venv-minimal/* MISST/__pycache__/* MISST/MISST.log MISST/config.json MISST/separated/* MISST/Pretrained/*.th output/* Build/7za.exe ================================================ FILE: Build/build-CPU.json ================================================ { "version": "auto-py-to-exe-configuration_v1", "pyinstallerOptions": [ { "optionDest": "noconfirm", "value": true }, { "optionDest": "filenames", "value": "F:/Repos/MISST/MISST/MISSTapp.py" }, { "optionDest": "onefile", "value": false }, { "optionDest": "console", "value": false }, { "optionDest": "icon_file", "value": "F:/Repos/MISST/MISST/Assets/icon.ico" }, { "optionDest": "ascii", "value": false }, { "optionDest": "clean_build", "value": false }, { "optionDest": "strip", "value": false }, { "optionDest": "noupx", "value": false }, { "optionDest": "disable_windowed_traceback", "value": false }, { "optionDest": "embed_manifest", "value": true }, { "optionDest": "uac_admin", "value": false }, { "optionDest": "uac_uiaccess", "value": false }, { "optionDest": "win_private_assemblies", "value": false }, { "optionDest": "win_no_prefer_redirects", "value": false }, { "optionDest": "bootloader_ignore_signals", "value": false }, { "optionDest": "argv_emulation", "value": false }, { "optionDest": "datas", "value": "F:/Repos/MISST/MISST/Assets;Assets/" }, { "optionDest": "datas", "value": "F:/Repos/MISST/venv-minimal/Lib/site-packages/customtkinter;customtkinter/" }, { "optionDest": "datas", "value": "F:/Repos/MISST/MISST/ffmpeg.exe;." }, { "optionDest": "datas", "value": "F:/Repos/MISST/MISST/Pretrained;Pretrained/" }, { "optionDest": "datas", "value": "F:/Repos/MISST/venv-minimal/Lib/site-packages/demucs;demucs/" } ], "nonPyinstallerOptions": { "increaseRecursionLimit": true, "manualArguments": "" } } ================================================ FILE: Build/build-CUDA.json ================================================ { "version": "auto-py-to-exe-configuration_v1", "pyinstallerOptions": [ { "optionDest": "noconfirm", "value": true }, { "optionDest": "filenames", "value": "F:/Repos/MISST/MISST/MISSTapp.py" }, { "optionDest": "onefile", "value": false }, { "optionDest": "console", "value": false }, { "optionDest": "icon_file", "value": "F:/Repos/MISST/MISST/Assets/icon.ico" }, { "optionDest": "ascii", "value": false }, { "optionDest": "clean_build", "value": false }, { "optionDest": "strip", "value": false }, { "optionDest": "noupx", "value": false }, { "optionDest": "disable_windowed_traceback", "value": false }, { "optionDest": "embed_manifest", "value": true }, { "optionDest": "uac_admin", "value": false }, { "optionDest": "uac_uiaccess", "value": false }, { "optionDest": "win_private_assemblies", "value": false }, { "optionDest": "win_no_prefer_redirects", "value": false }, { "optionDest": "bootloader_ignore_signals", "value": false }, { "optionDest": "argv_emulation", "value": false }, { "optionDest": "datas", "value": "F:/Repos/MISST/MISST/Assets;Assets/" }, { "optionDest": "datas", "value": "F:/Repos/MISST/venv/Lib/site-packages/customtkinter;customtkinter/" }, { "optionDest": "datas", "value": "F:/Repos/MISST/MISST/ffmpeg.exe;." }, { "optionDest": "datas", "value": "F:/Repos/MISST/MISST/Pretrained;Pretrained/" }, { "optionDest": "datas", "value": "F:/Repos/MISST/venv/Lib/site-packages/demucs;demucs/" } ], "nonPyinstallerOptions": { "increaseRecursionLimit": true, "manualArguments": "" } } ================================================ FILE: Build/build-INNO.iss ================================================ [Setup] AppName=MISST AppVersion=3.1.0 AppPublisher=@Frikallo AppPublisherURL=https://github.com/Frikallo/MISST AppSupportURL=https://github.com/Frikallo/MISST AppUpdatesURL=https://github.com/Frikallo/MISST DefaultDirName={autopf}\MISST DisableProgramGroupPage=yes UninstallDisplayIcon={app}\MISST.exe OutputDir=F:\Repos\MISST\output OutputBaseFilename=MISST SetupIconFile=F:\Repos\MISST\MISST\Assets\icon.ico Compression=lzma2 SolidCompression=yes PrivilegesRequired=lowest LicenseFile=F:\Repos\MISST\LICENSE DisableWelcomePage=no WizardStyle=modern [Languages] Name: "english"; MessagesFile: "compiler:Default.isl" [Tasks] Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked [Icons] Name: "{autoprograms}\MISST"; Filename: "{app}\MISST\MISST.exe" Name: "{autodesktop}\MISST"; Filename: "{app}\MISST\MISST.exe"; Tasks: desktopicon [Files] Source: "7za.exe"; DestDir: "{tmp}"; DestName: "7za.exe"; Flags: deleteafterinstall; Source: "{tmp}\MISST.7z"; DestDir: "{app}"; Flags: external deleteafterinstall [Code] #IFDEF UNICODE #DEFINE AW "W" #ELSE #DEFINE AW "A" #ENDIF const WAIT_TIMEOUT = $00000102; SEE_MASK_NOCLOSEPROCESS = $00000040; INFINITE = $FFFFFFFF; { Infinite timeout } type TShellExecuteInfo = record cbSize: DWORD; fMask: Cardinal; Wnd: HWND; lpVerb: string; lpFile: string; lpParameters: string; lpDirectory: string; nShow: Integer; hInstApp: THandle; lpIDList: DWORD; lpClass: string; hkeyClass: THandle; dwHotKey: DWORD; hMonitor: THandle; hProcess: THandle; end; function ShellExecuteEx(var lpExecInfo: TShellExecuteInfo): BOOL; external 'ShellExecuteEx{#AW}@shell32.dll stdcall'; function WaitForSingleObject(hHandle: THandle; dwMilliseconds: DWORD): DWORD; external 'WaitForSingleObject@kernel32.dll stdcall'; function CloseHandle(hObject: THandle): BOOL; external 'CloseHandle@kernel32.dll stdcall'; type TMsg = record hwnd: HWND; message: UINT; wParam: Longint; lParam: Longint; time: DWORD; pt: TPoint; end; const PM_REMOVE = 1; function PeekMessage(var lpMsg: TMsg; hWnd: HWND; wMsgFilterMin, wMsgFilterMax, wRemoveMsg: UINT): BOOL; external 'PeekMessageA@user32.dll stdcall'; function TranslateMessage(const lpMsg: TMsg): BOOL; external 'TranslateMessage@user32.dll stdcall'; function DispatchMessage(const lpMsg: TMsg): Longint; external 'DispatchMessageA@user32.dll stdcall'; procedure AppProcessMessage; var Msg: TMsg; begin while PeekMessage(Msg, WizardForm.Handle, 0, 0, PM_REMOVE) do begin TranslateMessage(Msg); DispatchMessage(Msg); end; end; procedure Unzip(source: String; targetdir: String); var unzipTool, unzipParams : String; // path and param for the unzip tool ExecInfo: TShellExecuteInfo; // info object for ShellExecuteEx() begin // source and targetdir might contain {tmp} or {app} constant, so expand/resolve it to path names source := ExpandConstant(source); targetdir := ExpandConstant(targetdir); // prepare 7zip execution unzipTool := ExpandConstant('{tmp}\7za.exe'); ExtractTemporaryFile('7za.exe'); unzipParams := ' x "' + source + '" -o"' + targetdir + '" -y'; // prepare information about the application being executed by ShellExecuteEx() ExecInfo.cbSize := SizeOf(ExecInfo); ExecInfo.fMask := SEE_MASK_NOCLOSEPROCESS; ExecInfo.Wnd := 0; ExecInfo.lpFile := unzipTool; ExecInfo.lpParameters := unzipParams; ExecInfo.nShow := SW_HIDE; if not FileExists(unzipTool) then begin MsgBox('UnzipTool not found: ' + unzipTool, mbError, MB_OK); end else if not FileExists(source) then begin MsgBox('File was not found while trying to unzip: ' + source, mbError, MB_OK); end else begin { The unzip tool is executed via ShellExecuteEx(). Then the installer uses a while loop with the condition WaitForSingleObject and a very minimal timeout to execute AppProcessMessage. AppProcessMessage is itself a helper function, because Inno Setup does not provide Application.ProcessMessages(). Its job is to be the message pump to the Inno Setup GUI. This trick makes the window responsive/draggable again, while the extraction is done in the background. } if ShellExecuteEx(ExecInfo) then begin while WaitForSingleObject(ExecInfo.hProcess, 100) = WAIT_TIMEOUT do begin AppProcessMessage; if WizardForm.ProgressGauge.Position = 100 then WizardForm.ProgressGauge.Position := 0 else WizardForm.ProgressGauge.Position := WizardForm.ProgressGauge.Position + 1; end; CloseHandle(ExecInfo.hProcess); end; end; end; var DownloadPage: TDownloadWizardPage; function OnDownloadProgress(const Url, FileName: String; const Progress, ProgressMax: Int64): Boolean; begin if Progress = ProgressMax then Log(Format('Successfully downloaded file to {tmp}: %s', [FileName])); Result := True; end; procedure InitializeWizard; begin DownloadPage := CreateDownloadPage(SetupMessage(msgWizardPreparing), SetupMessage(msgPreparingDesc), @OnDownloadProgress); end; function NextButtonClick(CurPageID: Integer): Boolean; var ProgramVersion: string; DownloadURL: string; DownloadFileName: string; begin if CurPageID = wpReady then begin // Prompt the user to select the version of the program ProgramVersion := ''; if MsgBox('Do you want to download the CUDA version of MISST 3.1.0?', mbConfirmation, MB_YESNO) = IDYES then begin ProgramVersion := 'cuda'; end else begin ProgramVersion := 'cpu'; end; // Set the download URL and filename based on the selected version if ProgramVersion = 'cuda' then begin DownloadURL := 'https://github.com/Frikallo/MISST/releases/download/V3.1.0/MISST_CUDA_3.1.0_Release_Win.7z'; DownloadFileName := 'MISST.7z'; end else begin DownloadURL := 'https://github.com/Frikallo/MISST/releases/download/V3.1.0/MISST_CPU_3.1.0_Release_Win.7z'; DownloadFileName := 'MISST.7z'; end; DownloadPage.Clear; DownloadPage.Add(DownloadURL, DownloadFileName, ''); DownloadPage.Show; try try DownloadPage.Download; Result := True; except SuppressibleMsgBox(AddPeriod(GetExceptionMessage), mbCriticalError, MB_OK, IDOK); Result := False; end; finally DownloadPage.Hide; end; end else Result := True; end; function GetFirstSubfolder(Param: String): String; var FindRec: TFindRec; begin Result := ''; if FindFirst(ExpandConstant('{app}\*'), FindRec) then begin try while FindNext(FindRec) do begin if (FindRec.Attributes and FILE_ATTRIBUTE_DIRECTORY <> 0) and (FindRec.Name <> '.') and (FindRec.Name <> '..') then begin Result := FindRec.Name; Break; end; end; finally FindClose(FindRec); end; end; end; procedure CurStepChanged(CurStep: TSetupStep); var ExtractResultCode: Integer; ArchivePath: string; begin if CurStep = ssInstall then begin ArchivePath := ExpandConstant('{tmp}\MISST.7z'); ExtractResultCode := 0; if not FileExists(ArchivePath) then begin MsgBox('The MISST.7z archive file is missing.', mbError, MB_OK); WizardForm.Close; end else begin WizardForm.StatusLabel.Caption := 'Extracting...'; WizardForm.ProgressGauge.Max := 100; // Set the maximum value for the progress bar WizardForm.ProgressGauge.Position := 0; // Initialize the progress bar position Unzip(ArchivePath, ExpandConstant('{app}')); RenameFile(ExpandConstant('{app}\'+GetFirstSubfolder('')),ExpandConstant('{app}\MISST')); end; end; end; [Run] Filename: "{app}\MISST\MISST.exe"; Description: "{cm:LaunchProgram,MISST}"; Flags: nowait postinstall skipifsilent ================================================ FILE: Installation Guide - MacOS.md ================================================ # How to get started with MISST - MacOS ## **Manual installation on Mac0S using miniconda3** This worked for @[CAprogs](https://github.com/CAprogs) on a **MacbookPro 2021 M1 pro**. # ## _**Follow these steps**_ if you don't have **MINICONDA** , you should install it using this [**link**](https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-arm64.pkg). # For **Pyaudio** package you should install [**Homebrew**](https://github.com/Homebrew/brew/releases/latest) first. Then run `brew install portaudio` in your **terminal** ( this is required to install **pyaudio** later ) # Now follow these steps 🤓 - Download the **MISST Zip file** [**here**](https://github.com/Frikallo/MISST/archive/refs/tags/V3.1.0.zip) - Create your virtual env using **conda** _(Copy and paste in your Terminal)_ Enter `miniconda3` folder ⬇️ ``` cd miniconda3 ``` # Create a `venv` named _**MISSTvenv**_ ⬇️ ``` conda create --name MISSTvenv ``` # Activate the `MISSTvenv` ⬇️ ``` conda activate MISSTvenv ``` # Install `pip` ( inside the MISSTvenv ) ⬇️ ``` conda install pip ``` # Install _**the requirements packages**_ ( inside the MISSTvenv ). Replace < `path/to/requirements.txt` > with your **path** to the **requirements.txt** file ⬇️ ``` conda install --file path/to/requirements.txt ``` # At this point I encountered some `issues` when installing **packages** with `pip` / `conda`. ( All packages weren't installed ) # Before proceeding, please ensure that you have `Git` **installed** on your macOS system. - In your terminal, enter the following command ⬇️ ``` git --version ``` 1. If you see the **Git version** displayed, it means `Git` is **already installed** on your system, and you can proceed to the next step. 2. If `Git` is **not installed**, you can install it using `Homebrew` ⬇️ ( See the Doumentation [**here**](https://git-scm.com/download/mac) ) ``` brew install git ``` # Now just run the following command ( inside the MISSTvenv ) ⬇️ ``` pip install -r requirements.txt ( GPU ) pip install -r requirements-minimal.txt ( CPU ) ``` If that doesn't work, try installing the packages one by one ⬇️ ``` pip install customtkinter git+https://github.com/Frikallo/gputil.git@master music_tag psutil PILLOW pypresence lyrics_extractor demucs pyaudio soundfile scipy vcolorpicker ``` Then install torch with or without `CUDA` ⬇️ ``` pip install torch==2.0.1+cu117 torchaudio==2.0.2+cu117 torchvision==0.15.2+cu117 -f https://download.pytorch.org/whl/torch_stable.html ``` ``` pip install torch==2.0.1 torchvision==0.15.2 torchaudio==2.0.2 ``` Then **run** ( inside the MISSTvenv ) ⬇️ ``` conda install pyqt ``` # - Enter the `MISSTapp.py` Folder ( replace with the real path ) ``` cd path/to/MISSTapp.py ``` - `Run` the App 🧞‍♂️ ( inside the MISSTvenv ) ``` python MISSTapp.py ``` ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. 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. Copyright (C) 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 . 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: Copyright (C) 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 . 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 . ================================================ FILE: MISST/Assets/Themes/MISST.json ================================================ { "CTk": { "fg_color": ["gray92", "gray14"] }, "CTkToplevel": { "fg_color": ["gray92", "gray14"] }, "CTkFrame": { "corner_radius": 6, "border_width": 0, "fg_color": ["gray86", "gray17"], "top_fg_color": ["gray81", "gray20"], "border_color": ["gray65", "gray28"] }, "CTkButton": { "corner_radius": 6, "border_width": 0, "fg_color": ["#3B8ED0", "#1F6AA5"], "hover_color": ["#36719F", "#144870"], "border_color": ["#3E454A", "#949A9F"], "text_color": ["gray10", "#DCE4EE"], "text_color_disabled": ["gray74", "gray60"] }, "CTkLabel": { "corner_radius": 0, "fg_color": "transparent", "text_color": ["gray10", "#DCE4EE"] }, "CTkEntry": { "corner_radius": 6, "border_width": 2, "fg_color": ["#F9F9FA", "#343638"], "border_color": ["#979DA2", "#565B5E"], "text_color":["gray10", "#DCE4EE"], "placeholder_text_color": ["gray52", "gray62"] }, "CTkCheckbox": { "corner_radius": 6, "border_width": 3, "fg_color": ["#3B8ED0", "#1F6AA5"], "border_color": ["#3E454A", "#949A9F"], "hover_color": ["#3B8ED0", "#1F6AA5"], "checkmark_color": ["#DCE4EE", "gray90"], "text_color": ["gray10", "#DCE4EE"], "text_color_disabled": ["gray60", "gray45"] }, "CTkSwitch": { "corner_radius": 1000, "border_width": 3, "button_length": 0, "fg_Color": ["#939BA2", "#4A4D50"], "progress_color": ["#3B8ED0", "#1F6AA5"], "button_color": ["gray36", "#D5D9DE"], "button_hover_color": ["gray20", "gray100"], "text_color": ["gray10", "#DCE4EE"], "text_color_disabled": ["gray60", "gray45"] }, "CTkRadiobutton": { "corner_radius": 1000, "border_width_checked": 6, "border_width_unchecked": 3, "fg_color": ["#3B8ED0", "#1F6AA5"], "border_color": ["#3E454A", "#949A9F"], "hover_color": ["#36719F", "#144870"], "text_color": ["gray10", "#DCE4EE"], "text_color_disabled": ["gray60", "gray45"] }, "CTkProgressBar": { "corner_radius": 1000, "border_width": 0, "fg_color": ["#939BA2", "#4A4D50"], "progress_color": ["#3B8ED0", "#1F6AA5"], "border_color": ["gray", "gray"] }, "CTkSlider": { "corner_radius": 1000, "button_corner_radius": 1000, "border_width": 6, "button_length": 0, "fg_color": ["#939BA2", "#4A4D50"], "progress_color": ["gray40", "#AAB0B5"], "button_color": ["#3B8ED0", "#1F6AA5"], "button_hover_color": ["#36719F", "#144870"] }, "CTkOptionMenu": { "corner_radius": 6, "fg_color": ["#3B8ED0", "#1F6AA5"], "button_color": ["#36719F", "#144870"], "button_hover_color": ["#27577D", "#203A4F"], "text_color": ["#DCE4EE", "#DCE4EE"], "text_color_disabled": ["gray74", "gray60"] }, "CTkComboBox": { "corner_radius": 6, "border_width": 2, "fg_color": ["#F9F9FA", "#343638"], "border_color": ["#979DA2", "#565B5E"], "button_color": ["#979DA2", "#565B5E"], "button_hover_color": ["#6E7174", "#7A848D"], "text_color": ["gray10", "#DCE4EE"], "text_color_disabled": ["gray50", "gray45"] }, "CTkScrollbar": { "corner_radius": 1000, "border_spacing": 4, "fg_color": "transparent", "button_color": ["gray55", "gray41"], "button_hover_color": ["gray40", "gray53"] }, "CTkSegmentedButton": { "corner_radius": 6, "border_width": 2, "fg_color": ["#979DA2", "gray29"], "selected_color": ["#3B8ED0", "#1F6AA5"], "selected_hover_color": ["#36719F", "#144870"], "unselected_color": ["#979DA2", "gray29"], "unselected_hover_color": ["gray70", "gray41"], "text_color": ["#DCE4EE", "#DCE4EE"], "text_color_disabled": ["gray74", "gray60"] }, "CTkTextbox": { "corner_radius": 6, "border_width": 0, "fg_color": ["#F9F9FA", "#1D1E1E"], "border_color": ["#979DA2", "#565B5E"], "text_color":["gray10", "#DCE4EE"], "scrollbar_button_color": ["gray55", "gray41"], "scrollbar_button_hover_color": ["gray40", "gray53"] }, "CTkScrollableFrame": { "label_fg_color": ["gray78", "gray23"] }, "DropdownMenu": { "fg_color": ["gray90", "gray20"], "hover_color": ["gray75", "gray28"], "text_color": ["gray10", "gray90"] }, "CTkFont": { "macOS": { "family": "SF Display", "size": 13, "weight": "normal" }, "Windows": { "family": "Roboto", "size": 13, "weight": "normal" }, "Linux": { "family": "Roboto", "size": 13, "weight": "normal" } } } ================================================ FILE: MISST/Assets/Themes/maluableJSON ================================================ { "CTk": { "fg_color": ["gray92", "gray14"] }, "CTkToplevel": { "fg_color": ["gray92", "gray14"] }, "CTkFrame": { "corner_radius": 6, "border_width": 0, "fg_color": ["gray86", "gray17"], "top_fg_color": ["gray81", "gray20"], "border_color": ["gray65", "gray28"] }, "CTkButton": { "corner_radius": 6, "border_width": 0, "fg_color": ["defaultLightColor", "defaultDarkColor"], "hover_color": ["defaultLightHoverColor", "defaultDarkHoverColor"], "border_color": ["#3E454A", "#949A9F"], "text_color": ["gray10", "#DCE4EE"], "text_color_disabled": ["gray74", "gray60"] }, "CTkLabel": { "corner_radius": 0, "fg_color": "transparent", "text_color": ["gray10", "#DCE4EE"] }, "CTkEntry": { "corner_radius": 6, "border_width": 2, "fg_color": ["#F9F9FA", "#343638"], "border_color": ["#979DA2", "#565B5E"], "text_color":["gray10", "#DCE4EE"], "placeholder_text_color": ["gray52", "gray62"] }, "CTkCheckbox": { "corner_radius": 6, "border_width": 3, "fg_color": ["defaultLightColor", "defaultDarkColor"], "border_color": ["#3E454A", "#949A9F"], "hover_color": ["defaultLightColor", "defaultDarkColor"], "checkmark_color": ["#DCE4EE", "gray90"], "text_color": ["gray10", "#DCE4EE"], "text_color_disabled": ["gray60", "gray45"] }, "CTkSwitch": { "corner_radius": 1000, "border_width": 3, "button_length": 0, "fg_Color": ["#939BA2", "#4A4D50"], "progress_color": ["defaultLightColor", "defaultDarkColor"], "button_color": ["gray36", "#D5D9DE"], "button_hover_color": ["gray20", "gray100"], "text_color": ["gray10", "#DCE4EE"], "text_color_disabled": ["gray60", "gray45"] }, "CTkRadiobutton": { "corner_radius": 1000, "border_width_checked": 6, "border_width_unchecked": 3, "fg_color": ["defaultLightColor", "defaultDarkColor"], "border_color": ["#3E454A", "#949A9F"], "hover_color": ["defaultLightHoverColor", "defaultDarkHoverColor"], "text_color": ["gray10", "#DCE4EE"], "text_color_disabled": ["gray60", "gray45"] }, "CTkProgressBar": { "corner_radius": 1000, "border_width": 0, "fg_color": ["#939BA2", "#4A4D50"], "progress_color": ["defaultLightColor", "defaultDarkColor"], "border_color": ["gray", "gray"] }, "CTkSlider": { "corner_radius": 1000, "button_corner_radius": 1000, "border_width": 6, "button_length": 0, "fg_color": ["#939BA2", "#4A4D50"], "progress_color": ["gray40", "#AAB0B5"], "button_color": ["defaultLightColor", "defaultDarkColor"], "button_hover_color": ["defaultLightHoverColor", "defaultDarkHoverColor"] }, "CTkOptionMenu": { "corner_radius": 6, "fg_color": ["defaultLightColor", "defaultDarkColor"], "button_color": ["defaultLightHoverColor", "defaultDarkHoverColor"], "button_hover_color": ["defaultLightDarker", "defaultDarkDarker"], "text_color": ["#DCE4EE", "#DCE4EE"], "text_color_disabled": ["gray74", "gray60"] }, "CTkComboBox": { "corner_radius": 6, "border_width": 2, "fg_color": ["#F9F9FA", "#343638"], "border_color": ["#979DA2", "#565B5E"], "button_color": ["#979DA2", "#565B5E"], "button_hover_color": ["#6E7174", "#7A848D"], "text_color": ["gray10", "#DCE4EE"], "text_color_disabled": ["gray50", "gray45"] }, "CTkScrollbar": { "corner_radius": 1000, "border_spacing": 4, "fg_color": "transparent", "button_color": ["gray55", "gray41"], "button_hover_color": ["gray40", "gray53"] }, "CTkSegmentedButton": { "corner_radius": 6, "border_width": 2, "fg_color": ["#979DA2", "gray29"], "selected_color": ["defaultLightColor", "defaultDarkColor"], "selected_hover_color": ["defaultLightHoverColor", "defaultDarkHoverColor"], "unselected_color": ["#979DA2", "gray29"], "unselected_hover_color": ["gray70", "gray41"], "text_color": ["#DCE4EE", "#DCE4EE"], "text_color_disabled": ["gray74", "gray60"] }, "CTkTextbox": { "corner_radius": 6, "border_width": 0, "fg_color": ["#F9F9FA", "#1D1E1E"], "border_color": ["#979DA2", "#565B5E"], "text_color":["gray10", "#DCE4EE"], "scrollbar_button_color": ["gray55", "gray41"], "scrollbar_button_hover_color": ["gray40", "gray53"] }, "CTkScrollableFrame": { "label_fg_color": ["gray78", "gray23"] }, "DropdownMenu": { "fg_color": ["gray90", "gray20"], "hover_color": ["gray75", "gray28"], "text_color": ["gray10", "gray90"] }, "CTkFont": { "macOS": { "family": "SF Display", "size": 13, "weight": "normal" }, "Windows": { "family": "Roboto", "size": 13, "weight": "normal" }, "Linux": { "family": "Roboto", "size": 13, "weight": "normal" } } } ================================================ FILE: MISST/Assets/config_base.json ================================================ { "defaultLightColor": "#3B8ED0", "defaultDarkColor": "#1F6AA5", "defaultLightHoverColor": "#36719F", "defaultDarkHoverColor": "#144870", "defaultLightDarker": "#27577D", "defaultDarkDarker": "#203A4F", "chosenLightColor": "#3B8ED0", "chosenDarkColor": "#1F6AA5", "chosenLightHoverColor": "#36719F", "chosenDarkHoverColor": "#144870", "chosenLightDarker": "#27577D", "chosenDarkDarker": "#203A4F", "rpc": "true", "autoplay": "true", "accelerate_on_gpu": "false", "chosen_model": "htdemucs", "importsDest": "./separated", "eq": "false", "eq_move_sliders_together": "true", "eq_1": "0.0", "eq_2": "0.0", "eq_3": "0.0", "eq_4": "0.0", "eq_5": "0.0", "eq_6": "0.0", "eq_7": "0.0", "eq_8": "0.0", "eq_9": "0.0", "speed": "1.0", "pitch": "1.0", "reverb": "0.0", "discord_client_id": "1007423253373001810", "cse_id": "8102f2649f8824245", "cse_api_key": "AIzaSyBxUlDVX64RZL5Dvw6CtQ4JsyOjASiascY" } ================================================ FILE: MISST/MISSTSetup.py ================================================ import os import threading import typing from pathlib import Path import customtkinter import requests class MISSTSetup(customtkinter.CTkFrame): """ Class for handling the setup of MISST """ def __init__(self, parent:typing.Any, model:str) -> None: """ Initialize the setup Args: parent (tkinter.Tk): The parent of the frame model (str): The chosen model """ super().__init__(parent) self.parent = parent self.model_urls = self.get_model_urls(model) for url in self.model_urls: if not os.path.isfile("Pretrained/"+url.split("/")[-1]): break else: self.parent.logger.info("All models are already downloaded") self.destroy() return # delete old model files for file in os.listdir("Pretrained/"): if file.endswith(".th"): os.remove("Pretrained/" + file) self.progress_var = customtkinter.DoubleVar() self.width = 755 self.height = 430 self.FONT = "Roboto Medium" self.configure(width=self.width, height=self.height) self.create_widgets() def get_model_urls(self, model:str) -> typing.List[str]: models = [] with open("Pretrained/" + model + ".yaml", "r") as f: for line in f.readlines(): if "models: " in line: models = line.split("'")[1::2] break remote_file = Path("Pretrained/files.txt") root: str = '' remote_models = {} for line in remote_file.read_text().split('\n'): line = line.strip() if line.startswith('#'): continue elif line.startswith('root:'): root = line.split(':', 1)[1].strip() else: sig = line.split('-', 1)[0] assert sig not in remote_models remote_models[sig] = "https://dl.fbaipublicfiles.com/demucs/" + root + line urls = [] for model in models: urls.append(remote_models[model]) return urls def create_widgets(self) -> None: """ Create the widgets """ self.label = customtkinter.CTkLabel(self, text="Setting up models...", font=(self.FONT, 20)) self.label.place(relx=0.5, rely=0.45, anchor="center") self.progressbar = customtkinter.CTkProgressBar(self, orientation="horizontal", width=300, height=15, variable=self.progress_var) self.progressbar.place(relx=0.5, rely=0.55, anchor="center") try: self.start_setup() except: self.label.configure(text="Download failed. Please try again.") threading.Timer(2, self.destroy).start() def start_setup(self) -> None: """ Start the setup """ self.thread = threading.Thread(target=self.setup_models) self.thread.start() def setup_models(self) -> None: """ Setup the models """ total_files = len(self.model_urls) for i, url in enumerate(self.model_urls): self.label.configure(text="Setting up models {}/{}".format(i + 1, total_files)) if not os.path.isfile(url.split("/")[-1]): self.download_file(url) self.progress_var.set((i + 1) / total_files * 100) self.label.configure(text="Setup is complete. Welcome to MISST!") threading.Timer(2, self.destroy).start() def download_file(self, url:str) -> None: """ Download a file Args: file (str): The file to download """ response = requests.get(url, stream=True) total_length = response.headers.get('content-length') try: with open("Pretrained/" + url.split("/")[-1], 'wb') as f: if total_length is None: # no content length header f.write(response.content) else: dl = 0 total_length = int(total_length) chunk = total_length // 50 for data in response.iter_content(chunk_size=chunk): dl += len(data) f.write(data) self.progress_var.set((dl / total_length)) self.update_idletasks() # Update the GUI to refresh the progress bar except: os.remove("Pretrained/" + url.split("/")[-1]) self.label.configure(text="Downloaded file is corrupted or an Error occured. Please try again.") raise Exception("Downloaded file is corrupted or an Error occured. Please try again.") ================================================ FILE: MISST/MISSTapp.py ================================================ import os os.chdir(os.path.dirname(os.path.abspath(__file__))) import base64 import datetime import io import random import shutil import signal import subprocess import sys import tempfile import threading import time import tkinter import traceback import webbrowser import customtkinter import GPUtil import music_tag import psutil from __version__ import __version__ as version from lyrics_extractor import SongLyrics from MISSThelpers import MISSTconsole, MISSThelpers from MISSTlogger import MISSTlogger from MISSTplayer import MISSTplayer from MISSTpreprocess import MISSTpreprocess from MISSTsettings import MISSTconfig, MISSTsettings from MISSTSetup import MISSTSetup from PIL import Image from pypresence import Presence customtkinter.set_appearance_mode("System") # Modes: "System" (standard), "Dark", "Light" customtkinter.set_default_color_theme("./Assets/Themes/MISST.json") # Themes: "blue" (standard), "green", "dark-blue" class MISSTapp(customtkinter.CTk): """ The main MISST application. """ def __init__(self) -> None: """ Initialize the MISST application. """ super().__init__() self.player = MISSTplayer([ "Assets/silent/silence.flac", "Assets/silent/silence.flac", "Assets/silent/silence.flac", "Assets/silent/silence.flac" ], [0]*4 ) self.logger = MISSTlogger().logger self.settings = MISSTsettings() self.preprocess = MISSTpreprocess() self.rpc = self.settings.getSetting("rpc") self.discord_client_id = self.settings.getSetting("discord_client_id") if self.rpc == "true": try: self.RPC = Presence(self.discord_client_id) self.RPC.connect() self.RPC_CONNECTED = True except: self.logger.error(traceback.format_exc()) self.logger.error("RPC connection failed or aborted.") self.RPC_CONNECTED = False else: self.RPC_CONNECTED = False tokens = [self.settings.getSetting("cse_api_key"), self.settings.getSetting("cse_id")] self.lyric_engine = SongLyrics(tokens[0],tokens[1]) self.importsDest = os.path.abspath(self.settings.getSetting("importsDest")) if not os.path.isdir(self.importsDest): os.mkdir(self.importsDest) self.FFMpegAvailable = True if shutil.which("ffmpeg") != None else False self.version = version for line in MISSThelpers.GenerateSystemInfo(self).split("\n"): if line != "": self.logger.info(line) self.playing = False self.current_song = "" # configure window self.title("MISST") self.iconbitmap(r"./Assets/icon.ico") self.WIDTH = 755 self.HEIGHT = 430 #self.WIDTH = int(self.winfo_screenwidth() * 0.3932291666666667) #self.HEIGHT = int(self.winfo_screenheight() * 0.3981481481481481) self.geometry(f"{self.WIDTH}x{self.HEIGHT}") self.minsize(self.WIDTH, self.HEIGHT) self.maxsize(755, 430) #customtkinter.set_widget_scaling(((self.WIDTH / 755) + (self.HEIGHT / 430)) / 2) # widget dimensions and text size #customtkinter.set_window_scaling(((self.WIDTH / 755) + (self.HEIGHT / 430)) / 2) # window geometry dimensions self.check_var1 = tkinter.StringVar(value="on") self.check_var2 = tkinter.StringVar(value="on") self.check_var3 = tkinter.StringVar(value="on") self.check_var4 = tkinter.StringVar(value="on") self.nc_var = tkinter.StringVar(value="off") self.ImageCache = { "empty" : customtkinter.CTkImage(Image.open(f"./Assets/UIAssets/empty.png"), size=(1, 1)), "playing" : customtkinter.CTkImage(dark_image=Image.open("./Assets/Player/player-pause-light.png"), light_image=Image.open("./Assets/Player/player-pause.png"), size=(32,32)), "paused" : customtkinter.CTkImage(dark_image=Image.open("./Assets/Player/player-play-light.png"), light_image=Image.open("./Assets/Player/player-play.png"), size=(32,32)), "shuffle" : customtkinter.CTkImage(dark_image=Image.open("./Assets/Player/player-shuffle-light.png"), light_image=Image.open("./Assets/Player/player-shuffle.png"), size=(25,25)), "loop" : customtkinter.CTkImage(dark_image=Image.open("./Assets/Player/loop-light.png"), light_image=Image.open("./Assets/Player/loop.png"), size=(25,25)), "loop-off" : customtkinter.CTkImage(dark_image=Image.open("./Assets/Player/loop-off-light.png"), light_image=Image.open("./Assets/Player/loop-off.png"), size=(25,25)), "skip-forward" : customtkinter.CTkImage(dark_image=Image.open("./Assets/Player/player-skip-forward-light.png"), light_image=Image.open("./Assets/Player/player-skip-forward.png"), size=(30,30)), "skip-back" : customtkinter.CTkImage(dark_image=Image.open("./Assets/Player/player-skip-back-light.png"), light_image=Image.open("./Assets/Player/player-skip-back.png"), size=(30,30)), "settings" : customtkinter.CTkImage(dark_image=Image.open("./Assets/UIAssets/settings-light.png"), light_image=Image.open("./Assets/UIAssets/settings.png"), size=(25,25)), "equalizer" : customtkinter.CTkImage(dark_image=Image.open("./Assets/UIAssets/equalizer-light.png"), light_image=Image.open("./Assets/UIAssets/equalizer.png"), size=(25,25)), "github" : customtkinter.CTkImage(dark_image=Image.open("./Assets/UIAssets/code-light.png"), light_image=Image.open("./Assets/UIAssets/code.png"), size=(25,25)), "import" : customtkinter.CTkImage(dark_image=Image.open("./Assets/UIAssets/import-dark.png"), light_image=Image.open("./Assets/UIAssets/import-light.png"), size=(30,30)), "spotify" : customtkinter.CTkImage(Image.open("./Assets/Sources/Spotify.png"), size=(40,40)), "youtube" : customtkinter.CTkImage(Image.open("./Assets/Sources/YoutubeMusic.png"), size=(40,40)), "applemusic" : customtkinter.CTkImage(Image.open("./Assets/Sources/AppleMusic.png"), size=(40,40)), "soundcloud" : customtkinter.CTkImage(Image.open("./Assets/Sources/Soundcloud.png"), size=(40,40)), "return" : customtkinter.CTkImage(dark_image=Image.open("./Assets/UIAssets/goback_dark.png"), light_image=Image.open("./Assets/UIAssets/goback.png"), size=(25,25)), "no-cover-art" : customtkinter.CTkImage(dark_image=Image.open("./Assets/UIAssets/default-light.png"), light_image=Image.open("./Assets/UIAssets/default.png"), size=(40,40)) } self.loop = False self.autoplay = True self.FONT = "Roboto Medium" self.createWidgets() # Check if setup is needed (next version will have a better way of doing this) # updater = MISSTupdater(self) # try: # updater.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) # except: # pass required_files = MISSTSetup.get_model_urls(self, self.settings.getSetting("chosen_model")) required_files = [file.split("/")[-1] for file in required_files] if not all([os.path.isfile(f"Pretrained/{file}") for file in required_files]): self.logger.info("Setup required.") self.model_setup_widget = MISSTSetup(self, self.settings.getSetting("chosen_model")) self.model_setup_widget.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) else: self.logger.info("Setup not required.") def on_closing(): self.destroy() self.quit() self.player.stop() current_pid = psutil.Process().pid # Terminate child processes process = psutil.Process(current_pid) children = process.children(recursive=True) self.logger.info(f"Terminating {len(children)} child processes.") for child in children: child.terminate() # Terminate the current process self.logger.info("MISST closed.") os.kill(current_pid, signal.SIGTERM) sys.exit() self.protocol("WM_DELETE_WINDOW", on_closing) def createWidgets(self) -> None: """ Creates the widgets for the main window. """ self.west_frame = customtkinter.CTkFrame(master=self, width=self.WIDTH * (175 / self.WIDTH), height=self.HEIGHT * (430 / self.HEIGHT), corner_radius=0) self.west_frame.grid(row=0, column=0, sticky="nsew", padx=(0, 5), rowspan=4) self.north_frame = customtkinter.CTkFrame(master=self, width=self.WIDTH * (350 / self.WIDTH), height=self.HEIGHT * (100 / self.HEIGHT), corner_radius=8) self.north_frame.grid(row=0, column=1, sticky="nsew", padx=10, pady=(5, 0)) self.center_frame = customtkinter.CTkFrame(master=self, width=self.WIDTH * (350 / self.WIDTH), height=self.HEIGHT * (200 / self.HEIGHT), corner_radius=8) self.center_frame.grid(row=1, column=1, sticky="nsew", padx=10, pady=10) self.south_frame = customtkinter.CTkFrame(master=self, width=self.WIDTH * (350 / self.WIDTH), height=self.HEIGHT * (100 / self.HEIGHT), corner_radius=8) self.south_frame.grid(row=2, column=1, sticky="nsew", padx=10, pady=(0, 5)) self.interface_frame = customtkinter.CTkFrame(master=self, width=self.WIDTH * (195 / self.WIDTH), height=self.HEIGHT * (100 / self.HEIGHT), corner_radius=8) self.interface_frame.grid(row=0, column=2, sticky="nsew", padx=(5, 0), pady=(5, 0)) self.east_frame = customtkinter.CTkTabview(master=self, width=self.WIDTH * (195 / self.WIDTH), height=self.HEIGHT * (100 / self.HEIGHT), corner_radius=8) self.east_frame.grid(row=1, column=2, sticky="nsew", padx=(5, 0), pady=(0, 5), rowspan=3) self.east_frame.add("Imported") self.east_frame.add("Export") self.east_frame.tab("Imported").grid_columnconfigure(0, weight=1) self.east_frame.tab("Export").grid_columnconfigure(0, weight=1) # Interface Frame self.shuffle_button = customtkinter.CTkButton( master=self.interface_frame, image=self.ImageCache["shuffle"], command=lambda: self.shuffle(), text="", width=5, height=5, fg_color='transparent', hover_color=self.interface_frame.cget("bg_color"), corner_radius=8 ) self.loop_button = customtkinter.CTkButton( master=self.interface_frame, image=self.ImageCache["loop-off"], command=lambda: self.loopEvent(), text="", width=5, height=5, fg_color='transparent', hover_color=self.interface_frame.cget("bg_color"), corner_radius=8 ) self.next_button = customtkinter.CTkButton( master=self.interface_frame, image=self.ImageCache["skip-forward"], command=lambda: print("test"), text="", width=5, height=5, fg_color='transparent', hover_color=self.interface_frame.cget("bg_color"), corner_radius=8, state=tkinter.DISABLED ) self.previous_button = customtkinter.CTkButton( master=self.interface_frame, image=self.ImageCache["skip-back"], command=lambda: print("test"), text="", width=5, height=5, fg_color='transparent', hover_color=self.interface_frame.cget("bg_color"), corner_radius=8, state=tkinter.DISABLED ) self.playpause_button = customtkinter.CTkButton( master=self.interface_frame, image=self.ImageCache["paused"], command=lambda: self.playpause(), text="", width=5, height=5, fg_color='transparent', hover_color=self.interface_frame.cget("bg_color"), corner_radius=8, state=tkinter.DISABLED ) self.next_button.place(relx=0.67, rely=0.5, anchor=tkinter.CENTER) self.previous_button.place(relx=0.33, rely=0.5, anchor=tkinter.CENTER) self.shuffle_button.place(relx=0.16, rely=0.5, anchor=tkinter.CENTER) self.loop_button.place(relx=0.84, rely=0.5, anchor=tkinter.CENTER) self.playpause_button.place(relx=0.50, rely=0.5, anchor=tkinter.CENTER) ## EAST FRAME ------------- --------------------------------------------------------------------------------------- # Imported Tab self.search_entry = customtkinter.CTkEntry( master=self.east_frame.tab("Imported"), width=150, height=25, placeholder_text="Search for audio", ) self.search_entry.place(relx=0.5, rely=0.05, anchor=tkinter.CENTER) self.listframe = customtkinter.CTkFrame( master=self.east_frame.tab("Imported"), width=150, height=175, corner_radius=8 ) self.listframe.place(relx=0.5, rely=0.45, anchor=tkinter.CENTER) self.songs_box = customtkinter.CTkTextbox( master=self.listframe, width=140, height=175, bg_color='transparent', fg_color='transparent', corner_radius=8, ) self.songs_box.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) self.index_entry = customtkinter.CTkEntry( master=self.east_frame.tab("Imported"), width=150, height=25, placeholder_text="Enter index of audio", ) self.index_entry.place(relx=0.5, rely=0.85, anchor=tkinter.CENTER) self.playbutton = customtkinter.CTkButton( master=self.east_frame.tab("Imported"), text="Play", width=150, height=25, command=lambda: self.play_search(self.index_entry.get(), MISSThelpers.MISSTlistdir(self, self.importsDest)), ) self.playbutton.place(relx=0.5, rely=0.95, anchor=tkinter.CENTER) importsBoxUpdates = threading.Thread(target=self.imports_check, args=(self.search_entry, self.songs_box)) importsBoxUpdates.daemon = True importsBoxUpdates.start() # Export Tab self.export_components = { "Bass": (None, None), "Other": (None, None), "Drums": (None, None), "Vocals": (None, None) } def activate(button, slider): button_text = button.cget("text") if button_text == "Bass": sound = 0 self.slider1.set(0.5) if button.cget("border_color") == "#3E454A" else self.slider1.set(0) self.checkbox1.select() if button.cget("border_color") == "#3E454A" else self.checkbox1.deselect() elif button_text == "Drums": sound = 1 self.slider2.set(0.5) if button.cget("border_color") == "#3E454A" else self.slider2.set(0) self.checkbox2.select() if button.cget("border_color") == "#3E454A" else self.checkbox2.deselect() elif button_text == "Other": sound = 2 self.slider3.set(0.5) if button.cget("border_color") == "#3E454A" else self.slider3.set(0) self.checkbox3.select() if button.cget("border_color") == "#3E454A" else self.checkbox3.deselect() elif button_text == "Vocals": sound = 3 self.slider4.set(0.5) if button.cget("border_color") == "#3E454A" else self.slider4.set(0) self.checkbox4.select() if button.cget("border_color") == "#3E454A" else self.checkbox4.deselect() if button.cget("border_color") == "#3E454A": button.configure(border_color=self.settings.getSetting("chosenLightColor") if customtkinter.get_appearance_mode() == "Light" else self.settings.getSetting("chosenDarkColor")) slider.set(0.5) else: button.configure(border_color="#3E454A") slider.set(0) self.player.set_volume(sound, slider.get()) def slider_event(slider, button): button_text = button.cget("text") if button_text == "Bass": sound = 0 self.slider1.set(self.export_components["Bass"][0].get()) self.checkbox1.select() if self.export_components["Bass"][0].get() != 0 else self.checkbox1.deselect() elif button_text == "Drums": sound = 1 self.slider2.set(self.export_components["Drums"][0].get()) self.checkbox2.select() if self.export_components["Drums"][0].get() != 0 else self.checkbox2.deselect() elif button_text == "Other": sound = 2 self.slider3.set(self.export_components["Other"][0].get()) self.checkbox3.select() if self.export_components["Other"][0].get() != 0 else self.checkbox3.deselect() elif button_text == "Vocals": sound = 3 self.slider4.set(self.export_components["Vocals"][0].get()) self.checkbox4.select() if self.export_components["Vocals"][0].get() != 0 else self.checkbox4.deselect() self.player.set_volume(sound, slider) if slider == 0: button.configure(border_color="#3E454A") else: button.configure(border_color=self.settings.getSetting("chosenLightColor") if customtkinter.get_appearance_mode() == "Light" else self.settings.getSetting("chosenDarkColor")) widgets = ["Bass", "Other", "Drums", "Vocals"] sliders = [] i = 0 for widget in widgets: activate_button = customtkinter.CTkButton( master=self.east_frame.tab("Export"), text=widget, width=70, height=70, border_width=2, border_color=self.settings.getSetting("chosenLightColor") if customtkinter.get_appearance_mode() == "Light" else self.settings.getSetting("chosenDarkColor"), bg_color='transparent', fg_color='transparent', hover_color=self.east_frame.cget("bg_color"), ) factor = 0.25 if i < 2 else 0.75 activate_button.place( relx=factor, rely=0.25 if i % 2 == 0 else 0.6, anchor=tkinter.CENTER ) volume_slider = customtkinter.CTkSlider( master=self.east_frame.tab("Export"), width=70, height=10, number_of_steps=10 ) sliders.append(volume_slider) volume_slider.place( relx=factor, rely=0.42 if i % 2 == 0 else 0.77, anchor=tkinter.CENTER ) activate_button.configure( command=lambda button=activate_button, slider=volume_slider: activate(button, slider) ) volume_slider.configure( command=lambda slider=volume_slider, button=activate_button: slider_event(slider, button) ) i += 1 self.export_components[activate_button.cget("text")] = volume_slider, activate_button self.export_button = customtkinter.CTkButton( master=self.east_frame.tab("Export"), text="Export", width=150, height=25, command=lambda: threading.Thread(target=self.export, args=(self.current_song, sliders), daemon=True).start() ) self.export_button.place(relx=0.5, rely=0.95, anchor=tkinter.CENTER) ## WEST FRAME ---------------------------------------------------------------------------------------------------- self.logolabel = customtkinter.CTkLabel( master=self.west_frame, text=f"MISST {version}", font=(self.FONT, -16) ) self.logolabel.place(relx=0.5, rely=0.12, anchor=tkinter.CENTER) self.themelabel = customtkinter.CTkLabel(master=self.west_frame, text="Appearance Mode:") self.themelabel.place(relx=0.5, rely=0.7, anchor=tkinter.CENTER) self.thememenu = customtkinter.CTkOptionMenu( master=self.west_frame, values=["System", "Dark", "Light"], command=lambda x: MISSThelpers.change_theme(x) ) self.thememenu.place(relx=0.5, rely=0.8, anchor=tkinter.CENTER) self.settings_button = customtkinter.CTkButton( master=self.west_frame, font=(self.FONT, -12), text="", image=self.ImageCache["settings"], bg_color='transparent', fg_color='transparent', hover_color=self.west_frame.cget("bg_color"), width=5, height=5, command=lambda: self.draw_settings_frame(), ) self.settings_button.place(relx=0.3, rely=0.9, anchor=tkinter.CENTER) self.equalizer = customtkinter.CTkButton( master=self.west_frame, font=(self.FONT, -12), text="", image=self.ImageCache["equalizer"], bg_color='transparent', fg_color='transparent', hover_color=self.west_frame.cget("bg_color"), width=5, height=5, corner_radius=16, command=lambda: self.draw_effects_frame(), ) self.equalizer.place(relx=0.7, rely=0.9, anchor=tkinter.CENTER) self.github_button = customtkinter.CTkButton( master=self.west_frame, font=(self.FONT, -12), text="", image=self.ImageCache["github"], bg_color='transparent', fg_color='transparent', hover_color=self.west_frame.cget("bg_color"), width=5, height=5, command=lambda: webbrowser.open("https://github.com/Frikallo/MISST", new=2), ) self.github_button.place(relx=0.5, rely=0.9, anchor=tkinter.CENTER) ## NORTH FRAME ---------------------------------------------------------------------------------------------------- self.songlabel = customtkinter.CTkButton( master=self.north_frame, text=f"Play Something!", width=240, height=50, font=(self.FONT, -14), command=lambda: self.draw_lyrics_box(), fg_color='transparent', hover_color=self.north_frame.cget("bg_color"), text_color=self.logolabel.cget("text_color"), image = self.ImageCache["empty"], ) self.songlabel.place(relx=0.5, rely=0.3, anchor=tkinter.CENTER) self.progressbar = customtkinter.CTkSlider(master=self.north_frame, width=225, height=15, from_=0, to=100, number_of_steps=100, command=lambda x: self.slider_event(x), state=tkinter.DISABLED) self.progressbar.place(relx=0.5, rely=0.7, anchor=tkinter.CENTER) self.progressbar.set(0) self.progress_label_left = customtkinter.CTkLabel( master=self.north_frame, text="0:00", font=(self.FONT, -12), width=5 ) self.progress_label_left.place(relx=0.1, rely=0.7, anchor=tkinter.CENTER) self.progress_label_right = customtkinter.CTkLabel( master=self.north_frame, text="0:00", font=(self.FONT, -12), width=5 ) self.progress_label_right.place(relx=0.9, rely=0.7, anchor=tkinter.CENTER) ## CENTER FRAME ---------------------------------------------------------------------------------------------------- self.checkbox1 = customtkinter.CTkCheckBox( master=self.center_frame, text="Bass", command=lambda: MISSThelpers.checkbox_event(self.check_var1, self.export_components["Bass"], 0, self.player, self.slider1), variable=self.check_var1, onvalue="on", offvalue="off", ) self.checkbox1.place(relx=0.1, rely=0.2, anchor=tkinter.W) self.checkbox2 = customtkinter.CTkCheckBox( master=self.center_frame, text="Drums", command=lambda: MISSThelpers.checkbox_event(self.check_var2, self.export_components["Drums"], 1, self.player, self.slider2), variable=self.check_var2, onvalue="on", offvalue="off", ) self.checkbox2.place(relx=0.1, rely=0.35, anchor=tkinter.W) self.checkbox3 = customtkinter.CTkCheckBox( master=self.center_frame, text="Other", command=lambda: MISSThelpers.checkbox_event(self.check_var3, self.export_components["Other"], 2, self.player, self.slider3), variable=self.check_var3, onvalue="on", offvalue="off", ) self.checkbox3.place(relx=0.1, rely=0.5, anchor=tkinter.W) self.checkbox4 = customtkinter.CTkCheckBox( master=self.center_frame, text="Vocals", command=lambda: MISSThelpers.checkbox_event(self.check_var4, self.export_components["Vocals"], 3, self.player, self.slider4), variable=self.check_var4, onvalue="on", offvalue="off", ) self.checkbox4.place(relx=0.1, rely=0.65, anchor=tkinter.W) self.slider1 = customtkinter.CTkSlider( master=self.center_frame, from_=0, to=1, command=lambda x: MISSThelpers.slider_event(x, self.export_components["Bass"], 0, self.player, self.check_var1), number_of_steps=10, ) self.slider1.place(relx=0.6, rely=0.2, anchor=tkinter.CENTER) self.slider2 = customtkinter.CTkSlider( master=self.center_frame, from_=0, to=1, command=lambda x: MISSThelpers.slider_event(x, self.export_components["Drums"], 1, self.player, self.check_var2), number_of_steps=10, ) self.slider2.place(relx=0.6, rely=0.35, anchor=tkinter.CENTER) self.slider3 = customtkinter.CTkSlider( master=self.center_frame, from_=0, to=1, command=lambda x: MISSThelpers.slider_event(x, self.export_components["Other"], 2, self.player, self.check_var3), number_of_steps=10, ) self.slider3.place(relx=0.6, rely=0.5, anchor=tkinter.CENTER) self.slider4 = customtkinter.CTkSlider( master=self.center_frame, from_=0, to=1, command=lambda x: MISSThelpers.slider_event(x, self.export_components["Vocals"], 3, self.player, self.check_var4), number_of_steps=10, ) self.slider4.place(relx=0.6, rely=0.65, anchor=tkinter.CENTER) self.effects_checkbox = customtkinter.CTkSwitch( master=self.center_frame, text="Effects", command=self.effects, variable=self.nc_var, onvalue="on", offvalue="off", fg_color=None ) self.effects_checkbox.place(relx=0.5, rely=0.9, anchor=tkinter.CENTER) self.effects_checkbox.configure(state=tkinter.DISABLED) self.effects_button = customtkinter.CTkButton( master=self.center_frame, text="Effects", font=(self.FONT, -12, "underline"), command=self.draw_effects_frame, fg_color=self.center_frame.cget("fg_color"), hover_color=self.center_frame.cget("bg_color"), width=25, height=25, ) self.effects_button.place(relx=0.53, rely=0.9, anchor=tkinter.CENTER) self.effects_button.configure(state=tkinter.DISABLED) ## SOUTH FRAME ---------------------------------------------------------------------------------------------------- self.import_button = customtkinter.CTkButton( master=self.south_frame, command=lambda: self.imports_toggle(), image=self.ImageCache["import"], fg_color='transparent', hover_color=self.south_frame.cget("bg_color"), text="Import Song(s)", font=(self.FONT, -14), width=240, height=50, text_color=self.logolabel.cget("text_color"), ) self.import_button.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) def raise_above_all(self, window:customtkinter.CTkToplevel) -> None: """ Raises a window above all other windows Args: window (tkinter.Tk): The window to raise """ window.attributes("-topmost", 1) window.attributes("-topmost", 0) def draw_lyrics_box(self) -> None: """ Draws the lyrics box """ try: self.lyrics_window.destroy() # Destroy the window if it already exists except: pass self.lyrics_window = customtkinter.CTkToplevel(app) self.lyrics_window.geometry("580x435") self.lyrics_window.title("Lyrics") self.lyrics_window.after(201, lambda: self.lyrics_window.wm_iconbitmap(r"Assets/icon.ico")) # Weird bug where icon doesn't load unless it's done after 200ms self.lyrics_window.minsize(580, 435) self.lyrics_window.maxsize(580, 435) self.raise_above_all(self.lyrics_window) search_term = self.songlabel.cget("text") if search_term == "Play Something!": self.lyrics_window.destroy() return search_term = self.current_song self.lyrics_box = customtkinter.CTkTextbox( master=self.lyrics_window, font=(self.FONT, -14), width=500, height=375, bg_color=self.lyrics_window.cget("fg_color"), fg_color=self.lyrics_window.cget("fg_color"), state=tkinter.DISABLED, ) self.lyrics_box.place(relx=0.5, rely=0.45, anchor=tkinter.CENTER) def search(term): self.lyrics_box.configure(state=tkinter.NORMAL) try: lyrics = self.lyric_engine.get_lyrics(term) self.lyrics_box.delete("0.0", "end") self.lyrics_box.insert(tkinter.END, lyrics['lyrics']) config.setConfig(path, "lyrics", lyrics['lyrics']) except: self.logger.error(traceback.format_exc()) self.lyrics_box.delete("0.0", "end") self.lyrics_box.insert(tkinter.END, "Lyrics not found") self.lyrics_box.configure(state=tkinter.DISABLED) path = f"{self.importsDest}/{search_term}" config = MISSTconfig(path) if config.getConfig(path)["lyrics"] == "null": search(search_term) else: self.lyrics_box.configure(state=tkinter.NORMAL) self.lyrics_box.delete("0.0", "end") self.lyrics_box.insert(tkinter.END, config.getConfig(path)["lyrics"]) self.lyrics_box.configure(state=tkinter.DISABLED) self.lyric_entry = customtkinter.CTkEntry( master=self.lyrics_window, font=(self.FONT, -14), width=375, height=15, placeholder_text="Not the right lyrics? Click here to search for them!", ) self.lyric_entry.place(relx=0.4, rely=0.92, anchor=tkinter.CENTER) self.search_button = customtkinter.CTkButton( master=self.lyrics_window, command=lambda: search(self.lyric_entry.get()), text="Search", font=(self.FONT, -14), width=100, height=15, ) self.search_button.place(relx=0.84, rely=0.92, anchor=tkinter.CENTER) def imports_checkbox_event(self, current_var:tkinter.StringVar) -> None: """ Called when an import checkbox is clicked Args: current_var (tkinter.StringVar): The variable of the checkbox that was clicked """ vars = [self.import_Spotify_var, self.import_Youtube_var, self.import_AppleMusic_var, self.import_Soundcloud_var] checkboxes = [self.import_Spotify_checkbox, self.import_Youtube_checkbox, self.import_AppleMusic_checkbox, self.import_Soundcloud_checkbox] for var in vars: if var.get() == "on": var.set("off") checkboxes[vars.index(var)].deselect() current_var.set("on") checkboxes[vars.index(current_var)].select() def imports_toggle(self) -> None: """ Toggles the imports frame """ try: self.imports_frame.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) except: self.draw_imports_frame() def draw_imports_frame(self) -> None: """ Draws the imports frame """ self.imports_frame = customtkinter.CTkFrame( master=self, width=self.WIDTH * (755 / self.WIDTH), height=self.HEIGHT * (430 / self.HEIGHT) ) self.imports_frame.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) self.left_frame = customtkinter.CTkFrame( master=self.imports_frame, width=350, height=380 ) self.left_frame.place(relx=0.25, rely=0.47, anchor=tkinter.CENTER) self.right_frame = customtkinter.CTkFrame( master=self.imports_frame, width=350, height=380 ) self.right_frame.place(relx=0.75, rely=0.47, anchor=tkinter.CENTER) self.import_title = customtkinter.CTkLabel( master=self.left_frame, text="Choose a source", font=(self.FONT, -20), text_color=self.logolabel.cget("text_color"), ) self.import_title.place(relx=0.5, rely=0.1, anchor=tkinter.CENTER) self.import_Spotify_var = tkinter.StringVar() self.import_Youtube_var = tkinter.StringVar() self.import_AppleMusic_var = tkinter.StringVar() self.import_Soundcloud_var = tkinter.StringVar() self.import_Spotify_button = customtkinter.CTkLabel( master=self.left_frame, image=self.ImageCache["spotify"], fg_color='transparent', text="", font=(self.FONT, -14), width=50, height=50, text_color=self.logolabel.cget("text_color"), ) self.import_Spotify_button.place(relx=0.3, rely=0.2375, anchor=tkinter.CENTER) self.import_Spotify_checkbox = customtkinter.CTkCheckBox( master=self.left_frame, text="", command=lambda: self.imports_checkbox_event(self.import_Spotify_var), variable=self.import_Spotify_var, onvalue="on", offvalue="off", ) self.import_Spotify_checkbox.place(relx=0.61, rely=0.2375, anchor=tkinter.CENTER) self.import_Youtube_button = customtkinter.CTkLabel( master=self.left_frame, image=self.ImageCache["youtube"], fg_color='transparent', text="", font=(self.FONT, -14), width=50, height=50, text_color=self.logolabel.cget("text_color"), ) self.import_Youtube_button.place(relx=0.3, rely=0.3750, anchor=tkinter.CENTER) self.import_Youtube_checkbox = customtkinter.CTkCheckBox( master=self.left_frame, text="", command=lambda: self.imports_checkbox_event(self.import_Youtube_var), variable=self.import_Youtube_var, onvalue="on", offvalue="off", ) self.import_Youtube_checkbox.place(relx=0.61, rely=0.3750, anchor=tkinter.CENTER) self.import_Deezer_button = customtkinter.CTkLabel( master=self.left_frame, image=self.ImageCache["applemusic"], fg_color='transparent', text="", font=(self.FONT, -14), width=50, height=50, text_color=self.logolabel.cget("text_color"), ) self.import_Deezer_button.place(relx=0.3, rely=0.5125, anchor=tkinter.CENTER) self.import_AppleMusic_checkbox = customtkinter.CTkCheckBox( master=self.left_frame, text="", command=lambda: self.imports_checkbox_event(self.import_AppleMusic_var), variable=self.import_AppleMusic_var, onvalue="on", offvalue="off", ) self.import_AppleMusic_checkbox.place(relx=0.61, rely=0.5125, anchor=tkinter.CENTER) self.import_Soundcloud_button = customtkinter.CTkLabel( master=self.left_frame, image=self.ImageCache["soundcloud"], fg_color='transparent', text="", font=(self.FONT, -14), width=50, height=50, text_color=self.logolabel.cget("text_color"), ) self.import_Soundcloud_button.place(relx=0.3, rely=0.6500, anchor=tkinter.CENTER) self.import_Soundcloud_checkbox = customtkinter.CTkCheckBox( master=self.left_frame, text="", command=lambda: self.imports_checkbox_event(self.import_Soundcloud_var), variable=self.import_Soundcloud_var, onvalue="on", offvalue="off", ) self.import_Soundcloud_checkbox.place(relx=0.61, rely=0.6500, anchor=tkinter.CENTER) self.source_entry = customtkinter.CTkEntry( master=self.left_frame, width=200, text_color=self.logolabel.cget("text_color"), placeholder_text="Enter your share URL here", ) self.source_entry.place(relx=0.5, rely=0.8, anchor=tkinter.CENTER) self.import_button = customtkinter.CTkButton( master=self.left_frame, command=lambda: threading.Thread(target=self.sourcePreprocess, args=(self.source_entry.get(),), daemon=True).start(), text="Import", font=(self.FONT, -14), width=75, text_color=self.logolabel.cget("text_color"), ) self.import_button.place(relx=0.32, rely=0.9, anchor=tkinter.CENTER) self.or_label = customtkinter.CTkLabel( master=self.left_frame, text="OR", font=(self.FONT, -14), text_color=self.logolabel.cget("text_color"), ) self.or_label.place(relx=0.5, rely=0.9, anchor=tkinter.CENTER) self.import_file_button = customtkinter.CTkButton( master=self.left_frame, command=lambda: threading.Thread(target=self.filePreprocess, daemon=True).start(), text="From File", font=(self.FONT, -14), width=75, text_color=self.logolabel.cget("text_color"), ) self.import_file_button.place(relx=0.68, rely=0.9, anchor=tkinter.CENTER) self.preprocess_status_label = customtkinter.CTkLabel( master=self.right_frame, text="Preprocess Status", font=(self.FONT, -20), text_color=self.logolabel.cget("text_color"), ) self.preprocess_status_label.place(relx=0.5, rely=0.1, anchor=tkinter.CENTER) self.preprocess_terminal = customtkinter.CTkFrame( master=self.right_frame, width=275, height=290, fg_color="#0C0C0C", border_width=1, ) self.preprocess_terminal.place(relx=0.5, rely=0.55, anchor=tkinter.CENTER) self.preprocess_terminal_text = customtkinter.CTkTextbox( master=self.preprocess_terminal, font=(self.FONT, -14), width=250, height=250, bg_color="transparent", fg_color="transparent", text_color="#CCCCCC", ) self.preprocess_terminal_text.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) def get_usage_info(): while True: cpu_usage = psutil.cpu_percent() mem_usage = psutil.virtual_memory().percent try: gpu_usage = GPUtil.getGPUs()[0].load * 100 except: gpu_usage = "N/A" #CPU version of MISST self.system_info.configure( text=f"CPU: {cpu_usage:.1f}% | Mem: {mem_usage:.1f}% | GPU: {f'{gpu_usage:.1f}' if gpu_usage != 'N/A' else 'N/A'}%" ) time.sleep(1) threading.Thread(target=get_usage_info, daemon=True).start() self.system_info = customtkinter.CTkLabel( master=self.imports_frame, text=f"CPU: 00.0% | Mem: 00.0% | GPU: 00.0%", font=(self.FONT, -12), text_color=self.logolabel.cget("text_color"), state=tkinter.DISABLED, ) self.system_info.place(relx=0.76, rely=0.95, anchor=tkinter.CENTER) self.return_button = customtkinter.CTkButton( master=self.imports_frame, command=lambda: self.imports_frame.place_forget(), image=self.ImageCache["return"], fg_color='transparent', hover_color=self.imports_frame.cget("bg_color"), text="Return", font=(self.FONT, -12), width=5, text_color="#6D6D6D", ) self.return_button.place(relx=0.24, rely=0.95, anchor=tkinter.CENTER) self.console = MISSTconsole(self.preprocess_terminal_text, "MISST Preprocessor\nCopyright (C) @MISST App.\n") self.console.update("\nMISST> waiting") def retrieve_metadata(self, save_dir:str = None, temp_dir:str = None, file:str = None) -> None: """ Retrieves metadata from a file and saves it to a directory. Args: save_dir (str): The directory to save the metadata to. temp_dir (str): The directory to retrieve the metadata from. file (str): The file to retrieve the metadata from. """ self.console.update("\nMISST> Getting Metadata") if temp_dir is not None: save_dir = f"{self.importsDest}/{os.path.splitext(os.path.basename(os.listdir(temp_dir)[0]))[0]}" if not os.path.exists(save_dir): os.mkdir(save_dir) file = f"{temp_dir}/{os.listdir(temp_dir)[0]}" else: file = file config = MISSTconfig(save_dir) #Create config file try: f = music_tag.load_file(file) art = f['artwork'] raw_art = art.first.data image = Image.open(io.BytesIO(raw_art)) square_size = min(image.size) left = (image.width - square_size) // 2 top = (image.height - square_size) // 2 right = left + square_size bottom = top + square_size # Crop the square region from the center of the image cropped_image = image.crop((left, top, right, bottom)) image = cropped_image.resize((40, 40), Image.Resampling.LANCZOS) raw_art = image.tobytes() png_bytes = io.BytesIO() image.save(png_bytes, format="PNG") raw_art = png_bytes.getvalue() config.setConfig(save_dir, "image_url", MISSThelpers().freeimage_upload(raw_art)) config.setConfig(save_dir, "image_raw", base64.b64encode(raw_art).decode('utf-8')) self.console.endUpdate() self.console.addLine("\nMISST> Metadata Retrieved.") except: self.logger.error(traceback.format_exc()) self.console.endUpdate() self.console.addLine("\nMISST> Error getting metadata.") def filePreprocess(self) -> None: """ Preprocesses a file. """ self.console.editLine(f"MISST Preprocessor\nCopyright (C) @MISST App.\n", 0) self.import_file_button.configure(state=tkinter.DISABLED) self.import_button.configure(state=tkinter.DISABLED) file = tkinter.filedialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("mp3 files","*.mp3"),("wav files", "*.wav"),("flac files", "*.flac"),("all files","*.*")), multiple=False) if file != "": self.console.endUpdate() save_name = os.path.splitext(os.path.basename(file))[0] save_dir = f"{self.importsDest}/{save_name}" if not os.path.exists(save_dir): os.mkdir(save_dir) self.retrieve_metadata(save_dir=save_dir, file=file) thread = threading.Thread(target=MISSTpreprocess.preprocess, args=(self, file, self.importsDest, self.settings.getSetting("chosen_model"), "cuda" if self.settings.getSetting("accelerate_on_gpu") == "true" else "cpu"), daemon=True) thread.start() thread.join() self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) else: self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) def sourcePreprocess(self, url:str) -> None: """ Preprocesses a source. Args: url (str): The URL of the source to preprocess. """ self.console.editLine(f"MISST Preprocessor\nCopyright (C) @MISST App.\n", 0) if url != "": # Spotify Import if self.import_Spotify_var.get() == "on": self.import_file_button.configure(state=tkinter.DISABLED) self.import_button.configure(state=tkinter.DISABLED) if "https://open.spotify.com/track" not in url: self.console.endUpdate() self.console.addLine("\nMISST> Invalid URL.") self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) return self.console.endUpdate() self.console.update("\nMISST> Downloading") temp_dir = tempfile.mkdtemp() cmd = [os.path.abspath("./Assets/Bin/spotdl.exe"), f"{url}", "--output", temp_dir, "--ffmpeg", "./ffmpeg.exe" ] process = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, creationflags=0x08000000) if process.returncode != 0: self.logger.error(process.stderr) self.console.endUpdate() self.console.addLine("\nMISST> Error downloading file.") self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) return self.console.endUpdate() self.console.addLine("\nMISST> Downloaded.") self.retrieve_metadata(temp_dir=temp_dir) thread = threading.Thread(target=MISSTpreprocess.preprocess, args=(self, f"{temp_dir}/{os.listdir(temp_dir)[0]}", self.importsDest, self.settings.getSetting("chosen_model"), "cuda" if self.settings.getSetting("accelerate_on_gpu") == "true" else "cpu"), daemon=True) thread.start() thread.join() os.remove(os.path.join(temp_dir, os.listdir(temp_dir)[0])) os.rmdir(temp_dir) self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) self.source_entry.delete(0, tkinter.END) #Clear entry # Youtube Import elif self.import_Youtube_var.get() == "on": self.import_file_button.configure(state=tkinter.DISABLED) self.import_button.configure(state=tkinter.DISABLED) if "https://music.youtube.com/watch?v=" not in url and "https://www.youtube.com/watch?v=" not in url: self.console.endUpdate() self.console.addLine("\nMISST> Invalid URL.") self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) return self.console.endUpdate() self.console.update("\nMISST> Downloading") temp_dir = tempfile.mkdtemp() cmd = [os.path.abspath("./Assets/Bin/music-dl.exe"), "-v", "-x", "--embed-thumbnail", "--audio-format", "flac", "-o", f"{temp_dir}/%(title)s.%(ext)s", f"{url}", "--ffmpeg-location", "./ffmpeg.exe" ] process = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, creationflags=0x08000000) if process.returncode != 0: self.logger.error(process.stderr) self.console.endUpdate() self.console.addLine("\nMISST> Error downloading file.") self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) return self.console.endUpdate() self.console.addLine("\nMISST> Downloaded.") self.retrieve_metadata(temp_dir=temp_dir) thread = threading.Thread(target=MISSTpreprocess.preprocess, args=(self, f"{temp_dir}/{os.listdir(temp_dir)[0]}", self.importsDest, self.settings.getSetting("chosen_model"), "cuda" if self.settings.getSetting("accelerate_on_gpu") == "true" else "cpu"), daemon=True) thread.start() thread.join() os.remove(os.path.join(temp_dir, os.listdir(temp_dir)[0])) os.rmdir(temp_dir) self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) self.source_entry.delete(0, tkinter.END) #Clear entry # AppleMusic Import elif self.import_AppleMusic_var.get() == "on": self.import_file_button.configure(state=tkinter.DISABLED) self.import_button.configure(state=tkinter.DISABLED) if "https://music.apple.com/" not in url: self.console.endUpdate() self.console.addLine("\nMISST> Invalid URL.") self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) return self.console.endUpdate() self.console.update("\nMISST> Downloading") temp_dir = tempfile.mkdtemp() try: MISSThelpers.apple_music(url, temp_dir) # Download except: self.logger.error(traceback.format_exc()) self.console.endUpdate() self.console.addLine("\nMISST> Error downloading file.") self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) return self.console.endUpdate() self.console.addLine("\nMISST> Downloaded.") self.retrieve_metadata(temp_dir=temp_dir) thread = threading.Thread(target=MISSTpreprocess.preprocess, args=(self, f"{temp_dir}/{os.listdir(temp_dir)[0]}", self.importsDest, self.settings.getSetting("chosen_model"), "cuda" if self.settings.getSetting("accelerate_on_gpu") == "true" else "cpu"), daemon=True) thread.start() thread.join() os.remove(os.path.join(temp_dir, os.listdir(temp_dir)[0])) os.rmdir(temp_dir) self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) self.source_entry.delete(0, tkinter.END) #Clear entry # Soundcloud Import elif self.import_Soundcloud_var.get() == "on": self.import_file_button.configure(state=tkinter.DISABLED) self.import_button.configure(state=tkinter.DISABLED) if "https://soundcloud.com" not in url: self.console.endUpdate() self.console.addLine("\nMISST> Invalid URL.") self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) return self.console.endUpdate() self.console.update("\nMISST> Downloading") temp_dir = tempfile.mkdtemp() cmd = [ os.path.abspath("./Assets/Bin/music-dl.exe"), "-v", "-x", "--embed-thumbnail", "--audio-format", "flac", "-o", f"{temp_dir}/%(title)s.%(ext)s", f"{url}", "--ffmpeg-location", "./ffmpeg.exe" ] process = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, creationflags=0x08000000) if process.returncode != 0: self.logger.error(process.stderr) self.console.endUpdate() self.console.addLine("\nMISST> Error downloading file.") self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) return self.console.endUpdate() self.console.addLine("\nMISST> Downloaded.") self.retrieve_metadata(temp_dir=temp_dir) thread = threading.Thread(target=MISSTpreprocess.preprocess, args=(self, f"{temp_dir}/{os.listdir(temp_dir)[0]}", self.importsDest, self.settings.getSetting("chosen_model"), "cuda" if self.settings.getSetting("accelerate_on_gpu") == "true" else "cpu"), daemon=True) thread.start() thread.join() os.remove(os.path.join(temp_dir, os.listdir(temp_dir)[0])) os.rmdir(temp_dir) self.import_file_button.configure(state=tkinter.NORMAL) self.import_button.configure(state=tkinter.NORMAL) self.source_entry.delete(0, tkinter.END) #Clear entry else: pass else: self.console.endUpdate() self.console.addLine("\nMISST> Empty URL.") self.console.update("\nMISST> waiting") return return def change_model(self, model): self.settings.setSetting("chosen_model", model) self.setup = MISSTSetup(self, self.settings.getSetting("chosen_model")) try: self.setup.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) except: pass def draw_settings_frame(self) -> None: """ Draws the settings frame. """ self.settings_window = customtkinter.CTkFrame( master=self, width=self.WIDTH * (755 / self.WIDTH), height=self.HEIGHT * (430 / self.HEIGHT), corner_radius=0 ) self.settings_window.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) self.settings_frame = customtkinter.CTkFrame( master=self.settings_window, width=350, height=380, corner_radius=10 ) self.settings_frame.place(relx=0.25, rely=0.47, anchor=tkinter.CENTER) self.setting_header = customtkinter.CTkLabel( master=self.settings_frame, text="Settings", font=(self.FONT, -18) ) self.setting_header.place(relx=0.5, rely=0.1, anchor=tkinter.CENTER) self.general_frame = customtkinter.CTkTabview(master=self.settings_frame, width=300, height=160) self.general_frame.place(relx=0.5, rely=0.34, anchor=tkinter.CENTER) self.general_frame.add("General") self.general_frame.add("Advanced") self.general_header = customtkinter.CTkLabel( master=self.general_frame.tab("General"), text="General", font=(self.FONT, -16) ) self.general_header.place(relx=0.2, rely=0.15, anchor=tkinter.CENTER) self.autoplay_box = customtkinter.CTkSwitch( master=self.general_frame.tab("General"), text="Autoplay", font=(self.FONT, -12), command=lambda: MISSThelpers.autoplay_event(self), width=50, ) self.autoplay_box.place(relx=0.28, rely=0.4, anchor=tkinter.CENTER) if self.settings.getSetting('autoplay') == 'true': self.autoplay_box.select() self.rpc_box = customtkinter.CTkSwitch( master=self.general_frame.tab("General"), text="Discord RPC", font=(self.FONT, -12), command=lambda: MISSThelpers.rpc_event(self), width=50, ) self.rpc_box.place(relx=0.31, rely=0.625, anchor=tkinter.CENTER) if self.settings.getSetting('rpc') == 'true': self.rpc_box.select() self.preprocess_method_box = customtkinter.CTkSwitch( master=self.general_frame.tab("General"), text="Accelerate on GPU?", font=(self.FONT, -12), command=lambda: threading.Thread(target=MISSThelpers.accelerate_event, args=(self,), daemon=True).start(), width=50, ) self.preprocess_method_box.place(relx=0.38, rely=0.85, anchor=tkinter.CENTER) if self.settings.getSetting('accelerate_on_gpu') == 'true': self.preprocess_method_box.select() ### General Settings ### self.storage_frame = customtkinter.CTkFrame(master=self.settings_frame, width=300, height=140) self.storage_frame.place(relx=0.5, rely=0.76, anchor=tkinter.CENTER) self.storage_header = customtkinter.CTkLabel( master=self.storage_frame, text="Storage", font=(self.FONT, -16) ) self.storage_header.place(relx=0.2, rely=0.15, anchor=tkinter.CENTER) self.downloads_header = customtkinter.CTkLabel( master=self.storage_frame, text="Downloads:", font=(self.FONT, -12, "bold") ) self.downloads_header.place(relx=0.24, rely=0.4, anchor=tkinter.CENTER) bytes = MISSThelpers.getsize(MISSThelpers, self.importsDest) gb = bytes / 1000000000 gb = round(gb, 2) text = str(gb) + " GB" self.downloads_info = customtkinter.CTkLabel( master=self.storage_frame, text=text, font=(self.FONT, -12), width=25, state=tkinter.DISABLED, ) self.downloads_info.place(relx=0.46, rely=0.4, anchor=tkinter.CENTER) self.downloads_subheader = customtkinter.CTkLabel( master=self.storage_frame, text="Downloaded Content", font=(self.FONT, -11), state=tkinter.DISABLED, ) self.downloads_subheader.place(relx=0.29, rely=0.55, anchor=tkinter.CENTER) self.clear_downloads_button = customtkinter.CTkButton( master=self.storage_frame, text="Clear Downloads", font=(self.FONT, -12), width=15, height=2, command=lambda: MISSThelpers.clearDownloads(self) ) self.clear_downloads_button.place(relx=0.75, rely=0.475, anchor=tkinter.CENTER) self.storage_location_header = customtkinter.CTkLabel( master=self.storage_frame, text="Storage Location:", font=(self.FONT, -12, "bold") ) self.storage_location_header.place(relx=0.305, rely=0.7, anchor=tkinter.CENTER) dir = os.path.abspath(self.importsDest) dirlen = len(dir) n = 20 location_text = dir if dirlen <= n else "..." + dir[-(n - dirlen) :] self.storage_location_info = customtkinter.CTkLabel( master=self.storage_frame, text=location_text, font=(self.FONT, -11), width=25, state=tkinter.DISABLED, ) self.storage_location_info.place(relx=0.345, rely=0.85, anchor=tkinter.CENTER) self.change_location_button = customtkinter.CTkButton( master=self.storage_frame, text="Change Location", font=(self.FONT, -12), width=15, height=2, command=lambda: MISSThelpers.change_location(self), corner_radius=10, ) self.change_location_button.place(relx=0.75, rely=0.775, anchor=tkinter.CENTER) ### Advanced Settings ### self.advanced_header = customtkinter.CTkLabel( master=self.general_frame.tab("Advanced"), text="Advanced", font=(self.FONT, -16) ) self.advanced_header.place(relx=0.2, rely=0.15, anchor=tkinter.CENTER) self.chosen_model_header = customtkinter.CTkLabel( master=self.general_frame.tab("Advanced"), text="Model:", font=(self.FONT, -12, "bold") ) self.chosen_model_header.place(relx=0.2, rely=0.45, anchor=tkinter.CENTER) self.model_select = customtkinter.CTkOptionMenu( master=self.general_frame.tab("Advanced"), font=(self.FONT, -12), width=175, values=["hdemucs_mmi", "htdemucs", "htdemucs_ft", "mdx", "mdx_extra", "mdx_extra_q", "mdx_q", "repro_mdx_a", "repro_mdx_a_hybrid_only", "repro_mdx_a_time_only"] ) self.model_select.place(relx=0.65, rely=0.45, anchor=tkinter.CENTER) self.model_select.set(self.settings.getSetting("chosen_model")) self.save_model_button = customtkinter.CTkButton( master=self.general_frame.tab("Advanced"), text="Download and Save Model", font=(self.FONT, -12), command=lambda: self.change_model(self.model_select.get()), corner_radius=10, height=15, width=30, ) self.save_model_button.place(relx=0.5, rely=0.8, anchor=tkinter.CENTER) ### Theme Settings ### self.theme_frame = customtkinter.CTkFrame(master=self.settings_window, width=350, height=380) self.theme_frame.place(relx=0.75, rely=0.47, anchor=tkinter.CENTER) self.theme_header = customtkinter.CTkLabel( master=self.theme_frame, text="Theme", font=(self.FONT, -18) ) self.theme_header.place(relx=0.5, rely=0.1, anchor=tkinter.CENTER) self.theme_frame_mini = customtkinter.CTkFrame(master=self.theme_frame, width=300, height=292) self.theme_frame_mini.place(relx=0.5, rely=0.56, anchor=tkinter.CENTER) self.button_light = customtkinter.CTkButton( master=self.theme_frame_mini, height=100, width=200, corner_radius=10, border_color="white", fg_color=self.settings.getSetting("chosenLightColor"), hover_color=self.settings.getSetting("chosenLightColor"), border_width=2, text="Light", command=lambda: MISSThelpers.updateTheme(self, "light"), ) self.button_light.place(relx=0.5, rely=0.25, anchor=tkinter.CENTER) self.button_dark = customtkinter.CTkButton( master=self.theme_frame_mini, height=100, width=200, corner_radius=10, border_color="white", fg_color=self.settings.getSetting("chosenDarkColor"), hover_color=self.settings.getSetting("chosenDarkColor"), border_width=2, text="Dark", command=lambda: MISSThelpers.updateTheme(self, "dark"), ) self.button_dark.place(relx=0.5, rely=0.75, anchor=tkinter.CENTER) self.info_label = customtkinter.CTkLabel( master=self.settings_window, text="Note: You may need to restart the app for changes to take effect.", font=(self.FONT, -11), state=tkinter.DISABLED, height=10, ) self.info_label.place(relx=0.5, rely=0.95, anchor=tkinter.CENTER) self.reset_button = customtkinter.CTkButton( master=self.settings_window, text="Reset", font=(self.FONT, -12, "underline"), command=lambda: MISSThelpers.resetSettings(self), fg_color=self.settings_window.cget("fg_color"), hover_color=self.theme_frame.cget("fg_color"), width=25, height=25, text_color=self.info_label.cget("text_color") ) self.reset_button.place(relx=0.75, rely=0.95, anchor=tkinter.CENTER) self.return_button = customtkinter.CTkButton( master=self.settings_window, command=lambda: self.settings_window.destroy(), image=self.ImageCache["return"], fg_color='transparent', hover_color=self.theme_frame.cget("fg_color"), text="", font=(self.FONT, -14), width=25, height=25, text_color=self.logolabel.cget("text_color"), ) self.return_button.place(relx=0.25, rely=0.95, anchor=tkinter.CENTER) def eq_sliders_event(self, curVal:int, curSlider:int, sliders:list) -> None: """ Event that is called when a slider is moved. If the move sliders together option is enabled, it will move all the sliders together. Args: curVal (int): The current value of the slider. curSlider (int): The index of the slider that was moved. sliders (list): A list of all the sliders. """ self.settings.setSetting(f"eq_{curSlider+1}", str(curVal)) if self.move_sliders_together.get() == 0: return slider = sliders[curSlider] for slider in sliders: index = sliders.index(slider) distance = abs(index - curSlider) if curVal < 0: multiplier = 1 * distance set = curVal + multiplier slider.set(set if set < 0 else 0) self.settings.setSetting(f"eq_{index+1}", str(slider.get())) else: multiplier = -1 * distance set = curVal + multiplier slider.set(set if set > 0 else 0) self.settings.setSetting(f"eq_{index+1}", str(slider.get())) return def moveSlidersTogether(self) -> None: """ Event that is called when the move sliders together option is changed. It will save the setting. """ self.settings.setSetting("eq_move_sliders_together", "true" if str(self.move_sliders_together.get()) == "1" else "false") return def eqOnOff(self) -> None: """ Event that is called when the eq on/off button is changed. It will save the setting and enable/disable the eq sliders. """ self.settings.setSetting("eq", "true" if str(self.eqOnOffButton.get()) == "1" else "false") if self.eqOnOffButton.get() == 0: self.eqOnOffButton.configure(text="Off") for child in self.eq_frame.winfo_children(): child.configure(state=tkinter.DISABLED) self.eqOnOffButton.configure(state='normal') self.return_button.configure(state='normal') self.eq_header.configure(state='normal') else: self.eqOnOffButton.configure(text="On") for child in self.eq_frame.winfo_children(): child.configure(state='normal') return def draw_effects_frame(self) -> None: """ Draws the effects frame. """ self.effects_window = customtkinter.CTkFrame( master=self, width=self.WIDTH * (755 / self.WIDTH), height=self.HEIGHT * (430 / self.HEIGHT) ) self.effects_window.place(relx=0.5, rely=0.5, anchor=tkinter.CENTER) self.eq_frame = customtkinter.CTkFrame(master=self.effects_window, width=450, height=350) self.eq_frame.place(relx=0.35, rely=0.5, anchor=tkinter.CENTER) self.eq_header = customtkinter.CTkLabel( master=self.eq_frame, text="Equalizer", font=(self.FONT, -16) ) self.eq_header.place(relx=0.15, rely=0.12, anchor=tkinter.CENTER) self.return_button = customtkinter.CTkButton( master=self.eq_frame, command=lambda: self.effects_window.destroy(), image=self.ImageCache["return"], fg_color='transparent', hover_color=self.effects_window.cget("bg_color"), text="", font=(self.FONT, -14), width=5, text_color=self.logolabel.cget("text_color"), ) self.return_button.place(relx=0.87, rely=0.9, anchor=tkinter.CENTER) val = 0.02 frqs = ["62 Hz", "125 Hz", "250 Hz", "500 Hz", "1 KHz", "2.5 KHz", "4 KHz", "8 KHz", "16 KHz"] sliders = [eq_slider1, eq_slider2, eq_slider3, eq_slider4, eq_slider5, eq_slider6, eq_slider7, eq_slider8, eq_slider9] = [None] * 9 for i in range(0, len(sliders)): sliders[i] = customtkinter.CTkSlider( master=self.eq_frame, from_=-12, to=12, number_of_steps=24, orientation="vertical", height=175, command= lambda x, curSlider=i, sliders=sliders: self.eq_sliders_event(x, curSlider, sliders) ) sliders[i].set(float(self.settings.getSetting(f"eq_{i+1}"))) val += 0.1 sliders[i].place(relx=val, rely=0.5, anchor=tkinter.CENTER) val = 0.02 for frq in frqs: eq_label = customtkinter.CTkLabel( master=self.eq_frame, text=frq, font=(self.FONT, -10), state=tkinter.DISABLED ) val += 0.1 eq_label.place(relx=val, rely=0.8, anchor=tkinter.CENTER) self.eq_12dB_label = customtkinter.CTkLabel( master=self.eq_frame, text="+12dB", font=(self.FONT, -10), state=tkinter.DISABLED ) self.eq_12dB_label.place(relx=0.05, rely=0.27, anchor=tkinter.CENTER) self.eq_6dB_label = customtkinter.CTkLabel( master=self.eq_frame, text="+6dB", font=(self.FONT, -10), state=tkinter.DISABLED ) self.eq_6dB_label.place(relx=0.05, rely=0.395, anchor=tkinter.CENTER) self.eq_0dB_label = customtkinter.CTkLabel( master=self.eq_frame, text="0dB", font=(self.FONT, -10), state=tkinter.DISABLED ) self.eq_0dB_label.place(relx=0.05, rely=0.5, anchor=tkinter.CENTER) self.eq_m6dB_label = customtkinter.CTkLabel( master=self.eq_frame, text="-6dB", font=(self.FONT, -10), state=tkinter.DISABLED ) self.eq_m6dB_label.place(relx=0.05, rely=0.615, anchor=tkinter.CENTER) self.eq_m12dB_label = customtkinter.CTkLabel( master=self.eq_frame, text="-12dB", font=(self.FONT, -10), state=tkinter.DISABLED ) self.eq_m12dB_label.place(relx=0.05, rely=0.73, anchor=tkinter.CENTER) self.move_sliders_together = customtkinter.CTkCheckBox( master=self.eq_frame, text="Move nearby sliders together", font=(self.FONT, -12), command=lambda: self.moveSlidersTogether() ) self.move_sliders_together.place(relx=0.28, rely=0.9, anchor=tkinter.CENTER) if self.settings.getSetting("eq_move_sliders_together") == "true": self.move_sliders_together.select() self.moveSlidersTogether() else: self.move_sliders_together.deselect() self.moveSlidersTogether() self.eqOnOffButton = customtkinter.CTkSwitch( master=self.eq_frame, text="On", width=50, height=50, font=(self.FONT, -14), command=lambda: self.eqOnOff(), ) self.eqOnOffButton.place(relx=0.85, rely=0.12, anchor=tkinter.CENTER) if self.settings.getSetting("eq") == "true": self.eqOnOffButton.select() self.eqOnOff() else: self.eqOnOffButton.deselect() self.eqOnOff() # Effects self.effects_frame = customtkinter.CTkFrame(master=self.effects_window, width=200, height=350) self.effects_frame.place(relx=0.82, rely=0.5, anchor=tkinter.CENTER) self.effects_header = customtkinter.CTkLabel( master=self.effects_frame, text="Effects", font=(self.FONT, -16) ) self.effects_header.place(relx=0.5, rely=0.12, anchor=tkinter.CENTER) def setEffect(effect, value): self.settings.setSetting(effect, f"{value}") if effect == "speed": self.speed_slider.set(float(value)) elif effect == "pitch": self.pitch_slider.set(float(value)) elif effect == "bass": self.bass_slider.set(float(value)) elif effect == "reverb": self.reverb_slider.set(float(value)) # Effect - Speed self.speed_header = customtkinter.CTkLabel( master=self.effects_frame, text="Speed", font=(self.FONT, -14) ) self.speed_header.place(relx=0.17, rely=0.23, anchor=tkinter.CENTER) self.speed_slider = customtkinter.CTkSlider( master=self.effects_frame, from_=0.25, to=1.75, number_of_steps=6, width=165, height=10, command=lambda x: setEffect("speed", x) ) self.speed_slider.set(float(self.settings.getSetting("speed"))) self.speed_slider.place(relx=0.5, rely=0.3, anchor=tkinter.CENTER) speeds = [0.25, 0.5, 0.75, 1.0, 1.25, 1.5, 1.75] # create little indicators val = 0 for value in speeds: speed_label = customtkinter.CTkLabel( master=self.effects_frame, text=value, font=(self.FONT, -10), state=tkinter.DISABLED ) val += 0.125 speed_label.place(relx=val, rely=0.37, anchor=tkinter.CENTER) # Effect - Pitch self.pitch_header = customtkinter.CTkLabel( master=self.effects_frame, text="Pitch", font=(self.FONT, -14) ) self.pitch_header.place(relx=0.17, rely=0.48, anchor=tkinter.CENTER) self.pitch_slider = customtkinter.CTkSlider( master=self.effects_frame, from_=-1, to=1, number_of_steps=8, width=165, height=10, command=lambda x: setEffect("pitch", x) ) self.pitch_slider.set(float(self.settings.getSetting("pitch"))) self.pitch_slider.place(relx=0.5, rely=0.55, anchor=tkinter.CENTER) pitch_factors = [-1.0, -0.5, 0.0, 0.5, 1.0] # create little indicators val = -0.06 for value in pitch_factors: speed_label = customtkinter.CTkLabel( master=self.effects_frame, text=value, font=(self.FONT, -10), state=tkinter.DISABLED ) val += 0.19 speed_label.place(relx=val, rely=0.62, anchor=tkinter.CENTER) # Effect - Reverb self.reverb_header = customtkinter.CTkLabel( master=self.effects_frame, text="Reverb", font=(self.FONT, -14) ) self.reverb_header.place(relx=0.17, rely=0.73, anchor=tkinter.CENTER) self.reverb_slider = customtkinter.CTkSlider( master=self.effects_frame, from_=0, to=1.5, number_of_steps=6, width=165, height=10, command=lambda x: setEffect("reverb", x) ) self.reverb_slider.set(float(self.settings.getSetting("reverb"))) self.reverb_slider.place(relx=0.5, rely=0.8, anchor=tkinter.CENTER) reverb_factors = [0.0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5] # create little indicators val = 0 for value in reverb_factors: value = value if value != 0 else "Off" reverb_label = customtkinter.CTkLabel( master=self.effects_frame, text=value, font=(self.FONT, -10), state=tkinter.DISABLED ) val += 0.125 reverb_label.place(relx=val, rely=0.87, anchor=tkinter.CENTER) def imports_check(self, search_entry:customtkinter.CTkEntry, songs_box:customtkinter.CTkTextbox) -> None: """ Checks for new songs in the imports folder and adds them to the songs box Args: search_entry (tkinter.Entry): The search entry songs_box (tkinter.Text): The songs box """ def add_highlight(text, start, end): text.tag_add("start", start, end) text.tag_config("start", background = self.settings.getSetting("chosenLightColor") if customtkinter.get_appearance_mode() == "Light" else self.settings.getSetting("chosenDarkColor"), foreground= "black") entry_val = None num = 0 songs = [] for _ in MISSThelpers.MISSTlistdir(self, self.importsDest): num += 1 songs.append(f"{num}. {_}") while True: time.sleep(0.25) if self.songlabel.cget("text") == "Play Something!": self.export_button.configure(text="Nothing Playing") self.export_button.configure(state=tkinter.DISABLED) else: if (self.export_button.cget("text").startswith("Export")): pass else: self.export_button.configure(state=tkinter.NORMAL) self.export_button.configure(text="Export") if len(MISSThelpers.MISSTlistdir(self, self.importsDest)) != num: num = 0 songs = [] for _ in MISSThelpers.MISSTlistdir(self, self.importsDest): num += 1 songs.append(f"{num}. {_}") songs_box.configure(state="normal") songs_box.delete("0.0", "end") songs_box.insert("0.0", "\n\n".join(songs)) songs_box.configure(state=tkinter.DISABLED) if len(songs) == 0: songs_box.configure(state="normal") songs_box.delete("0.0", "end") songs_box.insert("0.0", "No songs Imported!") songs_box.configure(state=tkinter.DISABLED) search = search_entry.get() found_songs = [] for _ in songs: if search.lower() in _.lower(): found_songs.append(_) if entry_val == search_entry.get(): pass else: songs_box.configure(state="normal") songs_box.delete("0.0", "end") songs_box.insert("0.0", "\n\n".join(found_songs)) for line in songs_box.get("0.0", "end").splitlines(): if search.lower() in line.lower(): start = line.lower().find(search.lower()) end = line.lower().find(search.lower()) + len(search) line_num = songs_box.get("0.0", "end").splitlines().index(line) add_highlight(songs_box, f"{line_num + 1}.{start}", f"{line_num + 1}.{end}") songs_box.configure(state=tkinter.DISABLED) entry_val = search_entry.get() def play(self, dir:str) -> None: """ Plays a song Args: dir (str): The directory of the song """ self.player.change_files([ f"{self.importsDest}/{dir}/bass.flac", f"{self.importsDest}/{dir}/drums.flac", f"{self.importsDest}/{dir}/other.flac", f"{self.importsDest}/{dir}/vocals.flac" ], [self.slider1.get(), self.slider2.get(), self.slider3.get(), self.slider4.get() ] ) self.update_UI( f"{self.importsDest}/{dir}/other.flac", 0 ) def play_search(self, index_label:str, songs:list) -> None: """ Plays a song from the search box Args: index_label (str): The index of the song songs (list): The list of songs """ self.playbutton.configure(state=tkinter.DISABLED) try: index = int(index_label) song = songs[index - 1] self.playing = True self.effects_checkbox.deselect() self.effects() self.play(song) except: self.logger.error(traceback.format_exc()) pass self.playbutton.configure(state=tkinter.NORMAL) def export(self, songname:str, sliders:list) -> None: """ Exports a song Args: songname (str): The name of the song """ file = tkinter.filedialog.asksaveasfilename(initialfile=f"{songname}.mp3", filetypes=(('mp3 files', '*.mp3'),('All files', '*.*'))) if file == "": self.export_button.configure(text="Export Cancelled.") threading.Timer(1.5, lambda: self.export_button.configure(text="Export")).start() return self.export_button.configure(text="Exporting...") self.player.save([ f"{self.importsDest}/{songname}/bass.flac", f"{self.importsDest}/{songname}/drums.flac", f"{self.importsDest}/{songname}/other.flac", f"{self.importsDest}/{songname}/vocals.flac" ], [ sliders[0].get(), sliders[2].get(), sliders[1].get(), sliders[3].get() ], file, MISSTconfig.getConfig(self, f"{self.importsDest}/{songname}")["image_raw"] ) self.export_button.configure(text="Exported!") threading.Timer(1.5, lambda: self.export_button.configure(text="Export")).start() def shuffle(self) -> None: """ Plays a random song """ self.shuffle_button.configure(state=tkinter.DISABLED) try: songs = MISSThelpers.MISSTlistdir(self, self.importsDest) random.shuffle(songs) self.playing = True self.effects_checkbox.deselect() self.effects() self.play(songs[0]) except: # can ignore this error pass self.shuffle_button.configure(state=tkinter.NORMAL) def play_next(self, songName:str) -> None: """ Plays the next song Args: songName (str): The name of the current song """ self.next_button.configure(state=tkinter.DISABLED) try: songs = MISSThelpers.MISSTlistdir(self, self.importsDest) index = songs.index(songName) self.playing = True self.effects_checkbox.deselect() self.effects() self.play(songs[index + 1]) except: # can ignore this error pass self.next_button.configure(state=tkinter.NORMAL) def play_previous(self, songName:str) -> None: """ Plays the previous song Args: songName (str): The name of the current song """ self.previous_button.configure(state=tkinter.DISABLED) try: songs = MISSThelpers.MISSTlistdir(self, self.importsDest) index = songs.index(songName) self.playing = True self.effects_checkbox.deselect() self.effects() self.play(songs[index - 1]) except: # can ignore this error pass self.previous_button.configure(state=tkinter.NORMAL) def slider_event(self, value:int) -> None: """ Sets the position of the song Args: value (int): The position of the song """ frames_per_millisecond = self.player.frame_rate / 1000 ms = value * 1000 frame = int(ms * frames_per_millisecond) self.player.set_position(0, frame) self.player.set_position(1, frame) self.player.set_position(2, frame) self.player.set_position(3, frame) return def effects(self) -> None: """ Sets the effects state """ if self.effects_checkbox.get() == 'on': self.player.set_effects(True) else: self.player.set_effects(False) def playpause(self) -> None: """ Pauses or resumes the song """ if self.playing == True: self.playpause_button.configure(state="normal", image=self.ImageCache["paused"]) self.player.pause() self.playing = False self.progressbar.configure(state=tkinter.DISABLED) self.effects_checkbox.configure(state=tkinter.DISABLED) self.effects_button.configure(state=tkinter.DISABLED) self.effects() else: self.playpause_button.configure(state="normal", image=self.ImageCache["playing"]) self.player.resume() self.playing = True self.progressbar.configure(state="normal") self.effects_checkbox.configure(state="normal") self.effects_button.configure(state="normal") def loopEvent(self) -> None: """ Sets the loop state """ if self.loop == True: self.loop = False self.loop_button.configure(state="normal", image=self.ImageCache["loop-off"]) else: self.loop = True self.loop_button.configure(state="normal", image=self.ImageCache["loop"]) def update_progress_bar(self, current_time:int, total_duration:int) -> None: """ Updates the progress bar Args: current_time (int): The current time of the song total_duration (int): The total duration of the song """ progress = current_time / total_duration progress_in_seconds = int(progress * total_duration) self.progressbar.set(progress_in_seconds) self.progress_label_left.configure(text=f"{str(datetime.timedelta(seconds=progress_in_seconds))[2:7]}") self.progress_label_right.configure(text=f"{str(datetime.timedelta(seconds=total_duration))[2:7]}") def update_UI(self, audioPath:str, start_ms:int) -> None: """ Updates the UI Args: audioPath (str): The path to the song start_ms (int): The start time of the song """ try: self.lyrics_window.destroy() # Destroy the lyrics window if it exists except: pass try: self.next_button.configure(state="normal") self.previous_button.configure(state="normal") self.playpause_button.configure(state="normal") self.effects_checkbox.configure(state="normal") self.effects_button.configure(state="normal") self.effects_checkbox.deselect() self.effects() if self.playing == True: self.playpause_button.configure(image=self.ImageCache["playing"]) else: self.playpause_button.configure(image=self.ImageCache["paused"]) except: pass # This is just to prevent errors when the player is closed or the song is changed before the UI is updated. self.songlabel.configure(text="") song_name = os.path.basename(os.path.dirname(audioPath)) song_dir = os.path.dirname(audioPath) config = MISSTconfig(song_dir) self.next_button.configure(command=lambda: self.play_next(song_name)) self.previous_button.configure(command=lambda: self.play_previous(song_name)) try: byte_string = config.getConfig(song_dir)["image_raw"] byte_data = base64.b64decode(byte_string) byte_stream = io.BytesIO(byte_data) byte_stream.seek(0) cover_art = customtkinter.CTkImage(Image.open(byte_stream), size=(40, 40)) except: self.logger.error(traceback.format_exc()) self.logger.error("No cover art found.") cover_art = self.ImageCache["no-cover-art"] namelen = len(song_name) n = 30 shortname = song_name if namelen <= n else song_name[:(n - namelen)] + "..." self.current_song = song_name self.songlabel.configure(text=shortname) self.songlabel.configure(image=cover_art) duration = int(self.player.duration) self.progressbar.configure(from_=0, to=duration, state="normal") self.progressbar.set(start_ms // 1000) # Define a variable to track the current time current_time = start_ms // 1000 MISSThelpers.update_rpc( self, Ltext="Listening to separated audio", Dtext=song_name, image=config.getConfig(song_dir)["image_url"], large_text=song_name, end_time=time.time() + duration, small_image="icon-0", ) self.progressbar_active = False def reset_to_default(): self.logger.info("No more songs to play. Returning to default state.") self.playpause_button.configure(image=self.ImageCache["paused"], state=tkinter.DISABLED) self.playing = False self.progressbar.configure(state=tkinter.DISABLED) self.effects_checkbox.configure(state=tkinter.DISABLED) self.effects_button.configure(state=tkinter.DISABLED) self.progressbar.set(0) self.progress_label_left.configure(text="00:00") self.progress_label_right.configure(text="00:00") self.songlabel.configure(text="Play Something!", image=self.ImageCache["empty"]) self.next_button.configure(state=tkinter.DISABLED) self.previous_button.configure(state=tkinter.DISABLED) MISSThelpers.update_rpc( self, Ltext="Idle", Dtext="Nothing is playing", image="icon-0", large_text="MISST", ) def on_end(): if self.loop == True: try: self.play(song_name) except: self.logger.error(traceback.format_exc()) reset_to_default() elif self.autoplay == True: try: songs = MISSThelpers.MISSTlistdir(self, self.importsDest) index = songs.index(song_name) self.playing = True self.effects_checkbox.deselect() self.effects() self.play(songs[index + 1]) except: self.logger.error(traceback.format_exc()) reset_to_default() else: reset_to_default() def update_progress(): nonlocal current_time while True: time.sleep(0.1) # Update the progress bar every 100ms # Update the progress bar current_time = self.player.get_position(3) self.update_progress_bar(current_time, duration) # Increment the current time only if the user hasn't interacted with the progress bar if self.playing == False: MISSThelpers.update_rpc( self, Ltext="(Paused)", Dtext=song_name, image=config.getConfig(song_dir)["image_url"], large_text=song_name, end_time=None, small_image="icon-0", ) if not self.progressbar_active and self.playing == True: MISSThelpers.update_rpc( self, Ltext="Listening to separated audio", Dtext=song_name, image=config.getConfig(song_dir)["image_url"], large_text=song_name, end_time=time.time() + duration - current_time, small_image="icon-0", ) if current_time >= duration: stop_update_thread() on_end() return def stop_update_thread(): try: if self.update_timer: MISSThelpers.terminate_thread(self, self.update_timer) except: pass # Can ignore this error because the threads pointer is killed when this function is called (which is when a new song is played) def on_progressbar_drag_start(event): self.progressbar_active = True def on_progressbar_drag_stop(event): nonlocal current_time self.progressbar_active = False # Update the current time based on the user's selection current_time = self.progressbar.get() # Bind the drag start and drag stop events to the progress bar self.progressbar.bind("", on_progressbar_drag_start) self.progressbar.bind("", on_progressbar_drag_stop) # Stop the previous update thread if it exists stop_update_thread() # Start the progress update timer self.update_timer = threading.Thread(target=update_progress, daemon=True) self.update_timer.start() if __name__ == "__main__": app = MISSTapp() MISSThelpers.update_rpc(app, Ltext="Idle", Dtext="Nothing is playing") app.mainloop() ================================================ FILE: MISST/MISSThelpers.py ================================================ import ctypes import os import platform import re import shutil import sys import threading import time import tkinter import uuid from colorsys import hls_to_rgb, rgb_to_hls import customtkinter import demucs import music_tag import psutil import requests import torch from MISSTplayer import MISSTplayer from MISSTsettings import MISSTsettings from vcolorpicker import getColor, hex2rgb, rgb2hex, useLightTheme class MISSTconsole(): """ A class to handle the console output of MISST """ def __init__(self, terminal:customtkinter.CTkTextbox, ogText:str) -> None: """ Parameters terminal : tkinter.Text The tkinter.Text widget to be used as the console ogText : str The original text to be displayed in the console """ self.consoleText = ogText self.terminal = terminal self.curThread = None self.terminal.delete("0.0", "end") # delete all text self.terminal.insert("0.0", self.consoleText) self.terminal.configure(state="disabled") def updateThread(self, text:str) -> None: """ A thread to update the console text Args: text (str): The text to be added to the console """ t = 0 while True: time.sleep(0.5) if t > 3: t -= t periods = ["", ".", "..", "..."] self.terminal.configure(state="normal") self.terminal.delete("0.0", "end") self.terminal.insert("0.0", f"{self.consoleText}{text}{periods[t]}") self.terminal.configure(state="disabled") t += 1 def update(self, text:str) -> None: """ Update the console text Args: text (str): The text to be added to the console """ self.curThread = threading.Thread(target=self.updateThread, args=(text,), daemon=True) self.curThread.start() def endUpdate(self) -> None: """ End the update thread Args: text (str): The text to be added to the console """ MISSThelpers.terminate_thread(self, self.curThread) self.terminal.configure(state="normal") self.terminal.delete("0.0", "end") self.terminal.insert("0.0", self.consoleText) self.terminal.configure(state="disabled") def addLine(self, text:str) -> None: """ Add a line to the console Args: text (str): The text to be added to the console """ self.consoleText += f"{text}" self.terminal.configure(state="normal") self.terminal.delete("0.0", "end") self.terminal.insert("0.0", self.consoleText) self.terminal.configure(state="disabled") def editLine(self, text:str, line_number:int) -> None: """ Edit a line in the console Args: text (str): The text to be added to the console line_number (int): The line number to be edited """ self.consoleText = text self.terminal.configure(state="normal") self.terminal.delete(f"{line_number + 1}.0", f"end") self.terminal.insert(f"{line_number + 1}.0", text) self.terminal.configure(state="disabled") class MISSThelpers(): """ A class filled with helper methods for MISST """ def update_rpc( self, Ltext:str = None, Dtext:str = None, image:str = "icon-0", large_text:str = "MISST", end_time:int = None, small_image:str = None, ) -> None: """ Update the Discord Rich Presence Args: Ltext (str, optional): The large text to be displayed. Defaults to None. Dtext (str, optional): The details text to be displayed. Defaults to None. image (str, optional): The image to be displayed. Defaults to "icon-0". large_text (str, optional): The large text to be displayed. Defaults to "MISST". end_time (int, optional): The end time of the activity. Defaults to None. small_image (str, optional): The small image to be displayed. Defaults to None. """ start_time = time.time() if self.RPC_CONNECTED: try: self.RPC.update( large_image=image, small_image=small_image, start=start_time, end=end_time, large_text=large_text, state=Ltext, details=Dtext, ) except: return return def apple_music(url:str, outdir:str) -> None: """ Download an Apple Music song Args: url (str): The Apple Music song URL outdir (str): The output directory """ host = 'https://api.fabdl.com' info = requests.get(host + '/apple-music/get?url=', params={'url': url}).json()['result'] convert_task = requests.get(host + f'/apple-music/mp3-convert-task/{info["gid"]}/{info["id"]}') tid = convert_task.json()['result']['tid'] convert_task = requests.get(host + f'/apple-music/mp3-convert-progress/{tid}') r = requests.get(host + convert_task.json()['result']['download_url']) with open(f"{outdir}/{info['artists'] + ' - ' + info['name']}.mp3", 'wb') as f: f.write(r.content) try: audiofile = music_tag.load_file(f"{outdir}/{info['artists'] + ' - ' + info['name']}.mp3") audiofile['artwork'] = requests.get(info['image']).content audiofile.save() except: pass def change_theme(theme:str) -> None: """ Change the theme of the application Args: theme (str): The theme to be changed to """ customtkinter.set_appearance_mode(theme) def checkbox_event(checkbox:customtkinter.CTkCheckBox, export_slider:customtkinter.CTkSlider, sound:str, player:MISSTplayer, slider:customtkinter.CTkSlider) -> None: """ Change the volume of a sound Args: checkbox (tkinter.Checkbutton): The checkbox sound (str): The sound to be changed player (MISSTplayer): The sound player slider (tkinter.Scale): The volume slider """ if checkbox.get() == "on": player.set_volume(sound, slider.get()) else: slider.set(0) player.set_volume(sound, slider.get()) MISSThelpers.slider_event(slider.get(), export_slider, sound, player, checkbox) def slider_event(value:int, export_slider:customtkinter.CTkSlider, sound:str, player:MISSTplayer, checkbox:customtkinter.CTkCheckBox) -> None: """ Change the volume of a sound Args: value (int): The volume value sound (str): The sound to be changed player (MISSTplayer): The sound player checkbox (tkinter.Checkbutton): The checkbox """ settings = MISSTsettings() export_slider[0].set(value) if value >= 0.01: checkbox.set("on") export_slider[1].configure(border_color=settings.getSetting("chosenLightColor") if customtkinter.get_appearance_mode() == "Light" else settings.getSetting("chosenDarkColor")) player.set_volume(sound, value) else: checkbox.set("off") export_slider[1].configure(border_color="#3E454A") player.set_volume(sound, value) def MISSTlistdir(self, directory:str) -> list: """ List all MISST folders in a directory Args: directory (str): The directory to be searched """ try: os_list = os.listdir(directory) misst_list = [] for _ in os_list: required_files = ["bass.flac", "drums.flac", "other.flac", "vocals.flac", ".misst"] found = 0 for file in required_files: if os.path.isfile(f"{directory}/{_}/{file}"): found += 1 if len(required_files) == found: misst_list.append(_) return misst_list except: return [] def getsize(self, dir:str) -> int: """ Get the size of a directory Args: dir (str): The directory to be searched """ total = 0 for entry in os.scandir(dir): if entry.is_file(): total += entry.stat().st_size elif entry.is_dir(): total += self.getsize(self, entry.path) return total def adjust_color_lightness(r:int, g:int, b:int, factor:int) -> str: """ Adjust the lightness of a color Args: r (int): The red value g (int): The green value b (int): The blue value factor (int): The factor to be adjusted by """ h, l, s = rgb_to_hls(r / 255.0, g / 255.0, b / 255.0) l = max(min(l * factor, 1.0), 0.0) r, g, b = hls_to_rgb(h, l, s) return f"#{rgb2hex(int(r * 255), int(g * 255), int(b * 255))}" def darken_color(r:int, g:int, b:int, factor:int = 0.1) -> str: """ Darken a color Args: r (int): The red value g (int): The green value b (int): The blue value factor (int, optional): The factor to be darkened by. Defaults to 0.1. """ return MISSThelpers.adjust_color_lightness(r, g, b, 1 - factor) def updateTheme(self, color:str) -> str: """ Update the theme of the application Args: color (str): The color to be changed """ if color == "light": cur_color = self.settings.getSetting("chosenLightColor") old_color = (hex2rgb(cur_color.replace("#", ""))) useLightTheme(True if customtkinter.get_appearance_mode() == "Light" else False) self.withdraw() # Hide the window chosen_color = f"#{rgb2hex(getColor(old_color))}" self.deiconify() # Show the window rgb_chosen = hex2rgb(chosen_color.replace("#", "")) self.settings.setSetting("chosenLightColor", chosen_color) self.settings.setSetting("chosenLightHoverColor", MISSThelpers.darken_color(rgb_chosen[0], rgb_chosen[1], rgb_chosen[2], 0.2)) self.settings.setSetting("chosenLightDarker", MISSThelpers.darken_color(rgb_chosen[0], rgb_chosen[1], rgb_chosen[2], 0.35)) self.settings.applyThemeSettings("./Assets/Themes/MISST.json", "./Assets/Themes/maluableJSON") self.button_light.configure(fg_color=chosen_color, hover_color=chosen_color) else: cur_color = self.settings.getSetting("chosenDarkColor") old_color = (hex2rgb(cur_color.replace("#", ""))) useLightTheme(True if customtkinter.get_appearance_mode() == "Light" else False) self.withdraw() # Hide the window chosen_color = f"#{rgb2hex(getColor(old_color))}" self.deiconify() # Show the window rgb_chosen = hex2rgb(chosen_color.replace("#", "")) self.settings.setSetting("chosenDarkColor", chosen_color) self.settings.setSetting("chosenDarkHoverColor", MISSThelpers.darken_color(rgb_chosen[0], rgb_chosen[1], rgb_chosen[2], 0.2)) self.settings.setSetting("chosenDarkDarker", MISSThelpers.darken_color(rgb_chosen[0], rgb_chosen[1], rgb_chosen[2], 0.35)) self.settings.applyThemeSettings("./Assets/Themes/MISST.json", "./Assets/Themes/maluableJSON") self.button_dark.configure(fg_color=chosen_color, hover_color=chosen_color) return chosen_color def resetSettings(self) -> None: """ Reset the settings of the application """ cuda = torch.cuda.is_available() self.settings.resetDefaultTheme("./Assets/Themes/MISST.json", "./Assets/Themes/maluableJSON") self.settings.setSetting("rpc", "true") self.settings.setSetting("autoplay", "true") self.settings.setSetting("accelerate_on_gpu", "true" if cuda else "false") self.rpc_box.select() self.autoplay_box.select() self.preprocess_method_box.select() if cuda else self.preprocess_method_box.deselect() self.button_light.configure(fg_color=self.settings.getSetting("defaultLightColor"), hover_color=self.settings.getSetting("defaultLightColor")) self.button_dark.configure(fg_color=self.settings.getSetting("defaultDarkColor"), hover_color=self.settings.getSetting("defaultDarkColor")) self.model_select.set("htdemucs") self.settings.setSetting("chosen_model", "htdemucs") self.change_model(self.model_select.get()) def autoplay_event(self) -> None: """ Event for when the autoplay box is checked """ if self.autoplay_box.get() == 1: self.settings.setSetting("autoplay", "true") else: self.settings.setSetting("autoplay", "false") def rpc_event(self) -> None: """ Event for when the rpc box is checked """ if self.rpc_box.get() == 1: self.settings.setSetting("rpc", "true") else: self.settings.setSetting("rpc", "false") def accelerate_event(self) -> None: """ Event for when the accelerate box is checked """ if self.preprocess_method_box.get() == 1 and torch.cuda.is_available() == True: self.settings.setSetting("accelerate_on_gpu", "true") elif self.preprocess_method_box.get() == 1 and torch.cuda.is_available() == False: self.preprocess_method_box.deselect() self.preprocess_method_box.place(relx=0.39, rely=0.85, anchor=tkinter.CENTER) self.preprocess_method_box.configure(text="CUDA Not Available") self.settings.setSetting("accelerate_on_gpu", "false") time.sleep(1.5) self.preprocess_method_box.place(relx=0.38, rely=0.85, anchor=tkinter.CENTER) self.preprocess_method_box.configure(text="Accelerate on GPU?") else: self.settings.setSetting("accelerate_on_gpu", "false") def clearDownloads(self) -> None: """ Clear the downloads folder """ self.confirmation_frame = customtkinter.CTkFrame( master=self.settings_window, width=350, height=350, corner_radius=0 ) self.confirmation_frame.place(relx=0.25, rely=0.5, anchor=tkinter.CENTER) self.confirmation_header = customtkinter.CTkLabel( master=self.confirmation_frame, text="Are you sure?", font=(self.FONT, -16) ) self.confirmation_header.place(relx=0.5, rely=0.45, anchor=tkinter.CENTER) self.confirmation_yes = customtkinter.CTkButton( master=self.confirmation_frame, text="Yes", font=(self.FONT, -12), command=lambda: clear(), width=80, ) self.confirmation_yes.place(relx=0.35, rely=0.55, anchor=tkinter.CENTER) self.confirmation_no = customtkinter.CTkButton( master=self.confirmation_frame, text="No", font=(self.FONT, -12), command=lambda: self.confirmation_frame.destroy(), width=80, ) self.confirmation_no.place(relx=0.65, rely=0.55, anchor=tkinter.CENTER) def clear(): try: shutil.rmtree(self.importsDest) os.mkdir(self.importsDest) self.confirmation_frame.destroy() bytes = MISSThelpers.getsize(MISSThelpers, self.importsDest) gb = bytes / 1000000000 gb = round(gb, 2) text = str(gb) + " GB" self.downloads_info.configure(text=text) except: pass def change_location(self) -> None: """ Change the location of the downloads folder """ try: importsdest_nocheck = tkinter.filedialog.askdirectory( initialdir=os.path.abspath(self.importsDest) ) importsdest_nocheck = importsdest_nocheck.replace("\\", "/") if importsdest_nocheck != "" and os.path.isdir( os.path.abspath(importsdest_nocheck) ): dummypath = os.path.join(importsdest_nocheck, str(uuid.uuid4())) try: with open(dummypath, "w"): pass os.remove(dummypath) importsdest = importsdest_nocheck except IOError: importsdest = os.path.abspath(importsdest) self.settings.setSetting("importsDest", importsdest) self.importsDest = importsdest dir = os.path.abspath(self.importsDest) dirlen = len(dir) n = 20 location_text = dir if dirlen <= n else "..." + dir[-(n - dirlen) :] self.storage_location_info.configure(text=location_text) return None else: self.importsDest = os.path.abspath(self.importsDest) return None except Exception as e: print(e) self.importsDest = os.path.abspath(self.importsDest) return None def loading_label(label:customtkinter.CTkLabel, text:str, og_text:str = "") -> None: """ Loading animation for the settings window Args: label (tkinter.Label): The label to animate text (str): The text to append to the label og_text (str, optional): The original text of the label. Defaults to "". """ t = 0 try: while True: time.sleep(0.5) if label.cget("text") == "": break if t > 3: t -= t periods = ["", ".", "..", "..."] label.configure(text=f"{og_text}{text}{periods[t]}") t += 1 except: pass return def GenerateSystemInfo(self) -> str: """ Generate system info for the settings window """ info = "" info += "Python version:\t%s\n" % sys.version info += "System:\t%s\n" % platform.platform() info += "CPU:\t%s\n" % platform.processor() info += "Memory:\t%.3fMB\n" % (psutil.virtual_memory().total / 1048576) info += "PyTorch version:\t%s\n" % torch.__version__ info += "CUDA available:\t%s\n" % torch.cuda.is_available() if torch.cuda.is_available(): for i in range(torch.cuda.device_count()): info += "CUDA %d:\t%s\n" % (i, re.findall("\\((.*)\\)", str(torch.cuda.get_device_properties(i)))[0]) info += "Demucs version:\t%s\n" % demucs.__version__ info += "FFMpeg available:\t%s\n" % self.FFMpegAvailable info += "MISST version:\t%s\n" % self.version return info def freeimage_upload(self, img:str) -> str: """ Upload an image to freeimage.host Args: img (str): The path to the image """ key = "6d207e02198a847aa98d0a2a901485a5" response = requests.post( url="https://freeimage.host/api/1/upload", data={"key": key}, files={"source": img}, ) if not response.ok: raise Exception("Error uploading image", response.json()) return response.json()["image"]["url"] def terminate_thread(self, thread:threading.Thread) -> None: """ Terminate a thread Args: thread (threading.Thread): The thread to terminate """ if not thread.is_alive(): return exc = ctypes.py_object(SystemExit) res = ctypes.pythonapi.PyThreadState_SetAsyncExc( ctypes.c_long(thread.ident), exc) if res == 0: raise ValueError("nonexistent thread id") elif res > 1: # """if it returns a number greater than one, you're in trouble, # and you should call it again with exc=NULL to revert the effect""" ctypes.pythonapi.PyThreadState_SetAsyncExc(thread.ident, None) raise SystemError("PyThreadState_SetAsyncExc failed") ================================================ FILE: MISST/MISSTlogger.py ================================================ import datetime import logging import sys class MISSTlogger: """ MISSTlogger class """ def __init__(self) -> None: """ Initialize the logger """ loggerName = "MISST" logFormatter = logging.Formatter(fmt=" %(name)s :: %(levelname)-8s :: %(message)s") self.logger = logging.getLogger(loggerName) logging.basicConfig( filename="MISST.log", filemode="a", format=" %(name)s :: %(levelname)-8s :: %(message)s", level=logging.INFO, ) consoleHandler = logging.StreamHandler() consoleHandler.setFormatter(logFormatter) self.logger.addHandler(consoleHandler) self.logger.info(f'Logger initialized ({str(datetime.datetime.now()).split(".")[0]})') sys.excepthook = self.handler def handler(self, type, value, tb) -> None: self.logger.exception("Uncaught exception: {0}".format(str(value))) ================================================ FILE: MISST/MISSTplayer.py ================================================ import base64 import io import threading from typing import List import music_tag # for exporting song metadata import numpy as np import pyaudio import soundfile as sf from MISSTsettings import MISSTsettings from scipy.signal import butter, fftconvolve, filtfilt class MISSTplayer: """ MISSTplayer class """ def __init__(self, files:list, volumes:list) -> None: """ Initialize the player Args: files (list): List of file paths volumes (list): List of volume values """ self.files = files self.p = pyaudio.PyAudio() self.streams = [] self.paused = False self.positions = [0] * len(files) self.volumes = volumes self.chunk_size = 1024 self.effects = False self.settings = MISSTsettings() self.bands = lambda: [self.settings.getSetting(f"eq_{n}") for n in range(1,10)] # lambda so the player can access the latest information self.eq = lambda: True if self.settings.getSetting("eq") == "true" else False self.center_freqs = [62, 125, 250, 500, 1_000, 2_500, 4_000, 8_000, 16_000] # 62 Hz, 125 Hz, 250 Hz, 500 Hz, 1 KHz, 2.5 KHz, 4 KHz, 8 KHz, 16 KHz for file in self.files: data, self.frame_rate = sf.read(file, dtype='int16') self.duration = len(data) / self.frame_rate self.channels = data.shape[1] stream = self.p.open(format=self.p.get_format_from_width(2), channels=self.channels, rate=self.frame_rate, output=True) self.streams.append(stream) reverb_length = int(self.frame_rate * 0.3) self.impulse_response = self.generate_impulse_response(reverb_length, 0.5) self.reverb_tails = [np.zeros(self.chunk_size, dtype=np.float32) for _ in self.streams] def play(self) -> None: """ Play the audio """ self.paused = False while not self.paused: for i, stream in enumerate(self.streams): data = self.get_data(i) if data: stream.write(data) else: break def get_data(self, stream_index:int) -> bytes: """ Get the audio data Args: stream_index (int): Index of the stream """ data, _ = sf.read(self.files[stream_index], dtype='int16', start=self.positions[stream_index], frames=self.chunk_size) if len(data) > 0: self.positions[stream_index] += len(data) data = self.adjust_volume(data, self.volumes[stream_index]) if self.effects == True: try: data = self.apply_effects(data, float(self.settings.getSetting("speed")), float(self.settings.getSetting("reverb")), float(self.settings.getSetting("pitch")), stream_index) except: # json error pass try: if self.eq() == True: data = self.apply_eq(data) # apply eq last so it can be applied to nightcore data as well except: # json error pass return data def get_position(self, stream_index:int) -> float: """ Get the position of the audio Args: stream_index (int): Index of the stream """ return self.positions[stream_index] / float(self.frame_rate) def adjust_volume(self, data:bytes, volume:float) -> bytes: """ Adjust the volume of the audio Args: data (bytes): Audio data volume (float): Volume value """ data = bytearray(data) for i in range(0, len(data), 2): sample = int.from_bytes(data[i:i+2], byteorder='little', signed=True) sample = int(sample * volume) data[i:i+2] = sample.to_bytes(2, byteorder='little', signed=True) return bytes(data) def apply_effects(self, data: bytes, speed_factor: float, reverb_factor: float, pitch_shift: float, stream_index:int) -> bytes: """ Modify the audio Args: data (bytes): Audio data speed_factor (float): Speed value between 0.5 and 2.0 (0.5 = half speed, 2.0 = double speed) reverb_factor (float): Reverb value between 0.0 and 1.0 (0.0 = no reverb, 1.0 = full reverb) delay_time (float): Delay time in seconds stream_index (int): Index of the stream """ # Convert bytes to numpy array samples = np.frombuffer(data, dtype=np.int16) samples = samples.astype(np.float32) samples = samples.reshape((len(samples) // 2, 2)).T samples = samples.mean(axis=0) # Modify speed samples = self.modify_speed(samples, speed_factor) # Modify pitch samples = self.modify_pitch(samples, pitch_shift) # Add reverb samples = self.apply_reverb(samples, reverb_factor, stream_index) # Convert back to bytes samples = samples.astype(np.int16) samples = np.repeat(samples, 2) return samples.tobytes() def modify_speed(self, samples:np.ndarray, speed_factor:float) -> bytes: """ Modify the speed of the audio Args: samples (np.ndarray): Audio data speed_factor (float): Speed value between 0.5 and 2.0 (0.5 = half speed, 2.0 = double speed) """ if speed_factor == 1.0: return samples num_samples = len(samples) new_num_samples = int(num_samples / speed_factor) # Resample the audio to the new length resampled = np.interp( np.linspace(0, num_samples, new_num_samples, endpoint=False), np.arange(num_samples), samples ) return resampled def apply_antialiasing_filter(self, samples: np.ndarray, cutoff_freq: float, frame_rate: int) -> np.ndarray: """ Apply an anti-aliasing filter to the audio Args: samples (np.ndarray): Audio data cutoff_freq (float): Cutoff frequency in Hz frame_rate (int): Frame rate in Hz """ # Create a low-pass Butterworth filter nyquist = 0.5 * frame_rate normal_cutoff = cutoff_freq / nyquist b, a = butter(8, normal_cutoff, btype='low', analog=False) # Apply the filter to the samples filtered_samples = filtfilt(b, a, samples, axis=0) return filtered_samples def modify_pitch(self, samples:np.ndarray, pitch_shift:float) -> bytes: """ Modify the pitch of the audio Args: samples (np.ndarray): Audio data pitch_shift (float): Pitch value between -12.0 and 12.0 (-12.0 = one octave down, 12.0 = one octave up) """ if pitch_shift == 0: return samples pitch_shift *= 12 # Convert pitch shift from octaves to semitones samples = samples.astype(np.float32) / np.iinfo(np.int16).max # Convert samples to float32 between -1.0 and 1.0 # Continue with the pitch shift as before shift_ratio = 2 ** (pitch_shift / 12) # Shift by half-steps (semitones) time_axis = np.arange(samples.shape[0]) / self.frame_rate shifted_audio = np.interp(time_axis * shift_ratio, time_axis, samples) # Apply an anti-aliasing filter to attenuate high frequencies cutoff_freq = 0.9 * self.frame_rate / 2.0 # You can adjust the cutoff frequency as needed shifted_audio = self.apply_antialiasing_filter(shifted_audio, cutoff_freq, self.frame_rate) shifted_audio = np.clip(shifted_audio, -1.0, 1.0) # Clip samples to prevent overflow # Convert samples back to 16-bit integer range return shifted_audio * np.iinfo(np.int16).max def generate_impulse_response(self, length:int, decay_factor:float) -> np.ndarray: """ Generate impulse response Args: length (int): Length of the impulse response in samples (44100 samples = 1 second) decay_factor (float): Decay factor between 0.0 and 1.0 (0.0 = no decay, 1.0 = full decay) """ impulse_response = np.zeros(length, dtype=np.float32) impulse_response[0] = 1.0 # Generate decaying exponential tail for i in range(1, length): impulse_response[i] = impulse_response[i - 1] * decay_factor # Add some random noise for early reflections impulse_response += np.random.normal(0, 0.05, length) return impulse_response def apply_reverb(self, samples: np.ndarray, reverb_factor: float, stream_index: int) -> bytes: """ Add reverb to the audio Args: samples (np.ndarray): Audio data reverb_factor (float): Reverb value between 0.0 and 1.0 (0.0 = no reverb, 1.0 = full reverb) stream_index (int): Index of the stream """ if reverb_factor == 0: return samples samples = samples.astype(np.float32) / np.iinfo(np.int16).max # Convert samples to float32 between -1.0 and 1.0 # Apply reverb impulse response to the current chunk reverb_audio = fftconvolve(samples, self.impulse_response, mode='full') # Concatenate previous reverb tail with the current reverb tail reverb_audio[:len(self.reverb_tails[stream_index])] += self.reverb_tails[stream_index] # Store the current reverb tail for the next chunk self.reverb_tails[stream_index] = reverb_audio[len(samples):] mixed_audio = samples * (1 - reverb_factor) + reverb_audio[:len(samples)] * reverb_factor # Mix original and reverb audio mixed_audio = np.clip(mixed_audio, -1.0, 1.0) # Clip samples to prevent overflow # Convert samples back to 16-bit integer range return mixed_audio * np.iinfo(np.int16).max def apply_eq(self, data:bytes) -> bytes: """ Apply the equalizer effect to the audio Args: data (bytes): Audio data """ # Convert data to float32 audio_data = np.frombuffer(data, dtype=np.int16) try: gains = np.array(self.bands(), dtype=np.float32) # Gain values in dB except: gains = np.array([0] * 9, dtype=np.float32) # Number of frequency bands num_bands = len(gains) # Generate frequency range (20Hz to 20kHz) frequencies = np.fft.rfftfreq(len(audio_data), d=1 / 44100) # Create equalizer response response = np.zeros_like(frequencies) # Apply gain to each frequency band for i in range(num_bands): lower_cutoff = self.center_freqs[i] / np.sqrt(2) # Lower cutoff frequency upper_cutoff = self.center_freqs[i] * np.sqrt(2) # Upper cutoff frequency # Find indices within the frequency range indices = np.where((frequencies >= lower_cutoff) & (frequencies <= upper_cutoff))[0] # Apply gain to the corresponding indices response[indices] += gains[i] # Convert response to linear scale and normalize response_linear = 10 ** (response / 20) # Apply equalization to audio data audio_fft = np.fft.rfft(audio_data) audio_fft *= response_linear[:len(audio_fft)] equalized_audio = np.fft.irfft(audio_fft).astype(np.int16) # Clip the audio to avoid distortion equalized_audio = np.clip(equalized_audio, -32768, 32767) return equalized_audio.tobytes() def set_effects(self, effects:bool) -> None: """ Set the effects of the audio Args: effects (bool): Effects value """ self.effects = effects def set_volume(self, stream_index:int, volume:float) -> None: """ Set the volume of the audio Args: stream_index (int): Index of the stream volume (float): Volume value """ self.volumes[stream_index] = volume def set_position(self, stream_index:int, position:float) -> None: """ Set the position of the audio Args: stream_index (int): Index of the stream position (float): Position value """ self.positions[stream_index] = position def save(self, files:List[str], volumes:List[int], filename:str, cover_art:bytes=None) -> None: """ Save the audio Args: files (List[str]): List of audio files volumes (List[int]): List of volume values filename (str): Name of the file """ # Load the audio files and get the sample rate audio_data = [] sample_rate = None for file in files: data, sr = sf.read(file) audio_data.append(data) if sample_rate is None: sample_rate = sr adjusted_data = [] for i in range(len(audio_data)): adjusted_data.append(audio_data[i] * volumes[i]) overlapped_data = np.sum(adjusted_data, axis=0) sf.write(filename, overlapped_data, sample_rate) if cover_art is not None and cover_art != "null": byte_data = base64.b64decode(cover_art) byte_stream = io.BytesIO(byte_data) byte_stream.seek(0) f = music_tag.load_file(filename) f['artwork'] = byte_stream.read() f.save() def pause(self) -> None: """ Pause the audio """ self.paused = True def resume(self) -> None: """ Resume the audio """ if self.paused: self.paused = False threading.Thread(target=self.play, daemon=True).start() def stop(self) -> None: """ Stop the audio """ for i, stream in enumerate(self.streams): stream.stop_stream() stream.close() self.p.terminate() def change_files(self, new_files:list, volumes:list) -> None: """ Change the files of the audio Args: new_files (list): List of new files volumes (list): List of volumes """ self.paused = True self.volumes = volumes for i, stream in enumerate(self.streams): stream.stop_stream() stream.close() self.streams.clear() self.files = new_files self.positions = [0] * len(new_files) for file in self.files: data, self.frame_rate = sf.read(file, dtype='int16') self.duration = len(data) / self.frame_rate self.channels = data.shape[1] stream = self.p.open(format=self.p.get_format_from_width(2), channels=self.channels, rate=self.frame_rate, output=True) self.streams.append(stream) self.paused = False threading.Thread(target=self.play, daemon=True).start() ================================================ FILE: MISST/MISSTpreprocess.py ================================================ import concurrent.futures import logging import os import pathlib import time import traceback import wave import julius import numpy as np import soundfile import soundfile as sf import torch from demucs.apply import BagOfModels, apply_model from demucs.pretrained import get_model from MISSThelpers import MISSTconsole # Modified functions from https://github.com/facebookresearch/demucs, # https://pytorch.org/audio/main/tutorials/hybrid_demucs_tutorial.html # and https://github.com/CarlGao4/Demucs-Gui class MISSTpreprocess(): """ MISSTpreprocess class """ def __init__(self) -> None: pass def LoadModel(self, name:str, repo:str = None, device:str = "cuda" if torch.cuda.is_available() else "cpu",) -> BagOfModels: """ Load the model Args: name (str): Name of the model repo (str): Repository of the model device (str): Device to use """ model = get_model(name=name, repo=repo) model.to(device) model.eval() return model def GetData(self, model:BagOfModels) -> dict: """ Get the data from the model Args: model (demucs.pretrained.BagOfModels): Model to get the data from """ res = {} res["channels"] = model.audio_channels res["samplerate"] = model.samplerate if isinstance(model, BagOfModels): res["models"] = len(model.models) else: res["models"] = 1 res["sources"] = model.sources return res def Apply(self, model:BagOfModels, wav:np.ndarray, shifts:int = 1) -> dict: """ Apply the model to the audio Args: model (demucs.pretrained.BagOfModels): Model to apply wav (numpy.ndarray): Audio data shifts (int): Number of shifts """ audio = wav ref = audio.mean(0) audio -= ref.mean() audio /= ref.std() sources = apply_model(model, audio[None], shifts=shifts, split=False, overlap=0.25, progress=False)[0] sources *= ref.std() sources += ref.mean() return dict(zip(model.sources, sources)) def convert_audio_channels(self, wav:np.ndarray, channels:int = 2) -> np.ndarray: """ Convert the audio channels Args: wav (numpy.ndarray): Audio data channels (int): Number of channels """ *shape, src_channels, length = wav.shape if src_channels == channels: pass elif channels == 1: wav = wav.mean(dim=-2, keepdim=True) elif src_channels == 1: wav = wav.expand(*shape, channels, length) elif src_channels >= channels: wav = wav[..., :channels, :] else: raise Exception("Error changing audio dims") return wav def write_wav(self, wav:np.ndarray, filename:str, samplerate:int) -> None: """ Write the audio to a WAV file Args: wav (numpy.ndarray): Audio data filename (str): Filename samplerate (int): Samplerate """ if wav.dtype.is_floating_point: wav = (wav.clamp_(-1, 1) * (2**15 - 1)).short() with wave.open(filename, "wb") as f: f.setnchannels(wav.shape[1]) f.setsampwidth(2) f.setframerate(samplerate) f.writeframes(bytearray(wav.numpy())) def compress_wav_to_flac(self, wav_file:str, flac_file:str) -> None: """ Compress the WAV file to a FLAC file Args: wav_file (str): WAV filename flac_file (str): FLAC filename """ # Read the WAV file data, samplerate = sf.read(wav_file) # Write the FLAC file and delete the WAV file sf.write(flac_file, data, samplerate, format='FLAC') os.remove(wav_file) def convert_audio(self, wav:np.ndarray, from_samplerate:int, to_samplerate:int, channels:int) -> np.ndarray: """ Convert the audio Args: wav (numpy.ndarray): Audio data from_samplerate (int): From samplerate to_samplerate (int): To samplerate channels (int): Number of channels """ wav = self.convert_audio_channels(wav, channels) return julius.resample_frac(wav, from_samplerate, to_samplerate) def load_audio(self, fn:str, sr:int) -> np.ndarray: """ Load the audio Args: fn (str): Filename sr (int): Samplerate """ audio, raw_sr = soundfile.read(fn, dtype="float32") if len(audio.shape) == 1: audio = np.atleast_2d(audio).transpose() converted = self.convert_audio(torch.from_numpy(audio.transpose()), raw_sr, sr, 2) return converted.numpy() def apply_fade_in_out(self, input_file:str, output_file:str, fade_duration:float) -> None: """ Apply fade in and out to the audio Args: input_file (str): Input filename output_file (str): Output filename fade_duration (float): Fade duration """ # Read the audio file audio_data, sample_rate = sf.read(input_file) # Calculate the number of samples for the fade duration fade_samples = int(fade_duration * sample_rate) # Apply fade-in fade_in_curve = np.linspace(0.0, 1.0, fade_samples) audio_data[:fade_samples] *= fade_in_curve[:, np.newaxis] # Apply fade-out fade_out_curve = np.linspace(1.0, 0.0, fade_samples) audio_data[-fade_samples:] *= fade_out_curve[:, np.newaxis] # Save the modified audio to a new file sf.write(output_file, audio_data, sample_rate) def process( self, model:BagOfModels, infile:str, write:bool = True, outpath:pathlib.Path = pathlib.Path(""), split:float = 5.0, overlap:float = 0.25, sample_rate:int = 44100, device:str = "cuda" if torch.cuda.is_available() else "cpu", logger:logging.Logger = logging.getLogger("MISST"), console:MISSTconsole = None, ) -> None: """ Process the audio Args: model (demucs.pretrained.BagOfModels): Model to apply infile (str): Input filename write (bool): Write the output outpath (pathlib.Path): Output path split (float): Split (seconds) overlap (float): Overlap sample_rate (int): Sample rate device (str): Device logger (logging.Logger): Logger console (MISSTConsole): Console """ # Start the timer start_time = time.time() split = int(split * sample_rate) overlap = int(overlap * split) logger.info("Loading file") audio = self.load_audio(str(infile), sample_rate) logger.info(f"Loaded audio of shape {audio.shape}") orig_len = audio.shape[1] n = int(np.ceil((orig_len - overlap) / (split - overlap))) audio = np.pad(audio, [(0, 0), (0, n * (split - overlap) + overlap - orig_len)]) logger.info("Loading model to device %s" % device) model.to(device) stems = self.GetData(model)["sources"] new_audio = np.zeros((len(stems), 2, audio.shape[1])) total = np.zeros(audio.shape[1]) logger.info("Total splits of '%s' : %d" % (str(infile), n)) def separation(i): logger.info("Separation %d/%d" % (i + 1, n)) console.editLine(f"MISST Preprocessor\nCopyright (C) @MISST App.\n\nMISST> Split {i + 1}/{n} ({((i + 1)/n) * 100:.1f}%)", 0) l = i * (split - overlap) r = l + split result = self.Apply(model, torch.from_numpy(audio[:, l:r]).to(device)) for (j, stem) in enumerate(stems): new_audio[j, :, l:r] += result[stem].cpu().numpy() total[l:r] += 1 workers = 1 if device == "cuda" else (os.cpu_count() // 2) # CPU parallelization on half the cores available, CUDA kernels are already parallelized with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor: futures = [executor.submit(separation, i) for i in range(n)] concurrent.futures.wait(futures) if write: console.endUpdate() console.addLine("\nMISST> Preprocessed.") console.update("\nMISST> Writing to file") outpath.mkdir(exist_ok=True) for i in range(len(stems)): if np.all(total == 0): stem = np.zeros_like(new_audio[i]) else: stem = (new_audio[i] / total)[:, :orig_len] self.write_wav(torch.from_numpy(stem.transpose()), str(outpath / f"{stems[i]}.wav"), sample_rate) self.compress_wav_to_flac(str(outpath / f"{stems[i]}.wav"), str(outpath / f"{stems[i]}.flac")) self.apply_fade_in_out(str(outpath / f"{stems[i]}.flac"), str(outpath / f"{stems[i]}.flac"), 3.5) logger.info("Wrote to %s" % str(outpath)) logger.info("Done in %.2f seconds" % (time.time() - start_time)) console.endUpdate() else: pass del model # Free up memory def preprocess(self, file:str, outDir:str, chosen_model:str, device:str = "cuda") -> None: """ Preprocess the audio Args: file (str): Input filename outDir (str): Output directory device (str): Device """ self.logger.info(f"Preprocessing {file}...") console = MISSTconsole(self.preprocess_terminal_text, "MISST Preprocessor\nCopyright (C) @MISST App.\n") try: savename = os.path.basename(file).replace('.mp3', '').replace('.wav', '').replace('.flac', '') console.update("\nMISST> Loading model") processor = MISSTpreprocess() model = processor.LoadModel(name=chosen_model, repo=pathlib.Path("Pretrained")) console.endUpdate() console.addLine("\nMISST> Model loaded.") console.update("\nMISST> Preprocessing") processor.process(model, infile=pathlib.Path(file), outpath=pathlib.Path(f"{outDir}/{savename}"), device=device, console=console) del model # Free up memory except Exception as e: self.logger.error(e) self.logger.error(traceback.format_exc()) console.addLine("\nMISST> Error.") pass console.addLine("\nMISST> Done.") self.import_file_button.configure(state='normal') self.import_button.configure(state='normal') return ================================================ FILE: MISST/MISSTsettings.py ================================================ import json import os import shutil import torch class MISSTsettings(): """ Class for handling the settings of MISST """ def __init__(self) -> None: """ Initialize the settings """ # Check if the config file exists, if not create it # Path: MISST\MISSTsettings.py if not os.path.isfile("config.json"): self.createSettings() return def getSetting(self, setting:str) -> str: """ Get the setting from the saved config file Args: setting (str): The setting to be retrieved """ # Get the setting from the saved config file # Path: MISST\MISSTsettings.py # setting: The setting to be retrieved with open("config.json", "r") as f: data = json.load(f) return data[setting] def setSetting(self, setting:str, value:str) -> None: """ Set the setting in the saved config file Args: setting (str): The setting to be set value (str): The value to be set """ # Set the setting in the saved config file # Path: MISST\MISSTsettings.py # setting: The setting to be set # value: The value to be set with open("config.json", "r") as f: data = json.load(f) data[setting] = value with open("config.json", "w") as f: json.dump(data, f, indent=4) def applyThemeSettings(self, themeFile:str, baseTheme:str) -> None: """ Apply the chosen colorways to the theme file Args: themeFile (str): The theme file to be modified baseTheme (str): The base theme file """ # Apply the chosen colorways to the theme file # Path: MISST\MISSTsettings.py # themeFile: The theme file to be modified # colorways: The colorways to be applied with open(baseTheme, "r") as f: data = f.read() colorways = ["defaultLightColor", "defaultDarkColor", "defaultLightHoverColor", "defaultDarkHoverColor", "defaultLightDarker", "defaultDarkDarker"] for colorway in colorways: data = data.replace(colorway, self.getSetting(colorway.replace('default', 'chosen'))) with open(themeFile, "w") as f: f.write(data) def resetDefaultTheme(self, themeFile:str, baseTheme:str) -> None: """ Reset the theme file to the default theme Args: themeFile (str): The theme file to be modified baseTheme (str): The base theme file """ # Reset the theme file to the default theme # Path: MISST\MISSTsettings.py # themeFile: The theme file to be modified # colorways: The colorways to be applied with open(baseTheme, "r") as f: data = f.read() colorways = ["defaultLightColor", "defaultDarkColor", "defaultLightHoverColor", "defaultDarkHoverColor", "defaultLightDarker", "defaultDarkDarker"] for colorway in colorways: self.setSetting(colorway.replace('default', 'chosen'), self.getSetting(colorway)) data = data.replace(colorway, self.getSetting(colorway)) with open(themeFile, "w") as f: f.write(data) def createSettings(self) -> None: """ Create the config file """ # Creates a new config file in the apps directory with all the default settings. shutil.copy("Assets/config_base.json", "config.json") self.setSetting("accelerate_on_gpu", "true" if torch.cuda.is_available() else "false") #Automatically set GPU acceleration to true if available. class MISSTconfig: """ Class for handling the metadata of the current song """ def __init__(self, configPath:str) -> None: """ Initialize the config for the current song Args: configPath (str): The path to the config file """ # Check if the config file exists, if not create it # Path: MISST\MISSTsettings.py if not os.path.isfile(f"{configPath}/.misst"): self.createConfig(configPath) return def getConfig(self, configPath:str) -> str: """ Get the setting from the saved config file Args: configPath (str): The path to the config file """ # Get the setting from the saved config file # Path: MISST\MISSTsettings.py # setting: The setting to be retrieved with open(f"{configPath}/.misst", "r") as f: data = json.load(f) return data def setConfig(self, configPath:str, setting:str, value:str) -> None: """ Set the setting in the saved config file Args: configPath (str): The path to the config file setting (str): The setting to be set value (str): The value to be set """ # Set the setting in the saved config file # Path: MISST\MISSTsettings.py # setting: The setting to be set # value: The value to be set with open(f"{configPath}/.misst", "r") as f: data = json.load(f) data[setting] = value with open(f"{configPath}/.misst", "w") as f: json.dump(data, f, indent=4) def createConfig(self, configPath:str) -> None: """ Create the config file Args: configPath (str): The path to the config file """ # Creates a new config file in the apps directory with all the default settings. with open(f"{configPath}/.misst", "w") as f: json.dump({"image_url": "null", "image_raw": "null", "lyrics": "null"}, f, indent=4) f.close() ================================================ FILE: MISST/Pretrained/files.txt ================================================ # MDX Models root: mdx_final/ 0d19c1c6-0f06f20e.th 5d2d6c55-db83574e.th 7d865c68-3d5dd56b.th 7ecf8ec1-70f50cc9.th a1d90b5c-ae9d2452.th c511e2ab-fe698775.th cfa93e08-61801ae1.th e51eebcc-c1b80bdd.th 6b9c2ca1-3fd82607.th b72baf4e-8778635e.th 42e558d4-196e0e1b.th 305bc58f-18378783.th 14fc6a69-a89dd0ee.th 464b36d7-e5a9386e.th 7fd6ef75-a905dd85.th 83fc094f-4a16d450.th 1ef250f1-592467ce.th 902315c2-b39ce9c9.th 9a6b4851-03af0aa6.th fa0cb7f9-100d8bf4.th # Hybrid Transformer models root: hybrid_transformer/ 955717e8-8726e21a.th f7e0c4bc-ba3fe64a.th d12395a8-e57c48e6.th 92cfc3b6-ef3bcb9c.th 04573f0d-f3cf25b2.th 75fc33f5-1941ce65.th ================================================ FILE: MISST/Pretrained/hdemucs_mmi.yaml ================================================ models: ['75fc33f5'] segment: 44 ================================================ FILE: MISST/Pretrained/htdemucs.yaml ================================================ models: ['955717e8'] ================================================ FILE: MISST/Pretrained/htdemucs_ft.yaml ================================================ models: ['f7e0c4bc', 'd12395a8', '92cfc3b6', '04573f0d'] weights: [ [1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.], ] ================================================ FILE: MISST/Pretrained/mdx.yaml ================================================ models: ['0d19c1c6', '7ecf8ec1', 'c511e2ab', '7d865c68'] weights: [ [1., 1., 0., 0.], [0., 1., 0., 0.], [1., 0., 1., 1.], [1., 0., 1., 1.], ] segment: 44 ================================================ FILE: MISST/Pretrained/mdx_extra.yaml ================================================ models: ['e51eebcc', 'a1d90b5c', '5d2d6c55', 'cfa93e08'] segment: 44 ================================================ FILE: MISST/Pretrained/mdx_extra_q.yaml ================================================ models: ['83fc094f', '464b36d7', '14fc6a69', '7fd6ef75'] segment: 44 ================================================ FILE: MISST/Pretrained/mdx_q.yaml ================================================ models: ['6b9c2ca1', 'b72baf4e', '42e558d4', '305bc58f'] weights: [ [1., 1., 0., 0.], [0., 1., 0., 0.], [1., 0., 1., 1.], [1., 0., 1., 1.], ] segment: 44 ================================================ FILE: MISST/Pretrained/repro_mdx_a.yaml ================================================ models: ['9a6b4851', '1ef250f1', 'fa0cb7f9', '902315c2'] segment: 44 ================================================ FILE: MISST/Pretrained/repro_mdx_a_hybrid_only.yaml ================================================ models: ['fa0cb7f9', '902315c2', 'fa0cb7f9', '902315c2'] segment: 44 ================================================ FILE: MISST/Pretrained/repro_mdx_a_time_only.yaml ================================================ models: ['9a6b4851', '9a6b4851', '1ef250f1', '1ef250f1'] segment: 44 ================================================ FILE: MISST/__version__.py ================================================ __version__ = '3.1.0' ================================================ FILE: README.md ================================================
[![](./MISST/Assets/showcase/banner.png)](https://github.com/Frikallo/MISST) [![GitHub release](https://img.shields.io/github/release/frikallo/misst.svg)](https://github.com/Frikallo/MISST/releases/latest) [![Github All Releases](https://img.shields.io/github/downloads/frikallo/misst/total?color=blue)](https://github.com/Frikallo/MISST/releases/latest) [![License](https://img.shields.io/github/license/frikallo/misst?color=blue)](https://github.com/Frikallo/MISST/blob/main/LICENSE) [![Hits-of-Code](https://hitsofcode.com/github/frikallo/MISST?branch=main)](https://github.com/Frikallo/MISST/graphs/contributors)
--- ![](./MISST/Assets/showcase/showcaseimage1.png) | _`MISST` on Windows 11 with Dark mode and 'Blue' theme with 'Steve Lacy's Infrunami' playing_ ![](./MISST/Assets/showcase/showcaseimage2.png) | _`MISST` on Windows 11 with Light mode and 'Blue' theme with 'Frank Ocean's Ivy' playing_ ![](./MISST/Assets/showcase/showcaseimage3.png) | _`MISST` on Windows 11 Showcasing how versatile and personal you can be with MISST!_ ![](./MISST/Assets/showcase/showcaseimage4.png) | _`MISST` on Windows 11 Showcasing how importing audios is as easy as two clicks!_ ### Original Repository of MISST : **M**usic/**I**nstrumental **S**tem **S**eparation **T**ool. This application uses state-of-the-art [demucs](https://github.com/facebookresearch/demucs) source separation models to extract the 4 core stems from audio files (Bass, Drums, Other Instrumentals and Vocals). But it is not limited to this. MISST acts as a developped music player aswell, fit to enjoy and medal with your audio files as you see fit. MISST even comes prepared to import songs and playlists directly from your music library. This project is OpenSource, feel free to use, study and/or send pull request. ## Objectives: - [x] Import songs and playlists from your music library - [x] Easy to use UI - [x] Play your songs and playlists - [x] Extract and manipulate the 4 core stems from your audio files as they play - [x] Discord rich presence to show off your music to your friends - [x] Save your stems as audio files - [x] If imported from your music library, view lyrics and metadata just as you would in your old music player - [x] Minimal memory usage - [x] Customizable themes - [x] Additional Efects like nightcore - [x] Easy to use equalizer - [x] Preprocessing service available on both CPU and GPU - [x] Ability to change the pre-trained model used for separation - [x] Small save size, comparable to the size of the inputted audio - [ ] Docker image (WIP) - [ ] Stable on Windows, Linux and MacOS (WIP) - [ ] Proper installer/updater (Not a priority) ## Installation As of version 3.1.0, MISST is only available on windows with guaranteed compatibility. Until a later release : - if you are **not on a windows device** please refer to [Manual Installation](https://github.com/Frikallo/MISST/#manual-installation). - if you are **using conda on MacOs** device please refer to [Manual Installation - MacOS](https://github.com/CAprogs/MISST/blob/main/Installation%20Guide%20-%20MacOS.md) - Otherwise, refer to the latest [Release](https://github.com/Frikallo/MISST/releases/latest) ## Manual Installation These instructions are for those installing MISST v3.1.0 **manually** only. 1. Download & install Python 3.9 or higher (but no lower than 3.9.0) [here](https://www.python.org/downloads/) - **Note:** Ensure the *"Add Python to PATH"* box is checked 2. Download the Source code [here](https://github.com/Frikallo/MISST/releases/latest) 3. Open the command prompt from the MISST directory and run the following commands, separately - ``` $ python3 -m venv ./venv $ pip install -r requirements.txt $ python3 MISSTapp.py ``` - **Note:** Install `requirements-minimal.txt` if you don't intend to accelerate preprocessing with your GPU. From here you should be able to open and run the MISSTapp.py file - CUDA - CUDA must be installed and configured for the application to process any track with GPU acceleration. You will need to look up instruction on how to configure it on your operating system. Click [here](https://developer.nvidia.com/cuda-downloads) for nvidia's installation guide. ## Benchmark The audio processing performance was evaluated using an **NVIDIA GeForce RTX 2070 SUPER** with **8GB VRAM** and an **AMD Ryzen 3700X 8-Core Processor** on the htdemucs pretrained model. This test aimed to compare the processing time of audio on a CPU versus a GPU. Here are the results of the test: | Source | Source Length | CPU | GPU | Model | |------------------------------------------------------------------|---------------|-----------|-----------| --------- | | [Frank Ocean - Ivy](https://www.youtube.com/watch?v=AE005nZeF-A) | 4m 09.00s | 2m 22.16s | 0m 28.04s | htdemucs | ## Demo https://github.com/Frikallo/MISST/assets/88942100/15fb7ce3-9f83-4228-9ab0-f453593be632 [Open in YouTube](https://www.youtube.com/watch?v=XYJm5WW9Zvs) ## License The **MISST** code is [GPL-licensed](LICENSE). - **Please Note:** For all third-party application developers who wish to use MISST or its code, please honor the GPL license by providing credit to MISST and its developer. ## Issue Reporting Please be as detailed as possible when posting a new issue. If possible, check the "MISST.log" file in your install directory for detailed error information that can be provided to me. ## Contributing - For anyone interested in the ongoing development of **MISST**, please send us a pull request, and I will review it. - This project is 100% open-source and free for anyone to use and modify as they wish. - I only maintain the development for **MISST** and the models provided. ## More documentation to come...