File size: 5,929 Bytes
6182d7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36e50f2
 
 
 
 
 
6182d7b
 
 
 
 
 
 
 
 
 
 
 
 
 
36e50f2
 
 
 
 
 
 
 
 
 
6182d7b
 
 
 
 
 
 
9d2e562
 
 
 
 
 
6182d7b
9d2e562
 
 
 
 
 
 
 
 
 
 
 
 
 
6182d7b
9d2e562
6182d7b
9d2e562
 
 
 
 
 
 
 
6182d7b
9d2e562
6182d7b
9d2e562
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6182d7b
9d2e562
 
 
 
 
 
 
 
 
 
 
 
 
6182d7b
9d2e562
 
 
 
 
 
 
 
 
 
6182d7b
 
9d2e562
 
6182d7b
 
 
 
 
 
0b0c3a1
6182d7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36e50f2
9d2e562
36e50f2
 
6182d7b
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
import gradio as gr


_CSS = """
.audio-gallery-container {
    padding: 16px;
}
.audio-gallery-grid {
    display: grid;
    gap: 16px;
}
.audio-item {
    background: var(--block-background-fill, #1e1e2e);
    border: 1px solid var(--block-border-color, #3a3a5c);
    border-radius: 8px;
    padding: 12px;
    display: flex;
    flex-direction: column;
    gap: 8px;
}
.audio-label {
    font-weight: 600;
    font-size: 0.9rem;
    color: var(--body-text-color, #cdd6f4);
    text-transform: uppercase;
    letter-spacing: 0.05em;
}
.waveform-canvas {
    width: 100%;
    height: 60px;
    border-radius: 4px;
    background: var(--background-fill-secondary, #181825);
    display: block;
}
.audio-controls {
    display: flex;
    align-items: center;
    gap: 8px;
}
.audio-action-stack {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 6px;
}
.play-btn {
    background: #4a9eff;
    border: none;
    border-radius: 50%;
    width: 32px;
    height: 32px;
    cursor: pointer;
    font-size: 0.85rem;
    color: white;
    flex-shrink: 0;
}
.play-btn:hover {
    background: #6ab4ff;
}
.download-link {
    color: #4a9eff;
    font-size: 0.75rem;
    font-weight: 600;
    text-decoration: none;
}
.download-link:hover {
    color: #6ab4ff;
    text-decoration: underline;
}
.time-display {
    font-size: 0.8rem;
    color: var(--body-text-color, #a6adc8);
    font-family: monospace;
}
"""

GALLERY_JS = """
function formatTime(secs) {
    var m = Math.floor(secs / 60);
    var s = Math.floor(secs % 60).toString().padStart(2, '0');
    return m + ':' + s;
}

function drawWaveform(canvas) {
    var ctx = canvas.getContext('2d');
    var w = canvas.offsetWidth || 300;
    canvas.width = w;
    var h = canvas.height;
    ctx.clearRect(0, 0, w, h);
    ctx.fillStyle = '#4a9eff';
    var bars = 60;
    for (var i = 0; i < bars; i++) {
        var x = (i / bars) * w;
        var bw = Math.max(1, w / bars - 2);
        var amp = h * (0.2 + 0.7 * Math.abs(Math.sin(i * 0.45 + Math.random() * 0.3)));
        var y = (h - amp) / 2;
        ctx.fillRect(x, y, bw, amp);
    }
}

function initAudioItem(item) {
    if (item.getAttribute('data-initialized') === 'true') return;
    item.setAttribute('data-initialized', 'true');
    var audio = item.querySelector('audio');
    var canvas = item.querySelector('.waveform-canvas');
    var btn = item.querySelector('.play-btn');
    var timeDisplay = item.querySelector('.time-display');
    if (!audio || !canvas || !btn) return;

    drawWaveform(canvas);

    btn.addEventListener('click', function () {
        document.querySelectorAll('.audio-item audio').forEach(function (a) {
            if (a !== audio && !a.paused) {
                a.pause();
                a.closest('.audio-item').querySelector('.play-btn').textContent = '\\u25B6';
            }
        });
        if (audio.paused) {
            audio.play();
            btn.textContent = '\\u23F8';
        } else {
            audio.pause();
            btn.textContent = '\\u25B6';
        }
    });

    audio.addEventListener('timeupdate', function () {
        timeDisplay.textContent = formatTime(audio.currentTime);
    });

    audio.addEventListener('ended', function () {
        btn.textContent = '\\u25B6';
    });
}

// Auto-initialize new audio items as they are injected into the DOM
// Watch the entire document body since the gallery doesn't exist on page load
(function setupObserver() {
    document.querySelectorAll('.audio-item').forEach(initAudioItem);

    var observer = new MutationObserver(function (mutations) {
        mutations.forEach(function (m) {
            m.addedNodes.forEach(function (node) {
                if (node.nodeType !== 1) return; // element node only
                if (node.classList && node.classList.contains('audio-item')) {
                    initAudioItem(node);
                }
                if (node.querySelectorAll) {
                    node.querySelectorAll('.audio-item').forEach(initAudioItem);
                }
            });
        });
    });
    observer.observe(document.body, { childList: true, subtree: true });
})();
"""

class AudioGallery(gr.HTML):
    """Gradio HTML component that renders audio stems in a responsive grid."""

    DEFAULT_LABELS = ["Drums", "Vocals", "Guitar", "Bass", "Other", "Piano", "Music", "Full"]

    def __init__(
        self,
        audio_urls,
        *,
        value=None,
        labels=None,
        columns=3,
        label=None,
        **kwargs,
    ):
        labels = labels or self.DEFAULT_LABELS
        html = self._build_html(audio_urls, labels=labels, columns=columns)
        super().__init__(value=html, label=label, **kwargs)

    @staticmethod
    def _build_html(audio_urls, labels, columns):
        items = ""
        for i, url in enumerate(audio_urls):
            lbl = labels[i] if i < len(labels) else f"Track {i + 1}"
            items += (
                f'<div class="audio-item" data-index="{i}" data-initialized="false">'
                f'<div class="audio-label">{lbl}</div>'
                f'<canvas class="waveform-canvas" width="300" height="60"></canvas>'
                f'<audio src="{url}" preload="metadata"></audio>'
                f'<div class="audio-controls">'
                f'<div class="audio-action-stack">'
                f'<button class="play-btn" type="button">&#9654;</button>'
                f'<a class="download-link" href="{url}" download>Download</a>'
                f'</div>'
                f'<div class="time-display">0:00</div>'
                f'</div>'
                f'</div>\n'
            )
        return (
            f'<style>{_CSS}</style>'
            f'<div class="audio-gallery-container">'
            f'<div class="audio-gallery-grid" style="grid-template-columns: repeat({columns}, 1fr);">'
            f'{items}'
            f'</div>'
            f'</div>'
        )