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
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
---
tags: [gradio-custom-component, AudioGrid, audio-processing, custom-component-track]
title: gradio_audiogrid
short_description: Drag and drop component for audio files
colorFrom: blue
colorTo: yellow
sdk: gradio
pinned: false
app_file: space.py
---

# `gradio_audiogrid`

**AudioGrid** is a custom Gradio component that provides an intuitive drag-and-drop interface for managing audio files. Perfect for audio processing workflows, music production, and any application that needs to handle multiple audio files.

## Features

- 🎡 **Drag & Drop Audio Upload** - Intuitive file upload with visual feedback
- 🎯 **Smart Reordering** - Drag files anywhere to reorder them intelligently
- πŸ“± **Mobile Responsive** - Works great on desktop, tablet, and mobile
- 🎨 **Beautiful UI** - Clean, modern interface with proper spacing
- πŸ”„ **Flexible Positioning** - Drop files anywhere, not just on exact squares
- ❌ **Easy Removal** - One-click file removal
- πŸ“ **Multiple Formats** - Supports MP3, WAV, OGG, FLAC, AAC, M4A

---

## Installation

```bash
pip install gradio_audiogrid
```

## Usage

```python
import tempfile

import gradio as gr
import numpy as np
import soundfile as sf

from gradio_audiogrid import AudioGrid


def merge_audio_files(file_objects):
    """
    Merge audio files by concatenating their audio data using soundfile

    Args:
        file_objects: List of file objects from AudioMerger component

    Returns:
        tuple: (sample_rate, merged_audio_array) for Gradio Audio component
               or (None, None) if merging fails
    """
    if not file_objects or len(file_objects) == 0:
        return None, "❌ No audio files to merge"

    if len(file_objects) == 1:
        return None, "❌ Please upload at least 2 audio files to merge"

    try:
        _merged_audio = []
        sample_rate = None

        for i, file_path in enumerate(file_objects):
            # Read audio file
            audio_data, sr = sf.read(file_path)
            if sample_rate is None:
                sample_rate = sr
            elif sr != sample_rate:
                ratio = sample_rate / sr
                new_length = int(len(audio_data) * ratio)
                audio_data = np.interp(
                    np.linspace(0, len(audio_data), new_length),
                    np.arange(len(audio_data)),
                    audio_data
                )

            # Convert stereo to mono if needed (take average of channels)
            if len(audio_data.shape) > 1:
                audio_data = np.mean(audio_data, axis=1)

            _merged_audio.append(audio_data)
        if not _merged_audio:
            return None, "❌ No valid audio files found"

        # Concatenate all audio arrays
        final_audio = np.concatenate(_merged_audio)

        # Create temporary file for the merged audio
        with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as tmp_file:
            sf.write(tmp_file.name, final_audio, sample_rate)
            merged_file_path = tmp_file.name

        # Create status message
        total_duration = len(final_audio) / sample_rate
        status = f"""βœ… Successfully merged {len(file_objects)} audio files!
        
🎡 Result:
  β€’ Total duration: {total_duration:.2f} seconds
  β€’ Sample rate: {sample_rate} Hz
  β€’ Channels: Mono
  β€’ Format: WAV

🎧 Listen to the merged audio below!"""

        return merged_file_path, status

    except Exception as e:
        error_msg = f"❌ Error merging audio files: {str(e)}"
        return None, error_msg


def reset_everything():
    """Reset all components to initial state"""
    return [], None, "Ready to merge audio files! Upload at least 2 files to get started."


def update_file_status(file_objects):
    """Update the live status based on uploaded files"""

    if len(file_objects) == 0:
        return "No valid files uploaded"
    elif len(file_objects) == 1:
        return "πŸ“ 1 file uploaded"
    else:
        return f"πŸ“ {len(file_objects)} files ready"


# Create the Gradio interface
with gr.Blocks(title="🎡 Professional Audio Merger") as demo:
    gr.Markdown("""
    # 🎡 Professional Audio Grid

    Upload multiple audio files and sort them. You can apply any effect you want.

    **Features:**
    - 🎯 **Drag & Drop**: Upload by dragging files or clicking
    - πŸ”„ **Reorder**: Drag uploaded files to change merge order  
    - πŸ“Š **Multiple Formats**: Supports MP3, WAV, FLAC, OGG, M4A, AAC
    """)

    with gr.Row():
        with gr.Column(scale=2):
            gr.Markdown("### πŸ“ Upload & Arrange Audio Files")

            audio_files = AudioGrid(
                value=[],
                label="Drag files here or click to upload",
                interactive=True,
                elem_classes=["audio-merger-container"]
            )

            # Live status update
            file_status = gr.Textbox(
                value="No files uploaded yet",
                label="πŸ“Š Upload Status",
                interactive=False,
                lines=2
            )

        with gr.Column(scale=1):
            gr.Markdown("### πŸŽ›οΈ Controls")

            merge_btn = gr.Button(
                "🎡 Merge Audio Files",
                variant="primary",
                size="lg",
                elem_classes=["merge-button"]
            )

            clear_btn = gr.Button(
                "πŸ—‘οΈ Clear All",
                variant="secondary",
                size="lg"
            )

            gr.Markdown("""
            **Instructions:**
            1. Upload 2+ audio files
            2. Drag to reorder if needed
            3. Click "Merge Audio Files"
            4. Listen to the result!
            """)

    gr.Markdown("### 🎧 Merged Audio Result")

    with gr.Row():
        with gr.Column(scale=2):
            # Status/info output
            merge_status = gr.Textbox(
                value="Ready to merge audio files! Upload at least 2 files to get started.",
                label="πŸ” Merge Status & Details",
                interactive=False,
                lines=8
            )

        with gr.Column(scale=2):
            # Audio output
            merged_audio = gr.Audio(
                label="🎡 Merged Audio Player",
                type="filepath",
                interactive=False
            )

    # Event handlers
    merge_btn.click(
        fn=merge_audio_files,
        inputs=audio_files,
        outputs=[merged_audio, merge_status]
    )

    clear_btn.click(
        fn=reset_everything,
        outputs=[audio_files, merged_audio, merge_status]
    )

    # Live update of file status
    audio_files.change(
        fn=update_file_status,
        inputs=audio_files,
        outputs=file_status
    )

    gr.Markdown("""
    ---
    ### πŸ”§ Technical Details

    - **Audio Processing**: Uses SoundFile library for high-quality audio handling
    - **Concatenation**: Audio arrays are concatenated using NumPy for efficiency  
    - **Format Handling**: Automatically converts different sample rates and channels
    - **Output**: Generates WAV format for maximum compatibility
    - **Memory Efficient**: Processes files sequentially to minimize RAM usage

    **Supported Input Formats**: MP3, WAV, FLAC, OGG, M4A, AAC, and more
    **Output Format**: WAV (uncompressed, high quality)
    """)

if __name__ == "__main__":
    demo.launch(debug=True)

```

