Spaces:
Running

CED-Tiny / app.py
harp-dev's picture
Drop the comment on ssr_mode
c1bc11c verified
Raw History Blame Contribute Delete
4.2 kB
from __future__ import annotations
import spaces # imported first, as ZeroGPU requires
import math
import gradio as gr
import soundfile as sf
from ced_runtime import classify_audio, load_model
from pyharp import AudioLabel, LabelList, ModelCard, build_endpoint
from pyharp.tags import Channels, SampleRate, Subcategory
MIN_AUDIO_SECONDS = 0.25
MAX_AUDIO_SECONDS = 120
model_card = ModelCard(
name="CED-Tiny",
description=(
"Identify the most likely AudioSet sound events in an audio clip with "
"the lightweight CED-Tiny model on CPU. Repository: "
"https://github.com/RicherMans/CED Paper: "
"https://arxiv.org/abs/2308.11957"
),
author="Heinrich Dinkel et al. / Xiaomi",
tags=[Subcategory.GENERAL_AUDIO_ANALYSIS, SampleRate(16000), Channels(1), 'audioset', 'domain:general-audio'],
)
def _validate_audio(path: str | None) -> str:
if not path:
raise gr.Error("Please upload an audio file.")
try:
info = sf.info(path)
except Exception as exc:
raise gr.Error("Could not read the audio file.") from exc
duration = info.duration
if info.samplerate <= 0 or not math.isfinite(duration):
raise gr.Error("The audio file has invalid metadata.")
if duration < MIN_AUDIO_SECONDS:
raise gr.Error("Audio must be at least 0.25 seconds long.")
if duration > MAX_AUDIO_SECONDS:
raise gr.Error(
f"Audio must be no longer than {MAX_AUDIO_SECONDS} seconds. "
f"Received {duration:.1f} seconds."
)
return path
def process_fn(audio_path: str | None, top_k: int) -> tuple[str, LabelList]:
audio_path = _validate_audio(audio_path)
try:
count = int(top_k)
except (TypeError, ValueError, OverflowError) as exc:
raise gr.Error("Number of tags must be an integer from 1 to 30.") from exc
if not 1 <= count <= 30:
raise gr.Error("Number of tags must be between 1 and 30.")
tags = classify(audio_path, count)
# HARP shows labels over an audio output, so the input is returned for them to sit on. Each
# tag's probability is averaged over the whole clip, so each label spans it.
duration = sf.info(audio_path).duration
labels = LabelList()
for tag in tags:
labels.append(AudioLabel(
t=0.0,
duration=duration,
label=tag["label"],
description=f"probability {tag['score']:.0%}",
amplitude=tag["score"],
))
return audio_path, labels
@spaces.GPU
def classify(audio_path: str, count: int) -> list[dict]:
try:
return classify_audio(audio_path, count)
except Exception as exc:
raise gr.Error("CED-Tiny could not analyze this audio file.") from exc
# pyharp runs process_fn in a worker, which imports this file as __mp_main__ and starts with the
# server, so the model is loaded there, before the first request rather than during it.
if __name__ != "__main__":
load_model()
if __name__ == "__main__":
with gr.Blocks(title="CED-Tiny Audio Tagging") as demo:
input_components = [
gr.Audio(
type="filepath",
label="Audio",
)
.harp_required(True)
.set_info("Audio clip from 0.25 to 120 seconds."),
gr.Slider(
minimum=1,
maximum=30,
value=10,
step=1,
label="Number of Tags",
).set_info("Return the highest-scoring AudioSet labels."),
]
output_components = [
gr.Audio(type="filepath", label="Audio with Tags").set_info(
"The input, returned to carry the tags."
),
gr.JSON(label="Audio Tags").set_info(
"The highest-scoring AudioSet labels, each spanning the clip, with its probability."
),
]
build_endpoint(
model_card=model_card,
input_components=input_components,
output_components=output_components,
process_fn=process_fn,
)
demo.queue(default_concurrency_limit=1).launch(show_error=True, pwa=True, ssr_mode=False)