I have a void that boots one of my servers now I need a void named BootAceStep that takes a predefined string named AceStepFolder path and a bool named WSL if WSL is checked then set up the command running for wsl otherwise set it up for windows.
'extra example for wsl this is how you can make my acestepbooter'
string command = "cd ~/ACE-Step && conda activate ace_step && python infer-api-unity.py";
'extra example for windows this is how you can make my acestepbooter'
string command = "cd C:\AI\ACE-Step && conda activate ace_step && python infer-api-unity.py";
'This is the void that boots my other server for example'
private void BootSeedVC()
{
if (ServerStatus)
{
BasicTTS("Seed VC server is already running.");
return;
}
code
BasicTTS("Seed VC Booting");
string command = "cd ~/seed-vc && conda activate seeder && python3 singserver.py --gpu 0 --host 0.0.0.0 --port 6576";
var psi = new ProcessStartInfo
{
FileName = "wsl.exe",
Arguments = $"-e bash -li -c \"{command}\"",
UseShellExecute = false,
CreateNoWindow = false,
RedirectStandardOutput = false,
RedirectStandardError = false,
RedirectStandardInput = false
};
try
{
// Start the process and keep the reference
seedVcProcess = Process.Start(psi);
if (seedVcProcess == null)
{
BasicTTS("Failed to start process.");
return;
}
// Optional: handle process exit to cleanup
seedVcProcess.EnableRaisingEvents = true;
seedVcProcess.Exited += (s, e) =>
{
seedVcProcess.Dispose();
seedVcProcess = null;
// If you update UI here, invoke on UI thread:
this.Invoke((Action)(() =>
{
BasicTTS("Seed VC server has stopped.");
// Update UI elements as needed
}));
};
BasicTTS("Seed VC server started successfully.");
}
catch (Exception ex)
{
BasicTTS("Failed to launch WSL command: " + ex.Message);
seedVcProcess = null;
}
}
Assistant
Certainly! Here is a void called BootAceStep based on your requirements. It takes a folder path AceStepFolder and a boolean WSL. If WSL is true, it sets the command up for WSL usage, otherwise it sets it up for Windows.
csharp
User
error on powershell side At line:1 char:21
cd C:\AI\ACE-Step && conda activate ace_step && python infer-api-un ...
code
~~
The token '&&' is not a valid statement separator in this version.
At line:1 char:48
cd C:\AI\ACE-Step && conda activate ace_step && python infer-api-un ...
code
~~
The token '&&' is not a valid statement separator in this version.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : InvalidEndOfLine
Assistant
The error you're seeing comes from PowerShell interpreting && as an invalid token because && is a cmd.exe operator, but PowerShell does not natively support && as a command separator.
How to fix
In PowerShell, conditional or sequential command chaining works differently:
To run commands sequentially, just separate them by ;
To conditionally run the next command upon success, you can use if or try-catch statements, but for simple sequential commands, ; works.
Updated Windows command setup for PowerShell:
Replace the && with ; in the command so PowerShell can execute it correctly.
Using ; instead of && means commands will execute sequentially regardless of prior success/failure.
If you want conditional execution (only continue if prior succeeded), you'd need a more complex PowerShell script, e.g.:
powershell
cd C:\AI\ACE-Step; if ($?) { conda activate ace_step; if ($?) { python infer-api-unity.py } }
But usually sequential ; is sufficient.
If you want, I can produce a version of BootAceStep that generates the PowerShell commands using ; separators and handles paths correctly. Let me know.
User
provide entire
Assistant
Certainly! Here's the complete updated BootAceStep method incorporating the fix — replacing && with ; in the Windows PowerShell command, so it won't give you that error. It handles both WSL and Windows cases properly:
csharp
private Process acestepProcess = null;
private void BootAceStep(string AceStepFolder, bool WSL)
{
// Check if the server is already running
if (acestepProcess != null && !acestepProcess.HasExited)
{
BasicTTS("ACE-Step server is already running.");
return;
}
BasicTTS("ACE-Step Booting");
string command;
ProcessStartInfo psi;
if (WSL)
{
// For WSL, assume AceStepFolder is a Linux style path or correctly formed
command = $"cd {AceStepFolder} && conda activate ace_step && python infer-api-unity.py";
psi = new ProcessStartInfo
{
FileName = "wsl.exe",
Arguments = $"-e bash -li -c \"{command}\"",
UseShellExecute = false,
CreateNoWindow = false,
RedirectStandardOutput = false,
RedirectStandardError = false,
RedirectStandardInput = false
};
}
else
{
// For Windows + PowerShell, change && to ; because PowerShell doesn't support &&
// Also properly escape backslashes (double) in the path string
string winPathEscaped = AceStepFolder.Replace("\\", "\\\\");
command = $"cd {winPathEscaped}; conda activate ace_step; python infer-api-unity.py";
psi = new ProcessStartInfo
{
FileName = "powershell.exe",
Arguments = $"-NoExit -Command \"{command}\"",
UseShellExecute = false,
CreateNoWindow = false,
RedirectStandardOutput = false,
RedirectStandardError = false,
RedirectStandardInput = false
};
}
try
{
acestepProcess = Process.Start(psi);
if (acestepProcess == null)
{
BasicTTS("Failed to start process.");
return;
}
acestepProcess.EnableRaisingEvents = true;
acestepProcess.Exited += (s, e) =>
{
acestepProcess.Dispose();
acestepProcess = null;
this.Invoke((Action)(() =>
{
BasicTTS("ACE-Step server has stopped.");
// Update UI elements if needed
}));
};
BasicTTS("ACE-Step server started successfully.");
}
catch (Exception ex)
{
BasicTTS("Failed to launch ACE-Step command: " + ex.Message);
acestepProcess = null;
}
}
User
heres my uvicorn server how can I run the command with a custom port?
import os
Must be set before other imports that load OpenMP runtime
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import List, Optional
import uuid
from acestep.pipeline_ace_step import ACEStepPipeline
import asyncio
from contextlib import asynccontextmanager
async def run_generation_in_thread(pipeline, params, output_path):
loop = asyncio.get_running_loop()
# Run the blocking pipeline call in the thread pool
await loop.run_in_executor(None, lambda: pipeline(*params, save_path=output_path))
@asynccontextmanager
async def lifespan(app: FastAPI):
global preloaded_pipeline, pipeline_lock
cfg = PRELOAD_CONFIG
preloaded_pipeline = initialize_pipeline(
cfg["checkpoint_path"],
cfg["bf16"],
cfg["torch_compile"],
cfg["device_id"],
)
pipeline_lock = asyncio.Lock()
print("Preloaded model pipeline at startup.")
yield
preloaded_pipeline = None
pipeline_lock = None
print("Pipeline cleaned up on shutdown.")
Mount the current working directory (where audio files are saved) to /files route
Assistant
To run your existing uvicorn server on a custom port, you just need to pass your desired port number as the port argument to uvicorn.run().
How to run on a custom port:
1) Modify the bottom if __name__ == "__main__": block to accept a port parameter or use a variable.
Example to hardcode a different port (say 9000):
python
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=9000)
2) More flexibly, allow passing the port via an environment variable, a command line argument, or a parameter.
Using an environment variable:
python
if __name__ == "__main__":
import uvicorn
import os
port = int(os.getenv("ACEStep_PORT", 8000)) # default to 8000 if not set
uvicorn.run(app, host="0.0.0.0", port=port)
Now you can launch with, e.g.:
bash
ACEStep_PORT=9000 python yourscript.py
3) If you want to run the uvicorn command externally from command line instead of inside script, run:
If you want to integrate custom port launching from your C# method (like your previous booters):
You can append --port 1234 to the Python command:
bash
python infer-api-unity.py --port 9000
However, your Python script right now doesn’t parse command line args for port, so you'd need to add that support. Alternatively, modify your Python script to read from env or command line arg for port, and pass it similarly.
For example, parsing port from command line arguments:
Add near imports:
python
import sys
Then change the uvicorn.run() in main:
python
User
fix my entire script and return it pls
Assistant
Certainly! I've updated your entire script to support running the server on a custom port passed via command line argument --port PORTNUMBER. The default port remains 8000 if no port is specified.
Main changes:
Added import sys
Added simple parsing for --port in sys.argv
Used the parsed port when calling uvicorn.run()
Here is the full fixed script:
python
User
Microsoft Windows [Version 10.0.22631.5335]
(c) Microsoft Corporation. All rights reserved.
C:\AI\UVR5_UI>conda activate uvr
(uvr) C:\AI\UVR5_UI>python app.py
Discord is not running. Rich Presence will be disabled.
ERROR: Error loading ASGI app. Could not import module "main".
(uvr) C:\AI\UVR5_UI>
Assistant
The error message:
code
ERROR: Error loading ASGI app. Could not import module "main".
means that uvicorn or whatever ASGI server you are running is trying to import the Python module named main but it cannot find it or the module main.py has errors.
Why this happens
When running uvicorn main:app or similar, main here refers to the Python script/module named main.py.
If your script is named something else (like app.py), or the app variable is named differently, uvicorn won't find it.
Also, if your app file or any dependent code raises an ImportError or syntax error, it cannot be loaded.
What you can do to fix this:
Check your Python file name:
If your FastAPI app is in app.py, then you should start uvicorn with:
bash
uvicorn app:app --reload
Here, app:app means: look for app.py file and inside it, start the ASGI callable named app (the FastAPI instance).
If you are running python app.py:
That should work since your script is run directly, but remember if you want to run with uvicorn server, run the uvicorn command or inside the script uvicorn.run(...).
Make sure your file has no errors
Run just:
bash
python app.py
If there are import errors, syntax errors, or missing modules, they will show up.
If your script name is app.py and the app instance is app:
If you provide your full command that triggered the error, I can help more precisely!
User
write me a BootSplitter void for c# for this events
C:\AI\UVR5_UI>conda activate uvr
(uvr) C:\AI\UVR5_UI>python app.py
Discord is not running. Rich Presence will be disabled.
ERROR: Error loading ASGI app. Could not import module "main".
Sure! Here's a C# BootSplitter void that will activate your conda environment, then run the uvicorn server with your specified parameters, keeping the console window open (i.e., not disabling or hiding the window). It also captures process exit event to notify you.
csharp
using System;
using System.Diagnostics;
using System.Windows.Forms; // For this.Invoke, replace or remove if not in WinForms
private Process splitProcess = null;
private void BootSplitter()
{
// If already running, prevent duplicate start
if (splitProcess != null && !splitProcess.HasExited)
{
BasicTTS("Splitter server is already running.");
return;
}
BasicTTS("Starting Splitter server...");
// Prepare your command - since you want to activate conda and then run python or uvicorn,
// Windows batch doesn't support multiple separate commands in ProcessStartInfo directly,
// so run cmd.exe with /k (to keep the window open) and pass a command string.
// Note: /k keeps window open; /c would close it after running.
// The command string to run:
// conda activate uvr && uvicorn app:app --host 0.0.0.0 --port 8123 --reload
string commands = "conda activate uvr && uvicorn app:app --host 0.0.0.0 --port 8123 --reload";
var psi = new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/k \"{commands}\"",
WorkingDirectory = @"C:\AI\UVR5_UI", // Set your working directory here
UseShellExecute = false,
CreateNoWindow = false,
RedirectStandardOutput = false,
RedirectStandardError = false,
RedirectStandardInput = false
};
try
{
splitProcess = Process.Start(psi);
if (splitProcess == null)
{
BasicTTS("Failed to start splitter server process.");
return;
}
splitProcess.EnableRaisingEvents = true;
splitProcess.Exited += (s, e) =>
{
splitProcess.Dispose();
splitProcess = null;
// If this is a UI thread (such as WinForms), invoke on UI thread:
this.Invoke((Action)(() =>
{
BasicTTS("Splitter server has stopped.");
// Update UI elements if needed here
}));
};
BasicTTS("Splitter server started successfully.");
}
catch (Exception ex)
{
BasicTTS("Failed to launch splitter server: " + ex.Message);
splitProcess = null;
}
}
Not yet included in a published release.
private Process acestepProcess = null;
private void BootAceStep(string AceStepFolder, bool WSL)
{
// Check if the server is already running (adjust as needed)
if (acestepProcess != null && !acestepProcess.HasExited)
{
BasicTTS("ACE-Step server is already running.");
return;
}
BasicTTS("ACE-Step Booting");
string command;
ProcessStartInfo psi;
if (WSL)
{
// For WSL, we assume this folder path is Linux style or use ~ shortcut, so just use the passed path
// But to be safe, if user passes windows style path, you might want to convert it:
// For simplicity, let's trust AceStepFolder is properly formatted linux style path if WSL == true
command = $"cd {AceStepFolder} && conda activate ace_step && python infer-api-unity.py";
psi = new ProcessStartInfo
{
FileName = "wsl.exe",
Arguments = $"-e bash -li -c \"{command}\"",
UseShellExecute = false,
CreateNoWindow = false,
RedirectStandardOutput = false,
RedirectStandardError = false,
RedirectStandardInput = false
};
}
else
{
// For Windows, we need to escape backslashes in the path properly:
// If the user passed with backslashes, we need to escape them for the command string.
// Or convert to double backslashes.
// Also, Windows command prompt uses `&&` just like bash, so this should work.
// Make sure backslashes are escaped if needed
string winPathEscaped = AceStepFolder.Replace("\\", "\\\\");
command = $"cd {winPathEscaped} && conda activate ace_step && python infer-api-unity.py";
// On Windows without WSL, you can start using cmd.exe or powershell
// Let's use powershell for this example
psi = new ProcessStartInfo
{
FileName = "powershell.exe",
Arguments = $"-NoExit -Command \"{command}\"",
UseShellExecute = false,
CreateNoWindow = false,
RedirectStandardOutput = false,
RedirectStandardError = false,
RedirectStandardInput = false
};
}
try
{
acestepProcess = Process.Start(psi);
if (acestepProcess == null)
{
BasicTTS("Failed to start process.");
return;
}
acestepProcess.EnableRaisingEvents = true;
acestepProcess.Exited += (s, e) =>
{
acestepProcess.Dispose();
acestepProcess = null;
this.Invoke((Action)(() =>
{
BasicTTS("ACE-Step server has stopped.");
// Update UI elements if needed
}));
};
BasicTTS("ACE-Step server started successfully.");
}
catch (Exception ex)
{
BasicTTS("Failed to launch ACE-Step command: " + ex.Message);
acestepProcess = null;
}
}
Notes:
You should verify that AceStepFolder is a valid folder format depending on whether you use WSL or Windows.
If the folder path you provide for WSL is Windows-style, you'll want to convert it to WSL path (e.g., convert C:\AI\ACE-Step to /mnt/c/AI/ACE-Step), but I assumed you will give the path correctly.
In Windows, I used PowerShell to run the command with -NoExit: this keeps the window open in case you want to see output.
If you want to hide the window you can set CreateNoWindow = true and tweak options accordingly.
BasicTTS is assumed to be your existing method for text-to-speech or logging feedback.
Let me know if you'd like me to handle the path conversions or improve on this!
Summary of changes:
In the Windows branch, the command uses ; to separate commands inside PowerShell.
Backslashes in the Windows folder path are doubled to avoid escape issues.
WSL command remains as it was because && is valid in bash.
Error handling and process life cycle handling remains consistent.
Let me know if you'd like me to help with:
Path conversion between Windows and WSL format
Running commands with cmd.exe instead of PowerShell
@app.post("/generate", response_model=ACEStepOutput)
async def generate_audio(input_data: ACEStepInput):
if preloaded_pipeline is None or pipeline_lock is None:
raise HTTPException(status_code=503, detail="Model pipeline is not ready")
code
try:
params = (
input_data.audio_duration,
input_data.prompt,
input_data.lyrics,
input_data.infer_step,
input_data.guidance_scale,
input_data.scheduler_type,
input_data.cfg_type,
input_data.omega_scale,
", ".join(map(str, input_data.actual_seeds)),
input_data.guidance_interval,
input_data.guidance_interval_decay,
input_data.min_guidance_scale,
input_data.use_erg_tag,
input_data.use_erg_lyric,
input_data.use_erg_diffusion,
", ".join(map(str, input_data.oss_steps)),
input_data.guidance_scale_text,
input_data.guidance_scale_lyric,
)
# Generate a unique filename & full output path
filename = f"output_{uuid.uuid4().hex}.wav"
output_path = os.path.join(os.getcwd(), filename)
async with pipeline_lock:
await run_generation_in_thread(preloaded_pipeline, params, output_path)
# Return the URL path to download the file via /files route
return ACEStepOutput(
status="success",
output_path=f"files/{filename}", # <-- IMPORTANT: Add the /files prefix here!
message="Audio generated successfully",
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error generating audio: {str(e)}")
if name == "main":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
if __name__ == "__main__":
import uvicorn
port = 8000 # default port
# simple parse for --port ARG from sys.argv
if "--port" in sys.argv:
try:
port_idx = sys.argv.index("--port")
if port_idx + 1 < len(sys.argv):
port = int(sys.argv[port_idx+1])
except Exception:
pass
uvicorn.run(app, host="0.0.0.0", port=port)
Now you can run:
bash
python infer-api-unity.py --port 9000
Summary:
To configure custom port, set the port parameter in uvicorn.run().
You can hardcode, use environment variable, or parse command line arguments.
If running externally with uvicorn CLI, just pass --port.
To run from another program, like your C# code, either include the port in the command line args, or export an environment variable before starting.
If you want, I can help you modify the BootAceStep method to pass a custom port to your infer-api-unity.py script and update your script to parse it. Just let me know!
import os
import sys # Added for command line argument parsing
# Must be set before other imports that load OpenMP runtime
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from typing import List, Optional
import uuid
from acestep.pipeline_ace_step import ACEStepPipeline
import asyncio
from contextlib import asynccontextmanager
# Globals for pipeline & lock
preloaded_pipeline: Optional[ACEStepPipeline] = None
pipeline_lock: Optional[asyncio.Lock] = None
PRELOAD_CONFIG = {
"checkpoint_path": "",
"bf16": True,
"torch_compile": False,
"device_id": 0,
}
class ACEStepInput(BaseModel):
audio_duration: float
prompt: str
lyrics: str
infer_step: int
guidance_scale: float
scheduler_type: str
cfg_type: str
omega_scale: float
actual_seeds: List[int]
guidance_interval: float
guidance_interval_decay: float
min_guidance_scale: float
use_erg_tag: bool
use_erg_lyric: bool
use_erg_diffusion: bool
oss_steps: List[int]
guidance_scale_text: float = 0.0
guidance_scale_lyric: float = 0.0
class ACEStepOutput(BaseModel):
status: str
output_path: Optional[str]
message: str
def initialize_pipeline(
checkpoint_path: str,
bf16: bool,
torch_compile: bool,
device_id: int,
) -> ACEStepPipeline:
current_cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES")
if current_cuda_visible_devices != str(device_id):
os.environ["CUDA_VISIBLE_DEVICES"] = str(device_id)
dtype = "bfloat16" if bf16 else "float32"
pipeline = ACEStepPipeline(
checkpoint_dir=checkpoint_path,
dtype=dtype,
torch_compile=torch_compile,
)
return pipeline
async def run_generation_in_thread(pipeline, params, output_path):
loop = asyncio.get_running_loop()
# Run the blocking pipeline call in the thread pool
await loop.run_in_executor(None, lambda: pipeline(*params, save_path=output_path))
@asynccontextmanager
async def lifespan(app: FastAPI):
global preloaded_pipeline, pipeline_lock
cfg = PRELOAD_CONFIG
preloaded_pipeline = initialize_pipeline(
cfg["checkpoint_path"],
cfg["bf16"],
cfg["torch_compile"],
cfg["device_id"],
)
pipeline_lock = asyncio.Lock()
print("Preloaded model pipeline at startup.")
yield
preloaded_pipeline = None
pipeline_lock = None
print("Pipeline cleaned up on shutdown.")
app = FastAPI(title="ACEStep Pipeline API", lifespan=lifespan)
# Mount the current working directory (where audio files are saved) to /files route
app.mount("/files", StaticFiles(directory=os.getcwd()), name="files")
@app.post("/generate", response_model=ACEStepOutput)
async def generate_audio(input_data: ACEStepInput):
if preloaded_pipeline is None or pipeline_lock is None:
raise HTTPException(status_code=503, detail="Model pipeline is not ready")
try:
params = (
input_data.audio_duration,
input_data.prompt,
input_data.lyrics,
input_data.infer_step,
input_data.guidance_scale,
input_data.scheduler_type,
input_data.cfg_type,
input_data.omega_scale,
", ".join(map(str, input_data.actual_seeds)),
input_data.guidance_interval,
input_data.guidance_interval_decay,
input_data.min_guidance_scale,
input_data.use_erg_tag,
input_data.use_erg_lyric,
input_data.use_erg_diffusion,
", ".join(map(str, input_data.oss_steps)),
input_data.guidance_scale_text,
input_data.guidance_scale_lyric,
)
# Generate a unique filename & full output path
filename = f"output_{uuid.uuid4().hex}.wav"
output_path = os.path.join(os.getcwd(), filename)
async with pipeline_lock:
await run_generation_in_thread(preloaded_pipeline, params, output_path)
# Return the URL path to download the file via /files route
return ACEStepOutput(
status="success",
output_path=f"files/{filename}", # <-- IMPORTANT: Add the /files prefix here!
message="Audio generated successfully",
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error generating audio: {str(e)}")
@app.get("/health")
async def health_check():
return {"status": "healthy"}
if __name__ == "__main__":
import uvicorn
port = 8000 # default port if none specified
# Parse --port from command line arguments if provided
if "--port" in sys.argv:
try:
idx = sys.argv.index("--port")
if idx + 1 < len(sys.argv):
port = int(sys.argv[idx + 1])
except Exception:
print("Invalid port argument passed; falling back to default port 8000")
uvicorn.run(app, host="0.0.0.0", port=port)
How to run with a custom port:
bash
python your_script_name.py --port 9000
This will launch your FastAPI server on port 9000.
If no --port is provided, it defaults to port 8000.
Let me know if you want me to also help update your C# launcher BootAceStep method so it passes a port argument consistently!
Notes:
The above uses cmd.exe /k with a command string: first activates your conda environment (uvr), then immediately runs the uvicorn server command.
Make sure conda is in the system's PATH or that conda activate uvr works correctly in your environment.
The window will stay open after starting the server, so you can see any console output or errors.
Adjust the WorkingDirectory to your actual project directory — here I used C:\AI\UVR5_UI.
BasicTTS is your existing function to read out or log status.
If you are not inside a UI thread context that supports this.Invoke, replace that line with just a direct call to BasicTTS or appropriate synchronization.
Let me know if you want me to help converting this for a different context (WPF, console app etc.) or to capture output streams!