Spaces:
Running
Running
add demo files
Browse files- app.py +128 -0
- audios/a.txt +0 -0
- model/a.txt +0 -0
- normalization.py +43 -0
- requirements.txt +1 -0
app.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import sys
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import altair as alt
|
| 5 |
+
|
| 6 |
+
import io
|
| 7 |
+
import streamlit as st
|
| 8 |
+
from fake_audio_detection.model import predict_audio_blocks
|
| 9 |
+
|
| 10 |
+
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 11 |
+
sys.path.append(parent_dir)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
st.title("🔎 DeepVoice Detection")
|
| 15 |
+
|
| 16 |
+
APP_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 17 |
+
|
| 18 |
+
# if you want to code your training part
|
| 19 |
+
DATASET_DIR = os.path.join(APP_DIR, "dataset/")
|
| 20 |
+
MODEL_PATH = os.path.join(APP_DIR, "model/noma-1")
|
| 21 |
+
|
| 22 |
+
REAL_DIR = os.path.join(APP_DIR, "audios/real")
|
| 23 |
+
FAKE_DIR = os.path.join(APP_DIR, "audios/fake")
|
| 24 |
+
|
| 25 |
+
# Then continue as before
|
| 26 |
+
real_audio = {
|
| 27 |
+
f"Real - {f}": os.path.join(REAL_DIR, f)
|
| 28 |
+
for f in os.listdir(REAL_DIR)
|
| 29 |
+
if f.endswith((".wav", ".mp3"))
|
| 30 |
+
}
|
| 31 |
+
fake_audio = {
|
| 32 |
+
f"Fake - {f}": os.path.join(FAKE_DIR, f)
|
| 33 |
+
for f in os.listdir(FAKE_DIR)
|
| 34 |
+
if f.endswith((".wav", ".mp3"))
|
| 35 |
+
}
|
| 36 |
+
all_audio = {**real_audio, **fake_audio}
|
| 37 |
+
|
| 38 |
+
selected_label = st.radio("Select an audio file to play:", list(all_audio.keys()))
|
| 39 |
+
selected_path = all_audio[selected_label]
|
| 40 |
+
|
| 41 |
+
st.write("#### Try with your audios")
|
| 42 |
+
uploaded_file = st.file_uploader("Choose an audio file", type=["wav", "mp3", "ogg"])
|
| 43 |
+
|
| 44 |
+
selected_label = "Default Audio"
|
| 45 |
+
|
| 46 |
+
if uploaded_file is not None:
|
| 47 |
+
st.markdown(f"**Now Playing:** `{uploaded_file.name}`")
|
| 48 |
+
audio_bytes = uploaded_file.read()
|
| 49 |
+
file_extension = uploaded_file.name.split(".")[-1].lower()
|
| 50 |
+
st.audio(audio_bytes, format=f"audio/{file_extension}")
|
| 51 |
+
else:
|
| 52 |
+
st.markdown(f"**Now Playing:** `{selected_label}`")
|
| 53 |
+
with open(selected_path, "rb") as audio_file:
|
| 54 |
+
audio_bytes = audio_file.read()
|
| 55 |
+
st.audio(audio_bytes, format="audio/wav")
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
if st.button("Run Prediction") and os.path.exists(MODEL_PATH):
|
| 59 |
+
audio_bytes = None
|
| 60 |
+
if uploaded_file:
|
| 61 |
+
bytes_data = uploaded_file.getvalue()
|
| 62 |
+
audio_bytes = io.BytesIO(bytes_data)
|
| 63 |
+
with st.spinner("Analyzing audio..."):
|
| 64 |
+
times, probas = predict_audio_blocks(MODEL_PATH, selected_path, audio_bytes)
|
| 65 |
+
|
| 66 |
+
preds = probas.argmax(axis=1)
|
| 67 |
+
confidences = probas.max(axis=1)
|
| 68 |
+
preds_as_string = ["Fake" if i == 0 else "Real" for i in preds]
|
| 69 |
+
df = pd.DataFrame(
|
| 70 |
+
{"Seconds": times, "Prediction": preds_as_string, "Confidence": confidences}
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
def get_color(row):
|
| 74 |
+
if row["Confidence"] < 0.3:
|
| 75 |
+
return "Uncertain"
|
| 76 |
+
return row["Prediction"]
|
| 77 |
+
|
| 78 |
+
df["Confidence Level"] = df.apply(get_color, axis=1)
|
| 79 |
+
|
| 80 |
+
# Plot
|
| 81 |
+
st.markdown("### Prediction by 1s Blocks")
|
| 82 |
+
st.markdown(
|
| 83 |
+
"Hover above each bar to see the confidence level of each prediction."
|
| 84 |
+
)
|
| 85 |
+
chart = (
|
| 86 |
+
alt.Chart(df)
|
| 87 |
+
.mark_bar()
|
| 88 |
+
.encode(
|
| 89 |
+
x=alt.X("Seconds:O", title="Seconds"),
|
| 90 |
+
y=alt.value(30),
|
| 91 |
+
color=alt.Color(
|
| 92 |
+
"Confidence Level:N",
|
| 93 |
+
scale=alt.Scale(
|
| 94 |
+
domain=["Fake", "Real", "Uncertain"],
|
| 95 |
+
range=["steelblue", "green", "gray"],
|
| 96 |
+
),
|
| 97 |
+
),
|
| 98 |
+
tooltip=["Seconds", "Prediction", "Confidence"],
|
| 99 |
+
)
|
| 100 |
+
.properties(width=700, height=150)
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
text = (
|
| 104 |
+
alt.Chart(df)
|
| 105 |
+
.mark_text(
|
| 106 |
+
align="right",
|
| 107 |
+
baseline="top",
|
| 108 |
+
dy=10,
|
| 109 |
+
color="white",
|
| 110 |
+
xOffset=10,
|
| 111 |
+
yOffset=-20,
|
| 112 |
+
fontSize=14,
|
| 113 |
+
)
|
| 114 |
+
.encode(x=alt.X("Seconds:O"), y=alt.value(15), text="Prediction:N")
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
st.altair_chart(chart + text, use_container_width=True)
|
| 118 |
+
|
| 119 |
+
st.markdown("### Overall prediction")
|
| 120 |
+
if all(element == "Real" for element in preds_as_string):
|
| 121 |
+
st.markdown("The audio is **Real**")
|
| 122 |
+
elif all(element == "Fake" for element in preds_as_string):
|
| 123 |
+
st.markdown("The audio is **Fake**")
|
| 124 |
+
else:
|
| 125 |
+
st.markdown("Some parts of the audio have been detected as **Fake**")
|
| 126 |
+
|
| 127 |
+
elif not os.path.exists(MODEL_PATH):
|
| 128 |
+
st.warning(f"Missing model: {MODEL_PATH}")
|
audios/a.txt
ADDED
|
File without changes
|
model/a.txt
ADDED
|
File without changes
|
normalization.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from typing import Callable, Dict
|
| 3 |
+
|
| 4 |
+
from sklearn.base import BaseEstimator, TransformerMixin
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class CustomNormalizer(BaseEstimator, TransformerMixin):
|
| 8 |
+
"""
|
| 9 |
+
This class exist only to fit in pipeline format
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
def __init__(self, method="z-score"):
|
| 13 |
+
self.method = method
|
| 14 |
+
|
| 15 |
+
def fit(self, X, y=None):
|
| 16 |
+
return self
|
| 17 |
+
|
| 18 |
+
def transform(self, X):
|
| 19 |
+
X_array = np.array(X)
|
| 20 |
+
return NormalizationTools.normalize(X_array, self.method)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class NormalizationTools:
|
| 24 |
+
@staticmethod
|
| 25 |
+
def l2(matrix: np.ndarray) -> np.ndarray:
|
| 26 |
+
norms = np.linalg.norm(matrix, axis=1, keepdims=True)
|
| 27 |
+
norms[norms == 0] = 1
|
| 28 |
+
return matrix / norms
|
| 29 |
+
|
| 30 |
+
# Dispatcher method
|
| 31 |
+
@staticmethod
|
| 32 |
+
def normalize(matrix: np.ndarray, method: str) -> np.ndarray:
|
| 33 |
+
method_map: Dict[str, Callable[[np.ndarray], np.ndarray]] = {
|
| 34 |
+
"l2": NormalizationTools.l2,
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
if method not in method_map:
|
| 38 |
+
raise ValueError(
|
| 39 |
+
f"Unknown normalization method '{method}', verify config file."
|
| 40 |
+
f"Available methods: {list(method_map.keys())}"
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
return method_map[method](matrix)
|
requirements.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
git+https://github.com/mozilla-ai/fake-audio-detection.git
|