## `AudioGrid`

### Initialization

<table>
<thead>
<tr>
<th align="left">name</th>
<th align="left" style="width: 25%;">type</th>
<th align="left">default</th>
<th align="left">description</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><code>value</code></td>
<td align="left" style="width: 25%;">

```python
list[str] | Callable | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">default list of audio file paths. If a function is provided, the function will be called</td>
</tr>

<tr>
<td align="left"><code>label</code></td>
<td align="left" style="width: 25%;">

```python
str | I18nData | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">the label for this component,</td>
</tr>

<tr>
<td align="left"><code>every</code></td>
<td align="left" style="width: 25%;">

```python
Timer | float | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Continuously calls `value` to recalculate it if `value` is a</td>
</tr>

<tr>
<td align="left"><code>inputs</code></td>
<td align="left" style="width: 25%;">

```python
Component | Sequence[Component] | set[Component] | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">Components that are used as inputs to calculate `value` if</td>
</tr>

<tr>
<td align="left"><code>show_label</code></td>
<td align="left" style="width: 25%;">

```python
bool | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">if True, will display label. scale: relative size compared to adjacent Components. For example if</td>
</tr>

<tr>
<td align="left"><code>scale</code></td>
<td align="left" style="width: 25%;">

```python
int | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">relative size compared to adjacent Components. For example if</td>
</tr>

<tr>
<td align="left"><code>min_width</code></td>
<td align="left" style="width: 25%;">

```python
int
```

</td>
<td align="left"><code>160</code></td>
<td align="left">minimum pixel width, will wrap if not sufficient screen space to satisfy this value. If a certain</td>
</tr>

<tr>
<td align="left"><code>interactive</code></td>
<td align="left" style="width: 25%;">

```python
bool | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">if True, will be rendered as an editable upload area; if False, editing will be</td>
</tr>

<tr>
<td align="left"><code>visible</code></td>
<td align="left" style="width: 25%;">

```python
bool
```

</td>
<td align="left"><code>True</code></td>
<td align="left">If False, component will be hidden. elem_id: An optional string that is assigned as the id of this</td>
</tr>

<tr>
<td align="left"><code>elem_id</code></td>
<td align="left" style="width: 25%;">

```python
str | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">An optional string that is assigned as the id of this</td>
</tr>

<tr>
<td align="left"><code>elem_classes</code></td>
<td align="left" style="width: 25%;">

```python
list[str] | str | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">An optional list of strings</td>
</tr>

<tr>
<td align="left"><code>render</code></td>
<td align="left" style="width: 25%;">

```python
bool
```

</td>
<td align="left"><code>True</code></td>
<td align="left">If False, component will not render be rendered in the Blocks context. Should be used if the</td>
</tr>

<tr>
<td align="left"><code>key</code></td>
<td align="left" style="width: 25%;">

```python
int | str | tuple[int | str, ...] | None
```

</td>
<td align="left"><code>None</code></td>
<td align="left">in a gr.render, Components</td>
</tr>

<tr>
<td align="left"><code>preserved_by_key</code></td>
<td align="left" style="width: 25%;">

```python
list[str] | str | None
```

</td>
<td align="left"><code>"value"</code></td>
<td align="left">A list of parameters from this</td>
</tr>
</tbody></table>


### Events

| name | description |
|:-----|:------------|
| `change` | Triggered when the value of the AudioGrid changes either because of user input (e.g. a user types in a textbox) OR because of a function update (e.g. an image receives a value from the output of an event trigger). See `.input()` for a listener that is only triggered by user input. |
| `input` | This listener is triggered when the user changes the value of the AudioGrid. |
| `submit` | This listener is triggered when the user presses the Enter key while the AudioGrid is focused. |
| `upload` | This listener is triggered when the user uploads a file into the AudioGrid. |



### User function

The impact on the users predict function varies depending on whether the component is used as an input or output for an event (or both).

- When used as an Input, the component only impacts the input signature of the user function.
- When used as an output, the component only impacts the return signature of the user function.

The code snippet below is accurate in cases where the component is used as both an input and an output.

- **As output:** Is passed, passes list of file paths as a list[str] into the function.
- **As input:** Should return, list of audio file paths to display in the component.

 ```python
 def predict(
     value: list[str]
 ) -> list[str]:
     return value
 ```