Spaces:
Sleeping
Sleeping
Create main_app.py
Browse files- main_app.py +126 -0
main_app.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, io, pathlib, urllib.request
|
| 2 |
+
import numpy as np
|
| 3 |
+
import streamlit as st
|
| 4 |
+
from PIL import Image
|
| 5 |
+
from matplotlib import cm
|
| 6 |
+
|
| 7 |
+
st.write("### ✅ Voice Guard Streamlit — env-only v4 (no st.secrets)")
|
| 8 |
+
|
| 9 |
+
# ---- import Detector from app/ or src/ ----
|
| 10 |
+
Detector, _last_err = None, None
|
| 11 |
+
for mod in ["app.inference_wav2vec", "app.inference",
|
| 12 |
+
"src.inference_wav2vec", "src.inference"]:
|
| 13 |
+
try:
|
| 14 |
+
Detector = __import__(mod, fromlist=["Detector"]).Detector
|
| 15 |
+
break
|
| 16 |
+
except Exception as e:
|
| 17 |
+
_last_err = e
|
| 18 |
+
if Detector is None:
|
| 19 |
+
st.error(f"Could not import Detector from app/ or src/. Last error: {_last_err}")
|
| 20 |
+
st.stop()
|
| 21 |
+
|
| 22 |
+
# ---- ENV config only ----
|
| 23 |
+
def cfg(name: str, default: str = "") -> str:
|
| 24 |
+
v = os.getenv(name)
|
| 25 |
+
return v if v not in (None, "") else default
|
| 26 |
+
|
| 27 |
+
def ensure_weights() -> str:
|
| 28 |
+
wp = cfg("MODEL_WEIGHTS_PATH", "app/models/weights/wav2vec2_classifier.pth")
|
| 29 |
+
url = cfg("MODEL_WEIGHTS_URL", "")
|
| 30 |
+
dest = pathlib.Path(wp)
|
| 31 |
+
if not dest.exists() and url:
|
| 32 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 33 |
+
with st.spinner(f"Downloading model weights to {dest} …"):
|
| 34 |
+
urllib.request.urlretrieve(url, str(dest))
|
| 35 |
+
st.toast("Weights downloaded", icon="✅")
|
| 36 |
+
if not dest.exists() and not url:
|
| 37 |
+
st.warning(
|
| 38 |
+
f"Model weights not found at '{wp}'. "
|
| 39 |
+
"Upload the .pth there OR set MODEL_WEIGHTS_URL in Settings → Variables & secrets."
|
| 40 |
+
)
|
| 41 |
+
return str(dest)
|
| 42 |
+
|
| 43 |
+
@st.cache_resource(show_spinner=True)
|
| 44 |
+
def load_detector():
|
| 45 |
+
return Detector(weights_path=ensure_weights())
|
| 46 |
+
|
| 47 |
+
det = load_detector()
|
| 48 |
+
|
| 49 |
+
# ---- helpers ----
|
| 50 |
+
def cam_to_png_bytes(cam: np.ndarray) -> bytes:
|
| 51 |
+
cam = np.asarray(cam, dtype=np.float32)
|
| 52 |
+
cam = np.nan_to_num(cam, nan=0.0); cam = np.clip(cam, 0.0, 1.0)
|
| 53 |
+
rgb = (cm.magma(cam)[..., :3] * 255).astype(np.uint8)
|
| 54 |
+
buf = io.BytesIO(); Image.fromarray(rgb).save(buf, "PNG")
|
| 55 |
+
return buf.getvalue()
|
| 56 |
+
|
| 57 |
+
def analyze(wav_bytes: bytes, source_hint: str):
|
| 58 |
+
proba = det.predict_proba(wav_bytes, source_hint=source_hint)
|
| 59 |
+
exp = det.explain(wav_bytes, source_hint=source_hint)
|
| 60 |
+
return proba, exp
|
| 61 |
+
|
| 62 |
+
# ---- UI ----
|
| 63 |
+
st.set_page_config(page_title="Voice Guard", page_icon="🛡️", layout="wide")
|
| 64 |
+
st.title("🛡️ Voice Guard — Human vs AI Speech")
|
| 65 |
+
|
| 66 |
+
left, right = st.columns([1,2], gap="large")
|
| 67 |
+
with left:
|
| 68 |
+
st.subheader("Input")
|
| 69 |
+
tab_rec, tab_up = st.tabs(["🎙️ Microphone", "📁 Upload"])
|
| 70 |
+
wav_bytes, source_hint = None, None
|
| 71 |
+
|
| 72 |
+
with tab_rec:
|
| 73 |
+
st.caption("Record ~3–7 s. If mic fails, use Upload.")
|
| 74 |
+
try:
|
| 75 |
+
from audio_recorder_streamlit import audio_recorder
|
| 76 |
+
audio = audio_recorder(text="Record",
|
| 77 |
+
recording_color="#ff6a00",
|
| 78 |
+
neutral_color="#2b2b2b",
|
| 79 |
+
icon_size="2x")
|
| 80 |
+
if audio:
|
| 81 |
+
wav_bytes, source_hint = audio, "microphone"
|
| 82 |
+
st.audio(wav_bytes, format="audio/wav")
|
| 83 |
+
except Exception:
|
| 84 |
+
st.info("Recorder not available—use Upload tab.")
|
| 85 |
+
|
| 86 |
+
with tab_up:
|
| 87 |
+
f = st.file_uploader("Upload wav/mp3/m4a/aac", type=["wav","mp3","m4a","aac"])
|
| 88 |
+
if f:
|
| 89 |
+
wav_bytes, source_hint = f.read(), "upload"
|
| 90 |
+
st.audio(wav_bytes)
|
| 91 |
+
|
| 92 |
+
st.markdown("---")
|
| 93 |
+
run = st.button("🔍 Analyze", type="primary", use_container_width=True,
|
| 94 |
+
disabled=wav_bytes is None)
|
| 95 |
+
|
| 96 |
+
with right:
|
| 97 |
+
st.subheader("Results")
|
| 98 |
+
if run and wav_bytes:
|
| 99 |
+
try:
|
| 100 |
+
with st.spinner("Analyzing…"):
|
| 101 |
+
proba, exp = analyze(wav_bytes, source_hint or "auto")
|
| 102 |
+
ph = float(proba.get("human",0.0)); pa = float(proba.get("ai",0.0))
|
| 103 |
+
label = (proba.get("label","human") or "human").upper()
|
| 104 |
+
thr = float(proba.get("threshold",0.5))
|
| 105 |
+
rule = proba.get("decision","threshold")
|
| 106 |
+
thr_src = proba.get("threshold_source","—")
|
| 107 |
+
rscore = proba.get("replay_score", None)
|
| 108 |
+
|
| 109 |
+
c1,c2,c3 = st.columns(3)
|
| 110 |
+
with c1: st.metric("Human", f"{ph*100:.1f}%")
|
| 111 |
+
with c2: st.metric("AI", f"{pa*100:.1f}%")
|
| 112 |
+
with c3:
|
| 113 |
+
color = "#22c55e" if label=="HUMAN" else "#fb7185"
|
| 114 |
+
st.markdown(f"**Final Label:** <span style='color:{color}'>{label}</span>", unsafe_allow_html=True)
|
| 115 |
+
st.caption(f"thr({thr_src})={thr:.2f} • rule={rule} • replay={'—' if rscore is None else f'{float(rscore):.2f}'}")
|
| 116 |
+
|
| 117 |
+
st.markdown("##### Explanation Heatmap")
|
| 118 |
+
cam = np.asarray(exp.get("cam"), dtype=np.float32)
|
| 119 |
+
st.image(cam_to_png_bytes(cam), caption="Spectrogram importance", use_column_width=True)
|
| 120 |
+
|
| 121 |
+
with st.expander("Raw JSON (debug)"):
|
| 122 |
+
st.json({"proba": proba, "explain": {"cam_shape": list(cam.shape)}})
|
| 123 |
+
except Exception as e:
|
| 124 |
+
st.error(f"Analyze failed: {e}")
|
| 125 |
+
|
| 126 |
+
st.caption("Upload 3–7s clips for the most reliable experience across browsers.")
|