Strictly adhere to PEP-8 standards, ensuring code is clean, well-structured, and follows Python's style guide for readability.
Use appropriate modules like typing for type hints, ensuring code clarity, maintainability, and leveraging Python's standard libraries effectively.
Focus on time, space, robustness, scalability; write optimized, efficient code that can handle large datasets and scale seamlessly.
Implement comprehensive error handling, catching exceptions gracefully, providing meaningful error messages, and ensuring code robustness under unexpected conditions.
Ensure the developer agent writes advanced, maintainable Python code, balancing performance and readability while adhering to best practices.
TASK :
below code write without gradio module
we have make command line interface
import spaces
import gradio as gr
import edge_tts
import asyncio
import tempfile
import os
Get all available voices
async def get_voices():
voices = await edge_tts.list_voices()
return {f"{v['ShortName']} - {v['Locale']} ({v['Gender']})": v['ShortName'] for v in voices}
Text-to-speech function
async def text_to_speech(text, voice, rate, pitch):
if not text.strip():
return None, gr.Warning("Please enter text to convert.")
if not voice:
return None, gr.Warning("Please select a voice.")
description = """
Experience the power of Voicecloning.be for text-to-speech conversion.
"""
demo = gr.Interface(
fn=tts_interface,
inputs=[
gr.Textbox(label="Input Text", lines=5),
gr.Dropdown(choices=[""] + list(voices.keys()), label="Select Voice", value=""),
gr.Slider(minimum=-50, maximum=50, value=0, label="Speech Rate Adjustment (%)", step=1),
gr.Slider(minimum=-20, maximum=20, value=0, label="Pitch Adjustment (Hz)", step=1)
],
outputs=[
gr.Audio(label="Generated Audio", type="filepath"),
gr.Markdown(label="Warning", visible=False)
],
title="Voicecloning.be Text-to-Speech",
description=description,
article="Experience the power of Voicecloning.be for text-to-speech conversion.",
analytics_enabled=False,
allow_flagging=False
)
return demo
Run the application
if name == "main":
demo = asyncio.run(create_demo())
demo.launch()
Certainly! Below is a Python script that replaces the Gradio-based interface with a Command-Line Interface (CLI) for the text-to-speech functionality using the edge_tts library. This script adheres strictly to PEP-8 standards, incorporates type hints from the typing module, and includes comprehensive error handling to ensure robustness and maintainability.
Overview
The script performs the following actions:
List Available Voices: Retrieves and displays all available voices for selection.
Parse Command-Line Arguments: Utilizes argparse to handle user inputs for text, voice selection, speech rate, pitch adjustment, and output file path.
Text-to-Speech Conversion: Converts the provided text into speech using the selected voice, rate, and pitch, saving the output as an MP3 file.
Error Handling: Ensures that all potential errors are gracefully handled, providing meaningful messages to the user.
Code Implementation
python
import argparse
import asyncio
import os
import sys
import tempfile
from typing import Dict, Optional, Tuple
import edge_tts
async def get_voices() -> Dict[str, str]:
"""
Retrieve all available voices from the edge_tts service.
Returns:
A dictionary mapping voice descriptions to their short names.
"""
try:
voices = await edge_tts.list_voices()
return {
f"{v['ShortName']} - {v['Locale']} ({v['Gender']})": v['ShortName']
for v in voices
}
except Exception as e:
raise RuntimeError(f"Failed to retrieve voices: {e}")
async def text_to_speech(
text: str,
voice: str,
rate: int,
pitch: int,
output_path: Optional[str] = None
) -> str:
"""
Convert text to speech and save as an MP3 file.
Args:
text: The text to convert.
voice: The selected voice short name.
rate: Speech rate adjustment in percentage.
pitch: Pitch adjustment in Hz.
output_path: Optional path to save the output MP3 file.
Returns:
The file path to the generated MP3 audio.
Raises:
ValueError: If text or voice parameters are invalid.
RuntimeError: If TTS conversion fails.
"""
if not text.strip():
raise ValueError("Input text cannot be empty.")
if not voice.strip():
raise ValueError("A valid voice must be selected.")
rate_str = f"{rate:+d}%"
pitch_str = f"{pitch:+d}Hz"
communicator = edge_tts.Communicate(
text=text,
voice=voice,
rate=rate_str,
pitch=pitch_str
)
try:
if output_path:
await communicator.save(output_path)
return output_path
else:
with tempfile.NamedTemporaryFile(
delete=False, suffix=".mp3"
) as tmp_file:
tmp_path = tmp_file.name
await communicator.save(tmp_path)
return tmp_path
except Exception as e:
raise RuntimeError(f"Text-to-speech conversion failed: {e}")
def parse_arguments(voices: Dict[str, str]) -> argparse.Namespace:
"""
Parse command-line arguments provided by the user.
Args:
voices: A dictionary of available voices.
Returns:
The populated namespace with parsed arguments.
"""
parser = argparse.ArgumentParser(
description="Voicecloning.be Text-to-Speech Command-Line Interface"
)
parser.add_argument(
"-t",
"--text",
type=str,
required=True,
help="Text to convert to speech."
)
parser.add_argument(
"-v",
"--voice",
type=str,
required=True,
choices=voices.keys(),
help="Voice to use for speech."
)
parser.add_argument(
"-r",
"--rate",
type=int,
default=0,
help="Speech rate adjustment in percentage (e.g., -10 for slower, +10 for faster). Default is 0."
)
parser.add_argument(
"-p",
"--pitch",
type=int,
default=0,
help="Pitch adjustment in Hz (e.g., -5 for lower, +5 for higher). Default is 0."
)
parser.add_argument(
"-o",
"--output",
type=str,
default=None,
help="Output file path for the generated MP3. If not provided, a temporary file will be used."
)
return parser.parse_args()
async def main() -> None:
"""
The main function to execute the CLI for text-to-speech conversion.
"""
try:
voices = await get_voices()
except RuntimeError as e:
print(f"Error: {e}", file=sys.stderr)
sys.exit(1)
if not voices:
print("No voices available.", file=sys.stderr)
sys.exit(1)
args = parse_arguments(voices)
voice_short_name = voices.get(args.voice)
if not voice_short_name:
print("Selected voice is not available.", file=sys.stderr)
sys.exit(1)
try:
output_file = await text_to_speech(
text=args.text,
voice=voice_short_name,
rate=args.rate,
pitch=args.pitch,
output_path=args.output
)
print(f"Audio successfully saved to: {output_file}")
except ValueError as ve:
print(f"Input Error: {ve}", file=sys.stderr)
sys.exit(1)
except RuntimeError as re:
print(f"Processing Error: {re}", file=sys.stderr)
sys.exit(1)
except Exception as ex:
print(f"An unexpected error occurred: {ex}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print("\nOperation cancelled by user.", file=sys.stderr)
sys.exit(1)
Detailed Explanation
Imports and Type Hints:
Utilizes necessary standard libraries such as argparse for CLI parsing, asyncio for asynchronous operations, tempfile for handling temporary files, and typing for type annotations.
Imports the edge_tts library for text-to-speech capabilities.
Voice Retrieval:
The get_voices asynchronous function fetches available voices from the edge_tts service and structures them into a dictionary for easy access and display.
Text-to-Speech Conversion:
The text_to_speech asynchronous function handles the conversion of input text to speech.
It validates the input parameters, adjusts the rate and pitch as specified, and either saves the output to a user-defined path or generates a temporary file.
Comprehensive error handling ensures that issues during conversion are reported back to the user.
Command-Line Argument Parsing:
The parse_arguments function leverages argparse to define and parse the necessary command-line arguments, including text input, voice selection, rate and pitch adjustments, and optional output file path.
It restricts voice selection to the available voices retrieved from the edge_tts service.
Main Execution Flow:
The main asynchronous function orchestrates the overall flow:
Retrieves available voices.
Parses user-provided command-line arguments.
Validates the selected voice.
Initiates the text-to-speech conversion.
Handles and reports any errors encountered during the process.
Upon successful conversion, it notifies the user of the location of the generated audio file.
Entry Point Handling:
The if __name__ == "__main__": block ensures that the script can be executed directly.
It also gracefully handles keyboard interruptions, allowing users to cancel the operation cleanly.
Usage Instructions
Installation:
Ensure that Python 3.7 or higher is installed.
Install the necessary dependencies using pip:
bash
pip install edge-tts
Running the Script:
Save the script to a file, e.g., tts_cli.py.
Execute the script via the command line with the required arguments. For example:
bash
python tts_cli.py \
--text "Hello, this is a test of the text-to-speech system." \
--voice "en-US-AriaNeural - en-US (Female)" \
--rate 10 \
--pitch 5 \
--output output_audio.mp3
Arguments:
--text (-t): The text you want to convert to speech.
--voice (-v): The voice to use. Must be one of the available voices listed.
--rate (-r): (Optional) Adjusts the speech rate by the specified percentage. Defaults to 0.
--pitch (-p): (Optional) Adjusts the pitch by the specified Hz. Defaults to 0.
--output (-o): (Optional) Specifies the output file path for the generated MP3. If omitted, a temporary file is created.
Listing Available Voices:
To view all available voices, you can modify the script to print the voices dictionary or implement an additional command-line argument to list voices. For simplicity, you can run the script without specifying the --voice argument to see the available options from the error message.
Example
Here's an example command that converts text to speech with specific voice, rate, and pitch adjustments:
Upon successful execution, the script will generate an MP3 file named welcome_audio.mp3 containing the synthesized speech.
Conclusion
This CLI-based Python script provides a flexible and robust alternative to the Gradio interface for text-to-speech conversion. It adheres to best coding practices, ensuring readability, maintainability, and efficiency. With comprehensive error handling and clear user instructions, it serves as a reliable tool for developers and users alike.