Kabatubare commited on
Commit
e1791c4
·
verified ·
1 Parent(s): 53b1abc

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -16
app.py CHANGED
@@ -7,55 +7,60 @@ import logging
7
  from transformers import AutoModelForAudioClassification
8
  import random
9
 
 
10
  logging.basicConfig(level=logging.INFO)
11
 
 
12
  model_path = "./"
13
  model = AutoModelForAudioClassification.from_pretrained(model_path)
14
 
15
  def custom_feature_extraction(waveform, sr, n_mels=128, n_fft=2048, hop_length=512, target_length=1024):
 
16
  S = librosa.feature.melspectrogram(y=waveform, sr=sr, n_mels=n_mels, n_fft=n_fft, hop_length=hop_length)
17
  S_DB = librosa.power_to_db(S, ref=np.max)
18
 
 
19
  pitches, _ = librosa.piptrack(y=waveform, sr=sr, n_fft=n_fft, hop_length=hop_length)
20
- pitches = pitches.mean(axis=0, keepdims=True)
 
 
21
  spectral_centroids = librosa.feature.spectral_centroid(y=waveform, sr=sr, n_fft=n_fft, hop_length=hop_length)
22
 
23
- features = np.concatenate([S_DB, pitches, spectral_centroids], axis=0)
 
24
  features_tensor = torch.tensor(features).float()
25
 
26
- current_length = features_tensor.shape[1]
27
- if current_length > target_length:
28
  features_tensor = features_tensor[:, :target_length]
29
- elif current_length < target_length:
30
- padding = target_length - current_length
31
- features_tensor = F.pad(features_tensor, (0, padding), "constant", 0)
32
 
33
  return features_tensor.unsqueeze(0)
34
 
35
  def apply_time_shift(waveform, max_shift_fraction=0.1):
36
- shift = int(max_shift_fraction * waveform.size)
37
- shift = random.randint(-shift, shift)
38
  return np.roll(waveform, shift)
39
 
40
- def predict_voice(audio_file_path):
41
  try:
42
- waveform, sample_rate = librosa.load(audio_file_path, sr=None)
43
  augmented_waveform = apply_time_shift(waveform)
44
-
45
  original_features = custom_feature_extraction(waveform, sample_rate)
46
  augmented_features = custom_feature_extraction(augmented_waveform, sample_rate)
47
 
48
  with torch.no_grad():
49
  outputs_original = model(original_features)
50
  outputs_augmented = model(augmented_features)
51
-
52
  logits = (outputs_original.logits + outputs_augmented.logits) / 2
53
  predicted_index = logits.argmax()
54
  label = model.config.id2label[predicted_index.item()]
55
  confidence = torch.softmax(logits, dim=1).max().item() * 100
56
 
57
  result = f"The voice is classified as '{label}' with a confidence of {confidence:.2f}%."
58
- logging.info("Prediction successful.")
59
  except Exception as e:
60
  result = f"Error during processing: {e}"
61
  logging.error(result)
@@ -64,8 +69,8 @@ def predict_voice(audio_file_path):
64
 
65
  iface = gr.Interface(
66
  fn=predict_voice,
67
- inputs=gr.inputs.Audio(label="Upload Audio File", type="filepath"),
68
- outputs=gr.outputs.Textbox(label="Prediction"),
69
  title="Voice Authenticity Detection",
70
  description="Detects whether a voice is real or AI-generated. Upload an audio file to see the results."
71
  )
 
7
  from transformers import AutoModelForAudioClassification
8
  import random
9
 
10
+ # Configure logging
11
  logging.basicConfig(level=logging.INFO)
12
 
13
+ # Load the model
14
  model_path = "./"
15
  model = AutoModelForAudioClassification.from_pretrained(model_path)
16
 
17
  def custom_feature_extraction(waveform, sr, n_mels=128, n_fft=2048, hop_length=512, target_length=1024):
18
+ # Generate Mel spectrogram
19
  S = librosa.feature.melspectrogram(y=waveform, sr=sr, n_mels=n_mels, n_fft=n_fft, hop_length=hop_length)
20
  S_DB = librosa.power_to_db(S, ref=np.max)
21
 
22
+ # Pitch feature (using piptrack to estimate pitches and then averaging)
23
  pitches, _ = librosa.piptrack(y=waveform, sr=sr, n_fft=n_fft, hop_length=hop_length)
24
+ pitch_mean = np.mean(pitches, axis=0, keepdims=True)
25
+
26
+ # Spectral centroid
27
  spectral_centroids = librosa.feature.spectral_centroid(y=waveform, sr=sr, n_fft=n_fft, hop_length=hop_length)
28
 
29
+ # Concatenate features and normalize
30
+ features = np.concatenate([S_DB, pitch_mean, spectral_centroids], axis=0)
31
  features_tensor = torch.tensor(features).float()
32
 
33
+ # Adjust the tensor's length
34
+ if features_tensor.shape[1] > target_length:
35
  features_tensor = features_tensor[:, :target_length]
36
+ elif features_tensor.shape[1] < target_length:
37
+ padding = target_length - features_tensor.shape[1]
38
+ features_tensor = F.pad(features_tensor, (0, padding), 'constant', 0)
39
 
40
  return features_tensor.unsqueeze(0)
41
 
42
  def apply_time_shift(waveform, max_shift_fraction=0.1):
43
+ shift_amount = int(max_shift_fraction * len(waveform))
44
+ shift = random.randint(-shift_amount, shift_amount)
45
  return np.roll(waveform, shift)
46
 
47
+ def predict_voice(audio_file):
48
  try:
49
+ waveform, sample_rate = librosa.load(audio_file, sr=None)
50
  augmented_waveform = apply_time_shift(waveform)
51
+
52
  original_features = custom_feature_extraction(waveform, sample_rate)
53
  augmented_features = custom_feature_extraction(augmented_waveform, sample_rate)
54
 
55
  with torch.no_grad():
56
  outputs_original = model(original_features)
57
  outputs_augmented = model(augmented_features)
 
58
  logits = (outputs_original.logits + outputs_augmented.logits) / 2
59
  predicted_index = logits.argmax()
60
  label = model.config.id2label[predicted_index.item()]
61
  confidence = torch.softmax(logits, dim=1).max().item() * 100
62
 
63
  result = f"The voice is classified as '{label}' with a confidence of {confidence:.2f}%."
 
64
  except Exception as e:
65
  result = f"Error during processing: {e}"
66
  logging.error(result)
 
69
 
70
  iface = gr.Interface(
71
  fn=predict_voice,
72
+ inputs=gr.Audio(label="Upload Audio File", type="filepath"),
73
+ outputs=gr.Textbox(label="Prediction"),
74
  title="Voice Authenticity Detection",
75
  description="Detects whether a voice is real or AI-generated. Upload an audio file to see the results."
76
  )