#!/usr/bin/env bash
# 修复 03: nudenet(用 GitHub API 资源端点, browser_download_url 会跳登录页) + ecapa(hf CLI Xet 失败)
# 所有 curl 带 --speed-time 防卡死, --retry 自动重连(-C - 续传)
set -uo pipefail
T=/srv/mirror/models/triton
PY=/home/ecs-user/dlvenv/bin/python
MSAPI=https://www.modelscope.cn/api/v1/models
G="--connect-timeout 20 --speed-limit 51200 --speed-time 30 --retry 30 --retry-delay 3 -C -"

# ---- nudenet 640m.onnx (期望 103538690 bytes), GitHub API asset endpoint ----
echo "=== fix nudenet (api asset) ==="
WANT=103538690
AID=176832019   # notAI-tech/NudeNet v3.4-weights 640m.onnx
out="$T/nudenet/detector_640.onnx"
got=$(stat -c%s "$out" 2>/dev/null || echo 0)
if [ "$got" != "$WANT" ]; then
  curl -fL $G -s -H "Accept: application/octet-stream" -o "$out" \
       "https://api.github.com/repos/notAI-tech/NudeNet/releases/assets/$AID" || true
  got=$(stat -c%s "$out" 2>/dev/null || echo 0)
fi
[ "$got" = "$WANT" ] && echo "  [ok] nudenet $got" || echo "  [WARN] nudenet got=$got want=$WANT"

# ---- ecapa: modelscope 列表 + hf-mirror 字节 ----
echo "=== fix ecapa ==="
ED="$T/ecapa_tdnn/spkrec-ecapa-voxceleb"
rm -rf "$ED/.cache"; mkdir -p "$ED"
curl -s --max-time 20 "$MSAPI/speechbrain/spkrec-ecapa-voxceleb/repo/files?Revision=master&Recursive=true" -o /tmp/ecapa.json
$PY -c "import json;d=json.load(open('/tmp/ecapa.json'));[print(f['Path']+'\t'+str(f['Size'])) for f in d['Data']['Files'] if f['Type']=='blob' and not f['Path'].startswith('example')]" > /tmp/ecapa.tsv
while IFS=$'\t' read -r path size; do
  [ -z "$path" ] && continue
  o="$ED/$path"; mkdir -p "$(dirname "$o")"
  if [ -f "$o" ] && [ "$(stat -c%s "$o")" = "$size" ]; then echo "  [skip] $path"; continue; fi
  curl -fL $G -s -o "$o" "https://hf-mirror.com/speechbrain/spkrec-ecapa-voxceleb/resolve/main/$path" \
   || curl -fL $G -s -o "$o" "$MSAPI/speechbrain/spkrec-ecapa-voxceleb/repo?Revision=master&FilePath=$path"
  echo "  [ok] $path ($(stat -c%s "$o" 2>/dev/null))"
done < /tmp/ecapa.tsv

for d in "$T"/*/; do ( cd "$d" && find . -type f ! -name .files ! -path './*/.cache/*' -printf '%P\n' | sort > .files ); done
echo "=== 03b done ==="
find "$T" -type f ! -name .files -printf "%10s  %P\n" | sort -k2
