file_utils.py 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. from cmath import e
  2. import os
  3. from re import A
  4. import wave
  5. import logging
  6. from pydub import AudioSegment
  7. import matplotlib.pyplot as plt
  8. import numpy as np
  9. import pandas as pd
  10. import librosa.display
  11. # Configure logging
  12. logging.basicConfig(level=logging.INFO)
  13. logger = logging.getLogger(__name__)
  14. trainer_classes = {}
  15. def ensure_directory_exists(directory):
  16. if not os.path.exists(directory):
  17. os.makedirs(directory)
  18. def list_files_in_directory(directory, extension=None):
  19. if not os.path.exists(directory):
  20. raise FileNotFoundError(f"Directory {directory} does not exist.")
  21. files = []
  22. for file in os.listdir(directory):
  23. if extension and not file.endswith(extension):
  24. continue
  25. files.append(directory+file)
  26. return files
  27. def list_directories_in_directory(directory):
  28. if not os.path.exists(directory):
  29. raise FileNotFoundError(f"Directory {directory} does not exist.")
  30. directories = [d for d in os.listdir(directory) if os.path.isdir(os.path.join(directory, d))]
  31. return directories
  32. def save_file(directory, filename, data):
  33. ensure_directory_exists(directory)
  34. file_path = os.path.join(directory, filename)
  35. with open(file_path, 'wb') as file:
  36. file.write(data)
  37. def delete_file(file_path):
  38. if os.path.exists(file_path):
  39. os.remove(file_path)
  40. def get_file_metadata(file_path):
  41. if not os.path.exists(file_path):
  42. raise FileNotFoundError(f"File {file_path} does not exist.")
  43. try:
  44. with wave.open(file_path, 'rb') as wf:
  45. frames = wf.getnframes()
  46. rate = wf.getframerate()
  47. length = frames / float(rate)
  48. size = os.path.getsize(file_path) / 1024 # size in KB
  49. return round(length, 2), round(size, 2)
  50. except wave.Error as e:
  51. logger.error(f"Error processing WAV file {file_path}: {e}")
  52. raise ValueError(f"Error processing WAV file: {e}")
  53. def is_valid_wav(file_path):
  54. try:
  55. with wave.open(file_path, 'rb') as wf:
  56. return True
  57. except wave.Error:
  58. return False
  59. def get_file_size(file_path):
  60. if not os.path.exists(file_path):
  61. raise FileNotFoundError(f"File {file_path} does not exist.")
  62. size = os.path.getsize(file_path)
  63. return get_Size_String(size)
  64. def get_Size_String(value):
  65. ext = ["Byte","KB","MB","GB","TB"]
  66. i = 0
  67. while value > 1024:
  68. value /= 1024
  69. i += 1
  70. return f"{value:.2f} {ext[i]}"
  71. def update_training_time(model_name, additional_time):
  72. training_time_path = f"./model/hotword/{model_name}/training_time.txt"
  73. ensure_directory_exists(os.path.dirname(training_time_path))
  74. if os.path.exists(training_time_path):
  75. with open(training_time_path, "r") as f:
  76. total_time = int(f.read().strip())
  77. else:
  78. total_time = 0
  79. total_time += additional_time
  80. with open(training_time_path, "w") as f:
  81. f.write(str(total_time))
  82. def get_training_time(model_name):
  83. training_time_path = f"./model/hotword/{model_name}/training_time.txt"
  84. if os.path.exists(training_time_path):
  85. with open(training_time_path, "r") as f:
  86. return int(f.read().strip())
  87. return 0
  88. def resample_training_data(training_directory, background_directory=None):
  89. print(" training_directory: "+training_directory)
  90. print(" background_directory: "+background_directory)
  91. input_dir = os.path.join(training_directory)
  92. output_dir = os.path.join(input_dir, 'processed/')
  93. print(" input_dir: "+input_dir)
  94. print(" output_dir: "+output_dir)
  95. ensure_directory_exists(output_dir)
  96. hotword_files = list_files_in_directory(input_dir, extension='.wav')
  97. if background_directory:
  98. background_files = list_files_in_directory(background_directory, extension='.wav')
  99. else:
  100. background_files = []
  101. for hotword_file in hotword_files:
  102. hotword_audio = AudioSegment.from_wav(hotword_file)
  103. fname1=os.path.splitext(os.path.basename(hotword_file))[0]+".wav"
  104. hotword_audio.export(os.path.join(output_dir, fname1), format='wav') # Save raw hotword
  105. for background_file in background_files:
  106. fname1=os.path.splitext(os.path.basename(hotword_file))[0]
  107. fname2=os.path.splitext(os.path.basename(background_file))[0]
  108. mixed_filename = f"{fname1}_{fname2}.wav"
  109. ofile = os.path.join(output_dir, mixed_filename)
  110. if os.path.exists(ofile)==False:
  111. background_audio = AudioSegment.from_wav(background_file)
  112. mixed_audio = hotword_audio.overlay(background_audio, position=0)
  113. print(f" Mixed Filename: {mixed_filename}")
  114. mixed_audio.export(ofile, format='wav')
  115. def preprocessing_training_data(model_dir,data_dir, sc_data_dir, fail_data_dir):
  116. import librosa
  117. data_path_dict = {
  118. 0: list_files_in_directory(fail_data_dir, extension='.wav'),
  119. 1: list_files_in_directory(data_dir, extension='.wav'),
  120. 2: list_files_in_directory(sc_data_dir, extension='.wav')
  121. }
  122. #walley_sample = "training/background/rec04.wav"
  123. #data, sample_rate = librosa.load(walley_sample)
  124. #plt.title("Wave Form")
  125. #librosa.display.waveplot(data, sr=sample_rate)
  126. #plt.show()
  127. #mfccs = librosa.feature.mfcc(y=data, sr=sample_rate, n_mfcc=40)
  128. #print("Shape of mfcc:", mfccs.shape)
  129. #plt.title("MFCC")
  130. #librosa.display.specshow(mfccs, sr=sample_rate, x_axis='time')
  131. #plt.show()
  132. all_data = []
  133. print(" Load training data")
  134. for class_label, list_of_files in data_path_dict.items():
  135. for single_file in list_of_files:
  136. try:
  137. if single_file[0:2]=="./":
  138. single_file = single_file[2:]
  139. print(f" {class_label}: {single_file}")
  140. audio, sample_rate = librosa.load(single_file)
  141. print(f" Sample-Rate: {sample_rate}")
  142. mfcc = librosa.feature.mfcc(y=audio, sr=sample_rate, n_mfcc=40)
  143. print(f" mfcc: {mfcc}")
  144. mfcc_processed = np.mean(mfcc.T, axis=0)
  145. print(f" mfcc_processed: mfcc_processed")
  146. all_data.append([mfcc_processed, class_label])
  147. print(" Next")
  148. except Exception as e:
  149. print(f" Exception: {str(e)}")
  150. print(f" Info: Succesfully Preprocessed Class Label {class_label}")
  151. df = pd.DataFrame(all_data, columns=["feature", "class_label"])
  152. df.to_pickle(model_dir+"/audio_data.csv")