Spaces:
Runtime error
Runtime error
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -19,8 +19,9 @@ os.environ.setdefault("HF_XET_HIGH_PERFORMANCE", "1")
|
|
| 19 |
|
| 20 |
N_CPUS = os.cpu_count() or 2
|
| 21 |
BATCH_SIZE = 64 # max clips per ONNX forward pass
|
| 22 |
-
API_TIMEOUT =
|
| 23 |
API_RETRIES = 2
|
|
|
|
| 24 |
|
| 25 |
|
| 26 |
def _ts() -> str:
|
|
@@ -72,39 +73,51 @@ def _batch_embed(arrays: list[np.ndarray]) -> np.ndarray:
|
|
| 72 |
|
| 73 |
# ββ Audio fetching ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
def _fetch_audio_urls(repo_id: str, n: int, token: str | None) -> tuple[list[str], str]:
|
| 76 |
-
"""
|
| 77 |
headers = {"Authorization": f"Bearer {token}"} if token else {}
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
| 79 |
last_err = ""
|
| 80 |
-
for
|
| 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 |
-
except Exception as exc:
|
| 107 |
-
last_err = f"{exc} (attempt {attempt})"
|
| 108 |
return [], last_err
|
| 109 |
|
| 110 |
|
|
@@ -149,24 +162,37 @@ def _fetch_repo_audio(
|
|
| 149 |
)
|
| 150 |
return repo, arrays
|
| 151 |
|
| 152 |
-
# Streaming fallback
|
| 153 |
-
log.append(f"[{_ts()}] {short}: β datasets-server failed ({api_status}) β streaming fallback")
|
| 154 |
t1 = time.time()
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
except Exception as exc:
|
| 172 |
log.append(f"[{_ts()}] {short}: β {exc} (total={int((time.time()-t0)*1000)}ms)")
|
|
|
|
| 19 |
|
| 20 |
N_CPUS = os.cpu_count() or 2
|
| 21 |
BATCH_SIZE = 64 # max clips per ONNX forward pass
|
| 22 |
+
API_TIMEOUT = 15 # seconds per datasets-server attempt
|
| 23 |
API_RETRIES = 2
|
| 24 |
+
STREAMING_TIMEOUT = 45 # seconds before giving up on streaming fallback
|
| 25 |
|
| 26 |
|
| 27 |
def _ts() -> str:
|
|
|
|
| 73 |
|
| 74 |
# ββ Audio fetching ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 75 |
|
| 76 |
+
def _parse_audio_urls(rows: list) -> list[str]:
|
| 77 |
+
urls = []
|
| 78 |
+
for row in rows:
|
| 79 |
+
audio = row["row"].get("audio", {})
|
| 80 |
+
if isinstance(audio, list):
|
| 81 |
+
audio = audio[0] if audio else {}
|
| 82 |
+
if isinstance(audio, dict) and "src" in audio:
|
| 83 |
+
urls.append(audio["src"])
|
| 84 |
+
return urls
|
| 85 |
+
|
| 86 |
+
|
| 87 |
def _fetch_audio_urls(repo_id: str, n: int, token: str | None) -> tuple[list[str], str]:
|
| 88 |
+
"""Try /rows then /first-rows endpoints with retry. Returns (urls, status)."""
|
| 89 |
headers = {"Authorization": f"Bearer {token}"} if token else {}
|
| 90 |
+
endpoints = [
|
| 91 |
+
("/rows", {"dataset": repo_id, "config": "default", "split": "train", "offset": 0, "length": n}),
|
| 92 |
+
("/first-rows", {"dataset": repo_id, "config": "default", "split": "train"}),
|
| 93 |
+
]
|
| 94 |
last_err = ""
|
| 95 |
+
for endpoint, params in endpoints:
|
| 96 |
+
for attempt in range(1, API_RETRIES + 1):
|
| 97 |
+
try:
|
| 98 |
+
t0 = time.time()
|
| 99 |
+
resp = requests.get(
|
| 100 |
+
f"{DATASETS_SERVER}{endpoint}", params=params,
|
| 101 |
+
headers=headers, timeout=API_TIMEOUT,
|
| 102 |
+
)
|
| 103 |
+
elapsed = int((time.time() - t0) * 1000)
|
| 104 |
+
if not resp.ok:
|
| 105 |
+
last_err = f"{endpoint} HTTP {resp.status_code} (attempt {attempt}, {elapsed}ms)"
|
| 106 |
+
break # 4xx/5xx β no point retrying same endpoint
|
| 107 |
+
key = "rows" if endpoint == "/rows" else "rows"
|
| 108 |
+
rows = resp.json().get(key, [])
|
| 109 |
+
if not rows:
|
| 110 |
+
last_err = f"{endpoint} empty ({elapsed}ms)"
|
| 111 |
+
break
|
| 112 |
+
urls = _parse_audio_urls(rows[:n])
|
| 113 |
+
if urls:
|
| 114 |
+
return urls, f"{endpoint} {elapsed}ms"
|
| 115 |
+
last_err = f"{endpoint} no src ({elapsed}ms)"
|
| 116 |
+
break
|
| 117 |
+
except requests.Timeout:
|
| 118 |
+
last_err = f"{endpoint} timeout>{API_TIMEOUT}s (attempt {attempt})"
|
| 119 |
+
except Exception as exc:
|
| 120 |
+
last_err = f"{endpoint} {exc} (attempt {attempt})"
|
|
|
|
|
|
|
| 121 |
return [], last_err
|
| 122 |
|
| 123 |
|
|
|
|
| 162 |
)
|
| 163 |
return repo, arrays
|
| 164 |
|
| 165 |
+
# Streaming fallback with timeout
|
| 166 |
+
log.append(f"[{_ts()}] {short}: β datasets-server failed ({api_status}) β streaming fallback (timeout={STREAMING_TIMEOUT}s)")
|
| 167 |
t1 = time.time()
|
| 168 |
+
|
| 169 |
+
def _stream() -> list[np.ndarray]:
|
| 170 |
+
from datasets import load_dataset, Audio as HFAudio
|
| 171 |
+
ds = load_dataset(repo, split="train", streaming=True, token=token)
|
| 172 |
+
ds = ds.cast_column("audio", HFAudio(decode=False))
|
| 173 |
+
result = []
|
| 174 |
+
for j, row in enumerate(ds):
|
| 175 |
+
if j >= n_samples:
|
| 176 |
+
break
|
| 177 |
+
raw = row["audio"]
|
| 178 |
+
audio_bytes = raw.get("bytes") or open(raw["path"], "rb").read()
|
| 179 |
+
a, sr = sf.read(io.BytesIO(audio_bytes))
|
| 180 |
+
result.append(_to_array(a, sr, audio_sec))
|
| 181 |
+
elapsed = int((time.time() - t1) * 1000)
|
| 182 |
+
log.append(f"[{_ts()}] {short}: streaming clip {j+1}/{n_samples} ({len(audio_bytes)//1024}KB, {elapsed}ms so far)")
|
| 183 |
+
return result
|
| 184 |
+
|
| 185 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as ex:
|
| 186 |
+
fut = ex.submit(_stream)
|
| 187 |
+
try:
|
| 188 |
+
arrays = fut.result(timeout=STREAMING_TIMEOUT)
|
| 189 |
+
total_ms = int((time.time() - t0) * 1000)
|
| 190 |
+
log.append(f"[{_ts()}] {short}: β streaming done, {len(arrays)} clips, total={total_ms}ms")
|
| 191 |
+
return repo, arrays
|
| 192 |
+
except concurrent.futures.TimeoutError:
|
| 193 |
+
total_ms = int((time.time() - t0) * 1000)
|
| 194 |
+
log.append(f"[{_ts()}] {short}: β streaming timeout after {STREAMING_TIMEOUT}s β skipping")
|
| 195 |
+
return repo, []
|
| 196 |
|
| 197 |
except Exception as exc:
|
| 198 |
log.append(f"[{_ts()}] {short}: β {exc} (total={int((time.time()-t0)*1000)}ms)")
|