Spaces:
Running
Running
File size: 10,605 Bytes
77ec945 030b699 77ec945 | 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 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | """Paramatch Classification Frontend — HF Spaces Gradio app.
Calls a remote backend (HF Space or URL) via gradio_client for predictions,
renders results as styled HTML cards.
Set the BACKEND_SPACE env var (or HF Spaces secret) to the backend
Space name or URL, e.g. "your-username/paramatch-backend" or "http://localhost:7860".
"""
from __future__ import annotations
import argparse
import os
import subprocess
import tempfile
import gradio as gr
import librosa
from gradio_client import Client, handle_file
MAX_DURATION_SEC = 30
# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------
DEFAULT_TOP_K = 3
# ---------------------------------------------------------------------------
# CSS
# ---------------------------------------------------------------------------
CARD_CSS = """\
.result-container {
display: flex;
flex-direction: column;
gap: 8px;
}
.result-card {
border: 1px solid var(--border-color-primary);
border-radius: 12px;
padding: 12px 16px;
background: var(--background-fill-primary);
transition: box-shadow 0.2s;
}
.result-card:first-child {
border: 2px solid var(--color-accent);
box-shadow: 0 2px 12px var(--color-accent-soft);
}
.result-card-header {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 4px;
}
.rank-badge {
font-size: 1.2em;
min-width: 28px;
text-align: center;
}
.prob-bar-container {
flex: 1;
height: 6px;
background: var(--background-fill-secondary);
border-radius: 3px;
overflow: hidden;
}
.prob-bar {
height: 100%;
border-radius: 3px;
transition: width 0.3s ease;
}
.prob-text {
font-size: 0.95em;
font-weight: 600;
min-width: 52px;
text-align: right;
}
.speaker-name {
font-size: 1.1em;
padding-left: 38px;
color: var(--body-text-color);
}"""
RANK_ICONS = ["\U0001f947", "\U0001f948", "\U0001f949"]
# ---------------------------------------------------------------------------
# HTML builder
# ---------------------------------------------------------------------------
def build_result_html(data: dict) -> str:
"""Build styled HTML cards from backend response."""
results = data.get("results", [])
if not results:
return (
'<div style="text-align:center;padding:32px 16px;color:var(--body-text-color-subdued);">'
'<p style="font-size:1.3em;margin-bottom:8px;">音声をアップロードして「分析」を押してください</p>'
'<p style="font-size:0.9em;">対応形式: WAV, MP3, OGG, FLAC など</p>'
"</div>"
)
show_badges = len(results) > 1
cards: list[str] = []
for i, r in enumerate(results):
prob_pct = r.get("probability", 0)
bar_color = "var(--color-accent)"
if show_badges:
rank_icon = (
RANK_ICONS[i]
if i < len(RANK_ICONS)
else f"<span style='font-weight:600;'>{i + 1}</span>"
)
badge_html = f'<span class="rank-badge">{rank_icon}</span>'
name_pad = "padding-left:38px;"
else:
badge_html = '<span class="rank-badge">\U0001f3af</span>'
name_pad = "padding-left:38px;"
card = f"""\
<div class="result-card">
<div class="result-card-header">
{badge_html}
<div class="prob-bar-container">
<div class="prob-bar" style="width:{prob_pct:.1f}%;background:{bar_color};"></div>
</div>
<span class="prob-text" style="color:{bar_color};">{prob_pct:.1f}%</span>
</div>
<div class="speaker-name" style="{name_pad}">{r.get("speaker_name", "Unknown")}</div>
</div>"""
cards.append(card)
return (
f'<style>{CARD_CSS}</style><div class="result-container">{"".join(cards)}</div>'
'<p style="text-align:right;font-size:0.95em;margin-top:8px;">※敬称略</p>'
)
# ---------------------------------------------------------------------------
# Backend client
# ---------------------------------------------------------------------------
backend_space = os.environ.get("BACKEND_SPACE", "")
backend_client: Client | None = None
def get_client() -> Client:
global backend_client
if backend_client is None:
if not backend_space:
raise gr.Error(
"BACKEND_SPACE env var is not set. "
"Set it to the backend Space name or URL."
)
backend_client = Client(backend_space)
return backend_client
def compress_audio(audio_path: str) -> str:
"""Compress audio to 16kHz mono OGG Vorbis to reduce network transfer."""
stem = os.path.splitext(os.path.basename(audio_path))[0]
out_path = os.path.join(tempfile.gettempdir(), f"{stem}.ogg")
subprocess.run(
["ffmpeg", "-y", "-i", audio_path, "-ar", "16000", "-ac", "1",
"-c:a", "libvorbis", "-q:a", "4", out_path],
capture_output=True, check=True,
)
return out_path
def process(audio_file: str | None) -> str:
if audio_file is None:
return build_result_html({})
duration = librosa.get_duration(path=audio_file)
if duration > MAX_DURATION_SEC:
raise gr.Error(
f"音声が長すぎます({duration:.1f}秒)。{MAX_DURATION_SEC}秒以内の音声をアップロードしてください。"
)
try:
compressed = compress_audio(audio_file)
except subprocess.CalledProcessError:
raise gr.Error("音声ファイルの読み込みに失敗しました。別のファイルをお試しください。")
try:
client = get_client()
data = client.predict(handle_file(compressed), DEFAULT_TOP_K, api_name="/classify")
finally:
os.unlink(compressed)
if not data.get("results"):
return (
'<div style="text-align:center;padding:32px 16px;color:var(--body-text-color-subdued);">'
'<p style="font-size:1.3em;margin-bottom:8px;">一致する話者が見つかりませんでした</p>'
'<p style="font-size:0.9em;">別の音声ファイルをお試しください</p>'
"</div>"
)
return build_result_html(data)
# ---------------------------------------------------------------------------
# App
# ---------------------------------------------------------------------------
TITLE_HTML = """\
<h1 style="text-align:center;margin-bottom:4px;">
<ruby>Paramatch<rp>(</rp><rt>ぱらまっち</rt><rp>)</rp></ruby> — 声優推定デモ
</h1>
"""
DESCRIPTION_MD = f"""\
音声ファイルをアップロードすると、話者識別モデル **Paramatch** が声優の方々の声との類似性を分析し、その結果をスコアとして算出します。
### 開発の目的
話者識別モデル **Paramatch** は、実演家の皆様や事務所・権利者の方々が、生成AI等による**無断学習やなりすまし**といった状況の事実確認を行う際の、客観的な判断をサポートするために開発されました。
このデモ版の公開は、表現者のアイデンティティである「声」の権利を守るための有効な対抗策を模索し、実際の不正事例に対する技術の有効性を検証することを主な目的としています。
"""
DISCLAIMER_ACCURACY_MD = f"""\
### 注意事項
- **{MAX_DURATION_SEC}秒以下**の、BGMやノイズ、複数人の会話が含まれない**声のみのクリアな音声**をご使用ください。
- 音声ファイルの**長さが長いほど精度が向上**します。数秒程度の短い音声では、正確な推定が難しい場合があります。
- 表示される声優名やスコアはあくまで参考値であり、**高スコアであっても、該当する声優本人を元とした音声であることを保証するものではありません。**
声質が似ている別の話者が検知されたり、逆に本人であっても状況によりスコアが低くなったり検知できなかったりする場合があります。
- 本モデルは現在研究開発途中であり、認識精度は完全ではありません。このデモの結果は**参考情報としてのみ**ご利用ください。法的判断の根拠等として使用することはできません。
"""
DISCLAIMER_DATA_MD = """\
### データの取り扱いについて
- 学習データは適切な公開ソースから収集したものであり、音声からの情報解析を行う**Paramatchモデルの学習にのみ**使用しています。音声合成等の生成モデルや、弊社の他製品等への転用は行っておりません。
- アップロードされた音声は、このデモでの分析処理のみに使用され、サーバーへの保存や二次利用は一切行われません。
"""
def ping() -> str:
print("Ping received")
return "pong"
def build_app() -> gr.Blocks:
with gr.Blocks(
title="Paramatch — 声優推定デモ",
theme=gr.themes.Ocean(),
delete_cache=(3600, 600),
) as demo:
gr.HTML(TITLE_HTML)
gr.Markdown(DESCRIPTION_MD)
with gr.Row():
with gr.Column(scale=1):
audio_input = gr.Audio(label="入力音声", type="filepath")
submit_btn = gr.Button("分析", variant="primary")
with gr.Column(scale=1):
output_html = gr.HTML(
value=build_result_html({}),
label="推定結果",
)
gr.Markdown(DISCLAIMER_ACCURACY_MD)
gr.Markdown(DISCLAIMER_DATA_MD)
submit_btn.click(
fn=process,
inputs=[audio_input],
outputs=output_html,
api_visibility="private",
)
gr.Textbox(visible=False).change(fn=ping, inputs=[], outputs=[], api_name="ping")
return demo
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Paramatch Classification Frontend")
parser.add_argument(
"--share", action="store_true", help="Create a public Gradio link"
)
parser.add_argument(
"--top-k", type=int, default=DEFAULT_TOP_K, help="Default top-K results"
)
parser.add_argument("--port", type=int, default=None)
args = parser.parse_args()
DEFAULT_TOP_K = args.top_k
app = build_app()
app.queue(default_concurrency_limit=1, max_size=10, api_open=False).launch(
share=args.share,
server_port=args.port,
)
|