Create transcribe_whisper.py
Browse files- code/transcribe_whisper.py +61 -0
code/transcribe_whisper.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
]# === LOAD INITIAL DATA ===
|
| 2 |
+
with open(INPUT_JSON, "r", encoding="utf-8") as f:
|
| 3 |
+
data = json.load(f)
|
| 4 |
+
|
| 5 |
+
# === HELPER: TRANSCRIBE FILE ===
|
| 6 |
+
def transcribe_file(filepath):
|
| 7 |
+
with open(filepath, "rb") as audio_file:
|
| 8 |
+
response = openai.audio.transcriptions.create(
|
| 9 |
+
model="whisper-1",
|
| 10 |
+
file=audio_file,
|
| 11 |
+
language=LANGUAGE
|
| 12 |
+
)
|
| 13 |
+
return response.text
|
| 14 |
+
|
| 15 |
+
# === PROCESS EACH FILE ===
|
| 16 |
+
total_time = 0
|
| 17 |
+
count = 0
|
| 18 |
+
|
| 19 |
+
for filename in sorted(os.listdir(FOLDER_PATH)):
|
| 20 |
+
match = re.match(r"(\d+)\.m4a", filename)
|
| 21 |
+
if not match:
|
| 22 |
+
continue
|
| 23 |
+
|
| 24 |
+
file_id = int(match.group(1))
|
| 25 |
+
file_path = os.path.join(FOLDER_PATH, filename)
|
| 26 |
+
|
| 27 |
+
# Find matching entry by ID
|
| 28 |
+
entry = next((item for item in data if item["id"] == file_id), None)
|
| 29 |
+
if entry is None:
|
| 30 |
+
print(f"Skipping {file_id}.m4a – No matching entry found.")
|
| 31 |
+
continue
|
| 32 |
+
|
| 33 |
+
try:
|
| 34 |
+
print(f"Transcribing {file_id}.m4a...")
|
| 35 |
+
start_time = time.time()
|
| 36 |
+
transcription = transcribe_file(file_path)
|
| 37 |
+
duration = time.time() - start_time
|
| 38 |
+
|
| 39 |
+
entry["file"] = file_path
|
| 40 |
+
entry["transcription"] = transcription
|
| 41 |
+
entry["transcription_time"] = duration
|
| 42 |
+
|
| 43 |
+
total_time += duration
|
| 44 |
+
count += 1
|
| 45 |
+
|
| 46 |
+
print(f"→ Done in {duration:.2f} seconds")
|
| 47 |
+
except Exception as e:
|
| 48 |
+
print(f"Error transcribing {file_id}.m4a: {e}")
|
| 49 |
+
|
| 50 |
+
# === SAVE OUTPUT ===
|
| 51 |
+
with open(OUTPUT_JSON, "w", encoding="utf-8") as f:
|
| 52 |
+
json.dump(data, f, ensure_ascii=False, indent=2)
|
| 53 |
+
|
| 54 |
+
# === SUMMARY ===
|
| 55 |
+
if count > 0:
|
| 56 |
+
avg_time = total_time / count
|
| 57 |
+
print(f"\nFinished transcribing {count} files.")
|
| 58 |
+
print(f"Total transcription time: {total_time:.2f} seconds")
|
| 59 |
+
print(f"Average transcription time: {avg_time:.2f} seconds")
|
| 60 |
+
else:
|
| 61 |
+
print("No files were transcribed.")
|