[Winsmano Ambani] commited on
Commit
fc3b2ec
·
0 Parent(s):

Initial commit: English to Pidgin audio collector

Browse files
Files changed (3) hide show
  1. app.py +431 -0
  2. combined_sentences.csv +0 -0
  3. requirements.txt +5 -0
app.py ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Gradio Audio Dataset Collector
3
+ --------------------------------
4
+ Features:
5
+ - Upload a CSV of English sentences. Optional column: pidgin_text.
6
+ - For each row: view English (read-only), edit/add Pidgin translation, record audio from mic.
7
+ - Listen before saving; overwrite allowed. No timestamps in filenames — saved as `<row_id>.wav`.
8
+ - Navigate Previous/Next or jump via dropdown. Review table updates live.
9
+ - Export metadata CSV and a ZIP (audio + metadata) for sharing.
10
+
11
+ CSV requirements:
12
+ - If your CSV has columns named `english_text` (required) and optionally `pidgin_text` and `row_id`.
13
+ - If `row_id` is missing, it will be created as 0..N-1.
14
+
15
+ Run:
16
+ pip install gradio pandas numpy soundfile scipy
17
+ python app.py
18
+
19
+ Then open the local URL Gradio prints.
20
+ """
21
+
22
+ import os
23
+ import io
24
+ import shutil
25
+ from typing import Tuple, Optional, List
26
+
27
+ import numpy as np
28
+ import pandas as pd
29
+
30
+ import gradio as gr
31
+
32
+ # Optional audio writers
33
+ try:
34
+ import soundfile as sf
35
+ HAVE_SF = True
36
+ except Exception:
37
+ HAVE_SF = False
38
+
39
+ from scipy.io import wavfile
40
+
41
+ AUDIO_DIR = "recordings"
42
+ META_CSV_PATH = "combined_sentences.csv"
43
+ EXPORT_ZIP_PATH = "dataset_export.zip"
44
+ DEFAULT_CSV_PATH = "combined_sentences.csv"
45
+ STATE_FILE = "app_state.txt"
46
+
47
+ os.makedirs(AUDIO_DIR, exist_ok=True)
48
+
49
+ # -----------------------------
50
+ # Helpers
51
+ # -----------------------------
52
+ def save_state(idx: int):
53
+ with open(STATE_FILE, 'w') as f:
54
+ f.write(str(idx))
55
+
56
+ def load_state() -> int:
57
+ if os.path.exists(STATE_FILE):
58
+ try:
59
+ with open(STATE_FILE, 'r') as f:
60
+ return int(f.read().strip())
61
+ except:
62
+ pass
63
+ return 0
64
+
65
+ def load_csv(fileobj) -> Tuple[pd.DataFrame, int, List[int]]:
66
+ df = pd.read_csv(fileobj)
67
+ # Normalize columns
68
+ # Expect english_text; allow variations
69
+ if "english_text" not in df.columns:
70
+ # Try to infer a reasonable column
71
+ candidates = [c for c in df.columns if str(c).lower() in ["english", "text", "sentence", "prompt"]]
72
+ if candidates:
73
+ df = df.rename(columns={candidates[0]: "english_text"})
74
+ else:
75
+ raise ValueError("CSV must include an 'english_text' column (or a similar one like 'sentence').")
76
+
77
+ if "pidgin_text" not in df.columns:
78
+ df["pidgin_text"] = ""
79
+
80
+ if "row_id" not in df.columns:
81
+ df["row_id"] = range(len(df))
82
+
83
+ if "audio_file_path" not in df.columns:
84
+ df["audio_file_path"] = ""
85
+
86
+ # Ensure types
87
+ df["english_text"] = df["english_text"].astype(str)
88
+ df["pidgin_text"] = df["pidgin_text"].astype(str)
89
+ df["row_id"] = df["row_id"].astype(int)
90
+ df["audio_file_path"] = df["audio_file_path"].astype(str)
91
+
92
+ # Sort by row_id to keep ordering stable
93
+ df = df.sort_values("row_id").reset_index(drop=True)
94
+
95
+ idx = load_state()
96
+ idx = max(0, min(idx, len(df) - 1))
97
+ options = df["row_id"].tolist()
98
+ return df, idx, options
99
+
100
+
101
+ def get_row_view(df: pd.DataFrame, idx: int):
102
+ row = df.iloc[idx]
103
+ english = row["english_text"]
104
+ pidgin = row["pidgin_text"]
105
+ row_id = int(row["row_id"])
106
+ audio_path = row.get("audio_file_path", "") or ""
107
+ audio_display = audio_path if (audio_path and os.path.exists(audio_path)) else None
108
+ return row_id, english, pidgin, audio_display
109
+
110
+ def get_progress(df: pd.DataFrame) -> str:
111
+ if df.empty:
112
+ return "No data loaded"
113
+ has_text = df["pidgin_text"].str.strip() != ""
114
+ has_audio = df["audio_file_path"].str.strip() != ""
115
+ audio_exists = df["audio_file_path"].apply(lambda x: os.path.exists(x) if x else False)
116
+ completed = len(df[has_text & has_audio & audio_exists])
117
+ total = len(df)
118
+ return f"Progress: {completed}/{total} completed ({completed/total*100:.1f}%)"
119
+
120
+ def find_next_incomplete(df: pd.DataFrame, current_idx: int) -> int:
121
+ if df.empty:
122
+ return current_idx
123
+ incomplete = df[(df["pidgin_text"].str.strip() == "") | (df["audio_file_path"].str.strip() == "")]
124
+ if incomplete.empty:
125
+ return current_idx
126
+ next_incomplete = incomplete[incomplete.index > current_idx]
127
+ if not next_incomplete.empty:
128
+ return next_incomplete.index[0]
129
+ return incomplete.index[0]
130
+
131
+
132
+ def write_wav(filepath: str, audio_tuple) -> None:
133
+ """Write (sr, np.ndarray) to filepath as 16-bit PCM WAV."""
134
+ if audio_tuple is None:
135
+ return
136
+ sr, data = audio_tuple
137
+ # Ensure data is numpy array
138
+ data = np.array(data, dtype=np.float32)
139
+ # Ensure mono
140
+ if data.ndim > 1:
141
+ data = np.mean(data, axis=1)
142
+ # Normalize to [-1, 1] range
143
+ if np.max(np.abs(data)) > 0:
144
+ data = data / np.max(np.abs(data))
145
+ if HAVE_SF:
146
+ sf.write(filepath, data, samplerate=sr, subtype="PCM_16")
147
+ else:
148
+ # Convert to int16 for scipy writer
149
+ data_i16 = np.int16(data * 32767)
150
+ wavfile.write(filepath, sr, data_i16)
151
+
152
+
153
+ def save_current(df: pd.DataFrame, idx: int, pidgin_text: str, audio_np) -> Tuple[pd.DataFrame, str, Optional[str]]:
154
+ row = df.iloc[idx]
155
+ row_id = int(row["row_id"])
156
+ # Update text first
157
+ df.at[idx, "pidgin_text"] = pidgin_text or ""
158
+
159
+ saved_audio_path = None
160
+ # Save audio if provided; otherwise leave existing file as-is
161
+ if audio_np is not None:
162
+ # No timestamps — fixed name per row
163
+ saved_audio_path = os.path.join(AUDIO_DIR, f"{row_id}.wav")
164
+ write_wav(saved_audio_path, audio_np)
165
+ df.at[idx, "audio_file_path"] = saved_audio_path
166
+ else:
167
+ # Keep existing path
168
+ saved_audio_path = df.at[idx, "audio_file_path"] or None
169
+
170
+ # Persist metadata CSV and state
171
+ df.to_csv(META_CSV_PATH, index=False)
172
+ save_state(idx)
173
+
174
+ status = "Saved (text and audio)." if audio_np is not None else "Saved text (no new audio)."
175
+ return df, status, saved_audio_path
176
+
177
+
178
+ def goto_index(df: pd.DataFrame, idx: int):
179
+ idx = max(0, min(idx, len(df) - 1))
180
+ return get_row_view(df, idx), idx
181
+
182
+
183
+ def export_dataset(df: pd.DataFrame) -> Tuple[str, str]:
184
+ # Always refresh metadata before export
185
+ df.to_csv(META_CSV_PATH, index=False)
186
+ # Create ZIP containing recordings/ + metadata.csv
187
+ if os.path.exists(EXPORT_ZIP_PATH):
188
+ os.remove(EXPORT_ZIP_PATH)
189
+ # Make an archive in a temp folder structure
190
+ tmp_root = "_export_tmp"
191
+ if os.path.exists(tmp_root):
192
+ shutil.rmtree(tmp_root)
193
+ os.makedirs(tmp_root, exist_ok=True)
194
+
195
+ # Copy metadata
196
+ shutil.copy2(META_CSV_PATH, os.path.join(tmp_root, os.path.basename(META_CSV_PATH)))
197
+ # Copy audio dir
198
+ out_audio = os.path.join(tmp_root, os.path.basename(AUDIO_DIR))
199
+ shutil.copytree(AUDIO_DIR, out_audio, dirs_exist_ok=True)
200
+
201
+ shutil.make_archive("dataset_export", "zip", tmp_root)
202
+ shutil.rmtree(tmp_root)
203
+ return META_CSV_PATH, EXPORT_ZIP_PATH
204
+
205
+
206
+ # -----------------------------
207
+ # UI
208
+ # -----------------------------
209
+ with gr.Blocks(title="English→Pidgin Audio Collector", theme=gr.themes.Soft()) as demo:
210
+ gr.Markdown("""
211
+ # English → Pidgin Audio Collector
212
+ Upload your CSV of English sentences, or use the default provided below.
213
+ """)
214
+
215
+ state_df = gr.State(pd.DataFrame())
216
+ state_idx = gr.State(0)
217
+
218
+ with gr.Row():
219
+ csv_in = gr.File(label="Upload CSV", file_types=[".csv"], file_count="single")
220
+ load_btn = gr.Button("Load CSV", variant="primary")
221
+ default_btn = gr.Button("Use Default CSV", variant="secondary") # NEW BUTTON
222
+
223
+ with gr.Row():
224
+ row_picker = gr.Dropdown(label="Jump to Row ID", choices=[], interactive=True, allow_custom_value=True)
225
+
226
+ with gr.Row():
227
+ row_id_out = gr.Number(label="Row ID", interactive=False)
228
+ progress_out = gr.Markdown("No data loaded")
229
+
230
+ english_box = gr.Textbox(label="English (read-only)", interactive=False, lines=3)
231
+ pidgin_box = gr.Textbox(label="Pidgin (editable)", interactive=True, lines=3, placeholder="Type Pidgin translation here…")
232
+
233
+ def auto_save_text(df, idx, text):
234
+ try:
235
+ if df.empty: return df
236
+ df.at[idx, "pidgin_text"] = text or ""
237
+ df.to_csv(META_CSV_PATH, index=False)
238
+ return df
239
+ except Exception:
240
+ return df
241
+
242
+ pidgin_box.change(auto_save_text, [state_df, state_idx, pidgin_box], [state_df])
243
+
244
+ gr.Markdown("### Record / Review")
245
+ with gr.Row():
246
+ mic = gr.Audio(sources=["microphone"], type="numpy", label="Record Pidgin (mic)")
247
+ saved_audio_player = gr.Audio(label="Current Saved Audio", interactive=False)
248
+
249
+ with gr.Row():
250
+ save_btn = gr.Button("💾 Save / Overwrite", variant="primary")
251
+ rerecord_btn = gr.Button("↺ Clear Recording (Re-record)")
252
+
253
+ with gr.Row():
254
+ prev_btn = gr.Button("◀ Previous")
255
+ next_btn = gr.Button("Next ▶")
256
+ skip_btn = gr.Button("⏭ Skip to Incomplete", variant="secondary")
257
+
258
+ status_out = gr.Markdown(visible=True)
259
+
260
+ gr.Markdown("### Review Table (live)")
261
+ table = gr.Dataframe(
262
+ headers=["row_id", "english_text", "pidgin_text", "audio_file_path"],
263
+ interactive=False,
264
+ column_widths=["10%", "35%", "35%", "20%"]
265
+ )
266
+
267
+ with gr.Row():
268
+ export_meta_btn = gr.Button("Export Metadata CSV")
269
+ export_zip_btn = gr.Button("Export ZIP (Audio + Metadata)")
270
+ meta_file = gr.File(label="Download metadata.csv", interactive=False)
271
+ zip_file = gr.File(label="Download dataset_export.zip", interactive=False)
272
+
273
+ # -----------------------------
274
+ # Callbacks
275
+ # -----------------------------
276
+
277
+ def on_load(file):
278
+ try:
279
+ if file is None:
280
+ raise gr.Error("Please upload a CSV file.")
281
+ df, idx, options = load_csv(file.name)
282
+ (row_id, eng, pid, audio), idx = goto_index(df, idx)
283
+ table_df = df[["row_id", "english_text", "pidgin_text", "audio_file_path"]].copy()
284
+ table_df["english_text"] = table_df["english_text"].str[:50] + "..."
285
+ table_df["pidgin_text"] = table_df["pidgin_text"].str[:50] + "..."
286
+ progress = get_progress(df)
287
+ return (
288
+ df, idx, options, gr.update(value=row_id, interactive=False), eng, pid,
289
+ audio, table_df, gr.update(choices=options, value=row_id), "Loaded CSV.", progress
290
+ )
291
+ except Exception as e:
292
+ return pd.DataFrame(), 0, [], None, "", "", None, pd.DataFrame(), gr.update(choices=[]), f"Error: {str(e)}", "No data loaded"
293
+
294
+ load_btn.click(
295
+ fn=on_load,
296
+ inputs=[csv_in],
297
+ outputs=[state_df, state_idx, row_picker, row_id_out, english_box, pidgin_box, saved_audio_player, table, row_picker, status_out, progress_out]
298
+ )
299
+
300
+ # NEW: Load default CSV callback
301
+ def on_load_default():
302
+ try:
303
+ if not os.path.exists(DEFAULT_CSV_PATH):
304
+ return pd.DataFrame(), 0, [], None, "", "", None, pd.DataFrame(), gr.update(choices=[]), f"Default CSV not found at {DEFAULT_CSV_PATH}", "No data loaded"
305
+ df, idx, options = load_csv(DEFAULT_CSV_PATH)
306
+ (row_id, eng, pid, audio), idx = goto_index(df, idx)
307
+ table_df = df[["row_id", "english_text", "pidgin_text", "audio_file_path"]].copy()
308
+ table_df["english_text"] = table_df["english_text"].str[:50] + "..."
309
+ table_df["pidgin_text"] = table_df["pidgin_text"].str[:50] + "..."
310
+ progress = get_progress(df)
311
+ return (
312
+ df, idx, gr.update(choices=options, value=row_id), gr.update(value=row_id, interactive=False), eng, pid,
313
+ audio, table_df, gr.update(choices=options, value=row_id), "Loaded default CSV.", progress
314
+ )
315
+ except Exception as e:
316
+ return pd.DataFrame(), 0, gr.update(choices=[]), None, "", "", None, pd.DataFrame(), gr.update(choices=[]), f"Error: {str(e)}", "No data loaded"
317
+
318
+ default_btn.click(
319
+ fn=on_load_default,
320
+ inputs=None,
321
+ outputs=[state_df, state_idx, row_picker, row_id_out, english_box, pidgin_box, saved_audio_player, table, row_picker, status_out, progress_out]
322
+ )
323
+
324
+ def on_pick(df, current_idx, pick_id):
325
+ try:
326
+ if df is None or len(df) == 0:
327
+ return current_idx, None, "", "", None
328
+ idx = int(df.index[df["row_id"] == int(pick_id)][0])
329
+ (row_id, eng, pid, audio), idx = goto_index(df, idx)
330
+ return idx, row_id, eng, pid, audio
331
+ except Exception:
332
+ return current_idx, None, "", "", None
333
+
334
+ row_picker.change(
335
+ fn=on_pick,
336
+ inputs=[state_df, state_idx, row_picker],
337
+ outputs=[state_idx, row_id_out, english_box, pidgin_box, saved_audio_player]
338
+ )
339
+
340
+ def nav(df, idx, step):
341
+ try:
342
+ if df is None or len(df) == 0:
343
+ return idx, None, "", "", None, gr.update(), "No data loaded"
344
+ idx = max(0, min(idx + step, len(df) - 1))
345
+ (row_id, eng, pid, audio), idx = goto_index(df, idx)
346
+ progress = get_progress(df)
347
+ return idx, row_id, eng, pid, audio, gr.update(value=row_id), progress
348
+ except Exception:
349
+ return idx, None, "", "", None, gr.update(), "Error navigating"
350
+
351
+ def skip_to_incomplete(df, idx):
352
+ try:
353
+ if df is None or len(df) == 0:
354
+ return idx, None, "", "", None, gr.update(), "No data loaded"
355
+ idx = find_next_incomplete(df, idx)
356
+ (row_id, eng, pid, audio), idx = goto_index(df, idx)
357
+ progress = get_progress(df)
358
+ return idx, row_id, eng, pid, audio, gr.update(value=row_id), progress
359
+ except Exception:
360
+ return idx, None, "", "", None, gr.update(), "Error finding incomplete"
361
+
362
+ prev_btn.click(lambda df, idx: nav(df, idx, -1), [state_df, state_idx], [state_idx, row_id_out, english_box, pidgin_box, saved_audio_player, row_picker, progress_out])
363
+ next_btn.click(lambda df, idx: nav(df, idx, 1), [state_df, state_idx], [state_idx, row_id_out, english_box, pidgin_box, saved_audio_player, row_picker, progress_out])
364
+ skip_btn.click(skip_to_incomplete, [state_df, state_idx], [state_idx, row_id_out, english_box, pidgin_box, saved_audio_player, row_picker, progress_out])
365
+
366
+ def on_save(df, idx, pidgin_text, audio_np):
367
+ try:
368
+ if df is None or len(df) == 0:
369
+ return df, None, pd.DataFrame(), "No data to save", None, "No data loaded", ""
370
+ df, status, saved_path = save_current(df, idx, pidgin_text, audio_np)
371
+ table_df = df[["row_id", "english_text", "pidgin_text", "audio_file_path"]].copy()
372
+ table_df["english_text"] = table_df["english_text"].str[:50] + "..."
373
+ table_df["pidgin_text"] = table_df["pidgin_text"].str[:50] + "..."
374
+ (row_id, eng, pid, audio), idx = goto_index(df, idx)
375
+ progress = get_progress(df)
376
+ return df, saved_path if saved_path else None, table_df, status, None, progress, pid
377
+ except Exception as e:
378
+ return df, None, pd.DataFrame(), f"Save error: {str(e)}", None, "Error", ""
379
+
380
+ save_btn.click(
381
+ fn=on_save,
382
+ inputs=[state_df, state_idx, pidgin_box, mic],
383
+ outputs=[state_df, saved_audio_player, table, status_out, mic, progress_out, pidgin_box]
384
+ )
385
+
386
+ def on_rerecord():
387
+ return gr.update(value=None), "Recording cleared. You can re-record now."
388
+
389
+ rerecord_btn.click(on_rerecord, outputs=[mic, status_out])
390
+
391
+ def do_export_meta(df):
392
+ if df is None or len(df) == 0:
393
+ raise gr.Error("Load a CSV first.")
394
+ meta_path, _ = export_dataset(df)
395
+ return gr.update(value=meta_path)
396
+
397
+ export_meta_btn.click(do_export_meta, inputs=[state_df], outputs=[meta_file])
398
+
399
+ def do_export_zip(df):
400
+ if df is None or len(df) == 0:
401
+ raise gr.Error("Load a CSV first.")
402
+ _, zip_path = export_dataset(df)
403
+ return gr.update(value=zip_path)
404
+
405
+ export_zip_btn.click(do_export_zip, inputs=[state_df], outputs=[zip_file])
406
+
407
+ # Auto-load default CSV on startup
408
+ def auto_load():
409
+ try:
410
+ if os.path.exists(DEFAULT_CSV_PATH):
411
+ df, idx, options = load_csv(DEFAULT_CSV_PATH)
412
+ (row_id, eng, pid, audio), idx = goto_index(df, idx)
413
+ table_df = df[["row_id", "english_text", "pidgin_text", "audio_file_path"]].copy()
414
+ table_df["english_text"] = table_df["english_text"].str[:50] + "..."
415
+ table_df["pidgin_text"] = table_df["pidgin_text"].str[:50] + "..."
416
+ progress = get_progress(df)
417
+ return (
418
+ df, idx, gr.update(choices=options, value=row_id), row_id, eng, pid,
419
+ audio, table_df, "Auto-loaded default CSV.", progress
420
+ )
421
+ except Exception:
422
+ pass
423
+ return pd.DataFrame(), 0, gr.update(choices=[]), None, "", "", None, pd.DataFrame(), "No default CSV found.", "No data loaded"
424
+
425
+ demo.load(
426
+ fn=auto_load,
427
+ outputs=[state_df, state_idx, row_picker, row_id_out, english_box, pidgin_box, saved_audio_player, table, status_out, progress_out]
428
+ )
429
+
430
+ if __name__ == "__main__":
431
+ demo.launch(share=True)
combined_sentences.csv ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ gradio
2
+ pandas
3
+ numpy
4
+ soundfile
5
+ scipy