ellagranger commited on
Commit
384d531
·
1 Parent(s): dd51723

Docker output fix & BeatNet fix

Browse files
Files changed (3) hide show
  1. Dockerfile +3 -1
  2. app.py +12 -23
  3. scripts/patch_madmom.py +114 -0
Dockerfile CHANGED
@@ -38,4 +38,6 @@ COPY . /app
38
  ENV PORT=7860
39
  EXPOSE 7860
40
 
41
- CMD ["python", "app.py"]
 
 
 
38
  ENV PORT=7860
39
  EXPOSE 7860
40
 
41
+ ENV PYTHONUNBUFFERED=1
42
+ ENV PYTHONIOENCODING=UTF-8
43
+ CMD ["python", "-u", "app.py"]
app.py CHANGED
@@ -16,6 +16,14 @@ from pyharp.media.audio import save_audio
16
  from pyharp import LabelList, AudioLabel, OutputLabel
17
  from audiotools import AudioSignal
18
 
 
 
 
 
 
 
 
 
19
  LOUDNESS_DB = -16.
20
  SAMPLE_RATE = 48_000
21
  ENCODEC_SAMPLE_RATE = 16_000
@@ -28,30 +36,11 @@ model_card = ModelCard(
28
  tags=["beat detection"]
29
  )
30
 
31
- print("Initializing BeatNet model...")
32
  estimator = BeatNet(1, mode="offline", inference_model="DBN", plot=[], thread=False)
33
 
34
- def load_audio(audio_path):
35
- try:
36
- wav, sr = librosa.load(audio_path, mono=True)
37
- return wav, sr
38
-
39
- except Exception as e:
40
- print(f"Audio preprocessing failed: {e}")
41
- raise ValueError(f"Failed to load audio: {str(e)}")
42
-
43
  def process_fn(inp_audio):
44
- audio_np, sr = load_audio(inp_audio)
45
-
46
- print(f"sr: {sr}, audio shape: {audio_np.shape}")
47
- if audio_np.ndim == 1:
48
- audio_np = audio_np[None, None, :]
49
- else:
50
- audio_np = np.transpose(audio_np, (1, 0))[None, ...]
51
-
52
- print(f"formatted audio: {audio_np.shape}")
53
-
54
- output = estimator.process(audio_np)
55
 
56
  output_labels = LabelList()
57
 
@@ -61,8 +50,8 @@ def process_fn(inp_audio):
61
  t = t,
62
  label = f"{b}",
63
  description = f"Beat: {b}",
64
- color = OutputLabel.rgb_color_to_int(),
65
- amplitude = 1.0
66
  )
67
  )
68
 
 
16
  from pyharp import LabelList, AudioLabel, OutputLabel
17
  from audiotools import AudioSignal
18
 
19
+ import logging, sys
20
+ logging.basicConfig(
21
+ level=logging.INFO,
22
+ format="%(asctime)s %(levelname)s %(message)s",
23
+ handlers=[logging.StreamHandler(sys.stderr)],
24
+ )
25
+ log = logging.getLogger("app")
26
+
27
  LOUDNESS_DB = -16.
28
  SAMPLE_RATE = 48_000
29
  ENCODEC_SAMPLE_RATE = 16_000
 
36
  tags=["beat detection"]
37
  )
38
 
39
+ log.info("Initializing BeatNet model...")
40
  estimator = BeatNet(1, mode="offline", inference_model="DBN", plot=[], thread=False)
41
 
 
 
 
 
 
 
 
 
 
42
  def process_fn(inp_audio):
43
+ output = estimator.process(inp_audio)
 
 
 
 
 
 
 
 
 
 
44
 
45
  output_labels = LabelList()
46
 
 
50
  t = t,
51
  label = f"{b}",
52
  description = f"Beat: {b}",
53
+ color = OutputLabel.rgb_color_to_int(0, 164, 235),
54
+ amplitude = 1.0 if b == 1.0 else 0.0
55
  )
56
  )
57
 
scripts/patch_madmom.py ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # scripts/patch_madmom.py
2
+ import re
3
+ import site
4
+ from pathlib import Path
5
+
6
+ FUTURE_LINE = "from __future__ import absolute_import, division, print_function"
7
+
8
+ ALIASES = [
9
+ (re.compile(r"\bnp\.float\b"), "float"),
10
+ (re.compile(r"\bnp\.int\b"), "int"),
11
+ (re.compile(r"\bnp\.bool\b"), "bool"),
12
+ (re.compile(r"\bnp\.object\b"), "object"),
13
+ (re.compile(r"\bnp\.complex\b"), "complex"),
14
+ ]
15
+
16
+ def find_madmom_root() -> Path:
17
+ for p in site.getsitepackages():
18
+ cand = Path(p) / "madmom"
19
+ if cand.exists():
20
+ return cand
21
+ raise RuntimeError("madmom package not found in site-packages")
22
+
23
+ def patch_processors(madmom_root: Path) -> None:
24
+ proc = madmom_root / "processors.py"
25
+ if not proc.exists():
26
+ return
27
+ s = proc.read_text(encoding="utf-8")
28
+ s2 = s.replace(
29
+ "from collections import MutableSequence",
30
+ "from collections.abc import MutableSequence",
31
+ )
32
+ if s2 != s:
33
+ proc.write_text(s2, encoding="utf-8")
34
+
35
+ def patch_numpy_aliases(madmom_root: Path) -> None:
36
+ patched = 0
37
+ for f in madmom_root.rglob("*.py"):
38
+ try:
39
+ s = f.read_text(encoding="utf-8")
40
+ except Exception:
41
+ continue
42
+ s2 = s
43
+ for pat, repl in ALIASES:
44
+ s2 = pat.sub(repl, s2)
45
+ if s2 != s:
46
+ f.write_text(s2, encoding="utf-8")
47
+ patched += 1
48
+ print(f"Patched NumPy aliases in {patched} madmom files")
49
+
50
+ def patch_utils_future_safe(madmom_root: Path) -> None:
51
+ u = madmom_root / "utils" / "__init__.py"
52
+ if not u.exists():
53
+ raise RuntimeError("madmom/utils/__init__.py not found")
54
+
55
+ s = u.read_text(encoding="utf-8")
56
+
57
+ # Remove any existing future import (we'll reinsert correctly)
58
+ s = re.sub(
59
+ r"^\s*from __future__ import absolute_import,\s*division,\s*print_function\s*\n",
60
+ "",
61
+ s,
62
+ flags=re.M,
63
+ )
64
+
65
+ lines = s.splitlines(True)
66
+
67
+ # Find insertion point after shebang/encoding/docstring
68
+ i = 0
69
+ if i < len(lines) and lines[i].startswith("#!"):
70
+ i += 1
71
+ if i < len(lines) and re.match(r"^#.*coding[:=]\s*[-\w.]+", lines[i]):
72
+ i += 1
73
+ if i < len(lines) and re.match(r'^\s*[ruRU]?[\'"]{3}', lines[i]):
74
+ quote = lines[i].lstrip()[0:3] # ''' or """
75
+ i += 1
76
+ while i < len(lines) and quote not in lines[i]:
77
+ i += 1
78
+ if i < len(lines):
79
+ i += 1
80
+
81
+ # Insert future import at the right place
82
+ lines.insert(i, FUTURE_LINE + "\n")
83
+ s = "".join(lines)
84
+
85
+ compat = """
86
+ # --- Compatibility for Python 3 ---
87
+ try:
88
+ basestring
89
+ except NameError:
90
+ basestring = str
91
+
92
+ try:
93
+ integer
94
+ except NameError:
95
+ integer = int
96
+ # ---------------------------------
97
+ """
98
+ if "basestring = str" not in s:
99
+ s = s.replace(FUTURE_LINE + "\n", FUTURE_LINE + "\n" + compat)
100
+
101
+ s = re.sub(r"string_types\s*=\s*basestring", "string_types = (str,)", s)
102
+ s = re.sub(r"integer_types\s*=\s*\(int,\s*integer\)", "integer_types = (int,)", s)
103
+
104
+ u.write_text(s, encoding="utf-8")
105
+
106
+ def main() -> None:
107
+ madmom_root = find_madmom_root()
108
+ patch_processors(madmom_root)
109
+ # patch_numpy_aliases(madmom_root)
110
+ patch_utils_future_safe(madmom_root)
111
+ print("madmom patched OK:", madmom_root)
112
+
113
+ if __name__ == "__main__":
114
+ main()