umarfarzan commited on
Commit
2a63c36
·
verified ·
1 Parent(s): 2bb2314

Fix scoring of very short clips

Browse files
acliptic/models/moment_ranker5.py CHANGED
@@ -1,24 +1,55 @@
1
  """Adapter for Acliptic v5 (acliptic/ranker5.py): sound fingerprints + speech meaning + loudness + talk cues, judged
2
  in context. Needs no PyTorch and no separate text model (only ONNX Runtime and scikit-learn).
3
 
4
- models.json: {"type": "moment_ranker5", "path": "<dir with ranker5.pkl>", "version": "5.0"}
 
 
5
  Without audio, the sound and loudness inputs are missing and the ranker works from the transcript alone.
6
  """
7
  from __future__ import annotations
8
 
 
 
 
9
  import numpy as np
10
  import pandas as pd
11
 
12
  from .base import ModelInfo, ModelProvider, ModelUnavailable, ScoreRequest, SegmentScore
13
 
14
  CHUNK_SEGS = 20 # decode 10 minutes at a time
 
15
 
16
 
17
  class MomentRanker5Provider(ModelProvider):
18
- def __init__(self, id_: str, path: str, version: str, display_name: str = "", **_):
 
19
  self.id, self.path, self.version = id_, path, version
20
  self.display_name = display_name or f"Acliptic v{version}"
 
 
21
  self._ranker = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
  def info(self) -> ModelInfo:
24
  return ModelInfo(id=self.id, version=self.version, display_name=self.display_name, kind="real",
@@ -27,6 +58,7 @@ class MomentRanker5Provider(ModelProvider):
27
  "from real streams.")
28
 
29
  def _load(self):
 
30
  if self._ranker is None:
31
  try:
32
  from ..ranker5 import Ranker5
@@ -51,6 +83,7 @@ class MomentRanker5Provider(ModelProvider):
51
  return pd.concat(louds, ignore_index=True), np.concatenate(embs)
52
 
53
  def signals(self, req: ScoreRequest):
 
54
  from .. import config, sound
55
  from ..ranker5 import text_embeddings
56
  texts = [s.text for s in req.segments]
@@ -73,6 +106,7 @@ class MomentRanker5Provider(ModelProvider):
73
 
74
  # ---- live: one chunk at a time, ranked against the past only ----
75
  def live_score(self, f, dur, text, has_audio, state: dict) -> float:
 
76
  from .. import config, sound
77
  from ..ranker import SR, loudness_one
78
  from ..ranker5 import text_embeddings
 
1
  """Adapter for Acliptic v5 (acliptic/ranker5.py): sound fingerprints + speech meaning + loudness + talk cues, judged
2
  in context. Needs no PyTorch and no separate text model (only ONNX Runtime and scikit-learn).
3
 
4
+ models.json: {"type": "moment_ranker5", "path": "<dir with ranker5.pkl>", "version": "5.0",
5
+ "hf_repo": "<owner/name>", "hf_revision": "<commit>"}
6
+ With hf_repo the ranker, bge, CLAP and Whisper come from that Hugging Face repo, and `path` is only a fallback.
7
  Without audio, the sound and loudness inputs are missing and the ranker works from the transcript alone.
8
  """
9
  from __future__ import annotations
10
 
11
+ import logging
12
+ from pathlib import Path
13
+
14
  import numpy as np
15
  import pandas as pd
16
 
17
  from .base import ModelInfo, ModelProvider, ModelUnavailable, ScoreRequest, SegmentScore
18
 
19
  CHUNK_SEGS = 20 # decode 10 minutes at a time
20
+ log = logging.getLogger("acliptic.v5")
21
 
22
 
23
  class MomentRanker5Provider(ModelProvider):
24
+ def __init__(self, id_: str, path: str, version: str, display_name: str = "", hf_repo: str | None = None,
25
+ hf_revision: str | None = None, **_):
26
  self.id, self.path, self.version = id_, path, version
27
  self.display_name = display_name or f"Acliptic v{version}"
28
+ self.hf_repo, self.hf_revision = hf_repo, hf_revision
29
+ self.source = "local files" if not hf_repo else "not loaded yet"
30
  self._ranker = None
31
+ self._ready = not hf_repo
32
+
33
+ def prepare(self):
34
+ """Fetch the Hugging Face bundle and point the app's sound, text and speech models at it."""
35
+ if self._ready:
36
+ return
37
+ from .. import config, hub
38
+ try:
39
+ d = hub.fetch(self.hf_repo, self.hf_revision)
40
+ except Exception as e:
41
+ if not (Path(self.path) / "ranker5.pkl").exists():
42
+ self.source = "unavailable"
43
+ raise ModelUnavailable(f"{self.display_name}: couldn't load {self.hf_repo} from Hugging Face ({type(e).__name__})") from e
44
+ log.warning("Couldn't reach %s (%s); using the local copy", self.hf_repo, type(e).__name__)
45
+ self.source = "local copy (Hugging Face unavailable)"
46
+ else:
47
+ self.path = str(d)
48
+ config.ASR_MODEL = d / "faster-whisper-base.en"
49
+ config.CLAP_ONNX = d / "clap-onnx"
50
+ config.TEXT_EMB_ONNX = d / "bge-onnx"
51
+ self.source = f"Hugging Face: {self.hf_repo}"
52
+ self._ready = True
53
 
54
  def info(self) -> ModelInfo:
55
  return ModelInfo(id=self.id, version=self.version, display_name=self.display_name, kind="real",
 
58
  "from real streams.")
59
 
60
  def _load(self):
61
+ self.prepare()
62
  if self._ranker is None:
63
  try:
64
  from ..ranker5 import Ranker5
 
83
  return pd.concat(louds, ignore_index=True), np.concatenate(embs)
84
 
85
  def signals(self, req: ScoreRequest):
86
+ self.prepare()
87
  from .. import config, sound
88
  from ..ranker5 import text_embeddings
89
  texts = [s.text for s in req.segments]
 
106
 
107
  # ---- live: one chunk at a time, ranked against the past only ----
108
  def live_score(self, f, dur, text, has_audio, state: dict) -> float:
109
+ self.prepare()
110
  from .. import config, sound
111
  from ..ranker import SR, loudness_one
112
  from ..ranker5 import text_embeddings
acliptic/ranker5.py CHANGED
@@ -68,9 +68,10 @@ def _shift(x, k):
68
  """x moved k segments (k > 0: the value k segments earlier), edges filled with the nearest value."""
69
  if k == 0:
70
  return x
 
71
  if k > 0:
72
- return np.r_[np.repeat(x[:1], k), x[:-k]]
73
- return np.r_[x[-k:], np.repeat(x[-1:], -k)]
74
 
75
 
76
  def featurize5(raw: pd.DataFrame, clap: np.ndarray | None, temb: np.ndarray | None, proj: dict, causal: bool = False) -> pd.DataFrame:
 
68
  """x moved k segments (k > 0: the value k segments earlier), edges filled with the nearest value."""
69
  if k == 0:
70
  return x
71
+ n = len(x) # a clip shorter than the shift is all edge
72
  if k > 0:
73
+ return np.r_[np.repeat(x[:1], min(k, n)), x[:-k]]
74
+ return np.r_[x[-k:], np.repeat(x[-1:], min(-k, n))]
75
 
76
 
77
  def featurize5(raw: pd.DataFrame, clap: np.ndarray | None, temb: np.ndarray | None, proj: dict, causal: bool = False) -> pd.DataFrame: