touchmusic 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
touchmusic/__init__.py ADDED
@@ -0,0 +1,12 @@
1
+ """TouchMusic standalone performance instrument."""
2
+ import os
3
+ from .runtime import DATA
4
+
5
+ for _key, _folder in {'HF_HOME': 'models', 'HF_HUB_CACHE': 'models/hub',
6
+ 'TORCH_HOME': 'models/torch', 'NUMBA_CACHE_DIR': 'cache/numba',
7
+ 'MPLCONFIGDIR': 'cache/matplotlib'}.items():
8
+ _path = DATA / _folder
9
+ _path.mkdir(parents=True, exist_ok=True)
10
+ os.environ[_key] = str(_path)
11
+ os.environ['HF_HUB_DISABLE_XET'] = '1'
12
+ os.environ['USE_TF'] = '0'
touchmusic/__main__.py ADDED
@@ -0,0 +1,42 @@
1
+ import sys
2
+
3
+
4
+ def main():
5
+ import argparse
6
+ import traceback
7
+ from .runtime import VERSION
8
+ parser = argparse.ArgumentParser(description='TouchMusic live vocal and gesture instrument')
9
+ parser.add_argument('--version', action='version', version='TouchMusic ' + VERSION)
10
+ parser.add_argument('--load-engine', action='store_true', help='load the singing engine when the window opens')
11
+ parser.add_argument('--setup-ai', action='store_true', help='install the optional singing engine and pinned upstream source')
12
+ parser.add_argument('--cpu', action='store_true', help='use CPU wheels for --setup-ai')
13
+ args = parser.parse_args()
14
+ if args.setup_ai:
15
+ from .setup_runtime import setup_ai
16
+ setup_ai(cpu=args.cpu)
17
+ return
18
+ from .library import DATA
19
+ log = open(DATA / 'touchmusic.log', 'a', encoding='utf-8', buffering=1)
20
+ sys.stdout = log
21
+ sys.stderr = log
22
+ from PySide6.QtWidgets import QApplication
23
+ from PySide6.QtCore import QTimer
24
+ from .ui import MainWindow
25
+ app = QApplication(sys.argv)
26
+ app.setApplicationName('TouchMusic')
27
+ try:
28
+ window = MainWindow()
29
+ except Exception:
30
+ traceback.print_exc()
31
+ from PySide6.QtWidgets import QMessageBox
32
+ QMessageBox.critical(None, 'TouchMusic could not start', f'See {DATA / "touchmusic.log"} for details.')
33
+ raise
34
+ window.show()
35
+ print('TouchMusic window initialized', flush=True)
36
+ if args.load_engine:
37
+ QTimer.singleShot(0, window.load_model)
38
+ sys.exit(app.exec())
39
+
40
+
41
+ if __name__ == '__main__':
42
+ main()
@@ -0,0 +1,12 @@
1
+ torch==2.11.0
2
+ torchaudio==2.11.0
3
+ torchvision==0.26.0
4
+ transformers==4.46.3
5
+ huggingface-hub==0.36.0
6
+ accelerate>=0.34,<2
7
+ munch==4.0.0
8
+ einops>=0.8,<0.9
9
+ hydra-core>=1.3,<1.4
10
+ pyyaml>=6,<7
11
+ python-dotenv>=1,<2
12
+ librosa>=0.10,<0.12
@@ -0,0 +1,103 @@
1
+ """Offline alignment from exact streaming sample provenance.
2
+
3
+ The recorder writes one little-endian signed int64 source frame for every
4
+ wet-vocal sample. Unavailable converter output is represented by -1. These
5
+ functions run on a worker after recording closes, never on the audio callback.
6
+ """
7
+ from contextlib import ExitStack
8
+ import os
9
+ from pathlib import Path
10
+ import tempfile
11
+ import numpy as np
12
+ import soundfile as sf
13
+
14
+
15
+ def _temporary_output(output_path, input_paths):
16
+ output_path = Path(output_path)
17
+ if output_path.resolve() in {Path(path).resolve() for path in input_paths}:
18
+ raise ValueError('Choose a separate output file to preserve the original recording.')
19
+ output_path.parent.mkdir(parents=True, exist_ok=True)
20
+ descriptor, name = tempfile.mkstemp(prefix=output_path.stem + '-', suffix='.wav', dir=output_path.parent)
21
+ os.close(descriptor)
22
+ return Path(name)
23
+
24
+
25
+ def align_recording(wet_path, provenance_path, output_path, recording_start_frame=0, block_frames=65536):
26
+ """Place delayed vocal samples at their original capture time in a new WAV.
27
+
28
+ The output has the same duration as the wet recording. Negative origins,
29
+ pre-recording audio and origins beyond its end are omitted. Missing audio
30
+ remains silent. If an origin occurs twice, the later received sample wins.
31
+ The provenance sidecar must contain exactly one '<i8' value per wet frame.
32
+ Returns counts for reporting. Original inputs and existing output survive
33
+ validation/processing errors. Memory use is bounded by block_frames.
34
+ """
35
+ if block_frames < 1:
36
+ raise ValueError('block_frames must be positive.')
37
+ provenance_path = Path(provenance_path)
38
+ with sf.SoundFile(str(wet_path)) as source:
39
+ if provenance_path.stat().st_size != source.frames * 8:
40
+ raise ValueError('Provenance length must match the wet recording frame count.')
41
+ temporary = _temporary_output(output_path, [wet_path, provenance_path])
42
+ aligned = 0
43
+ try:
44
+ with provenance_path.open('rb') as mapping, sf.SoundFile(
45
+ str(temporary), 'w+', source.samplerate, source.channels, subtype='PCM_24'
46
+ ) as output:
47
+ zeros = np.zeros((min(block_frames, source.frames), source.channels), np.float32)
48
+ remaining = source.frames
49
+ while remaining:
50
+ count = min(len(zeros), remaining)
51
+ output.write(zeros[:count])
52
+ remaining -= count
53
+ for block in source.blocks(blocksize=block_frames, dtype='float32', always_2d=True):
54
+ origins = np.frombuffer(mapping.read(len(block) * 8), dtype='<i8')
55
+ targets = origins - int(recording_start_frame)
56
+ valid = (origins >= 0) & (targets >= 0) & (targets < source.frames)
57
+ indices = np.flatnonzero(valid)
58
+ if not len(indices):
59
+ continue
60
+ # Seek once for each contiguous source/destination run.
61
+ boundaries = np.flatnonzero((np.diff(indices) != 1) | (np.diff(targets[indices]) != 1)) + 1
62
+ for run in np.split(indices, boundaries):
63
+ output.seek(int(targets[run[0]]))
64
+ output.write(block[run[0]:run[-1] + 1])
65
+ aligned += len(indices)
66
+ os.replace(temporary, output_path)
67
+ finally:
68
+ temporary.unlink(missing_ok=True)
69
+ return {'frames': source.frames, 'aligned_frames': aligned,
70
+ 'omitted_frames': source.frames - aligned, 'sample_rate': source.samplerate}
71
+
72
+
73
+ def mix_stems(stem_paths, output_path, master_gain=1., block_frames=65536):
74
+ """Sum aligned mono/stereo stems from frame zero and soft-limit a new mix.
75
+
76
+ Files must share a rate and channel count. Shorter files are zero-padded.
77
+ Pass the aligned wet vocal plus accompaniment stems, excluding dry mic
78
+ and the original unaligned wet vocal. This reconstructs a mix from stems;
79
+ it does not reproduce historic master automation.
80
+ """
81
+ stem_paths = list(stem_paths)
82
+ if not stem_paths or block_frames < 1 or not np.isfinite(master_gain):
83
+ raise ValueError('Provide stems, a positive block size and a finite master gain.')
84
+ with ExitStack() as stack:
85
+ sources = [stack.enter_context(sf.SoundFile(str(path))) for path in stem_paths]
86
+ rate, channels = sources[0].samplerate, sources[0].channels
87
+ if any(source.samplerate != rate or source.channels != channels for source in sources):
88
+ raise ValueError('Stem sample rates and channel counts must match.')
89
+ length = max(source.frames for source in sources)
90
+ temporary = _temporary_output(output_path, stem_paths)
91
+ try:
92
+ with sf.SoundFile(str(temporary), 'w', rate, channels, subtype='PCM_24') as output:
93
+ for start in range(0, length, block_frames):
94
+ count = min(block_frames, length - start)
95
+ mixed = np.zeros((count, channels), np.float32)
96
+ for source in sources:
97
+ block = source.read(count, dtype='float32', always_2d=True)
98
+ mixed[:len(block)] += block
99
+ output.write(np.tanh(mixed * master_gain))
100
+ os.replace(temporary, output_path)
101
+ finally:
102
+ temporary.unlink(missing_ok=True)
103
+ return {'frames': length, 'sample_rate': rate, 'stems': len(sources)}