Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 5,634 Bytes
27c4f4a 2f2dad0 2e81dfe 27c4f4a 2f2dad0 fd8232b 2e81dfe fd8232b 2f2dad0 2e81dfe 2f2dad0 27c4f4a 2e81dfe 27c4f4a 2e81dfe 27c4f4a 2e81dfe 27c4f4a 2e81dfe 27c4f4a 2e81dfe 27c4f4a 2e81dfe 27c4f4a af58e15 27c4f4a |
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 |
import gradio as gr
import torch
import soundfile as sf
import io
import librosa
import numpy as np
from pytube import YouTube
import os
import random
from huggingface_hub import HfApi
import pandas as pd
from moviepy.editor import *
FS=16000
MAX_SIZE = FS * 30
HF_TOKEN_DEMO=os.getenv("HF_TOKEN_DEMO")
MODEL_REPO=os.getenv("MODEL_REPO")
MODELNAME=os.getenv("MODELNAME")
MODELNAME2=os.getenv("MODELNAME2")
username=os.getenv("username")
password=os.getenv("password")
hf_api = HfApi(
endpoint="https://huggingface.co", # Can be a Private Hub endpoint.
token=HF_TOKEN_DEMO, # Token is not persisted on the machine.
)
modelfile = hf_api.hf_hub_download(MODEL_REPO,MODELNAME2)
MODEL = torch.jit.load(modelfile)
def reformat_freq(sr, y):
if len(y.shape)==1 or y.shape[1]==1:
pass
#print("monocanal")
else:
# Avg two channels
y=y.mean(axis=1)
y = y.astype(np.float32)
if sr not in (
FS,
):
y = librosa.resample(y, orig_sr=sr, target_sr=FS)
return sr, y
def preprocess_audio(audio):
_, y = reformat_freq(*audio)
y = y[:MAX_SIZE]
y=torch.as_tensor(y,dtype=torch.float32)
y=torch.unsqueeze(y,0)
return y
def postprocess_output(score):
out=score.item()
out = round(100*out,2)
return "{:.2f}%".format(out)
def process_youtube_address(youtube_address):
print("Downloading youtube audio from video...")
try:
selected_video = YouTube(youtube_address)
audio=selected_video.streams.filter(only_audio=True, file_extension='mp4').first()
nrand=round(random.random()*1000)
audioname="audio-"+str(nrand)+".mp4a"
audiowav="audio-"+str(nrand)+".wav"
audiomp4a=audio.download('tmp',audioname)
os.system("ffmpeg -i " + audiomp4a + " -ac 1 -ar {} ".format(FS) + audiowav + "; rm tmp/" + audioname )
except Exception as inst:
print("Exception: {}".format(inst))
print("ERROR while downloading audio from " + youtube_address)
audiowav=None
return audiowav
def process_micro(micro):
x=preprocess_audio(micro)
output,_ = MODEL(x)
print(output)
result = postprocess_output(output)
return result
def process_file(file):
x,fs = librosa.load(file, sr=FS)
x=preprocess_audio((fs,x))
print("Running model")
output,_ = MODEL(x)
print(output)
result = postprocess_output(output)
return result
def process_files(files):
resout=[]
res2out=[]
fnames=[]
for f in files:
file=f.name
x,fs = librosa.load(file, sr=FS)
x=preprocess_audio((fs,x))
print("Running model")
output,_ = MODEL(x)
print(output)
result, res2 = postprocess_output(output)
resout.append(result)
res2out.append(res2)
fnames.append(os.path.basename(file))
resout = pd.DataFrame({"File":fnames, "Probability of Real": resout})
#return resout, res2out
return resout
def process_video(file):
video = VideoFileClip(file)
audio = video.audio
if not os.path.isdir('tmp'):
os.makedirs('tmp')
nrand=round(random.random()*1000)
audiowav="tmp/audio-"+str(nrand)+".wav"
audio.to_audiofile(audiowav)
result = process_file(audiowav)
os.remove(audiowav)
return result
def process_youtube(youtube_address):
audiofile=process_youtube_address(youtube_address)
if audiofile is not None:
result = process_file(audiofile)
return result
else:
return "Could not get audio from {}".format(youtube_address)
with gr.Blocks(title="Audio Fake Detector") as demo:
with gr.Tab("Individual Processing"):
gr.Markdown("# Welcome to Loccus.ai synthetic voice detection demo!")
with gr.Row():
with gr.Column():
m = gr.Audio(source="microphone", type="numpy",label="Micro")
f = gr.Audio(source="upload", type="filepath", label="Audio file")
y = gr.Textbox(label="Enter YouTube address here")
v = gr.Video(label="Enter a video", include_audio=True, scale=0.5)
with gr.Column():
with gr.Row(equal_height=True):
text = gr.Textbox(label="Probability of Real Voice")
#file= gr.Audio(source="upload", type="filepath", optional=True)
button_clear = gr.ClearButton([m,f,y,v,text])
m.stop_recording(process_micro, inputs=[m], outputs=text)
f.upload(process_file,inputs=[f], outputs=text)
y.submit(process_youtube, inputs=[y], outputs=text)
v.upload(process_video, inputs=[v], outputs=[text])
with gr.Tab("Batch Processing"):
gr.Markdown("# Welcome to Loccus.ai synthetic voice detection demo!")
with gr.Row():
with gr.Column():
f = gr.File(file_types=["audio"], label="Audio file", file_count="multiple")
with gr.Column():
with gr.Row(equal_height=True):
textbatch = gr.Dataframe(
headers=["File", "Probability of Real"],
datatype=["str", "str"],
)
#text = gr.Textbox(label="Probability of Real Voice")
#text2 = gr.Textbox(label="Amp Mean Score")
button_clear = gr.ClearButton([f,textbatch])
f.upload(process_files,inputs=[f], outputs=[textbatch])
#btn = gr.Button("Run")
#btn.click(fn=update, inputs=inp, outputs=out)
demo.launch(auth=(username,password))
|