Bagus commited on
Commit
159733c
·
verified ·
1 Parent(s): 66b4abd

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -35
app.py CHANGED
@@ -1,44 +1,120 @@
1
  import gradio as gr
2
  import torch
3
  import torchaudio
 
4
  from transformers import AutoFeatureExtractor, AutoModelForAudioXVector
5
 
6
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
7
 
8
- def similarity_fn(speaker1, speaker2):
9
- if not (speaker1 and speaker2):
10
- return gr.Textbox(value='<b style="color:red">ERROR: Please record audio for *both* speakers!</b>')
11
-
12
- wav1, _ = torchaudio.load(speaker1)
13
- wav2, _ = torchaudio.load(speaker2)
14
-
15
- feature_extractor = AutoFeatureExtractor.from_pretrained("microsoft/wavlm-base-plus-sv")
16
- model = AutoModelForAudioXVector.from_pretrained("microsoft/wavlm-base-plus-sv").to(device)
17
-
18
- input1 = feature_extractor(wav1.squeeze(0), return_tensors="pt", sampling_rate=16000).input_values.to(device)
19
- input2 = feature_extractor(wav2.squeeze(0), return_tensors="pt", sampling_rate=16000).input_values.to(device)
20
-
21
- with torch.no_grad():
22
- emb1 = model(input1).embeddings
23
- emb2 = model(input2).embeddings
24
- emb1 = torch.nn.functional.normalize(emb1, dim=-1).cpu()
25
- emb2 = torch.nn.functional.normalize(emb2, dim=-1).cpu()
26
- similarity = torch.nn.CosineSimilarity(dim=-1)(emb1, emb2).numpy()[0]
27
-
28
- if similarity >= 0.8:
29
- label = "The speakers are similar"
30
- color = "green"
31
- else:
32
- label = "The speakers are different"
33
- color = "red"
34
-
35
- return gr.Textbox(value=f"<span style='color:{color}'>{label}</span>")
36
-
37
- demo = gr.Interface(
38
- speaker1=gr.Audio(source="microphone", type="filepath"),
39
- speaker2=gr.Audio(source="microphone", type="filepath"),
40
- output=gr.Textbox(),
41
- fn=similarity_fn
42
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import torch
3
  import torchaudio
4
+ # from torchaudio.sox_effects import apply_effects_file
5
  from transformers import AutoFeatureExtractor, AutoModelForAudioXVector
6
 
7
  device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
8
 
9
+ STYLE = """
10
+ <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha256-YvdLHPgkqJ8DVUxjjnGVlMMJtNimJ6dYkowFFvp4kKs=" crossorigin="anonymous">
11
+ """
12
+ OUTPUT_OK = (
13
+ STYLE
14
+ + """
15
+ <div class="container">
16
+ <div class="row"><h1 style="text-align: center">The speakers are</h1></div>
17
+ <div class="row"><h1 class="display-1 text-success" style="text-align: center">{:.1f}%</h1></div>
18
+ <div class="row"><h1 style="text-align: center">similar</h1></div>
19
+ <div class="row"><h1 class="text-success" style="text-align: center">Welcome, human!</h1></div>
20
+ <div class="row"><small style="text-align: center">(You must get at least 80% to be considered the same person)</small><div class="row">
21
+ </div>
22
+ """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  )
24
+ OUTPUT_FAIL = (
25
+ STYLE
26
+ + """
27
+ <div class="container">
28
+ <div class="row"><h1 style="text-align: center">The speakers are</h1></div>
29
+ <div class="row"><h1 class="display-1 text-danger" style="text-align: center">{:.1f}%</h1></div>
30
+ <div class="row"><h1 style="text-align: center">similar</h1></div>
31
+ <div class="row"><h1 class="text-danger" style="text-align: center">You shall not pass!</h1></div>
32
+ <div class="row"><small style="text-align: center">(You must get at least 80% to be considered the same person)</small><div class="row">
33
+ </div>
34
+ """
35
+ )
36
+
37
+ EFFECTS = [
38
+ ["remix", "-"],
39
+ ["channels", "1"],
40
+ ["rate", "16000"],
41
+ ["gain", "-1.0"],
42
+ ["silence", "1", "0.1", "0.1%", "-1", "0.1", "0.1%"],
43
+ ["trim", "0", "10"],
44
+ ]
45
+
46
+ THRESHOLD = 0.80
47
+
48
+ model_name = "microsoft/wavlm-base-plus-sv"
49
+ feature_extractor = AutoFeatureExtractor.from_pretrained(model_name)
50
+ model = AutoModelForAudioXVector.from_pretrained(model_name).to(device)
51
+ cosine_sim = torch.nn.CosineSimilarity(dim=-1)
52
+
53
+
54
+ def similarity_fn(path1, path2):
55
+ if not (path1 and path2):
56
+ return '<b style="color:red">ERROR: Please record audio for *both* speakers!</b>'
57
+
58
+ # wav1, _ = apply_effects_file(path1, EFFECTS)
59
+ # wav2, _ = apply_effects_file(path2, EFFECTS)
60
+ wav1, _ = torchaudio.load(path1)
61
+ wav2, _ = torchaudio.load(path2)
62
+ print(wav1.shape, wav2.shape)
63
+
64
+ input1 = feature_extractor(wav1.squeeze(0), return_tensors="pt", sampling_rate=16000).input_values.to(device)
65
+ input2 = feature_extractor(wav2.squeeze(0), return_tensors="pt", sampling_rate=16000).input_values.to(device)
66
+
67
+ with torch.no_grad():
68
+ emb1 = model(input1).embeddings
69
+ emb2 = model(input2).embeddings
70
+ emb1 = torch.nn.functional.normalize(emb1, dim=-1).cpu()
71
+ emb2 = torch.nn.functional.normalize(emb2, dim=-1).cpu()
72
+ similarity = cosine_sim(emb1, emb2).numpy()[0]
73
 
74
+ if similarity >= THRESHOLD:
75
+ output = OUTPUT_OK.format(similarity * 100)
76
+ else:
77
+ output = OUTPUT_FAIL.format(similarity * 100)
78
+
79
+ return output
80
+
81
+
82
+ inputs = [
83
+ gr.Audio(sources=["microphone", "upload"], type="filepath", label="Speaker #1"),
84
+ gr.Audio(sources=["microphone", "upload"], type="filepath", label="Speaker #2"),
85
+ ]
86
+ output = gr.HTML(label="")
87
+
88
+
89
+ description = (
90
+ "This demo will compare two speech samples and determine if they are from the same speaker. "
91
+ "Try it with your own voice!"
92
+ )
93
+ article = (
94
+ "<p style='text-align: center'>"
95
+ "<a href='https://huggingface.co/microsoft/wavlm-base-plus-sv' target='_blank'>🎙️ Learn more about WavLM</a> | "
96
+ "<a href='https://arxiv.org/abs/2110.13900' target='_blank'>📚 WavLM paper</a> | "
97
+ "<a href='https://www.danielpovey.com/files/2018_icassp_xvectors.pdf' target='_blank'>📚 X-Vector paper</a>"
98
+ "</p>"
99
+ )
100
+ examples = [
101
+ ["samples/denzel_washington.mp3", "samples/denzel_washington.mp3"],
102
+ ["samples/heath_ledger_2.mp3", "samples/heath_ledger_3.mp3"],
103
+ ["samples/heath_ledger_3.mp3", "samples/denzel_washington.mp3"],
104
+ ["samples/denzel_washington.mp3", "samples/heath_ledger_2.mp3"],
105
+ ]
106
+
107
+ interface = gr.Interface(
108
+ fn=similarity_fn,
109
+ inputs=inputs,
110
+ outputs=output,
111
+ title="Voice Authentication with WavLM + X-Vectors",
112
+ description=description,
113
+ article=article,
114
+ layout="horizontal",
115
+ theme="huggingface",
116
+ allow_flagging=False,
117
+ live=False,
118
+ examples=examples,
119
+ )
120
+ interface.launch(enable_queue=True)