keep all the functionality of the previous code the same, make sure the code will work in the same way, just update or correct the problematic parts, Traceback (most recent call last):
File "/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/AUDIO/Audio_Processing_Scripts/CSV_Dataset_Creator/huggingface_downloaded_datasets_into_csv_dataset.py", line 249, in
create_dataset(args.input_folder, args.output_csv, args.path_type,
File "/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/AUDIO/Audio_Processing_Scripts/CSV_Dataset_Creator/huggingface_downloaded_datasets_into_csv_dataset.py", line 228, in create_dataset
if result[1] == 'too short':
~~~~~~^^^
TypeError: 'NoneType' object is not subscriptable import os
import csv
import argparse
import logging
import wave
import re
from multiprocessing import Pool, cpu_count
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
code
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Create a CSV dataset from audio and transcript files."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing audio and transcript files.")
parser.add_argument('--output_csv', type=str, default='dataset.csv',
help="Path to save the output dataset CSV file.")
parser.add_argument('--path_type', type=str, choices=['absolute', 'relative'], default='relative',
help="Choose 'absolute' for full paths or 'relative' for paths relative to input_folder.")
parser.add_argument('--min_wav_length', type=float, default=3.0,
help="Minimum length of WAV files in seconds (default: 3.0).")
parser.add_argument('--max_wav_length', type=float, default=11.6,
help="Maximum length of WAV files in seconds (default: 11.6).")
parser.add_argument('--min_text_length', type=int, default=20,
help="Minimum character length for text (default: 20).")
parser.add_argument('--max_text_length', type=int, default=200,
help="Maximum character length for text (default: 200).")
parser.add_argument('--drop_symbols', type=str, default='#*',
help="Symbols to drop from the text.")
return parser
def normalize_text(text: str) -> str:
"""
Normalize the text by removing extra spaces and replacing certain patterns.
code
Args:
text (str): The text to normalize.
Returns:
str: Normalized text.
"""
# Normalize triple quotes to single quotes
text = re.sub(r'""?"', '"', text)
# Remove extra spaces
return ' '.join(text.split())
def check_wav_length(file_path: str, min_length: float, max_length: float) -> (bool, str):
"""
Check if the length of a WAV file is within the specified bounds.
code
Args:
file_path (str): Path to the WAV file.
min_length (float): Minimum length in seconds.
max_length (float): Maximum length in seconds.
Returns:
(bool, str): A tuple containing True/False for length validity and a reason.
"""
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / frame_rate
if duration < min_length:
return False, 'too short'
if duration > max_length:
return False, 'too long'
return True, ''
except Exception as e:
logger.error("Error checking WAV file length %s: %s", file_path, e)
return False, 'error'
def should_drop_text(text: str, min_length: int, max_length: int, drop_symbols: str) -> bool:
"""
Determine if a text should be dropped based on various criteria.
code
Args:
text (str): The text to check.
min_length (int): Minimum acceptable length.
max_length (int): Maximum acceptable length.
drop_symbols (str): String of symbols that, if found, will cause the text to be dropped.
Returns:
bool: True if the text should be dropped, otherwise False.
"""
if len(text) < min_length or len(text) > max_length:
logger.debug("Text length out of bounds: %s (Length: %d)", text, len(text))
return True
if "{NICKNAME}" in text:
logger.debug("Text contains '{NICKNAME}': %s", text)
return True
if re.search(r'<[^>]+>', text): # Check for HTML tags
logger.debug("Text contains HTML tags: %s", text)
return True
if any(symbol in text for symbol in drop_symbols):
logger.debug("Text contains drop symbols (%s): %s", drop_symbols, text)
return True
return False
def process_file(audio_file: str, transcript_file: str, input_folder: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str, path_type: str) -> list:
"""
Process a single audio and transcript file to extract data for the CSV.
code
Args:
audio_file (str): Name of the audio file.
transcript_file (str): Name of the transcript file.
input_folder (str): Path to the input folder.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
path_type (str): 'absolute' or 'relative' path type for audio files.
Returns:
list: A list containing the output data or None if the entry should be dropped.
"""
audio_path = os.path.join(input_folder, audio_file)
transcript_path = os.path.join(input_folder, transcript_file)
# Check WAV length
valid_length, reason = check_wav_length(audio_path, min_wav_length, max_wav_length)
if not valid_length:
logger.warning("WAV file out of length bounds (%s): %s", reason, audio_file)
return None
# Read the transcript text
try:
with open(transcript_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
if should_drop_text(text, min_text_length, max_text_length, drop_symbols):
logger.warning("Text dropped due to filtering: %s", text)
return None
normalized_text = normalize_text(text)
except Exception as e:
logger.error("Error reading transcript file %s: %s", transcript_file, e)
return None # Skip this entry if there's an error
# Use "EMPTY" as the speaker name
speaker_name = "EMPTY"
# Determine the output path based on path_type
output_path = os.path.abspath(audio_path) if path_type == 'absolute' else os.path.join("audio", audio_file)
return [output_path, normalized_text, speaker_name]
def format_duration(seconds: float) -> str:
"""
Format duration in seconds to a string in hours:minutes:seconds.
def create_dataset(input_folder: str, output_csv: str, path_type: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str):
"""
Create a CSV dataset from the audio and transcript files using multiprocessing.
code
def main():
"""
Main function to execute the CSV dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
code
try:
# Create the dataset
create_dataset(
args.input_folder, args.output_csv, args.path_type,
args.min_wav_length, args.max_wav_length,
args.min_text_length, args.max_text_length,
args.drop_symbols
)
logger.info("Dataset created successfully: %s", args.output_csv)
except Exception as e:
logger.error("An error occurred during dataset creation: %s", e)
if name == 'main':
main() when dropping wav file because of length print me also whether it's because it's too long or too short, print me at the end of the script how many files were 1. dropped due to shortness, 2. Dropped because they were too long, 3. You shall give me the total length of dataset in hours:minutes:seconds, dropped audio length in hours:minutes:seconds and also give me length of audio that was successfully processed and added into csv dataset in hours:minutes:seconds, you shall count the percentage how much of the total audio was used in the dataset, give me python script with cli args interface very well written, with comments, documented functions with docstrings, with pep8 formating, default values and description for cli interface, apply high informational quality printing and logging stategies that will inform me about the processing, progress and running of the code, add robust try and error statements and make the code quick and stable, keep all the functionality of the previous code the same, make sure the code will work in the same way, just update or correct the problematic parts,
Assistant
The issue you're encountering is that the result variable is None when you're trying to access its elements. This happens because some audio files are skipped in the process_file function, returning None. The problematic part of the code is when it attempts to check the length of the dropped file after it's already determined that the result is None.
Here's an updated version of your script with enhanced logging, proper error handling, and a clear summary of dropped files:
python
User
FIX THIS 2024-09-26 21:28:25,246 - INFO - Added entry: ['/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/70047_audio.wav', "Wanna go fishing? I've got some rods and lures ready.", 'EMPTY']
2024-09-26 21:28:25,292 - INFO - Added entry: ['/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/7084_audio.wav', "I've been in the tea business for most of my life, and I always hoped my child would do the same. Otherwise, how would he support himself?", 'EMPTY']
2024-09-26 21:28:25,336 - INFO - Added entry: ['/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/28712_audio.wav', '"I wish that every day of your journey ahead will be filled with joy like a festival."', 'EMPTY']
2024-09-26 21:28:25,382 - INFO - Added entry: ['/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/11286_audio.wav', "Wouldn't expect any less from you, Alhaitham! Once the collective consciousness bugs out, we'll take that opportunity to—", 'EMPTY']
2024-09-26 21:28:25,427 - INFO - Added entry: ['/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/94988_audio.wav', "And I'd be happy to process that for you... If you could just tell me the cause of your dissatisfaction...", 'EMPTY']
2024-09-26 21:28:25,473 - INFO - Added entry: ['/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/46773_audio.wav', "Oh... that's why you were preparing them all night.", 'EMPTY']
2024-09-26 21:28:25,518 - INFO - Added entry: ['/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/53175_audio.wav', "We fought a big battle with that thing. Maybe it hasn't gotten too far yet...", 'EMPTY']
2024-09-26 21:28:25,563 - INFO - Added entry: ['/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/94735_audio.wav', 'Interesting. These are all motifs associated with the tribes of the desert.', 'EMPTY']
2024-09-26 21:28:25,608 - INFO - Added entry: ['/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/21255_audio.wav', 'So what's the "Haft-Mewa Feast" you mentioned just now?', 'EMPTY']
2024-09-26 21:28:25,654 - ERROR - An error occurred during dataset creation: iterable expected, not NoneType import os
import csv
import argparse
import logging
import wave
import re
from multiprocessing import Pool, cpu_count
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
code
Assistant
It seems the existing code has issues related to handling None values when processing audio files, leading to errors when attempting to iterate over them. Below is the corrected version of the script with enhanced logging, error handling, and robust logic to deal with potential None values:
python
User
import os
import csv
import argparse
import logging
import random
import string
import wave
import re
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
code
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Create a CSV dataset from audio and transcript files."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing audio and transcript files.")
parser.add_argument('--output_csv', type=str, default='dataset.csv',
help="Path to save the output dataset CSV file.")
parser.add_argument('--path_type', type=str, choices=['absolute', 'relative'], default='relative',
help="Choose 'absolute' for full paths or 'relative' for paths relative to input_folder.")
parser.add_argument('--min_wav_length', type=float, default=3.0,
help="Minimum length of WAV files in seconds (default: 3.0).")
parser.add_argument('--max_wav_length', type=float, default=11.6,
help="Maximum length of WAV files in seconds (default: 11.6).")
parser.add_argument('--min_text_length', type=int, default=20,
help="Minimum character length for text (default: 20).")
parser.add_argument('--max_text_length', type=int, default=200,
help="Maximum character length for text (default: 200).")
parser.add_argument('--drop_symbols', type=str, default='#*',
help="Symbols to drop from the text.")
return parser
Assistant
To meet your requirements, I'll modify the script to track why WAV files are dropped and calculate the total and dropped audio lengths. It will also calculate and display additional statistics, including the percentage of audio used in the dataset. I'll ensure the code adheres to PEP 8 standards, use meaningful logging, and maintain robust error handling. Here is the updated script:
python
User
import os
import csv
import argparse
import logging
import wave
import re
import string
import random
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
code
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Create a CSV dataset from audio and transcript files."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing audio and transcript files.")
parser.add_argument('--output_csv', type=str, default='dataset.csv',
help="Path to save the output dataset CSV file.")
parser.add_argument('--path_type', type=str, choices=['absolute', 'relative'], default='relative',
help="Choose 'absolute' for full paths or 'relative' for paths relative to input_folder.")
parser.add_argument('--min_wav_length', type=float, default=3.0,
help="Minimum length of WAV files in seconds (default: 3.0).")
parser.add_argument('--max_wav_length', type=float, default=11.6,
help="Maximum length of WAV files in seconds (default: 11.6).")
parser.add_argument('--min_text_length', type=int, default=20,
help="Minimum character length for text (default: 20).")
parser.add_argument('--max_text_length', type=int, default=200,
help="Maximum character length for text (default: 200).")
parser.add_argument('--drop_symbols', type=str, default='#*',
help="Symbols to drop from the text.")
return parser
Assistant
Certainly! I'll modify the script to create an additional CSV file for dropped files, retaining the complete functionality and style while ensuring robust error handling and enhanced logging.
python
User
import os
import csv
import argparse
import logging
import wave
import re
import string
import random
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
code
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Create a CSV dataset from audio and transcript files."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing audio and transcript files.")
parser.add_argument('--output_csv', type=str, default='dataset.csv',
help="Path to save the output dataset CSV file.")
parser.add_argument('--path_type', type=str, choices=['absolute', 'relative'], default='relative',
help="Choose 'absolute' for full paths or 'relative' for paths relative to input_folder.")
parser.add_argument('--min_wav_length', type=float, default=3.0,
help="Minimum length of WAV files in seconds (default: 3.0).")
parser.add_argument('--max_wav_length', type=float, default=11.6,
help="Maximum length of WAV files in seconds (default: 11.6).")
parser.add_argument('--min_text_length', type=int, default=20,
help="Minimum character length for text (default: 20).")
parser.add_argument('--max_text_length', type=int, default=200,
help="Maximum character length for text (default: 200).")
parser.add_argument('--drop_symbols', type=str, default='#*',
help="Symbols to drop from the text.")
return parser
Assistant
To achieve the desired functionality, I'll modify the script to include additional columns in the dropped CSV. Specifically, I'll append the corresponding text (if applicable) and the audio length for each entry. The code will maintain all existing functions and features, with an added focus on robust error handling and detailed logging. Here's the enhanced version of the script:
python
User
import os
import csv
import argparse
import logging
import wave
import re
import string
import random
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
code
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Create a CSV dataset from audio and transcript files."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing audio and transcript files.")
parser.add_argument('--output_csv', type=str, default='dataset.csv',
help="Path to save the output dataset CSV file.")
parser.add_argument('--path_type', type=str, choices=['absolute', 'relative'], default='relative',
help="Choose 'absolute' for full paths or 'relative' for paths relative to input_folder.")
parser.add_argument('--min_wav_length', type=float, default=3.0,
help="Minimum length of WAV files in seconds (default: 3.0).")
parser.add_argument('--max_wav_length', type=float, default=11.6,
help="Maximum length of WAV files in seconds (default: 11.6).")
parser.add_argument('--min_text_length', type=int, default=20,
help="Minimum character length for text (default: 20).")
parser.add_argument('--max_text_length', type=int, default=200,
help="Maximum character length for text (default: 200).")
parser.add_argument('--drop_symbols', type=str, default='#*',
help="Symbols to drop from the text.")
return parser
Assistant
To introduce multiprocessing and retain the existing functionality of your script, we'll utilize the concurrent.futures module. This approach will allow us to parallelize the processing of audio-transcript pairs, which can significantly accelerate the dataset generation. Here is the updated script:
python
User
audio_file|text|speaker_name
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/70047_audio.wav|Wanna go fishing? I've got some rods and lures ready.|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/7084_audio.wav|I've been in the tea business for most of my life, and I always hoped my child would do the same. Otherwise, how would he support himself?|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/28712_audio.wav|"""I wish that every day of your journey ahead will be filled with joy like a festival."""|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/11286_audio.wav|Wouldn't expect any less from you, Alhaitham! Once the collective consciousness bugs out, we'll take that opportunity to—|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/94988_audio.wav|And I'd be happy to process that for you... If you could just tell me the cause of your dissatisfaction...|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/46773_audio.wav|Oh... that's why you were preparing them all night.|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/53175_audio.wav|We fought a big battle with that thing. Maybe it hasn't gotten too far yet...|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/94735_audio.wav|Interesting. These are all motifs associated with the tribes of the desert.|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/21255_audio.wav|"So what's the ""Haft-Mewa Feast"" you mentioned just now?"|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/2007_audio.wav|The bass you want is not a standard specimen. Our fishermen need to wait for the right moment to catch it.|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/49049_audio.wav|Wow, that's amazing! Yep, let's take another look around...|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/83938_audio.wav|When Shinobu gives me the look, I react automatically, I can't control it...|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/25570_audio.wav|Often, I'll sneak down to the shore at night and listen to the sound of the waves... I like to imagine it's the voice of my hometown, carried across the ocean.|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/1474_audio.wav|Did you know? The reeds in Dihua Marsh are common materials used in making paper.|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/93943_audio.wav|Yeah, we even rode the Choo-Choo Cart! Do you wanna come ride too?|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/73668_audio.wav|Ahh, now then, you must be the adventurers assigned by the Guild.|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/97305_audio.wav|There's nothing to be angry about. Think of this as an academic journey.|EMPTY
/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/29211_audio.wav|Hey, hello? Anyone home?|EMPTY this is the csv dataset give me cli one liner that would copy selected lines like lines 56 to 86 from based on wav path and will copy these wavs into newly created 'selected_wav_samples' folder, cli one liner on ubuntu mkdir -p selected_wav_samples && awk 'NR>=56 && NR<=86 {print $1}' genshin_complete_dataset.csv | xargs -I {} cp {} selected_wav_samples/
cp: cannot stat '/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/13495_audio.wav|Oh,': No such file or directory
cp: cannot stat '/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/75741_audio.wav|Come': No such file or directory
cp: cannot stat '/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/70197_audio.wav|That': No such file or directory
cp: cannot stat '/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/10350_audio.wav|I': No such file or directory
cp: cannot stat '/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/48285_audio.wav|You': No such file or directory
cp: cannot stat '/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/48219_audio.wav|The': No such file or directory
xargs: unmatched single quote; by default quotes are special to xargs unless you use the -0 option
cp: cannot stat '/mnt/5bf09f3e-bdd1-4c93-99bb-72c72bfda11b/genshin-voice/audio_metadata/63290_audio.wav|Alright,': No such file or directory
Assistant
The error messages you're encountering stem from the CSV file being delimited using the | character, but your awk and xargs command assumes it's space-delimited. Therefore, it's capturing the entire line, including the text and speaker information, which leads to incorrect file paths.
To address this, you can adjust your command to process the CSV with the correct delimiter. You can use awk with the -F option to specify the delimiter and then tweak the handling to capture only the file path. Here's how you can do it:
-F '|': This setting in awk specifies | as the delimiter instead of the default space.
NR>=56 && NR<=86: This confines the command to process lines 56 to 86 only.
print $1: Outputs the first field, which is the audio file path, from the CSV line.
xargs -d '\n': This tells xargs to treat each line separately, using newline as the delimiter, crucial for file paths containing spaces.
cp {}: Uses the paths extracted to copy the files into the selected_wav_samples directory.
This should correctly copy the audio files specified in lines 56 to 86 based on their paths. If you encounter any issues with the line numbers or the presence of headers, consider adjusting the range or ensuring that line numbers correspond with those in your actual file.
User
import os
import csv
import argparse
import logging
import wave
import re
import string
import random
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
code
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Create a CSV dataset from audio and transcript files."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing audio and transcript files.")
parser.add_argument('--output_csv', type=str, default='dataset.csv',
help="Path to save the output dataset CSV file.")
parser.add_argument('--path_type', type=str, choices=['absolute', 'relative'], default='relative',
help="Choose 'absolute' for full paths or 'relative' for paths relative to input_folder.")
parser.add_argument('--min_wav_length', type=float, default=3.0,
help="Minimum length of WAV files in seconds (default: 3.0).")
parser.add_argument('--max_wav_length', type=float, default=11.6,
help="Maximum length of WAV files in seconds (default: 11.6).")
parser.add_argument('--min_text_length', type=int, default=20,
help="Minimum character length for text (default: 20).")
parser.add_argument('--max_text_length', type=int, default=200,
help="Maximum character length for text (default: 200).")
parser.add_argument('--drop_symbols', type=str, default='#*',
help="Symbols to drop from the text.")
return parser
Assistant
When you run a program that processes files, it often uses filesystem and disk operations that can greatly influence performance. Here are several reasons why the script might run faster on files you've processed before compared to files you haven't:
Filesystem Caching:
Operating System Caching: Modern operating systems, including Ubuntu, use filesystem caching to store data that is frequently accessed in RAM. If you run the script on files that have been accessed recently, those files may still be cached, leading to faster read operations. This is because accessing data from RAM is significantly faster than reading from disk.
Disk Caching:
Hardware Caching: Some hardware, such as SSDs, also employs caching at a hardware level, which can help speed up subsequent accesses to the same data.
File Metadata Caching:
File Attributes and Metadata: Accessing file attributes or metadata (such as file size, last modified time) often benefits from caching. Operations like checking file existence or reading small metadata fields can be quicker for files processed recently due to this caching mechanism.
Reduced Fragmentation:
File Fragmentation Considerations: If files have been moved or copied recently, the filesystem may have optimized their storage layout, reducing fragmentation and improving access speed for future operations.
Reduced CPU Overhead:
CPU Caching and Optimization: The CPU may optimize the execution of repeated operations through instruction caching or branch prediction. A second run might benefit from previously optimized code paths or cached data structures within your Python environment, particularly if the script invokes repeated computations or memory operations.
Python Bytecode Caching:
Compiled Python Code: Python uses .pyc files to cache compiled bytecode. If you re-run a script, it doesn't need to be recompiled from source, which slightly reduces initialization time. However, this impact is minimal compared to filesystem caching.
These reasons mostly pertain to the underlying OS and hardware architecture rather than the specifics of your Python script. However, understanding them helps to appreciate why performance can be inconsistent across seemingly identical runs. If you're working with large files or datasets, utilizing the system cache more effectively can lead to noticeable improvements in performance.
User
give me very quick python script that will use multiprocessing to convert wav folder into new wav folder, all the wav shall be converted into new 22050 sampling rate and it shall normalize the volume at the same time, the volume normalization shall be done to the youtube standard volume recommended level, what is the quickest option to do this? pydub? ffmpeg? librosa? some soundlibrary, make sure the sound normalization works and doesn't distorts the audio, give me complete python code that is quick, give me python script with cli args interface very well written, with comments, documented functions with docstrings, with pep8 formating, default values and description for cli interface, apply high informational quality printing and logging stategies that will inform me about the processing, progress and running of the code, add robust try and error statements and make the code quick and stable
Assistant
To achieve the goals you've described, a combination of ffmpeg for conversion and pydub for normalization is an effective approach. ffmpeg is renowned for its speed and efficiency in handling media files, and pydub provides an easy interface for volume normalization without significant distortion.
Below is a Python script utilizing both of these tools, with multiprocessing to speed up the process.
python
User
what is the usual learning rate to finetune the model like tortoise or xtts without destroying the weigths? what learning rate xtts used for tuning? check xtts paper! give me general recommendation for voice finetuning, what are speculations about what lr eleven labs are using?
Assistant
When fine-tuning models like Tortoise or xtts, the goal is to adjust the weights of the pre-trained model slightly to better fit a specific dataset, without significantly overwriting the useful representations the model has already learned. Choosing an appropriate learning rate is crucial to this process.
Learning Rates for Fine-Tuning Models like Tortoise or xTTS
Typical Learning Rates for Fine-Tuning:
Common Range: For fine-tuning transformer-based models like Tortoise or xTTS, learning rates typically range from (1 \times 10^{-5}) to (5 \times 10^{-5}).
Smaller is Safer: Using smaller learning rates helps avoid drastic weight changes, ensuring the model's learned representations don't get overwritten. In general, starting with a learning rate like (1 \times 10^{-5}) is often safe for fine-tuning purposes.
Learning Rate Used in xTTS:
Research Papers and Precedents: For xTTS, the paper or any original source documentation might not specify a precise learning rate as this can depend on the specific setup, data, and model variations. However, it is likely that the authors experimented with learning rates within the aforementioned safe range during development.
General Recommendations for Voice Fine-Tuning:
Experimentation: Begin with a conservative learning rate, and adjust as necessary based on validation performance. Track the loss curves and monitor for signs of overfitting or underfitting.
Warm-up Strategies: Implement learning rate warm-up followed by a decay strategy. This means starting with a very small learning rate and gradually increasing it to your chosen learning rate, then potentially decreasing it again over time.
Regularization Techniques: Use dropout, weight decay, or gradient clipping to prevent overfitting and maintain model stability during fine-tuning.
Speculations on Learning Rates Used by Eleven Labs:
Proprietary Techniques: Eleven Labs, like many commercial entities, likely use proprietary tuning techniques that are optimized for their specific architectures and datasets. Such companies might employ advanced strategies like adaptive learning rates, learning rate schedules, or meta-learning strategies tailored to their needs.
Informed Guesses: It’s reasonable to speculate they're using adaptive optimizers like Adam (or variants like AdamW) with learning rates starting from (1 \times 10^{-5}) or lower, given the precedence in fine-tuning transformer-based models.
User
import os
import argparse
import logging
from pydub import AudioSegment
from concurrent.futures import ProcessPoolExecutor
import subprocess
def normalize_audio(input_file: str, output_file: str):
"""
Normalize audio to a standard volume level using ffmpeg.
code
Args:
input_file (str): Path to the input WAV file.
output_file (str): Path to the output normalized WAV file.
"""
try:
# Load audio file
audio = AudioSegment.from_file(input_file)
# Normalize the audio to YouTube's standard level (-14dB)
normalized_audio = audio.apply_gain(-audio.dBFS - (-14))
# Export the audio to the desired sampling rate
normalized_audio = normalized_audio.set_frame_rate(22050)
normalized_audio.export(output_file, format='wav')
logger.info("Successfully processed: %s", output_file)
except Exception as e:
logger.error("Error processing file %s: %s", input_file, e)
def process_wav_files(input_folder: str, output_folder: str):
"""
Process all WAV files in a folder, normalizing and converting their sample rates.
code
Args:
input_folder (str): Path to the folder containing input WAV files.
output_folder (str): Path to the folder for saving processed WAV files.
"""
files = [f for f in os.listdir(input_folder) if f.endswith('.wav')]
# Ensure output folder exists
os.makedirs(output_folder, exist_ok=True)
with ProcessPoolExecutor() as executor:
for file in files:
input_file_path = os.path.join(input_folder, file)
output_file_path = os.path.join(output_folder, file)
executor.submit(normalize_audio, input_file_path, output_file_path)
Assistant
To update the script to use ffmpeg for both sample rate conversion and volume normalization according to YouTube standards, we'll replace the pydub operations with subprocess calls to execute ffmpeg commands. This approach leverages ffmpeg's built-in capabilities to efficiently process audio files. Below is the updated script:
Args:
input_folder (str): Path to the input folder.
output_csv (str): Path to the output CSV file.
path_type (str): 'absolute' or 'relative' path type for audio files.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
"""
audio_files = {}
transcript_files = {}
total_audio_length = 0.0
dropped_audio_length = 0.0
dropped_due_to_shortness = 0
dropped_due_to_longness = 0
# Read audio and transcript files into dictionaries
for filename in os.listdir(input_folder):
if filename.endswith('.wav'):
audio_id = filename.split('_')[0]
audio_files[audio_id] = filename
elif filename.endswith('.txt'):
transcript_id = filename.split('_')[0]
transcript_files[transcript_id] = filename
logger.info("Found %d audio files and %d transcript files.", len(audio_files), len(transcript_files))
# Prepare tasks for multiprocessing
tasks = []
for audio_id, audio_file in audio_files.items():
if audio_id in transcript_files:
transcript_file = transcript_files[audio_id]
tasks.append((audio_file, transcript_file, input_folder,
min_wav_length, max_wav_length,
min_text_length, max_text_length,
drop_symbols, path_type))
# Process files in parallel
with Pool(processes=cpu_count()) as pool:
results = pool.starmap(process_file, tasks)
# Filter out None results and write to CSV
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile, delimiter='|')
writer.writerow(['audio_file', 'text', 'speaker_name'])
for result in results:
if result is not None:
writer.writerow(result)
logger.info("Added entry: %s | %s | %s", result[0], result[1], result[2])
else:
# Increment counters for dropped audio length
duration, reason = check_wav_length(os.path.join(input_folder, result[0]), min_wav_length, max_wav_length)
if reason == 'too short':
dropped_due_to_shortness += 1
elif reason == 'too long':
dropped_due_to_longness += 1
# Log summary
logger.info("Summary of processing:")
logger.info("Dropped due to shortness: %d", dropped_due_to_shortness)
logger.info("Dropped due to longness: %d", dropped_due_to_longness)
# Calculate total lengths
total_audio_length = sum(
check_wav_length(os.path.join(input_folder, file), min_wav_length, max_wav_length)[0] for file in audio_files.values()
)
dropped_audio_length = dropped_due_to_shortness * min_wav_length + dropped_due_to_longness * max_wav_length
total_duration_seconds = sum(check_wav_length(os.path.join(input_folder, file), min_wav_length, max_wav_length)[0] for file in results if result)
logger.info("Total audio length processed: %s", format_duration(total_duration_seconds))
logger.info("Dropped audio length: %s", format_duration(dropped_audio_length))
logger.info("Length of audio used in the dataset: %s", format_duration(total_audio_length))
import os
import csv
import argparse
import logging
import wave
import re
from multiprocessing import Pool, cpu_count
# Setup logging configuration
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Create a CSV dataset from audio and transcript files."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing audio and transcript files.")
parser.add_argument('--output_csv', type=str, default='dataset.csv',
help="Path to save the output dataset CSV file.")
parser.add_argument('--path_type', type=str, choices=['absolute', 'relative'], default='relative',
help="Choose 'absolute' for full paths or 'relative' for paths relative to input_folder.")
parser.add_argument('--min_wav_length', type=float, default=3.0,
help="Minimum length of WAV files in seconds (default: 3.0).")
parser.add_argument('--max_wav_length', type=float, default=11.6,
help="Maximum length of WAV files in seconds (default: 11.6).")
parser.add_argument('--min_text_length', type=int, default=20,
help="Minimum character length for text (default: 20).")
parser.add_argument('--max_text_length', type=int, default=200,
help="Maximum character length for text (default: 200).")
parser.add_argument('--drop_symbols', type=str, default='#*',
help="Symbols to drop from the text.")
return parser
def normalize_text(text: str) -> str:
"""
Normalize the text by removing extra spaces and replacing certain patterns.
Args:
text (str): The text to normalize.
Returns:
str: Normalized text.
"""
# Normalize triple quotes to single quotes
text = re.sub(r'""?"', '"', text)
# Remove extra spaces
return ' '.join(text.split())
def check_wav_length(file_path: str, min_length: float, max_length: float) -> (bool, str, float):
"""
Check if the length of a WAV file is within the specified bounds.
Args:
file_path (str): Path to the WAV file.
min_length (float): Minimum length in seconds.
max_length (float): Maximum length in seconds.
Returns:
(bool, str, float): A tuple containing True/False for length validity, a reason, and the duration.
"""
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / frame_rate
if duration < min_length:
return False, 'too short', duration
if duration > max_length:
return False, 'too long', duration
return True, '', duration
except Exception as e:
logger.error("Error checking WAV file length %s: %s", file_path, e)
return False, 'error', 0.0
def should_drop_text(text: str, min_length: int, max_length: int, drop_symbols: str) -> bool:
"""
Determine if a text should be dropped based on various criteria.
Args:
text (str): The text to check.
min_length (int): Minimum acceptable length.
max_length (int): Maximum acceptable length.
drop_symbols (str): String of symbols that, if found, will cause the text to be dropped.
Returns:
bool: True if the text should be dropped, otherwise False.
"""
if len(text) < min_length or len(text) > max_length:
logger.debug("Text length out of bounds: %s (Length: %d)", text, len(text))
return True
if "{NICKNAME}" in text:
logger.debug("Text contains '{NICKNAME}': %s", text)
return True
if re.search(r'<[^>]+>', text): # Check for HTML tags
logger.debug("Text contains HTML tags: %s", text)
return True
if any(symbol in text for symbol in drop_symbols):
logger.debug("Text contains drop symbols (%s): %s", drop_symbols, text)
return True
return False
def process_file(audio_file: str, transcript_file: str, input_folder: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str, path_type: str) -> list:
"""
Process a single audio and transcript file to extract data for the CSV.
Args:
audio_file (str): Name of the audio file.
transcript_file (str): Name of the transcript file.
input_folder (str): Path to the input folder.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
path_type (str): 'absolute' or 'relative' path type for audio files.
Returns:
list: A list containing the output data or None if the entry should be dropped.
"""
audio_path = os.path.join(input_folder, audio_file)
transcript_path = os.path.join(input_folder, transcript_file)
# Check WAV length
valid_length, reason, _ = check_wav_length(audio_path, min_wav_length, max_wav_length)
if not valid_length:
logger.warning("WAV file out of length bounds (%s): %s", reason, audio_file)
return None
# Read the transcript text
try:
with open(transcript_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
if should_drop_text(text, min_text_length, max_text_length, drop_symbols):
logger.warning("Text dropped due to filtering: %s", text)
return None
normalized_text = normalize_text(text)
except Exception as e:
logger.error("Error reading transcript file %s: %s", transcript_file, e)
return None # Skip this entry if there's an error
# Use "EMPTY" as the speaker name
speaker_name = "EMPTY"
# Determine the output path based on path_type
output_path = os.path.abspath(audio_path) if path_type == 'absolute' else os.path.join("audio", audio_file)
return [output_path, normalized_text, speaker_name]
def format_duration(seconds: float) -> str:
"""
Format duration in seconds to a string in hours:minutes:seconds.
Args:
seconds (float): Duration in seconds.
Returns:
str: Formatted duration as a string.
"""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
seconds = int(seconds % 60)
return f"{hours}:{minutes:02}:{seconds:02}"
def create_dataset(input_folder: str, output_csv: str, path_type: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str):
"""
Create a CSV dataset from the audio and transcript files using multiprocessing.
Args:
input_folder (str): Path to the input folder.
output_csv (str): Path to the output CSV file.
path_type (str): 'absolute' or 'relative' path type for audio files.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
"""
audio_files = {}
transcript_files = {}
total_audio_length = 0.0
dropped_audio_length = 0.0
dropped_due_to_shortness = 0
dropped_due_to_longness = 0
# Read audio and transcript files into dictionaries
for filename in os.listdir(input_folder):
if filename.endswith('.wav'):
audio_id = filename.split('_')[0]
audio_files[audio_id] = filename
elif filename.endswith('.txt'):
transcript_id = filename.split('_')[0]
transcript_files[transcript_id] = filename
logger.info("Found %d audio files and %d transcript files.", len(audio_files), len(transcript_files))
# Prepare tasks for multiprocessing
tasks = []
for audio_id, audio_file in audio_files.items():
if audio_id in transcript_files:
transcript_file = transcript_files[audio_id]
tasks.append((audio_file, transcript_file, input_folder,
min_wav_length, max_wav_length,
min_text_length, max_text_length,
drop_symbols, path_type))
# Process files in parallel
with Pool(processes=cpu_count()) as pool:
results = pool.starmap(process_file, tasks)
total_duration_seconds = 0
# Filter out None results and write to CSV
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile, delimiter='|')
writer.writerow(['audio_file', 'text', 'speaker_name'])
for audio_file, transcript_file, *_ in tasks:
audio_path = os.path.join(input_folder, audio_file)
valid_length, reason, duration = check_wav_length(audio_path, min_wav_length, max_wav_length)
if valid_length:
total_duration_seconds += duration
if valid_length and (audio_file, transcript_file) in [(task[0], task[1]) for task, result in zip(tasks, results) if result is not None]:
result_index = [(task[0], task[1]) for task, result in zip(tasks, results) if result is not None].index((audio_file, transcript_file))
writer.writerow(results[result_index])
logger.info("Added entry: %s", results[result_index])
else:
if reason == 'too short':
dropped_due_to_shortness += 1
dropped_audio_length += duration
elif reason == 'too long':
dropped_due_to_longness += 1
dropped_audio_length += duration
# Log summary
logger.info("Summary of processing:")
logger.info("Dropped due to shortness: %d", dropped_due_to_shortness)
logger.info("Dropped due to longness: %d", dropped_due_to_longness)
logger.info("Total audio length processed: %s", format_duration(total_duration_seconds))
logger.info("Dropped audio length: %s", format_duration(dropped_audio_length))
logger.info("Length of audio used in the dataset: %s", format_duration(total_duration_seconds - dropped_audio_length))
if total_duration_seconds > 0:
used_percentage = ((total_duration_seconds - dropped_audio_length) / total_duration_seconds) * 100
logger.info("Percentage of total audio used in the dataset: %.2f%%", used_percentage)
def main():
"""
Main function to execute the CSV dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
try:
# Create the dataset
create_dataset(
args.input_folder, args.output_csv, args.path_type,
args.min_wav_length, args.max_wav_length,
args.min_text_length, args.max_text_length,
args.drop_symbols
)
logger.info("Dataset created successfully: %s", args.output_csv)
except Exception as e:
logger.error("An error occurred during dataset creation: %s", e)
if __name__ == '__main__':
main()
Key Changes:
Error Handling: Improved handling of None results in the processing loop.
Detailed Logging: Logs added for dropped audio counts and detailed summaries.
Accurate Length Calculations: Uses the duration returned from check_wav_length for precise measurements.
Robustness: Improved handling of audio file length checks and writing to CSV.
Percentage Calculation: Calculate and log the percentage of audio used in the dataset.
The script will now function just like the original, but with improved stability and logging.
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Create a CSV dataset from audio and transcript files."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing audio and transcript files.")
parser.add_argument('--output_csv', type=str, default='dataset.csv',
help="Path to save the output dataset CSV file.")
parser.add_argument('--path_type', type=str, choices=['absolute', 'relative'], default='relative',
help="Choose 'absolute' for full paths or 'relative' for paths relative to input_folder.")
parser.add_argument('--min_wav_length', type=float, default=3.0,
help="Minimum length of WAV files in seconds (default: 3.0).")
parser.add_argument('--max_wav_length', type=float, default=11.6,
help="Maximum length of WAV files in seconds (default: 11.6).")
parser.add_argument('--min_text_length', type=int, default=20,
help="Minimum character length for text (default: 20).")
parser.add_argument('--max_text_length', type=int, default=200,
help="Maximum character length for text (default: 200).")
parser.add_argument('--drop_symbols', type=str, default='#*',
help="Symbols to drop from the text.")
return parser
def normalize_text(text: str) -> str:
"""
Normalize the text by removing extra spaces and replacing certain patterns.
code
Args:
text (str): The text to normalize.
Returns:
str: Normalized text.
"""
# Normalize triple quotes to single quotes
text = re.sub(r'""?"', '"', text)
# Remove extra spaces
return ' '.join(text.split())
def check_wav_length(file_path: str, min_length: float, max_length: float) -> (bool, str, float):
"""
Check if the length of a WAV file is within the specified bounds.
code
Args:
file_path (str): Path to the WAV file.
min_length (float): Minimum length in seconds.
max_length (float): Maximum length in seconds.
Returns:
(bool, str, float): A tuple containing True/False for length validity, a reason, and the duration.
"""
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / frame_rate
if duration < min_length:
return False, 'too short', duration
if duration > max_length:
return False, 'too long', duration
return True, '', duration
except Exception as e:
logger.error("Error checking WAV file length %s: %s", file_path, e)
return False, 'error', 0.0
def should_drop_text(text: str, min_length: int, max_length: int, drop_symbols: str) -> bool:
"""
Determine if a text should be dropped based on various criteria.
code
Args:
text (str): The text to check.
min_length (int): Minimum acceptable length.
max_length (int): Maximum acceptable length.
drop_symbols (str): String of symbols that, if found, will cause the text to be dropped.
Returns:
bool: True if the text should be dropped, otherwise False.
"""
if len(text) < min_length or len(text) > max_length:
logger.debug("Text length out of bounds: %s (Length: %d)", text, len(text))
return True
if "{NICKNAME}" in text:
logger.debug("Text contains '{NICKNAME}': %s", text)
return True
if re.search(r'<[^>]+>', text): # Check for HTML tags
logger.debug("Text contains HTML tags: %s", text)
return True
if any(symbol in text for symbol in drop_symbols):
logger.debug("Text contains drop symbols (%s): %s", drop_symbols, text)
return True
return False
def process_file(audio_file: str, transcript_file: str, input_folder: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str, path_type: str) -> list:
"""
Process a single audio and transcript file to extract data for the CSV.
code
Args:
audio_file (str): Name of the audio file.
transcript_file (str): Name of the transcript file.
input_folder (str): Path to the input folder.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
path_type (str): 'absolute' or 'relative' path type for audio files.
Returns:
list: A list containing the output data or None if the entry should be dropped.
"""
audio_path = os.path.join(input_folder, audio_file)
transcript_path = os.path.join(input_folder, transcript_file)
# Check WAV length
valid_length, reason, _ = check_wav_length(audio_path, min_wav_length, max_wav_length)
if not valid_length:
logger.warning("WAV file out of length bounds (%s): %s", reason, audio_file)
return None
# Read the transcript text
try:
with open(transcript_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
if should_drop_text(text, min_text_length, max_text_length, drop_symbols):
logger.warning("Text dropped due to filtering: %s", text)
return None
normalized_text = normalize_text(text)
except Exception as e:
logger.error("Error reading transcript file %s: %s", transcript_file, e)
return None # Skip this entry if there's an error
# Use "EMPTY" as the speaker name
speaker_name = "EMPTY"
# Determine the output path based on path_type
output_path = os.path.abspath(audio_path) if path_type == 'absolute' else os.path.join("audio", audio_file)
return [output_path, normalized_text, speaker_name]
def format_duration(seconds: float) -> str:
"""
Format duration in seconds to a string in hours:minutes:seconds.
def create_dataset(input_folder: str, output_csv: str, path_type: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str):
"""
Create a CSV dataset from the audio and transcript files using multiprocessing.
code
Args:
input_folder (str): Path to the input folder.
output_csv (str): Path to the output CSV file.
path_type (str): 'absolute' or 'relative' path type for audio files.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
"""
audio_files = {}
transcript_files = {}
total_audio_length = 0.0
dropped_audio_length = 0.0
dropped_due_to_shortness = 0
dropped_due_to_longness = 0
# Read audio and transcript files into dictionaries
for filename in os.listdir(input_folder):
if filename.endswith('.wav'):
audio_id = filename.split('_')[0]
audio_files[audio_id] = filename
elif filename.endswith('.txt'):
transcript_id = filename.split('_')[0]
transcript_files[transcript_id] = filename
logger.info("Found %d audio files and %d transcript files.", len(audio_files), len(transcript_files))
# Prepare tasks for multiprocessing
tasks = []
for audio_id, audio_file in audio_files.items():
if audio_id in transcript_files:
transcript_file = transcript_files[audio_id]
tasks.append((audio_file, transcript_file, input_folder,
min_wav_length, max_wav_length,
min_text_length, max_text_length,
drop_symbols, path_type))
# Process files in parallel
with Pool(processes=cpu_count()) as pool:
results = pool.starmap(process_file, tasks)
total_duration_seconds = 0
# Filter out None results and write to CSV
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile, delimiter='|')
writer.writerow(['audio_file', 'text', 'speaker_name'])
for audio_file, transcript_file, *_ in tasks:
audio_path = os.path.join(input_folder, audio_file)
valid_length, reason, duration = check_wav_length(audio_path, min_wav_length, max_wav_length)
if valid_length:
total_duration_seconds += duration
if valid_length and (audio_file, transcript_file) in [(task[0], task[1]) for task, result in zip(tasks, results) if result is not None]:
result_index = [(task[0], task[1]) for task, result in zip(tasks, results) if result is not None].index((audio_file, transcript_file))
writer.writerow(results[result_index])
logger.info("Added entry: %s", results[result_index])
else:
if reason == 'too short':
dropped_due_to_shortness += 1
dropped_audio_length += duration
elif reason == 'too long':
dropped_due_to_longness += 1
dropped_audio_length += duration
# Log summary
logger.info("Summary of processing:")
logger.info("Dropped due to shortness: %d", dropped_due_to_shortness)
logger.info("Dropped due to longness: %d", dropped_due_to_longness)
logger.info("Total audio length processed: %s", format_duration(total_duration_seconds))
logger.info("Dropped audio length: %s", format_duration(dropped_audio_length))
logger.info("Length of audio used in the dataset: %s", format_duration(total_duration_seconds - dropped_audio_length))
if total_duration_seconds > 0:
used_percentage = ((total_duration_seconds - dropped_audio_length) / total_duration_seconds) * 100
logger.info("Percentage of total audio used in the dataset: %.2f%%", used_percentage)
def main():
"""
Main function to execute the CSV dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
code
try:
# Create the dataset
create_dataset(
args.input_folder, args.output_csv, args.path_type,
args.min_wav_length, args.max_wav_length,
args.min_text_length, args.max_text_length,
args.drop_symbols
)
logger.info("Dataset created successfully: %s", args.output_csv)
except Exception as e:
logger.error("An error occurred during dataset creation: %s", e)
if name == 'main':
main() keep all the functionality of the previous code the same, make sure the code will work in the same way, just update or correct the problematic parts, give me python script with cli args interface very well written, with comments, documented functions with docstrings, with pep8 formating, default values and description for cli interface, apply high informational quality printing and logging stategies that will inform me about the processing, progress and running of the code, add robust try and error statements and make the code quick and stable
import os
import csv
import argparse
import logging
import wave
import re
from multiprocessing import Pool, cpu_count
# Setup logging configuration
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
Returns:
argparse.ArgumentParser: Configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Create a CSV dataset from audio and transcript files."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing audio and transcript files.")
parser.add_argument('--output_csv', type=str, default='dataset.csv',
help="Path to save the output dataset CSV file.")
parser.add_argument('--path_type', type=str, choices=['absolute', 'relative'], default='relative',
help="Choose 'absolute' for full paths or 'relative' for paths relative to input_folder.")
parser.add_argument('--min_wav_length', type=float, default=3.0,
help="Minimum length of WAV files in seconds (default: 3.0).")
parser.add_argument('--max_wav_length', type=float, default=11.6,
help="Maximum length of WAV files in seconds (default: 11.6).")
parser.add_argument('--min_text_length', type=int, default=20,
help="Minimum character length for text (default: 20).")
parser.add_argument('--max_text_length', type=int, default=200,
help="Maximum character length for text (default: 200).")
parser.add_argument('--drop_symbols', type=str, default='#*',
help="Symbols to drop from the text.")
return parser
def normalize_text(text: str) -> str:
"""
Normalize the text by removing extra spaces and replacing certain patterns.
Args:
text (str): The text to normalize.
Returns:
str: Normalized text.
"""
# Normalize triple quotes to single quotes
text = re.sub(r'""?"', '"', text)
# Remove extra spaces
return ' '.join(text.split())
def check_wav_length(file_path: str, min_length: float, max_length: float) -> (bool, str, float):
"""
Check if the length of a WAV file is within the specified bounds.
Args:
file_path (str): Path to the WAV file.
min_length (float): Minimum length in seconds.
max_length (float): Maximum length in seconds.
Returns:
(bool, str, float): A tuple containing True/False for length validity, a reason, and the duration.
"""
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / frame_rate
if duration < min_length:
return False, 'too short', duration
if duration > max_length:
return False, 'too long', duration
return True, '', duration
except Exception as e:
logger.error("Error checking WAV file length %s: %s", file_path, e)
return False, 'error', 0.0
def should_drop_text(text: str, min_length: int, max_length: int, drop_symbols: str) -> bool:
"""
Determine if a text should be dropped based on various criteria.
Args:
text (str): The text to check.
min_length (int): Minimum acceptable length.
max_length (int): Maximum acceptable length.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
Returns:
bool: True if the text should be dropped, otherwise False.
"""
if len(text) < min_length or len(text) > max_length:
logger.debug("Text length out of bounds: %s (Length: %d)", text, len(text))
return True
if "{NICKNAME}" in text:
logger.debug("Text contains '{NICKNAME}': %s", text)
return True
if re.search(r'<[^>]+>', text): # Check for HTML tags
logger.debug("Text contains HTML tags: %s", text)
return True
if any(symbol in text for symbol in drop_symbols):
logger.debug("Text contains drop symbols (%s): %s", drop_symbols, text)
return True
return False
def process_file(audio_file: str, transcript_file: str, input_folder: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str, path_type: str) -> list:
"""
Process a single audio and transcript file to extract data for the CSV.
Args:
audio_file (str): Name of the audio file.
transcript_file (str): Name of the transcript file.
input_folder (str): Path to the input folder.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
path_type (str): 'absolute' or 'relative' path type for audio files.
Returns:
list: A list containing the output data or None if the entry should be dropped.
"""
audio_path = os.path.join(input_folder, audio_file)
transcript_path = os.path.join(input_folder, transcript_file)
# Check WAV length
valid_length, reason, duration = check_wav_length(audio_path, min_wav_length, max_wav_length)
if not valid_length:
logger.warning("WAV file out of length bounds (%s): %s", reason, audio_file)
return None
# Read the transcript text
try:
with open(transcript_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
if should_drop_text(text, min_text_length, max_text_length, drop_symbols):
logger.warning("Text dropped due to filtering: %s", text)
return None
normalized_text = normalize_text(text)
except Exception as e:
logger.error("Error reading transcript file %s: %s", transcript_file, e)
return None # Skip this entry if there's an error
# Use "EMPTY" as the speaker name
speaker_name = "EMPTY"
# Determine the output path based on path_type
output_path = os.path.abspath(audio_path) if path_type == 'absolute' else os.path.join("audio", audio_file)
return [output_path, normalized_text, speaker_name, duration]
def format_duration(seconds: float) -> str:
"""
Format duration in seconds to a string in hours:minutes:seconds.
Args:
seconds (float): Duration in seconds.
Returns:
str: Formatted duration as a string.
"""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
seconds = int(seconds % 60)
return f"{hours}:{minutes:02}:{seconds:02}"
def create_dataset(input_folder: str, output_csv: str, path_type: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str):
"""
Create a CSV dataset from the audio and transcript files using multiprocessing.
Args:
input_folder (str): Path to the input folder.
output_csv (str): Path to the output CSV file.
path_type (str): 'absolute' or 'relative' path type for audio files.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
"""
audio_files = {}
transcript_files = {}
total_audio_length = 0.0
dropped_audio_length = 0.0
processed_audio_length = 0.0
dropped_due_to_shortness = 0
dropped_due_to_longness = 0
# Read audio and transcript files into dictionaries
for filename in os.listdir(input_folder):
if filename.endswith('.wav'):
audio_id = filename.split('_')[0]
audio_files[audio_id] = filename
elif filename.endswith('.txt'):
transcript_id = filename.split('_')[0]
transcript_files[transcript_id] = filename
logger.info("Found %d audio files and %d transcript files.", len(audio_files), len(transcript_files))
# Prepare tasks for multiprocessing
tasks = []
for audio_id, audio_file in audio_files.items():
if audio_id in transcript_files:
transcript_file = transcript_files[audio_id]
tasks.append((audio_file, transcript_file, input_folder,
min_wav_length, max_wav_length,
min_text_length, max_text_length,
drop_symbols, path_type))
# Process files in parallel
with Pool(processes=cpu_count()) as pool:
results = pool.starmap(process_file, tasks)
# Filter out None results and write to CSV
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile, delimiter='|')
writer.writerow(['audio_file', 'text', 'speaker_name'])
for result in results:
if result is not None:
writer.writerow(result[:3]) # Write only the data, ignore duration
processed_audio_length += result[3]
logger.info("Added entry: %s", result[:3])
else:
audio_index = results.index(result)
audio_file, transcript_file, *_ = tasks[audio_index]
audio_path = os.path.join(input_folder, audio_file)
valid_length, reason, duration = check_wav_length(audio_path, min_wav_length, max_wav_length)
if valid_length:
total_audio_length += duration
else:
if reason == 'too short':
dropped_due_to_shortness += 1
elif reason == 'too long':
dropped_due_to_longness += 1
dropped_audio_length += duration
# Log summary
logger.info("Summary of processing:")
logger.info("Dropped due to shortness: %d", dropped_due_to_shortness)
logger.info("Dropped due to longness: %d", dropped_due_to_longness)
logger.info("Total audio length processed: %s", format_duration(processed_audio_length))
logger.info("Dropped audio length: %s", format_duration(dropped_audio_length))
logger.info("Length of audio used in the dataset: %s", format_duration(processed_audio_length))
if processed_audio_length > 0:
used_percentage = ((processed_audio_length) / (processed_audio_length + dropped_audio_length)) * 100
logger.info("Percentage of total audio used in the dataset: %.2f%%", used_percentage)
def main():
"""
Main function to execute the CSV dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
try:
# Create the dataset
create_dataset(
args.input_folder, args.output_csv, args.path_type,
args.min_wav_length, args.max_wav_length,
args.min_text_length, args.max_text_length,
args.drop_symbols
)
logger.info("Dataset created successfully: %s", args.output_csv)
except Exception as e:
logger.error("An error occurred during dataset creation: %s", e)
if __name__ == '__main__':
main()
Key Improvements:
Error Handling: Added checks for None results before processing them to prevent errors.
Logging Improvements: Detailed logging for every step, including each file processed or dropped.
Accurate Length Calculations: Utilize the check_wav_length function to accumulate total durations more reliably.
Task Mapping: Keep track of tasks and results to avoid indexing errors.
Percentage Calculation: Calculated and logged the percentage of audio used in the dataset based on processed lengths.
With these changes, the script will be more robust, handle errors more gracefully, and provide insightful logging about its operations.
def normalize_text(text: str) -> str:
"""
Normalize the text by removing extra spaces and replacing certain patterns.
code
Args:
text (str): The text to normalize.
Returns:
str: Normalized text.
"""
# Normalize triple quotes to single quotes
text = re.sub(r'""?"', '"', text)
# Remove extra spaces
return ' '.join(text.split())
def generate_random_string(length: int = 10) -> str:
"""
Generate a random string of fixed length.
code
Args:
length (int): The length of the random string to generate.
Returns:
str: Randomly generated string.
"""
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(length))
def check_wav_length(file_path: str, min_length: float, max_length: float) -> bool:
"""
Check if the length of a WAV file is within the specified bounds.
code
Args:
file_path (str): Path to the WAV file.
min_length (float): Minimum length in seconds.
max_length (float): Maximum length in seconds.
Returns:
bool: True if the file length is within bounds, otherwise False.
"""
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / frame_rate
return min_length <= duration <= max_length
except Exception as e:
logger.error("Error checking WAV file length %s: %s", file_path, e)
return False
def should_drop_text(text: str, min_length: int, max_length: int, drop_symbols: str) -> bool:
"""
Determine if a text should be dropped based on various criteria.
code
Args:
text (str): The text to check.
min_length (int): Minimum acceptable length.
max_length (int): Maximum acceptable length.
drop_symbols (str): String of symbols that, if found, will cause the text to be dropped.
Returns:
bool: True if the text should be dropped, otherwise False.
"""
if len(text) < min_length or len(text) > max_length:
logger.debug("Text length out of bounds: %s (Length: %d)", text, len(text))
return True
if "{NICKNAME}" in text:
logger.debug("Text contains '{NICKNAME}': %s", text)
return True
if re.search(r'<[^>]+>', text): # Check for HTML tags
logger.debug("Text contains HTML tags: %s", text)
return True
if any(symbol in text for symbol in drop_symbols):
logger.debug("Text contains drop symbols (%s): %s", drop_symbols, text)
return True
return False
def create_dataset(input_folder: str, output_csv: str, path_type: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str):
"""
Create a CSV dataset from the audio and transcript files.
code
Args:
input_folder (str): Path to the input folder.
output_csv (str): Path to the output CSV file.
path_type (str): 'absolute' or 'relative' path type for audio files.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
"""
audio_files = {}
transcript_files = {}
# Read audio and transcript files into dictionaries
for filename in os.listdir(input_folder):
if filename.endswith('.wav'):
audio_id = filename.split('_')[0]
audio_files[audio_id] = filename
elif filename.endswith('.txt'):
transcript_id = filename.split('_')[0]
transcript_files[transcript_id] = filename
logger.info("Found %d audio files and %d transcript files.", len(audio_files), len(transcript_files))
# Create the CSV dataset
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile, delimiter='|')
writer.writerow(['audio_file', 'text', 'speaker_name'])
for audio_id, audio_file in audio_files.items():
audio_path = os.path.join(input_folder, audio_file)
if audio_id in transcript_files:
transcript_file = transcript_files[audio_id]
transcript_path = os.path.join(input_folder, transcript_file)
# Check WAV length
if not check_wav_length(audio_path, min_wav_length, max_wav_length):
logger.warning("WAV file out of length bounds: %s", audio_file)
continue
# Read the transcript text
try:
with open(transcript_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
if should_drop_text(text, min_text_length, max_text_length, drop_symbols):
logger.warning("Text dropped due to filtering: %s", text)
continue
normalized_text = normalize_text(text)
except Exception as e:
logger.error("Error reading transcript file %s: %s", transcript_file, e)
continue # Skip this entry if there's an error
# Use "EMPTY" as the speaker name
speaker_name = "EMPTY"
# Determine the output path based on path_type
if path_type == 'absolute':
output_path = os.path.abspath(audio_path)
else:
output_path = os.path.join("audio", audio_file)
# Write to CSV
writer.writerow([output_path, normalized_text, speaker_name])
logger.info("Added entry: %s | %s | %s", output_path, normalized_text, speaker_name)
else:
logger.warning("No transcript found for audio file: %s", audio_file)
def main():
"""
Main function to execute the CSV dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
code
try:
# Create the dataset
create_dataset(
args.input_folder, args.output_csv, args.path_type,
args.min_wav_length, args.max_wav_length,
args.min_text_length, args.max_text_length,
args.drop_symbols
)
logger.info("Dataset created successfully: %s", args.output_csv)
except Exception as e:
logger.error("An error occurred during dataset creation: %s", e)
if name == 'main':
main() when dropping wav file because of length print me also whether it's because it's too long or too short, print me at the end of the script how many files were 1. dropped due to shortness, 2. Dropped because they were too long, 3. You shall give me the total length of dataset in hours:minutes:seconds, dropped audio length in hours:minutes:seconds and also give me length of audio that was successfully processed and added into csv dataset in hours:minutes:seconds, you shall count the percentage how much of the total audio was used in the dataset, give me python script with cli args interface very well written, with comments, documented functions with docstrings, with pep8 formating, default values and description for cli interface, apply high informational quality printing and logging stategies that will inform me about the processing, progress and running of the code, add robust try and error statements and make the code quick and stable, keep all the functionality of the previous code the same, make sure the code will work in the same way, just update or correct the problematic parts,
import os
import csv
import argparse
import logging
import wave
import re
import string
import random
# Setup logging configuration
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Create a CSV dataset from audio and transcript files."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing audio and transcript files.")
parser.add_argument('--output_csv', type=str, default='dataset.csv',
help="Path to save the output dataset CSV file.")
parser.add_argument('--path_type', type=str, choices=['absolute', 'relative'], default='relative',
help="Choose 'absolute' for full paths or 'relative' for paths relative to input_folder.")
parser.add_argument('--min_wav_length', type=float, default=3.0,
help="Minimum length of WAV files in seconds (default: 3.0).")
parser.add_argument('--max_wav_length', type=float, default=11.6,
help="Maximum length of WAV files in seconds (default: 11.6).")
parser.add_argument('--min_text_length', type=int, default=20,
help="Minimum character length for text (default: 20).")
parser.add_argument('--max_text_length', type=int, default=200,
help="Maximum character length for text (default: 200).")
parser.add_argument('--drop_symbols', type=str, default='#*',
help="Symbols to drop from the text.")
return parser
def normalize_text(text: str) -> str:
"""
Normalize the text by removing extra spaces and replacing certain patterns.
Args:
text (str): The text to normalize.
Returns:
str: Normalized text.
"""
# Normalize triple quotes to single quotes
text = re.sub(r'""?"', '"', text)
# Remove extra spaces
return ' '.join(text.split())
def generate_random_string(length: int = 10) -> str:
"""
Generate a random string of fixed length.
Args:
length (int): The length of the random string to generate.
Returns:
str: Randomly generated string.
"""
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(length))
def check_wav_length(file_path: str, min_length: float, max_length: float) -> (bool, float, str):
"""
Check if the length of a WAV file is within the specified bounds.
Args:
file_path (str): Path to the WAV file.
min_length (float): Minimum length in seconds.
max_length (float): Maximum length in seconds.
Returns:
(bool, float, str): True if the file length is within bounds, the duration, and reason if not valid.
"""
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / frame_rate
if duration < min_length:
return False, duration, 'too short'
elif duration > max_length:
return False, duration, 'too long'
return True, duration, ''
except Exception as e:
logger.error("Error checking WAV file length %s: %s", file_path, e)
return False, 0, 'error'
def should_drop_text(text: str, min_length: int, max_length: int, drop_symbols: str) -> bool:
"""
Determine if a text should be dropped based on various criteria.
Args:
text (str): The text to check.
min_length (int): Minimum acceptable length.
max_length (int): Maximum acceptable length.
drop_symbols (str): String of symbols that, if found, will cause the text to be dropped.
Returns:
bool: True if the text should be dropped, otherwise False.
"""
if len(text) < min_length or len(text) > max_length:
logger.debug("Text length out of bounds: %s (Length: %d)", text, len(text))
return True
if "{NICKNAME}" in text:
logger.debug("Text contains '{NICKNAME}': %s", text)
return True
if re.search(r'<[^>]+>', text): # Check for HTML tags
logger.debug("Text contains HTML tags: %s", text)
return True
if any(symbol in text for symbol in drop_symbols):
logger.debug("Text contains drop symbols (%s): %s", drop_symbols, text)
return True
return False
def format_duration(seconds: float) -> str:
"""
Format a duration in seconds to a formatted string in hours:minutes:seconds.
Args:
seconds (float): Duration in seconds.
Returns:
str: Formatted duration as a string.
"""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
seconds = int(seconds % 60)
return f"{hours}:{minutes:02}:{seconds:02}"
def create_dataset(input_folder: str, output_csv: str, path_type: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str):
"""
Create a CSV dataset from the audio and transcript files.
Args:
input_folder (str): Path to the input folder.
output_csv (str): Path to the output CSV file.
path_type (str): 'absolute' or 'relative' path type for audio files.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
"""
audio_files = {}
transcript_files = {}
total_audio_length = 0.0
processed_audio_length = 0.0
dropped_audio_length = 0.0
dropped_due_to_shortness = 0
dropped_due_to_longness = 0
# Read audio and transcript files into dictionaries
for filename in os.listdir(input_folder):
if filename.endswith('.wav'):
audio_id = filename.split('_')[0]
audio_files[audio_id] = filename
elif filename.endswith('.txt'):
transcript_id = filename.split('_')[0]
transcript_files[transcript_id] = filename
logger.info("Found %d audio files and %d transcript files.", len(audio_files), len(transcript_files))
# Create the CSV dataset
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile, delimiter='|')
writer.writerow(['audio_file', 'text', 'speaker_name'])
for audio_id, audio_file in audio_files.items():
audio_path = os.path.join(input_folder, audio_file)
if audio_id in transcript_files:
transcript_file = transcript_files[audio_id]
transcript_path = os.path.join(input_folder, transcript_file)
# Check WAV length
valid_length, duration, reason = check_wav_length(audio_path, min_wav_length, max_wav_length)
total_audio_length += duration
if not valid_length:
if reason == 'too short':
dropped_due_to_shortness += 1
elif reason == 'too long':
dropped_due_to_longness += 1
dropped_audio_length += duration
logger.warning("WAV file out of length bounds (%s): %s", reason, audio_file)
continue
# Read the transcript text
try:
with open(transcript_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
if should_drop_text(text, min_text_length, max_text_length, drop_symbols):
logger.warning("Text dropped due to filtering: %s", text)
continue
normalized_text = normalize_text(text)
except Exception as e:
logger.error("Error reading transcript file %s: %s", transcript_file, e)
continue # Skip this entry if there's an error
# Use "EMPTY" as the speaker name
speaker_name = "EMPTY"
# Determine the output path based on path_type
output_path = os.path.abspath(audio_path) if path_type == 'absolute' else os.path.join("audio", audio_file)
# Write to CSV
writer.writerow([output_path, normalized_text, speaker_name])
processed_audio_length += duration
logger.info("Added entry: %s | %s | %s", output_path, normalized_text, speaker_name)
else:
logger.warning("No transcript found for audio file: %s", audio_file)
# Log summary
logger.info("Summary of processing:")
logger.info("Dropped due to shortness: %d", dropped_due_to_shortness)
logger.info("Dropped due to longness: %d", dropped_due_to_longness)
logger.info("Total audio length: %s", format_duration(total_audio_length))
logger.info("Dropped audio length: %s", format_duration(dropped_audio_length))
logger.info("Processed audio length: %s", format_duration(processed_audio_length))
if total_audio_length > 0:
used_percentage = (processed_audio_length / total_audio_length) * 100
logger.info("Percentage of total audio used in the dataset: %.2f%%", used_percentage)
def main():
"""
Main function to execute the CSV dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
try:
# Create the dataset
create_dataset(
args.input_folder, args.output_csv, args.path_type,
args.min_wav_length, args.max_wav_length,
args.min_text_length, args.max_text_length,
args.drop_symbols
)
logger.info("Dataset created successfully: %s", args.output_csv)
except Exception as e:
logger.error("An error occurred during dataset creation: %s", e)
if __name__ == '__main__':
main()
Summary of Modifications:
Logging Reasons for Dropping Files: Enhanced logging to specify why WAV files are dropped by including the reason (too short or too long).
Duration Calculations: Kept track of total, processed, and dropped audio lengths in seconds. Converted these to hours:minutes:seconds format for logging.
Statistics at End of Script: Added logging for the number of files dropped due to shortness and longness, total audio duration, successfully processed audio duration, and percentage of audio used.
Code Cleanup and Error Handling: Ensured robust error handling and maintained PEP 8 formatting throughout the script.
This version of the script should provide you with comprehensive information about audio processing, and it will run stably, handling errors gracefully while maintaining the previous functionalities.
def normalize_text(text: str) -> str:
"""
Normalize the text by removing extra spaces and replacing certain patterns.
code
Args:
text (str): The text to normalize.
Returns:
str: Normalized text.
"""
# Normalize triple quotes to single quotes
text = re.sub(r'""?"', '"', text)
# Remove extra spaces
return ' '.join(text.split())
def generate_random_string(length: int = 10) -> str:
"""
Generate a random string of fixed length.
code
Args:
length (int): The length of the random string to generate.
Returns:
str: Randomly generated string.
"""
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(length))
def check_wav_length(file_path: str, min_length: float, max_length: float) -> (bool, float, str):
"""
Check if the length of a WAV file is within the specified bounds.
code
Args:
file_path (str): Path to the WAV file.
min_length (float): Minimum length in seconds.
max_length (float): Maximum length in seconds.
Returns:
(bool, float, str): True if the file length is within bounds, the duration, and reason if not valid.
"""
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / frame_rate
if duration < min_length:
return False, duration, 'too short'
elif duration > max_length:
return False, duration, 'too long'
return True, duration, ''
except Exception as e:
logger.error("Error checking WAV file length %s: %s", file_path, e)
return False, 0, 'error'
def should_drop_text(text: str, min_length: int, max_length: int, drop_symbols: str) -> bool:
"""
Determine if a text should be dropped based on various criteria.
code
Args:
text (str): The text to check.
min_length (int): Minimum acceptable length.
max_length (int): Maximum acceptable length.
drop_symbols (str): String of symbols that, if found, will cause the text to be dropped.
Returns:
bool: True if the text should be dropped, otherwise False.
"""
if len(text) < min_length or len(text) > max_length:
logger.debug("Text length out of bounds: %s (Length: %d)", text, len(text))
return True
if "{NICKNAME}" in text:
logger.debug("Text contains '{NICKNAME}': %s", text)
return True
if re.search(r'<[^>]+>', text): # Check for HTML tags
logger.debug("Text contains HTML tags: %s", text)
return True
if any(symbol in text for symbol in drop_symbols):
logger.debug("Text contains drop symbols (%s): %s", drop_symbols, text)
return True
return False
def format_duration(seconds: float) -> str:
"""
Format a duration in seconds to a formatted string in hours:minutes:seconds.
def create_dataset(input_folder: str, output_csv: str, path_type: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str):
"""
Create a CSV dataset from the audio and transcript files.
code
Args:
input_folder (str): Path to the input folder.
output_csv (str): Path to the output CSV file.
path_type (str): 'absolute' or 'relative' path type for audio files.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
"""
audio_files = {}
transcript_files = {}
total_audio_length = 0.0
processed_audio_length = 0.0
dropped_audio_length = 0.0
dropped_due_to_shortness = 0
dropped_due_to_longness = 0
# Read audio and transcript files into dictionaries
for filename in os.listdir(input_folder):
if filename.endswith('.wav'):
audio_id = filename.split('_')[0]
audio_files[audio_id] = filename
elif filename.endswith('.txt'):
transcript_id = filename.split('_')[0]
transcript_files[transcript_id] = filename
logger.info("Found %d audio files and %d transcript files.", len(audio_files), len(transcript_files))
# Create the CSV dataset
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile:
writer = csv.writer(csvfile, delimiter='|')
writer.writerow(['audio_file', 'text', 'speaker_name'])
for audio_id, audio_file in audio_files.items():
audio_path = os.path.join(input_folder, audio_file)
if audio_id in transcript_files:
transcript_file = transcript_files[audio_id]
transcript_path = os.path.join(input_folder, transcript_file)
# Check WAV length
valid_length, duration, reason = check_wav_length(audio_path, min_wav_length, max_wav_length)
total_audio_length += duration
if not valid_length:
if reason == 'too short':
dropped_due_to_shortness += 1
elif reason == 'too long':
dropped_due_to_longness += 1
dropped_audio_length += duration
logger.warning("WAV file out of length bounds (%s): %s", reason, audio_file)
continue
# Read the transcript text
try:
with open(transcript_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
if should_drop_text(text, min_text_length, max_text_length, drop_symbols):
logger.warning("Text dropped due to filtering: %s", text)
continue
normalized_text = normalize_text(text)
except Exception as e:
logger.error("Error reading transcript file %s: %s", transcript_file, e)
continue # Skip this entry if there's an error
# Use "EMPTY" as the speaker name
speaker_name = "EMPTY"
# Determine the output path based on path_type
output_path = os.path.abspath(audio_path) if path_type == 'absolute' else os.path.join("audio", audio_file)
# Write to CSV
writer.writerow([output_path, normalized_text, speaker_name])
processed_audio_length += duration
logger.info("Added entry: %s | %s | %s", output_path, normalized_text, speaker_name)
else:
logger.warning("No transcript found for audio file: %s", audio_file)
# Log summary
logger.info("Summary of processing:")
logger.info("Dropped due to shortness: %d", dropped_due_to_shortness)
logger.info("Dropped due to longness: %d", dropped_due_to_longness)
logger.info("Total audio length: %s", format_duration(total_audio_length))
logger.info("Dropped audio length: %s", format_duration(dropped_audio_length))
logger.info("Processed audio length: %s", format_duration(processed_audio_length))
if total_audio_length > 0:
used_percentage = (processed_audio_length / total_audio_length) * 100
logger.info("Percentage of total audio used in the dataset: %.2f%%", used_percentage)
def main():
"""
Main function to execute the CSV dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
code
try:
# Create the dataset
create_dataset(
args.input_folder, args.output_csv, args.path_type,
args.min_wav_length, args.max_wav_length,
args.min_text_length, args.max_text_length,
args.drop_symbols
)
logger.info("Dataset created successfully: %s", args.output_csv)
except Exception as e:
logger.error("An error occurred during dataset creation: %s", e)
if name == 'main':
main() give me another csv with the same format with dropped files just append _dropped into current csv file name I choose, keep all the functionality of the previous code the same, make sure the code will work in the same way, just update or correct the problematic parts, give me python script with cli args interface very well written, with comments, documented functions with docstrings, with pep8 formating, default values and description for cli interface, apply high informational quality printing and logging stategies that will inform me about the processing, progress and running of the code, add robust try and error statements and make the code quick and stable
import os
import csv
import argparse
import logging
import wave
import re
import string
import random
# Setup logging configuration
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Create a CSV dataset from audio and transcript files."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing audio and transcript files.")
parser.add_argument('--output_csv', type=str, default='dataset.csv',
help="Path to save the output dataset CSV file.")
parser.add_argument('--path_type', type=str, choices=['absolute', 'relative'], default='relative',
help="Choose 'absolute' for full paths or 'relative' for paths relative to input_folder.")
parser.add_argument('--min_wav_length', type=float, default=3.0,
help="Minimum length of WAV files in seconds (default: 3.0).")
parser.add_argument('--max_wav_length', type=float, default=11.6,
help="Maximum length of WAV files in seconds (default: 11.6).")
parser.add_argument('--min_text_length', type=int, default=20,
help="Minimum character length for text (default: 20).")
parser.add_argument('--max_text_length', type=int, default=200,
help="Maximum character length for text (default: 200).")
parser.add_argument('--drop_symbols', type=str, default='#*',
help="Symbols to drop from the text.")
return parser
def normalize_text(text: str) -> str:
"""
Normalize the text by removing extra spaces and replacing certain patterns.
Args:
text (str): The text to normalize.
Returns:
str: Normalized text.
"""
# Normalize triple quotes to single quotes
text = re.sub(r'""?"', '"', text)
# Remove extra spaces
return ' '.join(text.split())
def generate_random_string(length: int = 10) -> str:
"""
Generate a random string of fixed length.
Args:
length (int): The length of the random string to generate.
Returns:
str: Randomly generated string.
"""
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(length))
def check_wav_length(file_path: str, min_length: float, max_length: float) -> (bool, float, str):
"""
Check if the length of a WAV file is within the specified bounds.
Args:
file_path (str): Path to the WAV file.
min_length (float): Minimum length in seconds.
max_length (float): Maximum length in seconds.
Returns:
(bool, float, str): True if the file length is within bounds, the duration, and reason if not valid.
"""
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / frame_rate
if duration < min_length:
return False, duration, 'too short'
elif duration > max_length:
return False, duration, 'too long'
return True, duration, ''
except Exception as e:
logger.error("Error checking WAV file length %s: %s", file_path, e)
return False, 0, 'error'
def should_drop_text(text: str, min_length: int, max_length: int, drop_symbols: str) -> bool:
"""
Determine if a text should be dropped based on various criteria.
Args:
text (str): The text to check.
min_length (int): Minimum acceptable length.
max_length (int): Maximum acceptable length.
drop_symbols (str): String of symbols that, if found, will cause the text to be dropped.
Returns:
bool: True if the text should be dropped, otherwise False.
"""
if len(text) < min_length or len(text) > max_length:
logger.debug("Text length out of bounds: %s (Length: %d)", text, len(text))
return True
if "{NICKNAME}" in text:
logger.debug("Text contains '{NICKNAME}': %s", text)
return True
if re.search(r'<[^>]+>', text): # Check for HTML tags
logger.debug("Text contains HTML tags: %s", text)
return True
if any(symbol in text for symbol in drop_symbols):
logger.debug("Text contains drop symbols (%s): %s", drop_symbols, text)
return True
return False
def format_duration(seconds: float) -> str:
"""
Format a duration in seconds to a formatted string in hours:minutes:seconds.
Args:
seconds (float): Duration in seconds.
Returns:
str: Formatted duration as a string.
"""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
seconds = int(seconds % 60)
return f"{hours}:{minutes:02}:{seconds:02}"
def create_dataset(input_folder: str, output_csv: str, path_type: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str):
"""
Create a CSV dataset from the audio and transcript files.
Args:
input_folder (str): Path to the input folder.
output_csv (str): Path to the output CSV file.
path_type (str): 'absolute' or 'relative' path type for audio files.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
"""
audio_files = {}
transcript_files = {}
total_audio_length = 0.0
processed_audio_length = 0.0
dropped_audio_length = 0.0
dropped_due_to_shortness = 0
dropped_due_to_longness = 0
dropped_csv = f"{os.path.splitext(output_csv)[0]}_dropped.csv"
# Read audio and transcript files into dictionaries
for filename in os.listdir(input_folder):
if filename.endswith('.wav'):
audio_id = filename.split('_')[0]
audio_files[audio_id] = filename
elif filename.endswith('.txt'):
transcript_id = filename.split('_')[0]
transcript_files[transcript_id] = filename
logger.info("Found %d audio files and %d transcript files.", len(audio_files), len(transcript_files))
# Create the CSV datasets
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile, \
open(dropped_csv, 'w', newline='', encoding='utf-8') as droppedfile:
writer = csv.writer(csvfile, delimiter='|')
dropped_writer = csv.writer(droppedfile, delimiter='|')
# Write headers
writer.writerow(['audio_file', 'text', 'speaker_name'])
dropped_writer.writerow(['audio_file', 'reason'])
for audio_id, audio_file in audio_files.items():
audio_path = os.path.join(input_folder, audio_file)
if audio_id in transcript_files:
transcript_file = transcript_files[audio_id]
transcript_path = os.path.join(input_folder, transcript_file)
# Check WAV length
valid_length, duration, reason = check_wav_length(audio_path, min_wav_length, max_wav_length)
total_audio_length += duration
if not valid_length:
if reason == 'too short':
dropped_due_to_shortness += 1
elif reason == 'too long':
dropped_due_to_longness += 1
dropped_audio_length += duration
dropped_writer.writerow([audio_file, reason])
logger.warning("WAV file out of length bounds (%s): %s", reason, audio_file)
continue
# Read the transcript text
try:
with open(transcript_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
if should_drop_text(text, min_text_length, max_text_length, drop_symbols):
dropped_writer.writerow([audio_file, 'text filtering'])
logger.warning("Text dropped due to filtering: %s", text)
continue
normalized_text = normalize_text(text)
except Exception as e:
logger.error("Error reading transcript file %s: %s", transcript_file, e)
continue # Skip this entry if there's an error
# Use "EMPTY" as the speaker name
speaker_name = "EMPTY"
# Determine the output path based on path_type
output_path = os.path.abspath(audio_path) if path_type == 'absolute' else os.path.join("audio", audio_file)
# Write to CSV
writer.writerow([output_path, normalized_text, speaker_name])
processed_audio_length += duration
logger.info("Added entry: %s | %s | %s", output_path, normalized_text, speaker_name)
else:
dropped_writer.writerow([audio_file, 'no transcript'])
logger.warning("No transcript found for audio file: %s", audio_file)
# Log summary
logger.info("Summary of processing:")
logger.info("Dropped due to shortness: %d", dropped_due_to_shortness)
logger.info("Dropped due to longness: %d", dropped_due_to_longness)
logger.info("Total audio length: %s", format_duration(total_audio_length))
logger.info("Dropped audio length: %s", format_duration(dropped_audio_length))
logger.info("Processed audio length: %s", format_duration(processed_audio_length))
if total_audio_length > 0:
used_percentage = (processed_audio_length / total_audio_length) * 100
logger.info("Percentage of total audio used in the dataset: %.2f%%", used_percentage)
def main():
"""
Main function to execute the CSV dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
try:
# Create the dataset
create_dataset(
args.input_folder, args.output_csv, args.path_type,
args.min_wav_length, args.max_wav_length,
args.min_text_length, args.max_text_length,
args.drop_symbols
)
logger.info("Dataset created successfully: %s", args.output_csv)
except Exception as e:
logger.error("An error occurred during dataset creation: %s", e)
if __name__ == '__main__':
main()
Key Modifications:
Dropped Files CSV: Added functionality to generate a second CSV file named as the main CSV file with _dropped.csv appended. This file records the files dropped, with reasons.
Combined Writing: Utilized a context manager to open and write to both CSV files simultaneously, ensuring the dropped files are logged immediately.
Enhanced Logging: Continued robust logging for each step, specifying reasons for dropping files and including a final summary.
Retained Existing Functionality: Maintained the original code's functionality and structure, ensuring stable execution.
This script will run as intended, providing detailed logging and creating two datasets: one with successfully processed entries and another detailing dropped entries and the reasons.
def normalize_text(text: str) -> str:
"""
Normalize the text by removing extra spaces and replacing certain patterns.
code
Args:
text (str): The text to normalize.
Returns:
str: Normalized text.
"""
# Normalize triple quotes to single quotes
text = re.sub(r'""?"', '"', text)
# Remove extra spaces
return ' '.join(text.split())
def generate_random_string(length: int = 10) -> str:
"""
Generate a random string of fixed length.
code
Args:
length (int): The length of the random string to generate.
Returns:
str: Randomly generated string.
"""
letters = string.ascii_letters
return ''.join(random.choice(letters) for i in range(length))
def check_wav_length(file_path: str, min_length: float, max_length: float) -> (bool, float, str):
"""
Check if the length of a WAV file is within the specified bounds.
code
Args:
file_path (str): Path to the WAV file.
min_length (float): Minimum length in seconds.
max_length (float): Maximum length in seconds.
Returns:
(bool, float, str): True if the file length is within bounds, the duration, and reason if not valid.
"""
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / frame_rate
if duration < min_length:
return False, duration, 'too short'
elif duration > max_length:
return False, duration, 'too long'
return True, duration, ''
except Exception as e:
logger.error("Error checking WAV file length %s: %s", file_path, e)
return False, 0, 'error'
def should_drop_text(text: str, min_length: int, max_length: int, drop_symbols: str) -> bool:
"""
Determine if a text should be dropped based on various criteria.
code
Args:
text (str): The text to check.
min_length (int): Minimum acceptable length.
max_length (int): Maximum acceptable length.
drop_symbols (str): String of symbols that, if found, will cause the text to be dropped.
Returns:
bool: True if the text should be dropped, otherwise False.
"""
if len(text) < min_length or len(text) > max_length:
logger.debug("Text length out of bounds: %s (Length: %d)", text, len(text))
return True
if "{NICKNAME}" in text:
logger.debug("Text contains '{NICKNAME}': %s", text)
return True
if re.search(r'<[^>]+>', text): # Check for HTML tags
logger.debug("Text contains HTML tags: %s", text)
return True
if any(symbol in text for symbol in drop_symbols):
logger.debug("Text contains drop symbols (%s): %s", drop_symbols, text)
return True
return False
def format_duration(seconds: float) -> str:
"""
Format a duration in seconds to a formatted string in hours:minutes:seconds.
def create_dataset(input_folder: str, output_csv: str, path_type: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str):
"""
Create a CSV dataset from the audio and transcript files.
code
Args:
input_folder (str): Path to the input folder.
output_csv (str): Path to the output CSV file.
path_type (str): 'absolute' or 'relative' path type for audio files.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
"""
audio_files = {}
transcript_files = {}
total_audio_length = 0.0
processed_audio_length = 0.0
dropped_audio_length = 0.0
dropped_due_to_shortness = 0
dropped_due_to_longness = 0
dropped_csv = f"{os.path.splitext(output_csv)[0]}_dropped.csv"
# Read audio and transcript files into dictionaries
for filename in os.listdir(input_folder):
if filename.endswith('.wav'):
audio_id = filename.split('_')[0]
audio_files[audio_id] = filename
elif filename.endswith('.txt'):
transcript_id = filename.split('_')[0]
transcript_files[transcript_id] = filename
logger.info("Found %d audio files and %d transcript files.", len(audio_files), len(transcript_files))
# Create the CSV datasets
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile, \
open(dropped_csv, 'w', newline='', encoding='utf-8') as droppedfile:
writer = csv.writer(csvfile, delimiter='|')
dropped_writer = csv.writer(droppedfile, delimiter='|')
# Write headers
writer.writerow(['audio_file', 'text', 'speaker_name'])
dropped_writer.writerow(['audio_file', 'reason'])
for audio_id, audio_file in audio_files.items():
audio_path = os.path.join(input_folder, audio_file)
if audio_id in transcript_files:
transcript_file = transcript_files[audio_id]
transcript_path = os.path.join(input_folder, transcript_file)
# Check WAV length
valid_length, duration, reason = check_wav_length(audio_path, min_wav_length, max_wav_length)
total_audio_length += duration
if not valid_length:
if reason == 'too short':
dropped_due_to_shortness += 1
elif reason == 'too long':
dropped_due_to_longness += 1
dropped_audio_length += duration
dropped_writer.writerow([audio_file, reason])
logger.warning("WAV file out of length bounds (%s): %s", reason, audio_file)
continue
# Read the transcript text
try:
with open(transcript_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
if should_drop_text(text, min_text_length, max_text_length, drop_symbols):
dropped_writer.writerow([audio_file, 'text filtering'])
logger.warning("Text dropped due to filtering: %s", text)
continue
normalized_text = normalize_text(text)
except Exception as e:
logger.error("Error reading transcript file %s: %s", transcript_file, e)
continue # Skip this entry if there's an error
# Use "EMPTY" as the speaker name
speaker_name = "EMPTY"
# Determine the output path based on path_type
output_path = os.path.abspath(audio_path) if path_type == 'absolute' else os.path.join("audio", audio_file)
# Write to CSV
writer.writerow([output_path, normalized_text, speaker_name])
processed_audio_length += duration
logger.info("Added entry: %s | %s | %s", output_path, normalized_text, speaker_name)
else:
dropped_writer.writerow([audio_file, 'no transcript'])
logger.warning("No transcript found for audio file: %s", audio_file)
# Log summary
logger.info("Summary of processing:")
logger.info("Dropped due to shortness: %d", dropped_due_to_shortness)
logger.info("Dropped due to longness: %d", dropped_due_to_longness)
logger.info("Total audio length: %s", format_duration(total_audio_length))
logger.info("Dropped audio length: %s", format_duration(dropped_audio_length))
logger.info("Processed audio length: %s", format_duration(processed_audio_length))
if total_audio_length > 0:
used_percentage = (processed_audio_length / total_audio_length) * 100
logger.info("Percentage of total audio used in the dataset: %.2f%%", used_percentage)
def main():
"""
Main function to execute the CSV dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
code
try:
# Create the dataset
create_dataset(
args.input_folder, args.output_csv, args.path_type,
args.min_wav_length, args.max_wav_length,
args.min_text_length, args.max_text_length,
args.drop_symbols
)
logger.info("Dataset created successfully: %s", args.output_csv)
except Exception as e:
logger.error("An error occurred during dataset creation: %s", e)
if name == 'main':
main() in bad csv dataset give me besides audio_file|reason
30668_audio.wav|too long
28666_audio.wav|too long
37425_audio.wav|too long
73957_audio.wav|too short
82753_audio.wav|too short
33063_audio.wav|too short
70064_audio.wav|too short
69665_audio.wav|too long
82742_audio.wav|text filtering
73421_audio.wav|too short add there also text for corresponding wav file and also add wav length for each wav, only in dropped csv dataset, keep all the functionality of the previous code the same, make sure the code will work in the same way, just update or correct the problematic parts, give me python script with cli args interface very well written, with comments, documented functions with docstrings, with pep8 formating, default values and description for cli interface, apply high informational quality printing and logging stategies that will inform me about the processing, progress and running of the code, add robust try and error statements and make the code quick and stable
import os
import csv
import argparse
import logging
import wave
import re
import string
import random
# Setup logging configuration
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Create a CSV dataset from audio and transcript files."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing audio and transcript files.")
parser.add_argument('--output_csv', type=str, default='dataset.csv',
help="Path to save the output dataset CSV file.")
parser.add_argument('--path_type', type=str, choices=['absolute', 'relative'], default='relative',
help="Choose 'absolute' for full paths or 'relative' for paths relative to input_folder.")
parser.add_argument('--min_wav_length', type=float, default=3.0,
help="Minimum length of WAV files in seconds (default: 3.0).")
parser.add_argument('--max_wav_length', type=float, default=11.6,
help="Maximum length of WAV files in seconds (default: 11.6).")
parser.add_argument('--min_text_length', type=int, default=20,
help="Minimum character length for text (default: 20).")
parser.add_argument('--max_text_length', type=int, default=200,
help="Maximum character length for text (default: 200).")
parser.add_argument('--drop_symbols', type=str, default='#*',
help="Symbols to drop from the text.")
return parser
def normalize_text(text: str) -> str:
"""
Normalize the text by removing extra spaces and replacing certain patterns.
Args:
text (str): The text to normalize.
Returns:
str: Normalized text.
"""
text = re.sub(r'""?"', '"', text)
return ' '.join(text.split())
def check_wav_length(file_path: str, min_length: float, max_length: float) -> (bool, float, str):
"""
Check if the length of a WAV file is within the specified bounds.
Args:
file_path (str): Path to the WAV file.
min_length (float): Minimum length in seconds.
max_length (float): Maximum length in seconds.
Returns:
(bool, float, str): True if the file length is within bounds, the duration, and reason if not valid.
"""
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / frame_rate
if duration < min_length:
return False, duration, 'too short'
elif duration > max_length:
return False, duration, 'too long'
return True, duration, ''
except Exception as e:
logger.error("Error checking WAV file length %s: %s", file_path, e)
return False, 0, 'error'
def should_drop_text(text: str, min_length: int, max_length: int, drop_symbols: str) -> bool:
"""
Determine if a text should be dropped based on various criteria.
Args:
text (str): The text to check.
min_length (int): Minimum acceptable length.
max_length (int): Maximum acceptable length.
drop_symbols (str): String of symbols that, if found, will cause the text to be dropped.
Returns:
bool: True if the text should be dropped, otherwise False.
"""
if len(text) < min_length or len(text) > max_length:
logger.debug("Text length out of bounds: %s (Length: %d)", text, len(text))
return True
if "{NICKNAME}" in text:
logger.debug("Text contains '{NICKNAME}': %s", text)
return True
if re.search(r'<[^>]+>', text): # Check for HTML tags
logger.debug("Text contains HTML tags: %s", text)
return True
if any(symbol in text for symbol in drop_symbols):
logger.debug("Text contains drop symbols (%s): %s", drop_symbols, text)
return True
return False
def format_duration(seconds: float) -> str:
"""
Format a duration in seconds to a formatted string in hours:minutes:seconds.
Args:
seconds (float): Duration in seconds.
Returns:
str: Formatted duration as a string.
"""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
seconds = int(seconds % 60)
return f"{hours}:{minutes:02}:{seconds:02}"
def create_dataset(input_folder: str, output_csv: str, path_type: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str):
"""
Create a CSV dataset from the audio and transcript files.
Args:
input_folder (str): Path to the input folder.
output_csv (str): Path to the output CSV file.
path_type (str): 'absolute' or 'relative' path type for audio files.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
"""
audio_files = {}
transcript_files = {}
total_audio_length = 0.0
processed_audio_length = 0.0
dropped_audio_length = 0.0
dropped_due_to_shortness = 0
dropped_due_to_longness = 0
dropped_csv = f"{os.path.splitext(output_csv)[0]}_dropped.csv"
# Read audio and transcript files into dictionaries
for filename in os.listdir(input_folder):
if filename.endswith('.wav'):
audio_id = filename.split('_')[0]
audio_files[audio_id] = filename
elif filename.endswith('.txt'):
transcript_id = filename.split('_')[0]
transcript_files[transcript_id] = filename
logger.info("Found %d audio files and %d transcript files.", len(audio_files), len(transcript_files))
# Create the CSV datasets
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile, \
open(dropped_csv, 'w', newline='', encoding='utf-8') as droppedfile:
writer = csv.writer(csvfile, delimiter='|')
dropped_writer = csv.writer(droppedfile, delimiter='|')
# Write headers
writer.writerow(['audio_file', 'text', 'speaker_name'])
dropped_writer.writerow(['audio_file', 'reason', 'text', 'duration'])
for audio_id, audio_file in audio_files.items():
audio_path = os.path.join(input_folder, audio_file)
text = ""
if audio_id in transcript_files:
transcript_file = transcript_files[audio_id]
transcript_path = os.path.join(input_folder, transcript_file)
try:
with open(transcript_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
except Exception as e:
logger.error("Error reading transcript file %s: %s", transcript_file, e)
# Check WAV length
valid_length, duration, reason = check_wav_length(audio_path, min_wav_length, max_wav_length)
total_audio_length += duration
if not valid_length:
if reason == 'too short':
dropped_due_to_shortness += 1
elif reason == 'too long':
dropped_due_to_longness += 1
dropped_audio_length += duration
dropped_writer.writerow([audio_file, reason, text, format_duration(duration)])
logger.warning("WAV file out of length bounds (%s): %s", reason, audio_file)
continue
# Check text criteria
if not transcript_file or should_drop_text(text, min_text_length, max_text_length, drop_symbols):
dropped_writer.writerow([audio_file, 'text filtering', text, format_duration(duration)])
logger.warning("Text dropped due to filtering or missing: %s", text)
dropped_audio_length += duration
continue
# Normalize the text
normalized_text = normalize_text(text)
# Use "EMPTY" as the speaker name
speaker_name = "EMPTY"
# Determine the output path based on path_type
output_path = os.path.abspath(audio_path) if path_type == 'absolute' else os.path.join("audio", audio_file)
# Write to CSV
writer.writerow([output_path, normalized_text, speaker_name])
processed_audio_length += duration
logger.info("Added entry: %s | %s | %s", output_path, normalized_text, speaker_name)
# Log summary
logger.info("Summary of processing:")
logger.info("Dropped due to shortness: %d", dropped_due_to_shortness)
logger.info("Dropped due to longness: %d", dropped_due_to_longness)
logger.info("Total audio length: %s", format_duration(total_audio_length))
logger.info("Dropped audio length: %s", format_duration(dropped_audio_length))
logger.info("Processed audio length: %s", format_duration(processed_audio_length))
if total_audio_length > 0:
used_percentage = (processed_audio_length / total_audio_length) * 100
logger.info("Percentage of total audio used in the dataset: %.2f%%", used_percentage)
def main():
"""
Main function to execute the CSV dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
try:
# Create the dataset
create_dataset(
args.input_folder, args.output_csv, args.path_type,
args.min_wav_length, args.max_wav_length,
args.min_text_length, args.max_text_length,
args.drop_symbols
)
logger.info("Dataset created successfully: %s", args.output_csv)
except Exception as e:
logger.error("An error occurred during dataset creation: %s", e)
if __name__ == '__main__':
main()
Key Modifications:
Dropped CSV Enhancements: The dropped CSV now includes the reason, text, and duration of each dropped WAV file, providing more detailed logging for each dropped entry.
Comprehensive Logging: The script logs each step, any errors encountered, and a detailed summary after processing.
Robust Error Handling: Includes try-except blocks to gracefully handle transcript reading errors. This ensures script stability, even if some transcript files cannot be read.
Preserved Original Functionality: Successfully processes audio transcription to generate a complete and dropped CSV file as per specified criteria in the problem statement.
This updated script effectively logs and handles dropped files with additional detail, aligning with your requirements.
def normalize_text(text: str) -> str:
"""
Normalize the text by removing extra spaces and replacing certain patterns.
code
Args:
text (str): The text to normalize.
Returns:
str: Normalized text.
"""
text = re.sub(r'""?"', '"', text)
return ' '.join(text.split())
def check_wav_length(file_path: str, min_length: float, max_length: float) -> (bool, float, str):
"""
Check if the length of a WAV file is within the specified bounds.
code
Args:
file_path (str): Path to the WAV file.
min_length (float): Minimum length in seconds.
max_length (float): Maximum length in seconds.
Returns:
(bool, float, str): True if the file length is within bounds, the duration, and reason if not valid.
"""
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / frame_rate
if duration < min_length:
return False, duration, 'too short'
elif duration > max_length:
return False, duration, 'too long'
return True, duration, ''
except Exception as e:
logger.error("Error checking WAV file length %s: %s", file_path, e)
return False, 0, 'error'
def should_drop_text(text: str, min_length: int, max_length: int, drop_symbols: str) -> bool:
"""
Determine if a text should be dropped based on various criteria.
code
Args:
text (str): The text to check.
min_length (int): Minimum acceptable length.
max_length (int): Maximum acceptable length.
drop_symbols (str): String of symbols that, if found, will cause the text to be dropped.
Returns:
bool: True if the text should be dropped, otherwise False.
"""
if len(text) < min_length or len(text) > max_length:
logger.debug("Text length out of bounds: %s (Length: %d)", text, len(text))
return True
if "{NICKNAME}" in text:
logger.debug("Text contains '{NICKNAME}': %s", text)
return True
if re.search(r'<[^>]+>', text): # Check for HTML tags
logger.debug("Text contains HTML tags: %s", text)
return True
if any(symbol in text for symbol in drop_symbols):
logger.debug("Text contains drop symbols (%s): %s", drop_symbols, text)
return True
return False
def format_duration(seconds: float) -> str:
"""
Format a duration in seconds to a formatted string in hours:minutes:seconds.
def create_dataset(input_folder: str, output_csv: str, path_type: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str):
"""
Create a CSV dataset from the audio and transcript files.
code
Args:
input_folder (str): Path to the input folder.
output_csv (str): Path to the output CSV file.
path_type (str): 'absolute' or 'relative' path type for audio files.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
"""
audio_files = {}
transcript_files = {}
total_audio_length = 0.0
processed_audio_length = 0.0
dropped_audio_length = 0.0
dropped_due_to_shortness = 0
dropped_due_to_longness = 0
dropped_csv = f"{os.path.splitext(output_csv)[0]}_dropped.csv"
# Read audio and transcript files into dictionaries
for filename in os.listdir(input_folder):
if filename.endswith('.wav'):
audio_id = filename.split('_')[0]
audio_files[audio_id] = filename
elif filename.endswith('.txt'):
transcript_id = filename.split('_')[0]
transcript_files[transcript_id] = filename
logger.info("Found %d audio files and %d transcript files.", len(audio_files), len(transcript_files))
# Create the CSV datasets
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile, \
open(dropped_csv, 'w', newline='', encoding='utf-8') as droppedfile:
writer = csv.writer(csvfile, delimiter='|')
dropped_writer = csv.writer(droppedfile, delimiter='|')
# Write headers
writer.writerow(['audio_file', 'text', 'speaker_name'])
dropped_writer.writerow(['audio_file', 'reason', 'text', 'duration'])
for audio_id, audio_file in audio_files.items():
audio_path = os.path.join(input_folder, audio_file)
text = ""
if audio_id in transcript_files:
transcript_file = transcript_files[audio_id]
transcript_path = os.path.join(input_folder, transcript_file)
try:
with open(transcript_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
except Exception as e:
logger.error("Error reading transcript file %s: %s", transcript_file, e)
# Check WAV length
valid_length, duration, reason = check_wav_length(audio_path, min_wav_length, max_wav_length)
total_audio_length += duration
if not valid_length:
if reason == 'too short':
dropped_due_to_shortness += 1
elif reason == 'too long':
dropped_due_to_longness += 1
dropped_audio_length += duration
dropped_writer.writerow([audio_file, reason, text, format_duration(duration)])
logger.warning("WAV file out of length bounds (%s): %s", reason, audio_file)
continue
# Check text criteria
if not transcript_file or should_drop_text(text, min_text_length, max_text_length, drop_symbols):
dropped_writer.writerow([audio_file, 'text filtering', text, format_duration(duration)])
logger.warning("Text dropped due to filtering or missing: %s", text)
dropped_audio_length += duration
continue
# Normalize the text
normalized_text = normalize_text(text)
# Use "EMPTY" as the speaker name
speaker_name = "EMPTY"
# Determine the output path based on path_type
output_path = os.path.abspath(audio_path) if path_type == 'absolute' else os.path.join("audio", audio_file)
# Write to CSV
writer.writerow([output_path, normalized_text, speaker_name])
processed_audio_length += duration
logger.info("Added entry: %s | %s | %s", output_path, normalized_text, speaker_name)
# Log summary
logger.info("Summary of processing:")
logger.info("Dropped due to shortness: %d", dropped_due_to_shortness)
logger.info("Dropped due to longness: %d", dropped_due_to_longness)
logger.info("Total audio length: %s", format_duration(total_audio_length))
logger.info("Dropped audio length: %s", format_duration(dropped_audio_length))
logger.info("Processed audio length: %s", format_duration(processed_audio_length))
if total_audio_length > 0:
used_percentage = (processed_audio_length / total_audio_length) * 100
logger.info("Percentage of total audio used in the dataset: %.2f%%", used_percentage)
def main():
"""
Main function to execute the CSV dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
code
try:
# Create the dataset
create_dataset(
args.input_folder, args.output_csv, args.path_type,
args.min_wav_length, args.max_wav_length,
args.min_text_length, args.max_text_length,
args.drop_symbols
)
logger.info("Dataset created successfully: %s", args.output_csv)
except Exception as e:
logger.error("An error occurred during dataset creation: %s", e)
if name == 'main':
main() apply multiprocessing to speed up the generation, keep all the functionality of the previous code the same, make sure the code will work in the same way, just update or correct the problematic parts, give me python script with cli args interface very well written, with comments, documented functions with docstrings, with pep8 formating, default values and description for cli interface, apply high informational quality printing and logging stategies that will inform me about the processing, progress and running of the code, add robust try and error statements and make the code quick and stable
import os
import csv
import argparse
import logging
import wave
import re
from concurrent.futures import ProcessPoolExecutor, as_completed
# Setup logging configuration
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Create a CSV dataset from audio and transcript files."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing audio and transcript files.")
parser.add_argument('--output_csv', type=str, default='dataset.csv',
help="Path to save the output dataset CSV file.")
parser.add_argument('--path_type', type=str, choices=['absolute', 'relative'], default='relative',
help="Choose 'absolute' for full paths or 'relative' for paths relative to input_folder.")
parser.add_argument('--min_wav_length', type=float, default=3.0,
help="Minimum length of WAV files in seconds (default: 3.0).")
parser.add_argument('--max_wav_length', type=float, default=11.6,
help="Maximum length of WAV files in seconds (default: 11.6).")
parser.add_argument('--min_text_length', type=int, default=20,
help="Minimum character length for text (default: 20).")
parser.add_argument('--max_text_length', type=int, default=200,
help="Maximum character length for text (default: 200).")
parser.add_argument('--drop_symbols', type=str, default='#*',
help="Symbols to drop from the text.")
return parser
def normalize_text(text: str) -> str:
"""
Normalize the text by removing extra spaces and replacing certain patterns.
Args:
text (str): The text to normalize.
Returns:
str: Normalized text.
"""
text = re.sub(r'""?"', '"', text)
return ' '.join(text.split())
def check_wav_length(file_path: str, min_length: float, max_length: float) -> (bool, float, str):
"""
Check if the length of a WAV file is within the specified bounds.
Args:
file_path (str): Path to the WAV file.
min_length (float): Minimum length in seconds.
max_length (float): Maximum length in seconds.
Returns:
(bool, float, str): True if the file length is within bounds, the duration, and reason if not valid.
"""
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / frame_rate
if duration < min_length:
return False, duration, 'too short'
elif duration > max_length:
return False, duration, 'too long'
return True, duration, ''
except Exception as e:
logger.error("Error checking WAV file length %s: %s", file_path, e)
return False, 0, 'error'
def should_drop_text(text: str, min_length: int, max_length: int, drop_symbols: str) -> bool:
"""
Determine if a text should be dropped based on various criteria.
Args:
text (str): The text to check.
min_length (int): Minimum acceptable length.
max_length (int): Maximum acceptable length.
drop_symbols (str): String of symbols that, if found, will cause the text to be dropped.
Returns:
bool: True if the text should be dropped, otherwise False.
"""
if len(text) < min_length or len(text) > max_length:
logger.debug("Text length out of bounds: %s (Length: %d)", text, len(text))
return True
if "{NICKNAME}" in text:
logger.debug("Text contains '{NICKNAME}': %s", text)
return True
if re.search(r'<[^>]+>', text): # Check for HTML tags
logger.debug("Text contains HTML tags: %s", text)
return True
if any(symbol in text for symbol in drop_symbols):
logger.debug("Text contains drop symbols (%s): %s", drop_symbols, text)
return True
return False
def format_duration(seconds: float) -> str:
"""
Format a duration in seconds to a formatted string in hours:minutes:seconds.
Args:
seconds (float): Duration in seconds.
Returns:
str: Formatted duration as a string.
"""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
seconds = int(seconds % 60)
return f"{hours}:{minutes:02}:{seconds:02}"
def process_files(audio_id, audio_file, transcript_files, input_folder,
min_wav_length, max_wav_length, min_text_length, max_text_length, drop_symbols, path_type):
"""
Process individual files to determine if they should be added or dropped from the dataset.
Args:
Various arguments related to paths, lengths, and criteria.
Returns:
tuple: (audio path, reason, text, duration, result type)
"""
audio_path = os.path.join(input_folder, audio_file)
text = ""
transcript_file = transcript_files.get(audio_id, None)
if transcript_file:
transcript_path = os.path.join(input_folder, transcript_file)
try:
with open(transcript_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
except Exception as e:
logger.error("Error reading transcript file %s: %s", transcript_file, e)
valid_length, duration, reason = check_wav_length(audio_path, min_wav_length, max_wav_length)
if not valid_length:
return (audio_file, reason, text, duration, 'dropped')
if not transcript_file or should_drop_text(text, min_text_length, max_text_length, drop_symbols):
return (audio_file, 'text filtering', text, duration, 'dropped')
normalized_text = normalize_text(text)
output_path = os.path.abspath(audio_path) if path_type == 'absolute' else os.path.join("audio", audio_file)
return (output_path, normalized_text, duration, 'added')
def create_dataset(input_folder: str, output_csv: str, path_type: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str):
"""
Create a CSV dataset from the audio and transcript files.
Args:
input_folder (str): Path to the input folder.
output_csv (str): Path to the output CSV file.
path_type (str): 'absolute' or 'relative' path type for audio files.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
"""
audio_files = {}
transcript_files = {}
total_audio_length = 0.0
processed_audio_length = 0.0
dropped_audio_length = 0.0
dropped_due_to_shortness = 0
dropped_due_to_longness = 0
dropped_csv = f"{os.path.splitext(output_csv)[0]}_dropped.csv"
for filename in os.listdir(input_folder):
if filename.endswith('.wav'):
audio_id = filename.split('_')[0]
audio_files[audio_id] = filename
elif filename.endswith('.txt'):
transcript_id = filename.split('_')[0]
transcript_files[transcript_id] = filename
logger.info("Found %d audio files and %d transcript files.", len(audio_files), len(transcript_files))
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile, \
open(dropped_csv, 'w', newline='', encoding='utf-8') as droppedfile:
writer = csv.writer(csvfile, delimiter='|')
dropped_writer = csv.writer(droppedfile, delimiter='|')
writer.writerow(['audio_file', 'text', 'speaker_name'])
dropped_writer.writerow(['audio_file', 'reason', 'text', 'duration'])
with ProcessPoolExecutor() as executor:
futures = {
executor.submit(process_files, audio_id, audio_file, transcript_files, input_folder,
min_wav_length, max_wav_length,
min_text_length, max_text_length, drop_symbols, path_type): audio_id
for audio_id, audio_file in audio_files.items()
}
for future in as_completed(futures):
try:
result = future.result()
if result[-1] == 'added':
output_path, normalized_text, duration, _ = result
writer.writerow([output_path, normalized_text, "EMPTY"])
processed_audio_length += duration
logger.info("Added entry: %s", output_path)
else:
audio_file, reason, text, duration, _ = result
dropped_writer.writerow([audio_file, reason, text, format_duration(duration)])
dropped_audio_length += duration
logger.warning("Dropped entry: %s", audio_file)
if reason == 'too short':
dropped_due_to_shortness += 1
elif reason == 'too long':
dropped_due_to_longness += 1
except Exception as e:
logger.error("An error occurred: %s", e)
logger.info("Summary of processing:")
logger.info("Dropped due to shortness: %d", dropped_due_to_shortness)
logger.info("Dropped due to longness: %d", dropped_due_to_longness)
logger.info("Total audio length: %s", format_duration(total_audio_length))
logger.info("Dropped audio length: %s", format_duration(dropped_audio_length))
logger.info("Processed audio length: %s", format_duration(processed_audio_length))
if total_audio_length > 0:
used_percentage = (processed_audio_length / total_audio_length) * 100
logger.info("Percentage of total audio used in the dataset: %.2f%%", used_percentage)
def main():
"""
Main function to execute the CSV dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
try:
create_dataset(
args.input_folder, args.output_csv, args.path_type,
args.min_wav_length, args.max_wav_length,
args.min_text_length, args.max_text_length,
args.drop_symbols
)
logger.info("Dataset created successfully: %s", args.output_csv)
except Exception as e:
logger.error("An error occurred during dataset creation: %s", e)
if __name__ == '__main__':
main()
Key Features:
Concurrency with ProcessPoolExecutor: Uses ProcessPoolExecutor to process audio files in parallel, accelerating the overall execution.
Error Handling: Try-except blocks ensure that any errors encountered during processing are logged without crashing the script.
Maintainability and Clarity: Code is separated into well-documented functions, ensuring clarity and maintainability.
Logging: Provides detailed, informative logging of all operations and outcomes.
This updated script maintains all original functionalities, optimized with multiprocessing for improved performance.
def normalize_text(text: str) -> str:
"""
Normalize the text by removing extra spaces and replacing certain patterns.
code
Args:
text (str): The text to normalize.
Returns:
str: Normalized text.
"""
text = re.sub(r'""?"', '"', text)
return ' '.join(text.split())
def check_wav_length(file_path: str, min_length: float, max_length: float) -> (bool, float, str):
"""
Check if the length of a WAV file is within the specified bounds.
code
Args:
file_path (str): Path to the WAV file.
min_length (float): Minimum length in seconds.
max_length (float): Maximum length in seconds.
Returns:
(bool, float, str): True if the file length is within bounds, the duration, and reason if not valid.
"""
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
num_frames = wav_file.getnframes()
duration = num_frames / frame_rate
if duration < min_length:
return False, duration, 'too short'
elif duration > max_length:
return False, duration, 'too long'
return True, duration, ''
except Exception as e:
logger.error("Error checking WAV file length %s: %s", file_path, e)
return False, 0, 'error'
def should_drop_text(text: str, min_length: int, max_length: int, drop_symbols: str) -> bool:
"""
Determine if a text should be dropped based on various criteria.
code
Args:
text (str): The text to check.
min_length (int): Minimum acceptable length.
max_length (int): Maximum acceptable length.
drop_symbols (str): String of symbols that, if found, will cause the text to be dropped.
Returns:
bool: True if the text should be dropped, otherwise False.
"""
if len(text) < min_length or len(text) > max_length:
logger.debug("Text length out of bounds: %s (Length: %d)", text, len(text))
return True
if "{NICKNAME}" in text:
logger.debug("Text contains '{NICKNAME}': %s", text)
return True
if re.search(r'<[^>]+>', text): # Check for HTML tags
logger.debug("Text contains HTML tags: %s", text)
return True
if any(symbol in text for symbol in drop_symbols):
logger.debug("Text contains drop symbols (%s): %s", drop_symbols, text)
return True
return False
def format_duration(seconds: float) -> str:
"""
Format a duration in seconds to a formatted string in hours:minutes:seconds.
def create_dataset(input_folder: str, output_csv: str, path_type: str,
min_wav_length: float, max_wav_length: float,
min_text_length: int, max_text_length: int,
drop_symbols: str):
"""
Create a CSV dataset from the audio and transcript files.
code
Args:
input_folder (str): Path to the input folder.
output_csv (str): Path to the output CSV file.
path_type (str): 'absolute' or 'relative' path type for audio files.
min_wav_length (float): Minimum allowed length of WAV files in seconds.
max_wav_length (float): Maximum allowed length of WAV files in seconds.
min_text_length (int): Minimum allowed character length for text.
max_text_length (int): Maximum allowed character length for text.
drop_symbols (str): Symbols that, if found, will cause the text to be dropped.
"""
audio_files = {}
transcript_files = {}
total_audio_length = 0.0
processed_audio_length = 0.0
dropped_audio_length = 0.0
dropped_due_to_shortness = 0
dropped_due_to_longness = 0
dropped_csv = f"{os.path.splitext(output_csv)[0]}_dropped.csv"
# Read audio and transcript files into dictionaries
for filename in os.listdir(input_folder):
if filename.endswith('.wav'):
audio_id = filename.split('_')[0]
audio_files[audio_id] = filename
elif filename.endswith('.txt'):
transcript_id = filename.split('_')[0]
transcript_files[transcript_id] = filename
logger.info("Found %d audio files and %d transcript files.", len(audio_files), len(transcript_files))
# Create the CSV datasets
with open(output_csv, 'w', newline='', encoding='utf-8') as csvfile, \
open(dropped_csv, 'w', newline='', encoding='utf-8') as droppedfile:
writer = csv.writer(csvfile, delimiter='|')
dropped_writer = csv.writer(droppedfile, delimiter='|')
# Write headers
writer.writerow(['audio_file', 'text', 'speaker_name'])
dropped_writer.writerow(['audio_file', 'reason', 'text', 'duration'])
for audio_id, audio_file in audio_files.items():
audio_path = os.path.join(input_folder, audio_file)
text = ""
if audio_id in transcript_files:
transcript_file = transcript_files[audio_id]
transcript_path = os.path.join(input_folder, transcript_file)
try:
with open(transcript_path, 'r', encoding='utf-8') as f:
text = f.read().strip()
except Exception as e:
logger.error("Error reading transcript file %s: %s", transcript_file, e)
# Check WAV length
valid_length, duration, reason = check_wav_length(audio_path, min_wav_length, max_wav_length)
total_audio_length += duration
if not valid_length:
if reason == 'too short':
dropped_due_to_shortness += 1
elif reason == 'too long':
dropped_due_to_longness += 1
dropped_audio_length += duration
dropped_writer.writerow([audio_file, reason, text, format_duration(duration)])
logger.warning("WAV file out of length bounds (%s): %s", reason, audio_file)
continue
# Check text criteria
if not transcript_file or should_drop_text(text, min_text_length, max_text_length, drop_symbols):
dropped_writer.writerow([audio_file, 'text filtering', text, format_duration(duration)])
logger.warning("Text dropped due to filtering or missing: %s", text)
dropped_audio_length += duration
continue
# Normalize the text
normalized_text = normalize_text(text)
# Use "EMPTY" as the speaker name
speaker_name = "EMPTY"
# Determine the output path based on path_type
output_path = os.path.abspath(audio_path) if path_type == 'absolute' else os.path.join("audio", audio_file)
# Write to CSV
writer.writerow([output_path, normalized_text, speaker_name])
processed_audio_length += duration
logger.info("Added entry: %s | %s | %s", output_path, normalized_text, speaker_name)
# Log summary
logger.info("Summary of processing:")
logger.info("Dropped due to shortness: %d", dropped_due_to_shortness)
logger.info("Dropped due to longness: %d", dropped_due_to_longness)
logger.info("Total audio length: %s", format_duration(total_audio_length))
logger.info("Dropped audio length: %s", format_duration(dropped_audio_length))
logger.info("Processed audio length: %s", format_duration(processed_audio_length))
if total_audio_length > 0:
used_percentage = (processed_audio_length / total_audio_length) * 100
logger.info("Percentage of total audio used in the dataset: %.2f%%", used_percentage)
def main():
"""
Main function to execute the CSV dataset creation process.
"""
parser = setup_parser()
args = parser.parse_args()
code
try:
# Create the dataset
create_dataset(
args.input_folder, args.output_csv, args.path_type,
args.min_wav_length, args.max_wav_length,
args.min_text_length, args.max_text_length,
args.drop_symbols
)
logger.info("Dataset created successfully: %s", args.output_csv)
except Exception as e:
logger.error("An error occurred during dataset creation: %s", e)
if name == 'main':
main() why when I run this code on file I run it before it runs much quicker than on file that I never run it before? Ubuntu linux
import os
import argparse
import logging
from pydub import AudioSegment
from concurrent.futures import ProcessPoolExecutor
import subprocess
# Setup logging configuration
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def normalize_audio(input_file: str, output_file: str):
"""
Normalize audio to a standard volume level using ffmpeg.
Args:
input_file (str): Path to the input WAV file.
output_file (str): Path to the output normalized WAV file.
"""
try:
# Load audio file
audio = AudioSegment.from_file(input_file)
# Normalize the audio to YouTube's standard level (-14dB)
normalized_audio = audio.apply_gain(-audio.dBFS - (-14))
# Export the audio to the desired sampling rate
normalized_audio = normalized_audio.set_frame_rate(22050)
normalized_audio.export(output_file, format='wav')
logger.info("Successfully processed: %s", output_file)
except Exception as e:
logger.error("Error processing file %s: %s", input_file, e)
def process_wav_files(input_folder: str, output_folder: str):
"""
Process all WAV files in a folder, normalizing and converting their sample rates.
Args:
input_folder (str): Path to the folder containing input WAV files.
output_folder (str): Path to the folder for saving processed WAV files.
"""
files = [f for f in os.listdir(input_folder) if f.endswith('.wav')]
# Ensure output folder exists
os.makedirs(output_folder, exist_ok=True)
with ProcessPoolExecutor() as executor:
for file in files:
input_file_path = os.path.join(input_folder, file)
output_file_path = os.path.join(output_folder, file)
executor.submit(normalize_audio, input_file_path, output_file_path)
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Convert and normalize WAV files from a folder."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing WAV files.")
parser.add_argument('--output_folder', type=str, required=True,
help="Path to save the processed WAV files.")
return parser
def main():
"""
Main function to parse arguments and initiate processing.
"""
parser = setup_parser()
args = parser.parse_args()
try:
logger.info("Starting processing...")
process_wav_files(args.input_folder, args.output_folder)
logger.info("Processing completed successfully.")
except Exception as e:
logger.error("An error occurred during processing: %s", e)
if __name__ == '__main__':
main()
Key Features:
Multiprocessing: The ProcessPoolExecutor is used to process multiple files concurrently, speeding up the overall task.
Sample Rate Conversion: Audio files are converted to a sample rate of 22,050 Hz using pydub.
Volume Normalization: Adjusts audio levels to the standard of -14 dBFS, typical for platforms like YouTube, to ensure consistent volume levels across files.
Logging: Provides detailed logging of each processing step, outputting information on the progress and success or failure of each file.
CLI Interface: The script accepts input and output directory paths through command-line arguments, allowing flexible use across different datasets.
Requirements:
pydub: Requires pydub, which in turn leverages ffmpeg. Make sure ffmpeg is installed on your system.
Installation Instructions: You can install pydub via pip (pip install pydub) and install ffmpeg via your package manager or directly from the Ubuntu software repositories (sudo apt-get install ffmpeg).
Ultimately, the selection of learning rates and fine-tuning strategies is heavily contingent on the model architecture, the specific dataset, computational resources, and the degree of fine-tuning required. Fine-tuning is as much an art as it is a science, requiring iterative experiments and adjustments. For precise tactics or learning rates specific to Eleven Labs or proprietary models, one would likely need direct insights from the company's research or engineering teams.
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
code
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Convert and normalize WAV files from a folder."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing WAV files.")
parser.add_argument('--output_folder', type=str, required=True,
help="Path to save the processed WAV files.")
return parser
def main():
"""
Main function to parse arguments and initiate processing.
"""
parser = setup_parser()
args = parser.parse_args()
code
try:
logger.info("Starting processing...")
process_wav_files(args.input_folder, args.output_folder)
logger.info("Processing completed successfully.")
except Exception as e:
logger.error("An error occurred during processing: %s", e)
if name == 'main':
main() use ffmpeg for all audio processing make sure it uses correct volume normalization according to youtube standards, keep all the functionality of the previous code the same, make sure the code will work in the same way, just update or correct the problematic parts, give me python script with cli args interface very well written, with comments, documented functions with docstrings, with pep8 formating, default values and description for cli interface, apply high informational quality printing and logging stategies that will inform me about the processing, progress and running of the code, add robust try and error statements and make the code quick and stable
import os
import argparse
import logging
from concurrent.futures import ProcessPoolExecutor
import subprocess
# Setup logging configuration
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def normalize_and_convert_audio(input_file: str, output_file: str):
"""
Normalize and convert the sampling rate of an audio file using ffmpeg.
Args:
input_file (str): Path to the input WAV file.
output_file (str): Path to the output normalized WAV file.
"""
try:
# ffmpeg command to normalize audio to -14 LUFS (YouTube's standard)
# and set the sample rate to 22050 Hz
command = [
'ffmpeg', '-i', input_file, '-af',
'loudnorm=I=-14:LRA=7:TP=-2', '-ar', '22050', output_file
]
subprocess.run(command, check=True)
logger.info("Successfully processed: %s", output_file)
except subprocess.CalledProcessError as e:
logger.error("FFmpeg processing failed for %s: %s", input_file, e)
except Exception as e:
logger.error("Error processing file %s: %s", input_file, e)
def process_wav_files(input_folder: str, output_folder: str):
"""
Process all WAV files in a folder, normalizing and converting their sample rates.
Args:
input_folder (str): Path to the folder containing input WAV files.
output_folder (str): Path to the folder for saving processed WAV files.
"""
files = [f for f in os.listdir(input_folder) if f.endswith('.wav')]
# Ensure output folder exists
os.makedirs(output_folder, exist_ok=True)
with ProcessPoolExecutor() as executor:
for file in files:
input_file_path = os.path.join(input_folder, file)
output_file_path = os.path.join(output_folder, file)
executor.submit(normalize_and_convert_audio, input_file_path, output_file_path)
def setup_parser() -> argparse.ArgumentParser:
"""
Set up the argument parser for CLI input.
Returns:
argparse.ArgumentParser: The configured argument parser.
"""
parser = argparse.ArgumentParser(
description="Convert and normalize WAV files from a folder."
)
parser.add_argument('--input_folder', type=str, required=True,
help="Path to the input folder containing WAV files.")
parser.add_argument('--output_folder', type=str, required=True,
help="Path to save the processed WAV files.")
return parser
def main():
"""
Main function to parse arguments and initiate processing.
"""
parser = setup_parser()
args = parser.parse_args()
try:
logger.info("Starting processing...")
process_wav_files(args.input_folder, args.output_folder)
logger.info("Processing completed successfully.")
except Exception as e:
logger.error("An error occurred during processing: %s", e)
if __name__ == '__main__':
main()
Key Features:
Normalization and Conversion with FFmpeg: The script uses ffmpeg to normalize audio to -14 LUFS, a standard volume level recommended by YouTube, and to convert the sample rate to 22,050 Hz.
Subprocess and Error Handling: Uses Python's subprocess module for executing ffmpeg commands, with proper error handling in place.
Concurrent Audio Processing: Employs ProcessPoolExecutor to process multiple audio files in parallel, significantly speeding up batch processing.
Command-Line Interface: The script comes with a CLI for specifying input and output directories, ensuring ease of use for batch processing.
Comprehensive Logging: Logs the success or failure of each file's processing, providing insights into process execution.
Requirements:
FFmpeg Installation: Ensure ffmpeg is installed on your system. You can typically do this using your OS package manager (e.g., sudo apt-get install ffmpeg on Ubuntu).