SonicaB commited on
Commit
7c217cb
·
verified ·
1 Parent(s): 88239ed

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. fusion-app/app_local.py +56 -35
fusion-app/app_local.py CHANGED
@@ -1,4 +1,6 @@
1
  import gradio as gr
 
 
2
  import json, os, time, requests, io
3
  import numpy as np
4
  from pathlib import Path
@@ -7,8 +9,7 @@ from pydub import AudioSegment
7
  from utils_media import video_to_frame_audio, load_audio_16k, log_inference
8
  from fusion import clip_image_probs, wav2vec2_embed_energy, wav2vec2_zero_shot_probs, audio_prior_from_rms, fuse_probs, top1_label_from_probs
9
  from fusion import _ensure_audio_prototypes, _proto_embs
10
- from huggingface_hub import InferenceClient
11
- import requests
12
 
13
  HERE = Path(__file__).parent
14
  lables_PATH = HERE / "labels.json"
@@ -33,28 +34,42 @@ def _img_to_jpeg_bytes(pil: Image.Image) -> bytes:
33
  def clip_api_probs(pil_img, prompts, token):
34
  """
35
  Zero-shot image classification via CLIP using the official client.
 
36
  Returns a normalized np.array of shape [len(prompts)].
37
  """
38
  client = InferenceClient(token=token)
 
 
 
 
 
 
 
39
  try:
40
- # Note: parameter name is candidate_labels (not labels)
41
- result = client.zero_shot_image_classification(
42
  image=pil_img,
43
  candidate_labels=prompts,
44
  hypothesis_template="{}",
45
- model="openai/clip-vit-base-patch32",
46
- ) # -> list of {label, score}
47
- except requests.HTTPError as e:
48
- # Graceful fallback: if serverless 404s, call your local CLIP path
49
- if getattr(e, "response", None) and e.response.status_code == 404:
50
- from fusion import clip_image_probs as local_clip
51
- return local_clip(pil_img)
52
- raise
53
-
54
- scores = {d["label"]: float(d["score"]) for d in result}
55
- arr = np.array([scores.get(p, 0.0) for p in prompts], dtype=np.float32)
56
- s = arr.sum()
57
- return (arr / s) if s > 0 else np.ones(len(prompts), dtype=np.float32) / len(prompts)
 
 
 
 
 
 
 
58
 
59
  def _wave_float32_to_wav_bytes(wave_16k: np.ndarray, sr=16000) -> bytes:
60
  samples = (np.clip(wave_16k, -1, 1) * 32767.0).astype(np.int16)
@@ -66,28 +81,34 @@ def _wave_float32_to_wav_bytes(wave_16k: np.ndarray, sr=16000) -> bytes:
66
  def w2v2_api_embed(wave_16k, token):
67
  """
68
  Feature extraction via the official client.
 
69
  Returns a mean-pooled, L2-normalized embedding (np.float32).
70
  """
71
  client = InferenceClient(token=token)
 
 
 
 
 
 
 
 
 
72
  try:
73
- feats = client.feature_extraction(
74
- audio=wave_16k, # 1-D float32 mono PCM @ 16kHz
75
- model="facebook/wav2vec2-base",
76
- )
77
- except requests.HTTPError as e:
78
- # Graceful fallback to local audio features/classifier if serverless 404s
79
- if getattr(e, "response", None) and e.response.status_code == 404:
80
- from fusion import wav2vec2_embed_energy # or your local audio path
81
- emb, _ = wav2vec2_embed_energy(wave_16k)
82
- return emb
83
- raise
84
-
85
- arr = np.asarray(feats, dtype=np.float32) # [T, D] or [1, T, D]
86
- if arr.ndim == 3:
87
- arr = arr[0]
88
- vec = arr.mean(axis=0)
89
- n = np.linalg.norm(vec) + 1e-8
90
- return (vec / n).astype(np.float32)
91
 
92
  _PROTO_EMBS_API = None
93
 
 
1
  import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+ from huggingface_hub.utils import HfHubHTTPError
4
  import json, os, time, requests, io
