Skip to content

Reverse-engineer any video, shot by shot: filmed, AI-generated or coded, and how to remake it. Breakdowns in the open VIDEO.md format. 逆向一切视频,逐个镜头看是拍的、AI 生成的还是代码做的,再告诉你怎么复刻;拆解结果按 VIDEO.md 格式输出。

Size model threads to the machine

june2651186b98f2
diff --git a/docs/cli.md b/docs/cli.md
index ac86742..f2b013f 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -64,6 +64,8 @@ rea-video stems ref.mp4 -o out/ref
- 说话人(装了 `rea-video[asr]` 才做):pyannote segmentation 3.0 + 3D-Speaker CAM++(共约 35 MB)。两个以上的人说话时,每人一条 `stems/voice_S1.wav`…,台词带上是谁说的。
- 音效:BandIt v2 多语种版(约 149 MB;Watcharasupat、Wu、Orife,[arXiv 2407.07275](https://arxiv.org/abs/2407.07275),权重为 CC BY-SA 4.0),把声音拆成对白、音乐、音效三轨,取音效轨。报告里的音效从这一轨找,试听片段也从这一轨剪,听不到人声和配乐。速度约为音频时长的 1.5 倍;模型下载不了时,退回到在混音上找音效。
+分轨和文字识别的模型各用几个线程,按机器自动定:苹果芯片用性能核数,其他机器用物理核数,不超过本进程能用的核数(容器限核也算),最多 8 个;要手动指定就设 `REA_VIDEO_THREADS`。线程数对结果的影响在 16 位音频的精度以下,可以忽略。
+
输出示例(混合片):
```
diff --git a/rea_video/stems.py b/rea_video/stems.py
index be584e3..cdb108c 100644
--- a/rea_video/stems.py
+++ b/rea_video/stems.py
@@ -14,7 +14,7 @@ from pathlib import Path
import numpy as np
-from .util import fetch, sha256_file
+from .util import fetch, model_threads, sha256_file
LOG = logging.getLogger(__name__)
SR = 44100
@@ -28,9 +28,9 @@ GEN = CHUNK - 2 * TRIM
WINDOW = (0.5 - 0.5 * np.cos(2 * np.pi * np.arange(N_FFT) / N_FFT)).astype(np.float32) # periodic hann
-# threads per separation model: the models run alongside the picture analysis, and more threads than the machine's
-# performance cores only fight over them (4 is as fast as all of them alone, and leaves room; the output is the same)
-MODEL_THREADS = max(1, min(4, os.cpu_count() or 4))
+# threads per separation model, set from this machine (util.model_threads): the models run alongside the picture
+# analysis, and more threads than its full-speed cores only fight over them
+MODEL_THREADS = model_threads()
def models_dir() -> Path:
diff --git a/rea_video/util.py b/rea_video/util.py
index 5a7802f..7820969 100644
--- a/rea_video/util.py
+++ b/rea_video/util.py
@@ -185,3 +185,63 @@ def round_floats(obj: Any, nd: int = 4) -> Any:
except ImportError: # pragma: no cover
pass
return obj
+
+
+MAX_MODEL_THREADS = 8 # the ONNX models here stop getting faster past this, and would crowd out the picture analysis
+
+
+def _usable_cpus() -> int:
+ """Logical CPUs this process may run on (a container's or taskset's limit, where the OS reports one)."""
+ try:
+ return len(os.sched_getaffinity(0)) # type: ignore[attr-defined]
+ except (AttributeError, OSError):
+ return os.cpu_count() or 4
+
+
+def _fast_cores() -> int | None:
+ """Cores that run a model thread at full speed: Apple silicon's performance cores (mixing in efficiency cores
+ makes a model slower, not faster), else physical cores (a hyper-thread pair shares one core's arithmetic)."""
+ import subprocess
+
+ if sys.platform == "darwin":
+ for key in ("hw.perflevel0.physicalcpu", "hw.physicalcpu"):
+ try:
+ n = int(subprocess.run(["sysctl", "-n", key], capture_output=True, text=True, timeout=2).stdout.strip())
+ if n > 0:
+ return n
+ except (OSError, ValueError, subprocess.SubprocessError):
+ continue
+ return None
+ if sys.platform.startswith("linux"):
+ try:
+ cores, phys, core = set(), None, None
+ for line in Path("/proc/cpuinfo").read_text().splitlines():
+ k, _, v = line.partition(":")
+ k = k.strip()
+ if k == "physical id":
+ phys = v.strip()
+ elif k == "core id":
+ core = v.strip()
+ elif not line.strip():
+ if core is not None:
+ cores.add((phys, core))
+ phys = core = None
+ if core is not None:
+ cores.add((phys, core))
+ return len(cores) or None
+ except OSError:
+ return None
+ return None
+
+
+def model_threads() -> int:
+ """Threads for each ONNX model (sound separation, OCR): $REA_VIDEO_THREADS if set, else this machine's full-speed
+ cores, never more than the CPUs this process may use, at most MAX_MODEL_THREADS. More threads than that only make
+ the models and the picture analysis fight over the same cores. (The thread count can move a model's output by
+ ~1e-7, far below what a 16-bit file keeps.)"""
+ env = os.getenv("REA_VIDEO_THREADS", "").strip()
+ if env.isdigit() and int(env) > 0:
+ return int(env)
+ usable = _usable_cpus()
+ fast = _fast_cores() or max(1, usable // 2)
+ return max(1, min(fast, usable, MAX_MODEL_THREADS))