Checking environment...
C:\Meow\seed-vc\launcher.py:8: DeprecationWarning: sipPyTypeDict() is deprecated, the extension module should use sipPyTypeDictRef() instead
class LauncherWindow(QMainWindow):
File "C:\Meow\seed-vc\app_svc.py", line 52
@app.post("/voice_conversion/")
^
IndentationError: expected an indented block after function definition on line 47
Assistant
User
IndentationError: expected an indented block after function definition on line 47
if name == "main":
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint-path", type=str, help="Path to the checkpoint file", default=None)
parser.add_argument("--config-path", type=str, help="Path to the config file", default=None)
parser.add_argument("--share", type=str2bool, nargs="?", const=True, default=False, help="Whether to share the app")
parser.add_argument("--fp16", type=str2bool, nargs="?", const=True, help="Whether to use fp16", default=True)
parser.add_argument("--gpu", type=int, help="Which GPU id to use", default=0)
args = parser.parse_args()
cuda_target = f"cuda:{args.gpu}" if args.gpu else "cuda"
device = torch.device(cuda_target if torch.cuda.is_available() else "cpu")
main(args)
To convert the Gradio application into a Uvicorn HTTP server, we will remove the Gradio-specific code and replace it with a FastAPI server. FastAPI is a modern framework for building APIs with Python, and it is well-suited for this task because it can easily handle audio file uploads and streaming responses.
Here's the restructured code to achieve this:
import os
import torch
import torchaudio
import librosa
from fastapi import FastAPI, UploadFile, File
from fastapi.responses import StreamingResponse, JSONResponse
import numpy as np
from pydub import AudioSegment
from pathlib import Path
import yaml
from modules.commons import build_model, load_checkpoint, recursive_munch, str2bool
from hf_utils import load_custom_model_from_hf
# Initialize FastAPI
app = FastAPI()
# Load model and configuration globally
fp16 = False
device = None
def load_models(args):
global sr, hop_length, fp16
fp16 = args.fp16
ckpt_root = Path(__file__).parent / "checkpoints"
print(f"Using device: {device}")
print(f"Using fp16: {fp16}")
# Load your model checkpoint and configuration here, similar to above
# (Omitted for brevity, should include models and setup code)
return (
model,
semantic_fn,
vocoder_fn,
campplus_model,
to_mel,
mel_fn_args,
f0_fn,
)
model_f0, semantic_fn, vocoder_fn, campplus_model, to_mel_f0, mel_fn_args = None, None, None, None, None, None
f0_fn = None
sr, hop_length = None, None
@torch.no_grad()
@torch.inference_mode()
def voice_conversion(source, target, diffusion_steps, length_adjust, inference_cfg_rate, auto_f0_adjust, pitch_shift):
# Implement the actual voice conversion function as described above
# (Omitted for brevity, should include processing logic similar to the original function)
@app.post("/voice_conversion/")
async def convert_voice(
source: UploadFile = File(...),
target: UploadFile = File(...),
diffusion_steps: int = 10,
length_adjust: float = 1.0,
inference_cfg_rate: float = 0.7,
auto_f0_adjust: bool = True,
pitch_shift: int = 0
):
# Handle uploaded files
source_audio = f"temp/{source.filename}"
target_audio = f"temp/{target.filename}"
with open(source_audio, "wb") as buffer:
buffer.write(await source.read())
with open(target_audio, "wb") as buffer:
buffer.write(await target.read())
# Call the voice conversion function
audio_bytes, full_output = voice_conversion(
source_audio,
target_audio,
diffusion_steps,
length_adjust,
inference_cfg_rate,
auto_f0_adjust,
pitch_shift
)
# Create a StreamingResponse for the audio output
return StreamingResponse(iter([audio_bytes]), media_type="audio/mp3")
def main(args):
global model_f0, semantic_fn, vocoder_fn, campplus_model, to_mel_f0, mel_fn_args, f0_fn
model_f0, semantic_fn, vocoder_fn, campplus_model, to_mel_f0, mel_fn_args, f0_fn = load_models(args)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint-path", type=str, help="Path to the checkpoint file", default=None)
parser.add_argument("--config-path", type=str, help="Path to the config file", default=None)
parser.add_argument("--fp16", type=str2bool, nargs="?", const=True, help="Whether to use fp16", default=True)
parser.add_argument("--gpu", type=int, help="Which GPU id to use", default=0)
args = parser.parse_args()
cuda_target = f"cuda:{args.gpu}" if args.gpu else "cuda"
device = torch.device(cuda_target if torch.cuda.is_available() else "cpu")
main(args)
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Key Changes:
FastAPI Integration: We replaced the Gradio interface with FastAPI. The /voice_conversion/ endpoint takes the audio files and parameters as input.
File Handling: Uploaded files are saved temporarily, and the voice_conversion function works with those files.
Streaming Response: The result of the conversion is sent as a streaming response.
Starting the Server: Uvicorn runs the FastAPI app.
Note:
This code snippet omits some parts for brevity (like detailed model loading and the voice_conversion function). You will need to re-integrate that logic as indicated in the original Gradio app.
Ensure that you have the necessary error handling and input validation according to your requirements.
To run this server, you will need FastAPI, Uvicorn, and any other dependencies your model has, installed in your Python environment.
The IndentationError indicates that the function convert_voice is defined but lacks the necessary indentation for its body. This means that the code that should form part of that function is either not indented properly or is missing altogether.
Make sure all the code inside the function is indented correctly. Here's a corrected version of the convert_voice function with proper indentation that includes savable temporary files for source and target audios along with the code structure:
import os
import torch
import torchaudio
from fastapi import FastAPI, UploadFile, File
from fastapi.responses import StreamingResponse
import numpy as np
from pydub import AudioSegment
from pathlib import Path
# Other necessary imports...
app = FastAPI()
# Load model and configuration globally
fp16 = False
device = None
def load_models(args):
global sr, hop_length, fp16
fp16 = args.fp16
ckpt_root = Path(__file__).parent / "checkpoints"
print(f"Using device: {device}")
print(f"Using fp16: {fp16}")
# Load your model checkpoint and configuration here
# (This section needs to contain the relevant model loading code)
return (
model,
semantic_fn,
vocoder_fn,
campplus_model,
to_mel,
mel_fn_args,
f0_fn,
)
model_f0, semantic_fn, vocoder_fn, campplus_model, to_mel_f0, mel_fn_args = None, None, None, None, None, None
f0_fn = None
sr, hop_length = None, None
@torch.no_grad()
@torch.inference_mode()
def voice_conversion(source, target, diffusion_steps, length_adjust, inference_cfg_rate, auto_f0_adjust, pitch_shift):
# Implement the actual voice conversion function as described above
# (Omitted for brevity; should include processing logic similar to the original function)
@app.post("/voice_conversion/")
async def convert_voice(
source: UploadFile = File(...),
target: UploadFile = File(...),
diffusion_steps: int = 10,
length_adjust: float = 1.0,
inference_cfg_rate: float = 0.7,
auto_f0_adjust: bool = True,
pitch_shift: int = 0
):
# Handle uploaded files
source_audio = f"temp/{source.filename}"
target_audio = f"temp/{target.filename}"
os.makedirs("temp", exist_ok=True) # Create temp directory if it doesn't exist
with open(source_audio, "wb") as buffer:
buffer.write(await source.read())
with open(target_audio, "wb") as buffer:
buffer.write(await target.read())
# Call the voice conversion function
audio_bytes, full_output = voice_conversion(
source_audio,
target_audio,
diffusion_steps,
length_adjust,
inference_cfg_rate,
auto_f0_adjust,
pitch_shift
)
# Return the audio as StreamingResponse
return StreamingResponse(iter([audio_bytes]), media_type="audio/mp3")
def main(args):
global model_f0, semantic_fn, vocoder_fn, campplus_model, to_mel_f0, mel_fn_args, f0_fn
model_f0, semantic_fn, vocoder_fn, campplus_model, to_mel_f0, mel_fn_args, f0_fn = load_models(args)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint-path", type=str, help="Path to the checkpoint file", default=None)
parser.add_argument("--config-path", type=str, help="Path to the config file", default=None)
parser.add_argument("--fp16", type=str2bool, nargs="?", const=True, help="Whether to use fp16", default=True)
parser.add_argument("--gpu", type=int, help="Which GPU id to use", default=0)
args = parser.parse_args()
cuda_target = f"cuda:{args.gpu}" if args.gpu else "cuda"
device = torch.device(cuda_target if torch.cuda.is_available() else "cpu")
main(args)
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Key Points:
Indentation: Make sure the code inside the convert_voice function is properly indented.
Temporary Directories: The os.makedirs("temp", exist_ok=True) line ensures that the directory for temporary files exists before using it.
Loading Models: Make sure the placeholder for loading models with your actual model configuration is correctly filled in where indicated.
Cleanup: If intended, consider adding cleanup logic to remove temporary files after they are processed, as temporary files may accumulate with successive requests.
This code structure should resolve the IndentationError you encountered. If there are still issues, make sure to check other parts of the code for similar indentation problems.
The IndentationError you're encountering indicates that there is a missing indented block of code after the function definition. Specifically, it means the function voice_conversion is defined but does not have any code inside it.
To help resolve this, I'll provide a code structure that ensures all functions are properly defined and include placeholder comments for the functionality that you probably want to implement. Here’s a corrected and complete structure using FastAPI, ensuring all functions are properly defined with placeholder logic for the voice conversion process.
Corrected Code Structure
import os
import torch
import torchaudio
from fastapi import FastAPI, UploadFile, File
from fastapi.responses import StreamingResponse
import numpy as np
from pydub import AudioSegment
from pathlib import Path
import yaml
from modules.commons import build_model, load_checkpoint, recursive_munch, str2bool
from hf_utils import load_custom_model_from_hf
# Initialize FastAPI
app = FastAPI()
# Load model and configuration globally
fp16 = False
device = None
def load_models(args):
global sr, hop_length, fp16
fp16 = args.fp16
ckpt_root = Path(__file__).parent / "checkpoints"
print(f"Using device: {device}")
print(f"Using fp16: {fp16}")
# Load your model checkpoint and configuration here (placeholder)
# You will need to adapt this code to match your models
# Example: loading a model and printing some info
# model = some_model_loading_function(args.checkpoint_path)
return {
# Returning the required components for voice conversion
"model": None, # Replace None with the actual model variable
"semantic_fn": None,
"vocoder_fn": None,
"campplus_model": None,
"to_mel": None,
"mel_fn_args": None,
"f0_fn": None,
}
# Define global variables for models and parameters
model_f0, semantic_fn, vocoder_fn, campplus_model, to_mel_f0, mel_fn_args = (None,)*6
f0_fn = None
sr, hop_length = None, None
@torch.no_grad()
@torch.inference_mode()
def voice_conversion(source_audio_path, target_audio_path, diffusion_steps, length_adjust, inference_cfg_rate, auto_f0_adjust, pitch_shift):
# Implement the actual voice conversion logic here
# Example placeholder; replace with your actual implementation
print(f"Processing: {source_audio_path} and {target_audio_path}")
audio_bytes = b'' # Replace with actual audio processing result (byte stream)
full_output = None # Replace with your full output if necessary
# Return processed audio (placeholder)
return audio_bytes, full_output
@app.post("/voice_conversion/")
async def convert_voice(
source: UploadFile = File(...),
target: UploadFile = File(...),
diffusion_steps: int = 10,
length_adjust: float = 1.0,
inference_cfg_rate: float = 0.7,
auto_f0_adjust: bool = True,
pitch_shift: int = 0
):
# Handle uploaded source and target files
source_audio_path = f"temp/{source.filename}"
target_audio_path = f"temp/{target.filename}"
os.makedirs("temp", exist_ok=True) # Create temp directory if it doesn't exist
# Save the uploaded files temporarily
with open(source_audio_path, "wb") as buffer:
buffer.write(await source.read())
with open(target_audio_path, "wb") as buffer:
buffer.write(await target.read())
# Call the voice conversion function
audio_bytes, full_output = voice_conversion(
source_audio_path,
target_audio_path,
diffusion_steps,
length_adjust,
inference_cfg_rate,
auto_f0_adjust,
pitch_shift
)
# Return the audio as StreamingResponse
return StreamingResponse(iter([audio_bytes]), media_type="audio/mp3")
def main(args):
global model_f0, semantic_fn, vocoder_fn, campplus_model, to_mel_f0, mel_fn_args, f0_fn
model_parameters = load_models(args)
model_f0 = model_parameters["model"]
semantic_fn = model_parameters["semantic_fn"]
vocoder_fn = model_parameters["vocoder_fn"]
campplus_model = model_parameters["campplus_model"]
to_mel_f0 = model_parameters["to_mel"]
mel_fn_args = model_parameters["mel_fn_args"]
f0_fn = model_parameters["f0_fn"]
if __name__ == "__main__":
import argparse
# Argument parsing for model config paths and device configuration
parser = argparse.ArgumentParser()
parser.add_argument("--checkpoint-path", type=str, help="Path to the checkpoint file", default=None)
parser.add_argument("--config-path", type=str, help="Path to the config file", default=None)
parser.add_argument("--fp16", type=str2bool, nargs="?", const=True, help="Whether to use fp16", default=True)
parser.add_argument("--gpu", type=int, help="Which GPU id to use", default=0)
args = parser.parse_args()
cuda_target = f"cuda:{args.gpu}" if args.gpu else "cuda"
device = torch.device(cuda_target if torch.cuda.is_available() else "cpu")
main(args)
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Explanation of Key Components:
Function Definitions: Each function has a clearly defined indent level, with the voice_conversion function containing placeholder logic that will need to be replaced with your actual processing steps.
Temporary File Management: Ensures files are stored in a temp directory, preparing for multiple invocations without collision.
Placeholders for Models: The model loading logic is represented as a dictionary return structure for clarity, with placeholder variables that need to be replaced with your actual model implementation.
Error Handling: Make sure to handle any errors especially while reading files or during model inference to ensure robustness.
Ensure that you replace the placeholder logic with your actual voice conversion logic, keeping the indentation consistent throughout. If you encounter further issues, double-check the indentation levels and review any additional function definitions for missing content.