File size: 2,314 Bytes
c538cf2
 
 
 
f1b8f7c
 
c538cf2
 
 
 
 
f1b8f7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c538cf2
 
f1b8f7c
c538cf2
 
 
f1b8f7c
c538cf2
 
 
 
 
 
 
 
 
 
f1b8f7c
 
 
 
 
 
 
 
 
 
 
 
 
 
c538cf2
 
f1b8f7c
 
 
 
 
c538cf2
f1b8f7c
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
import gradio as gr
from transformers import pipeline
import numpy as np

# ─── LOAD MODEL ───────────────────────────────────────────

classifier = pipeline(
    "audio-classification",
    model="MIT/ast-finetuned-audioset-10-10-0.4593"
)

# ─── THREAT MAPPING ───────────────────────────────────────

def map_label(label, score):
    label = label.lower()

    if "engine" in label:
        return f"πŸͺš Chainsaw detected ({round(score, 2)})"

    if "gunshot" in label or "bang" in label or "explosion" in label:
        return f"πŸ”« Gunshot detected ({round(score, 2)})"

    if "vehicle" in label or "car" in label or "truck" in label:
        return f"πŸš— Vehicle detected ({round(score, 2)})"

    if "speech" in label or "talk" in label or "shout" in label:
        return f"πŸ‘€ Human detected ({round(score, 2)})"

    return f"🌿 Safe: {label} ({round(score, 2)})"

# ─── PREDICTION ───────────────────────────────────────────

def predict(audio):
    if audio is None:
        return "🎀 Waiting for audio..."

    sr, data = audio

    # Convert stereo β†’ mono
    if len(data.shape) > 1:
        data = data.mean(axis=1)

    data = data.astype(np.float32)

    results = classifier({
        "raw": data,
        "sampling_rate": sr
    })

    top = results[0]

    # πŸ”₯ APPLY MAPPING HERE
    return map_label(top["label"], top["score"])

# ─── UI ───────────────────────────────────────────────────

with gr.Blocks() as demo:
    gr.Markdown("## 🌲 Forest Guardian - Live Audio Detection")

    mic = gr.Audio(
        sources=["microphone"],
        streaming=True,   # πŸ”₯ LIVE STREAMING
        type="numpy"
    )

    output = gr.Textbox(label="Detection Result")

    mic.stream(fn=predict, inputs=mic, outputs=output)

# ─── RUN ──────────────────────────────────────────────────

demo.launch()