File size: 10,650 Bytes
f14265e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import gradio as gr
import librosa
import numpy as np
import pandas as pd
from sklearn.metrics.pairwise import cosine_similarity
import torch
from speechbrain.inference.speaker import EncoderClassifier
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import plotly.graph_objects as go
from sklearn.preprocessing import normalize
import os
from cryptography.fernet import Fernet
import pickle

# --- Configuration using Environment Variables ---
encrypted_file_path = os.environ.get("SPEAKER_EMBEDDINGS_FILE")
metadata_file = os.environ.get("METADATA_FILE")
visualization_method = os.environ.get("VISUALIZATION_METHOD", "pca")
max_length = 5 * 16000
num_closest_speakers = 20
pca_dim = 50

# --- Check for Missing Environment Variables ---
if not encrypted_file_path:
    raise ValueError("SPEAKER_EMBEDDINGS_FILE environment variable is not set.")
if not metadata_file:
    raise ValueError("METADATA_FILE environment variable is not set.")
# --- Check for valid visualization method ---
if visualization_method not in ["pca", "tsne"]:
    raise ValueError("Invalid VISUALIZATION_METHOD. Choose 'pca' or 'tsne'.")

# --- Debugging: Check Environment Variables ---
print(f"DECRYPTION_KEY: {os.getenv('DECRYPTION_KEY')}")
print(f"SPEAKER_EMBEDDINGS_FILE: {os.getenv('SPEAKER_EMBEDDINGS_FILE')}")
if os.getenv('SPEAKER_EMBEDDINGS_FILE'):
    print(
        f"Encrypted file path exists: {os.path.exists(os.getenv('SPEAKER_EMBEDDINGS_FILE'))}"
    )
else:
    print(
        "Encrypted file path does not exist: SPEAKER_EMBEDDINGS_FILE environment variable not set or file not found."
    )

# --- Decryption ---
key = os.getenv("DECRYPTION_KEY")
if not key:
    raise ValueError(
        "Decryption key is missing. Ensure DECRYPTION_KEY is set in the environment variables."
    )

fernet = Fernet(key.encode("utf-8"))

# --- Sample Audio Files ---
sample_audio_dir = "sample_audio"
sample_audio_files = [
    "Bob_Barker.mp3",
    "Howie_Mandel.m4a",
    "Katherine_Jenkins.mp3",
]

# --- Load Embeddings and Metadata ---
try:
    with open(encrypted_file_path, "rb") as encrypted_file:
        encrypted_data = encrypted_file.read()

    decrypted_data_bytes = fernet.decrypt(encrypted_data)

    # Deserialize using pickle.loads()
    speaker_embeddings = pickle.loads(decrypted_data_bytes)

    print("Speaker embeddings loaded successfully!")

except FileNotFoundError:
    raise FileNotFoundError(
        f"Could not find encrypted embeddings file at: {encrypted_file_path}"
    )
except Exception as e:
    raise Exception(f"Error during decryption or loading embeddings: {e}")

df = pd.read_csv(metadata_file, delimiter="\t")

# --- Convert Embeddings to NumPy Arrays ---
for spk_id, embeddings in speaker_embeddings.items():
    speaker_embeddings[spk_id] = [np.array(embedding) for embedding in embeddings]

# --- Speaker ID to Name Mapping ---
speaker_id_to_name = dict(zip(df["VoxCeleb1 ID"], df["VGGFace1 ID"]))

# --- Load SpeechBrain Classifier ---
classifier = EncoderClassifier.from_hparams(
    source="speechbrain/spkrec-xvect-voxceleb",
    savedir="pretrained_models/spkrec-xvect-voxceleb",
)

# --- Function to Calculate Average Embedding (Centroid) ---
def calculate_average_embedding(embeddings):
    avg_embedding = np.mean(embeddings, axis=0)
    return normalize(avg_embedding.reshape(1, -1)).flatten()

# --- Precompute Speaker Centroids ---
speaker_centroids = {
    spk_id: calculate_average_embedding(embeddings)
    for spk_id, embeddings in speaker_embeddings.items()
}

# --- Function to Prepare Data for Visualization ---
def prepare_data_for_visualization(speaker_centroids, closest_speaker_ids):
    all_embeddings = [
        centroid
        for speaker_id, centroid in speaker_centroids.items()
        if speaker_id in closest_speaker_ids
    ]
    all_speaker_ids = [
        speaker_id
        for speaker_id in speaker_centroids
        if speaker_id in closest_speaker_ids
    ]
    return np.array(all_embeddings), np.array(all_speaker_ids)

# --- Function to Reduce Dimensionality ---
def reduce_dimensionality(all_embeddings, method="tsne", perplexity=5, pca_dim=50):
    if method == "pca":
        reducer = PCA(n_components=2)
    elif method == "tsne":
        pca_reducer = PCA(n_components=pca_dim)
        all_embeddings = pca_reducer.fit_transform(all_embeddings)
        reducer = TSNE(n_components=2, random_state=42, perplexity=perplexity)
    else:
        raise ValueError("Invalid method. Choose 'pca' or 'tsne'.")
    reduced_embeddings = reducer.fit_transform(all_embeddings)
    return reducer, reduced_embeddings

# --- Function to Get Speaker Name from ID ---
def get_speaker_name(speaker_id):
    return speaker_id_to_name.get(speaker_id, f"Unknown ({speaker_id})")