5
  import numpy as np
6
  from pathlib import Path
 
9
  from utils_media import video_to_frame_audio, load_audio_16k, log_inference
10
  from fusion import clip_image_probs, wav2vec2_embed_energy, wav2vec2_zero_shot_probs, audio_prior_from_rms, fuse_probs, top1_label_from_probs
11
  from fusion import _ensure_audio_prototypes, _proto_embs
12
+
 
13
 
14
  HERE = Path(__file__).parent
15
  lables_PATH = HERE / "labels.json"
 
34
  def clip_api_probs(pil_img, prompts, token):
35
  """
36
  Zero-shot image classification via CLIP using the official client.
37
+ Strategy: try pinned model → retry with provider default → fallback to local.
38
  Returns a normalized np.array of shape [len(prompts)].
39
  """
40
  client = InferenceClient(token=token)
41
+
42
+ def _to_arr(result):
43
+ scores = {d["label"]: float(d["score"]) for d in result}
44
+ arr = np.array([scores.get(p, 0.0) for p in prompts], dtype=np.float32)
45
+ s = arr.sum()
46
+ return (arr / s) if s > 0 else np.ones(len(prompts), dtype=np.float32) / len(prompts)
47
+
48
  try:
49
+ res = client.zero_shot_image_classification(
 
50
  image=pil_img,
51
  candidate_labels=prompts,
52
  hypothesis_template="{}",
53
+ model=CLIP_MODEL,
54
+ )
55
+ return _to_arr(res)
56
+ except (StopIteration, HfHubHTTPError) as e:
57
+
58
+ print(f"[WARN] CLIP provider/model unavailable ({e}); retrying with provider default.", flush=True)
59
+ pass
60
+
61
+ try:
62
+ res = client.zero_shot_image_classification(
63
+ image=pil_img,
64
+ candidate_labels=prompts,
65
+ hypothesis_template="{}",
66
+ model=None,
67
+ )
68
+ return _to_arr(res)
69
+ except (StopIteration, HfHubHTTPError) as e:
70
+ print(f"[WARN] CLIP default route failed ({e}); falling back to local.", flush=True)
71
+ from fusion import clip_image_probs as local_clip
72
+ return local_clip(pil_img)
73
 
74
  def _wave_float32_to_wav_bytes(wave_16k: np.ndarray, sr=16000) -> bytes:
75
  samples = (np.clip(wave_16k, -1, 1) * 32767.0).astype(np.int16)
 
81
  def w2v2_api_embed(wave_16k, token):
82
  """
83
  Feature extraction via the official client.
84
+ Strategy: try pinned model → retry with provider default → fallback to local.
85
  Returns a mean-pooled, L2-normalized embedding (np.float32).
86
  """
87
  client = InferenceClient(token=token)
88
+
89
+ def _mean_l2(feats):
90
+ arr = np.asarray(feats, dtype=np.float32) # [T, D] or [1, T, D]
91
+ if arr.ndim == 3:
92
+ arr = arr[0]
93
+ vec = arr.mean(axis=0)
94
+ n = np.linalg.norm(vec) + 1e-8
95
+ return (vec / n).astype(np.float32)
96
+
97
  try:
98
+ feats = client.feature_extraction(audio=wave_16k, model=W2V2_MODEL)
99
+ return _mean_l2(feats)
100
+ except (StopIteration, HfHubHTTPError) as e:
101
+ print(f"[WARN] W2V2 provider/model unavailable ({e}); retrying with provider default.", flush=True)
102
+ pass
103
+
104
+ try:
105
+ feats = client.feature_extraction(audio=wave_16k, model=None)
106
+ return _mean_l2(feats)
107
+ except (StopIteration, HfHubHTTPError) as e:
108
+ print(f"[WARN] W2V2 default route failed ({e}); falling back to local.", flush=True)
109
+ from fusion import wav2vec2_embed_energy
110
+ emb, _ = wav2vec2_embed_energy(wave_16k)
111
+ return emb
 
 
 
 
112
 
113
  _PROTO_EMBS_API = None
114