Certainly! Below are the full updated scripts with detailed comments and labels for clarity.
[Python FastAPI Server: main.py]
import os
import sys
import torch
import logging
import yt_dlp
import json
import copy
import spaces
import gradio as gr
import urllib.parse
import assets.themes.loadThemes as loadThemes
from audio_separator.separator import Separator
from assets.i18n.i18n import I18nAuto
from assets.presence.discord_presence import RPCManager, track_presence
import uvicorn
from fastapi import FastAPI, UploadFile, File, Form, Request
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles # <--- Added import for static files
i18n = I18nAuto()
now_dir = os.getcwd()
sys.path.append(now_dir)
config_file = os.path.join(now_dir, "assets", "config.json")
models_file = os.path.join(now_dir, "assets", "models.json")
default_settings_file = os.path.join(now_dir, "assets", "default_settings.json")
custom_settings_file = os.path.join(now_dir, "assets", "custom_settings.json")
device = "cuda" if torch.cuda.is_available() else "cpu"
use_autocast = device == "cuda"
out_dir = "./outputs"
models_dir = "./models"
extensions = (".wav", ".flac", ".mp3", ".ogg", ".opus", ".m4a", ".aiff", ".ac3")
mdx23c_models = [
'MDX23C_D1581.ckpt',
'MDX23C-8KFFT-InstVoc_HQ.ckpt',
'MDX23C-8KFFT-InstVoc_HQ_2.ckpt',
'MDX23C-De-Reverb-aufr33-jarredou.ckpt',
'MDX23C-DrumSep-aufr33-jarredou.ckpt'
]
found_files = []
logs = []
def load_settings_from_file(filepath):
try:
with open(filepath, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception:
return None
def read_main_config():
try:
with open(config_file, "r", encoding="utf8") as f:
return json.load(f)
except Exception:
return {}
def get_initial_settings():
main_config = read_main_config()
load_custom = main_config.get('load_custom_settings', False)
settings_to_load = {}
default_settings = load_settings_from_file(default_settings_file)
if load_custom:
custom_settings = load_settings_from_file(custom_settings_file)
if custom_settings:
settings_to_load = copy.deepcopy(default_settings)
for section, params in custom_settings.items():
if section in settings_to_load:
for key, value in params.items():
settings_to_load[section][key] = value
else:
settings_to_load[section] = params
else:
settings_to_load = default_settings
else:
settings_to_load = default_settings
return settings_to_load or {}
initial_settings = get_initial_settings()
@track_presence("Performing MDXC Separationn")
@spaces.GPU(duration=60)
def mdxc_separator(audio_path, model, out_format, segment_size, override_seg_size, overlap, batch_size, norm_thresh, amp_thresh, single_stem):
model_path = os.path.join(models_dir, model)
try:
if not os.path.exists(model_path):
# Here you can add logging or notifications about model download
pass
separator = Separator(
log_level=logging.WARNING,
model_file_dir=models_dir,
output_dir=out_dir,
output_format=out_format,
use_autocast=use_autocast,
normalization_threshold=norm_thresh,
amplification_threshold=amp_thresh,
output_single_stem=single_stem,
mdxc_params={
"segment_size": segment_size,
"override_model_segment_size": override_seg_size,
"batch_size": batch_size,
"overlap": overlap,
}
)
separator.load_model(model_filename=model)
separation = separator.separate(audio_path)
stems = [os.path.join(out_dir, file_name) for file_name in separation]
if single_stem.strip():
return stems[0], None
return stems[0], stems[1]
except Exception as e:
raise RuntimeError(f"MDX23C separation failed: {e}") from e
def download_audio(url, output_dir="ytdl"):
os.makedirs(output_dir, exist_ok=True)
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'wav',
'preferredquality': '32',
}],
'outtmpl': os.path.join(output_dir, '%(title)s.%(ext)s'),
'postprocessor_args': [
'-acodec', 'pcm_f32le'
],
}
try:
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
info = ydl.extract_info(url, download=False)
video_title = info['title']
ydl.download([url])
file_path = os.path.join(output_dir, f"{video_title}.wav")
if os.path.exists(file_path):
return os.path.abspath(file_path)
else:
raise Exception("Something went wrong")
except Exception as e:
raise Exception(f"Error extracting audio with yt-dlp: {str(e)}")
app = FastAPI()
# <--- New: Serve the outputs folder as static files so client can download them by URL
app.mount("/outputs", StaticFiles(directory=out_dir), name="outputs")
@app.post("/mdx23c/separate")
async def separate_mdx23c(
request: Request, # <--- Added for base_url extraction
audio: UploadFile = File(...),
model: str = Form(...),
output_format: str = Form(...),
segment_size: int = Form(...),
override_segment_size: bool = Form(...),
overlap: int = Form(...),
batch_size: int = Form(...),
normalization_threshold: float = Form(...),
amplification_threshold: float = Form(...),
single_stem: str = Form("")
):
try:
# Save uploaded file temporarily
input_path = os.path.join("temp", audio.filename)
os.makedirs("temp", exist_ok=True)
with open(input_path, "wb") as f:
f.write(await audio.read())
stem1, stem2 = mdxc_separator(
audio_path=input_path,
model=model,
out_format=output_format,
segment_size=segment_size,
override_seg_size=override_segment_size,
overlap=overlap,
batch_size=batch_size,
norm_thresh=normalization_threshold,
amp_thresh=amplification_threshold,
single_stem=single_stem,
)
# Construct URLs to the output files (instead of local paths)
stem1_url = f"{request.base_url}outputs/{os.path.basename(stem1)}"
response = {"stem1": stem1_url}
if stem2:
stem2_url = f"{request.base_url}outputs/{os.path.basename(stem2)}"
response["stem2"] = stem2_url
return JSONResponse(content=response)
except Exception as e:
return JSONResponse(content={"error": str(e)}, status_code=500)
@app.get("/mdx23c/models")
def list_models():
return {"models": mdx23c_models}
@app.get("/mdx23c/download_audio")
def download_audio_endpoint(url: str):
try:
path = download_audio(url)
return {"audio_path": path}
except Exception as e:
return JSONResponse(content={"error": str(e)}, status_code=500)
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8123, reload=False)
[C# Client Class: SplitterClass.cs]
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
using System.Globalization;
public class SplitterClass : IDisposable
{
private readonly HttpClient _httpClient;
private readonly string _baseUrl;
/// <summary>
/// Creates an instance of SplitterClass pointing to the specified base URL
/// (e.g., "http://localhost:8123").
/// </summary>
/// <param name="baseUrl">Base URL of the FastAPI server</param>
public SplitterClass(string baseUrl = "http://localhost:8123")
{
_baseUrl = baseUrl.TrimEnd('/');
_httpClient = new HttpClient();
// Set the timeout to infinite to prevent timeouts
_httpClient.Timeout = System.Threading.Timeout.InfiniteTimeSpan;
}
/// <summary>
/// Gets the list of available MDX23C models from the server.
/// </summary>
/// <returns>List of model filenames</returns>
public async Task<List<string>> ListModelsAsync()
{
var response = await _httpClient.GetAsync($"{_baseUrl}/mdx23c/models");
response.EnsureSuccessStatusCode();
string json = await response.Content.ReadAsStringAsync();
using var jsonDoc = JsonDocument.Parse(json);
if (jsonDoc.RootElement.TryGetProperty("models", out var modelsElement))
{
var models = new List<string>();
foreach (var model in modelsElement.EnumerateArray())
{
models.Add(model.GetString());
}
return models;
}
else
{
throw new Exception("Invalid response format (missing 'models')");
}
}
/// <summary>
/// Downloads audio from a URL via the server's /mdx23c/download_audio endpoint.
/// </summary>
/// <param name="url">The URL of the audio/video to download</param>
/// <returns>The absolute path of the downloaded audio file on the server</returns>
public async Task<string> DownloadAudioAsync(string url)
{
var response = await _httpClient.GetAsync($"{_baseUrl}/mdx23c/download_audio?url={Uri.EscapeDataString(url)}");
var content = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
try
{
using var jsonDoc = JsonDocument.Parse(content);
if (jsonDoc.RootElement.TryGetProperty("error", out var errorElement))
throw new Exception(errorElement.GetString());
}
catch
{
response.EnsureSuccessStatusCode();
}
}
using var doc = JsonDocument.Parse(content);
if (doc.RootElement.TryGetProperty("audio_path", out var audioPathElement))
{
return audioPathElement.GetString();
}
else
{
throw new Exception("Invalid response format (missing 'audio_path')");
}
}
/// <summary>
/// Calls the /mdx23c/separate endpoint to perform separation.
/// Returns URLs to the separated stem files on the server.
/// </summary>
/// <param name="audioFilePath">Local path to the audio file to upload</param>
/// <param name="model">Model filename (one of the models from ListModelsAsync)</param>
/// <param name="outputFormat">Output format (e.g., "wav")</param>
/// <param name="segmentSize">Segment size (int)</param>
/// <param name="overrideSegmentSize">Whether to override segment size (bool)</param>
/// <param name="overlap">Overlap (int)</param>
/// <param name="batchSize">Batch size (int)</param>
/// <param name="normalizationThreshold">Normalization threshold (float)</param>
/// <param name="amplificationThreshold">Amplification threshold (float)</param>
/// <param name="singleStem">Single stem string (optional)</param>
/// <returns>Tuple containing one or two stem URLs returned from server</returns>
public async Task<(string Stem1Url, string Stem2Url)> SeparateMdx23cAsync(
string audioFilePath,
string model,
string outputFormat,
int segmentSize,
bool overrideSegmentSize,
int overlap,
int batchSize,
float normalizationThreshold,
float amplificationThreshold,
string singleStem = "")
{
if (!File.Exists(audioFilePath))
throw new FileNotFoundException("Audio file not found", audioFilePath);
using var multipartContent = new MultipartFormDataContent();
// Add file content
var fileContent = new ByteArrayContent(await File.ReadAllBytesAsync(audioFilePath));
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
multipartContent.Add(fileContent, "audio", Path.GetFileName(audioFilePath));
// Add form data fields exactly as FastAPI expects (match parameter names)
multipartContent.Add(new StringContent(model), "model");
multipartContent.Add(new StringContent(outputFormat), "output_format");
multipartContent.Add(new StringContent(segmentSize.ToString()), "segment_size");
multipartContent.Add(new StringContent(overrideSegmentSize.ToString().ToLower()), "override_segment_size");
multipartContent.Add(new StringContent(overlap.ToString()), "overlap");
multipartContent.Add(new StringContent(batchSize.ToString()), "batch_size");
multipartContent.Add(new StringContent(normalizationThreshold.ToString(CultureInfo.InvariantCulture)), "normalization_threshold");
multipartContent.Add(new StringContent(amplificationThreshold.ToString(CultureInfo.InvariantCulture)), "amplification_threshold");
// single_stem parameter - can be empty string
multipartContent.Add(new StringContent(singleStem), "single_stem");
var response = await _httpClient.PostAsync($"{_baseUrl}/mdx23c/separate", multipartContent);
var content = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
try
{
using var errorDoc = JsonDocument.Parse(content);
if (errorDoc.RootElement.TryGetProperty("error", out var errorEl))
throw new Exception(errorEl.GetString());
}
catch
{
response.EnsureSuccessStatusCode();
}
}
using var jsonDoc = JsonDocument.Parse(content);
string stem1Url = null, stem2Url = null;
if (jsonDoc.RootElement.TryGetProperty("stem1", out var stem1El))
stem1Url = stem1El.GetString();
if (jsonDoc.RootElement.TryGetProperty("stem2", out var stem2El))
stem2Url = stem2El.GetString();
return (stem1Url, stem2Url);
}
/// <summary>
/// Downloads a remote file from a URL and saves it locally.
/// </summary>
/// <param name="url">Remote file URL</param>
/// <param name="localPath">Local filesystem path to save file</param>
public async Task DownloadStemAsync(string url, string localPath)
{
using var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
await using var fs = new FileStream(localPath, FileMode.Create, FileAccess.Write, FileShare.None);
await response.Content.CopyToAsync(fs);
}
public void Dispose()
{
_httpClient.Dispose();
}
}
Summary:
If you want me to write a complete small console demo of the client usage including the download, just ask!