# --- Function to Generate Visualization ---
def generate_visualization(
    pca_reducer,
    reduced_embeddings,
    all_speaker_ids,
    new_embedding,
    predicted_speaker_id,
    visualization_method,
    perplexity,
    pca_dim,
):
    if visualization_method == "pca":
        new_embedding_reduced = pca_reducer.transform(new_embedding.reshape(1, -1))
    elif visualization_method == "tsne":
        combined_embeddings = np.vstack(
            [reduced_embeddings, new_embedding.reshape(1, -1)]
        )
        reducer = TSNE(n_components=2, random_state=42, perplexity=perplexity)
        combined_reduced = reducer.fit_transform(combined_embeddings)
        reduced_embeddings = combined_reduced[:-1]
        new_embedding_reduced = combined_reduced[-1].reshape(1, -1)
    else:
        raise ValueError("Invalid visualization method.")

    fig = go.Figure()
    fig.add_trace(
        go.Scatter(
            x=reduced_embeddings[:, 0],
            y=reduced_embeddings[:, 1],
            mode="markers",
            marker=dict(color="blue", size=8, opacity=0.5),
            text=[get_speaker_name(speaker_id) for speaker_id in all_speaker_ids],
            name="Other Speakers",
        )
    )

    if predicted_speaker_id in all_speaker_ids:
        predicted_speaker_index = list(all_speaker_ids).index(predicted_speaker_id)
        fig.add_trace(
            go.Scatter(
                x=[reduced_embeddings[predicted_speaker_index, 0]],
                y=[reduced_embeddings[predicted_speaker_index, 1]],
                mode="markers",
                marker=dict(
                    color="green",
                    size=10,
                    symbol="circle",
                    line=dict(color="black", width=2),
                ),
                name=get_speaker_name(predicted_speaker_id),
                text=[get_speaker_name(predicted_speaker_id)],
            )
        )

    fig.add_trace(
        go.Scatter(
            x=new_embedding_reduced[:, 0],
            y=new_embedding_reduced[:, 1],
            mode="markers",
            marker=dict(color="red", size=12, symbol="star"),
            name="New Voice",
            text=["New Voice"],
        )
    )

    fig.update_layout(
        title=f"Dimensionality Reduction of Speaker Embeddings using {visualization_method.upper()}",
        xaxis_title="Component 1",
        yaxis_title="Component 2",
        legend=dict(x=0, y=1, traceorder="normal", orientation="h"),
        hovermode="closest",
    )
    return fig

# --- Main Function ---
def identify_voice_and_visualize_with_averaging(audio_file, perplexity=5):
    try:
        if isinstance(audio_file, str):
            signal, fs = librosa.load(audio_file, sr=16000)
        elif isinstance(audio_file, np.ndarray):
            signal = audio_file
            fs = 16000
        else:
            raise ValueError(
                "Invalid audio input. Must be a file path or a NumPy array."
            )

        signal_tensor = torch.tensor(signal, dtype=torch.float32).unsqueeze(0)
        signal_tensor = torch.nn.functional.pad(
            signal_tensor, (0, max_length - signal_tensor.shape[1])
        )

        user_embedding = classifier.encode_batch(signal_tensor).cpu().detach().numpy()
        user_embedding = normalize(
            user_embedding.squeeze(axis=(0, 1)).reshape(1, -1)
        ).flatten()

        similarity_scores = {
            spk_id: cosine_similarity(
                user_embedding.reshape(1, -1), centroid.reshape(1, -1)
            )[0][0]
            for spk_id, centroid in speaker_centroids.items()
        }

        closest_speaker_ids = sorted(
            similarity_scores, key=similarity_scores.get, reverse=True
        )[:num_closest_speakers]
        predicted_speaker_id = closest_speaker_ids[0]
        highest_similarity = similarity_scores[predicted_speaker_id]

        all_embeddings, all_speaker_ids = prepare_data_for_visualization(
            speaker_centroids, closest_speaker_ids
        )
        reducer, reduced_embeddings = reduce_dimensionality(
            all_embeddings,
            method=visualization_method,
            perplexity=perplexity,
            pca_dim=pca_dim,
        )

        predicted_speaker_name = get_speaker_name(predicted_speaker_id)
        similarity_percentage = round(highest_similarity * 100, 2)  # Rounded here

        visualization = generate_visualization(
            reducer,
            reduced_embeddings,
            all_speaker_ids,
            user_embedding,
            predicted_speaker_id,
            visualization_method,
            perplexity,
            pca_dim,
        )

        result_text = (
            f"The voice resembles speaker: {predicted_speaker_name} "
            f"with a similarity of {similarity_percentage:.2f}%"  # Display rounded value
        )
        return result_text, visualization

    except Exception as e:
        return f"Error during processing: {e}", None

# --- Gradio Interface ---
# Create a directory for caching examples if it doesn't exist
cache_dir = "examples_cache"
if not os.path.exists(cache_dir):
    os.makedirs(cache_dir)

# Define the Gradio interface
iface = gr.Interface(
    fn=identify_voice_and_visualize_with_averaging,
    inputs=gr.Audio(type="filepath", label="Input Audio"),
    outputs=["text", gr.Plot()],
    title="Discover Your Celebrity Voice Twin!",
    description="Record your voice or upload an audio file, and see your celebrity match! Not ready to record? Try our sample voices to see how it works!",
    cache_examples=False,
    examples_per_page=3,
    examples=[
        [os.path.join(sample_audio_dir, sample_audio_files[0])],
        [os.path.join(sample_audio_dir, sample_audio_files[1])],
        [os.path.join(sample_audio_dir, sample_audio_files[2])],
    ],
)

# Launch the interface
iface.launch(debug=True, share=True)