-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathapp.py
More file actions
1908 lines (1634 loc) · 71 KB
/
app.py
File metadata and controls
1908 lines (1634 loc) · 71 KB
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
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os, json, subprocess, tempfile, threading, time, io, shutil, struct, concurrent.futures
from pathlib import Path
from flask import Flask, render_template, request, jsonify, send_file, Response, abort
# Optional diarization — requires HUGGINGFACE_TOKEN in .env
_diarization_pipeline = None
_diarization_lock = threading.Lock()
def get_diarization_pipeline():
global _diarization_pipeline
token = os.environ.get("HUGGINGFACE_TOKEN")
if not token:
return None
with _diarization_lock:
if _diarization_pipeline is None:
try:
from pyannote.audio import Pipeline
import torch
_diarization_pipeline = Pipeline.from_pretrained(
"pyannote/speaker-diarization-community-1",
token=token,
)
# Use Apple Silicon GPU if available, otherwise CPU
if torch.backends.mps.is_available():
_diarization_pipeline.to(torch.device("mps"))
print("✓ Speaker diarization pipeline loaded (MPS/GPU)")
else:
print("✓ Speaker diarization pipeline loaded (CPU)")
except Exception as e:
print(f"⚠️ Diarization pipeline failed to load: {e}")
return None
return _diarization_pipeline
def assign_speakers(segments, audio_path):
"""Run pyannote diarization and assign speaker labels to segments."""
pipeline = get_diarization_pipeline()
if pipeline is None:
return segments # no-op: keep S1 for all
try:
# pyannote works best with WAV — convert if needed
wav_path = audio_path
tmp_wav = None
if not audio_path.lower().endswith(".wav"):
tmp_wav = tempfile.NamedTemporaryFile(suffix=".wav", delete=False)
tmp_wav.close()
subprocess.run(
["ffmpeg", "-y", "-i", audio_path, "-ar", "16000", "-ac", "1", tmp_wav.name],
capture_output=True,
)
wav_path = tmp_wav.name
result = pipeline(wav_path)
# pyannote 3.x returns DiarizeOutput; extract the Annotation object
diarization = getattr(result, 'speaker_diarization', result)
# Build list of (start, end, speaker) turns
turns = [(turn.start, turn.end, speaker)
for turn, _, speaker in diarization.itertracks(yield_label=True)]
# Map each segment to the speaker with the most overlap
speaker_map = {} # pyannote label → S1/S2/...
for seg in segments:
best_speaker, best_overlap = None, 0.0
for t_start, t_end, spk in turns:
overlap = min(seg["end"], t_end) - max(seg["start"], t_start)
if overlap > best_overlap:
best_overlap = overlap
best_speaker = spk
if best_speaker is None:
best_speaker = turns[0][2] if turns else "SPEAKER_00"
# Normalise to S1/S2/... labels
if best_speaker not in speaker_map:
speaker_map[best_speaker] = f"S{len(speaker_map) + 1}"
seg["speaker"] = speaker_map[best_speaker]
if tmp_wav:
os.unlink(tmp_wav.name)
return segments
except Exception as e:
print(f"⚠️ Diarization failed: {e}")
if tmp_wav:
try: os.unlink(tmp_wav.name)
except: pass
return segments
# Speaker color mapping (matches frontend SPK_COLORS)
SPK_COLORS_RGB = {
"S1": (0x1D, 0x9E, 0x75),
"S2": (0x37, 0x8A, 0xDD),
"S3": (0xC8, 0x8C, 0x32),
"S4": (0xA0, 0x50, 0xB4),
}
def get_clip_speaker(clip, transcript):
"""Find which speaker has the most overlap with this clip's time range."""
best, best_overlap = "S1", 0.0
for seg in transcript:
overlap = min(clip["end"], seg["end"]) - max(clip["start"], seg["start"])
if overlap > best_overlap:
best_overlap = overlap
best = seg.get("speaker", "S1")
return best
def resolve_source_for_clip(clip, state):
"""Given a clip with start/end times, find the correct source file and real timestamps."""
source_files = state.get("source_files", [])
if not source_files:
# Legacy single-file project
sf = state.get("source_file", "")
return sf, clip["start"], clip["end"]
# Find which source file this clip belongs to by checking timestamp range
for i, sf in enumerate(source_files):
offset = sf["offset"]
end_time = offset + sf["duration"]
if clip["start"] >= offset and clip["start"] < end_time:
real_start = clip["start"] - offset
real_end = clip["end"] - offset
return sf["path"], real_start, real_end
# Fallback to last file
sf = source_files[-1]
return sf["path"], clip["start"] - sf["offset"], clip["end"] - sf["offset"]
# Load .env file if present (so OPENAI_API_KEY persists across sessions)
try:
from dotenv import load_dotenv
load_dotenv()
except ImportError:
pass
from openai import OpenAI
app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 2 * 1024 * 1024 * 1024 # 2 GB upload limit
# ─── APP CONFIG ──────────────────────────────────────────
_config_path = "config.json"
def load_config():
if os.path.exists(_config_path):
with open(_config_path) as f:
return json.load(f)
return {}
def save_config(cfg):
with open(_config_path, "w") as f:
json.dump(cfg, f, ensure_ascii=False, indent=2)
def copy_to_export_folder(filepath):
"""Copy a file to the configured export folder, if set."""
cfg = load_config()
export_dir = cfg.get("export_folder", "").strip()
if not export_dir:
return
export_dir = os.path.expanduser(export_dir)
if not os.path.isdir(export_dir):
return
try:
shutil.copy2(filepath, os.path.join(export_dir, os.path.basename(filepath)))
except Exception as e:
print(f"⚠️ Failed to copy to export folder: {e}")
# ─── PROJECT DIRECTORY ────────────────────────────────────
_active_project_dir = os.path.join("projects", "_session")
def set_project_dir(path):
global _active_project_dir
_active_project_dir = path
for sub in ['uploads', 'clips', 'narration', 'output']:
os.makedirs(os.path.join(path, sub), exist_ok=True)
def friendly_error(e):
"""Convert a raw exception into a short, human-readable error message."""
msg = str(e)
if "401" in msg or "invalid_api_key" in msg or "Incorrect API key" in msg:
return "Invalid API key — check OPENAI_API_KEY in your .env file"
if "429" in msg or "rate_limit" in msg or "quota" in msg:
return "OpenAI rate limit or quota exceeded — try again in a moment"
if "Connection" in msg or "timeout" in msg or "network" in msg.lower():
return "Network error — check your internet connection"
if "ffmpeg" in msg.lower():
return "ffmpeg error — make sure ffmpeg is installed (brew install ffmpeg)"
if "No such file" in msg:
return "Audio file not found — try uploading again"
# Trim raw API error JSON down to just the message field if present
if "'message':" in msg:
try:
import re
m = re.search(r"'message':\s*'([^']+)'", msg)
if m:
return m.group(1)[:120]
except Exception:
pass
return msg[:120] # cap length so it fits in the UI
def pdir(folder=""):
"""Return path to a subfolder in the active project directory, creating it if needed."""
path = os.path.join(_active_project_dir, folder) if folder else _active_project_dir
os.makedirs(path, exist_ok=True)
return path
os.makedirs("projects", exist_ok=True)
set_project_dir(_active_project_dir)
api_key = os.environ.get("OPENAI_API_KEY")
client = OpenAI(api_key=api_key) if api_key else None
if not api_key:
print("⚠️ OPENAI_API_KEY not set. Create a .env file with: OPENAI_API_KEY=sk-...")
def reload_api_keys():
"""Reload API keys from .env without restarting the server."""
global api_key, client
try:
from dotenv import load_dotenv
load_dotenv(override=True)
except ImportError:
pass
api_key = os.environ.get("OPENAI_API_KEY")
client = OpenAI(api_key=api_key) if api_key else None
# Check for ffmpeg
try:
subprocess.run(["ffmpeg", "-version"], capture_output=True, check=True)
except (subprocess.CalledProcessError, FileNotFoundError):
print("⚠️ ffmpeg not found. Install it with: brew install ffmpeg (Mac) or apt install ffmpeg (Linux)")
print(" Audio cutting and assembly will not work without ffmpeg.")
# In-memory state (persisted per-project)
# Progress tracking for async operations
progress = {"phase": None, "current": 0, "total": 0, "message": "", "audio_duration": 0}
def state_file():
return os.path.join(_active_project_dir, "state.json")
def load_state():
sf = state_file()
# Migrate legacy root-level state.json once, then remove it so it can't re-appear after reset
if not os.path.exists(sf) and os.path.exists("state.json"):
shutil.copy2("state.json", sf)
os.rename("state.json", "state.json.migrated")
if os.path.exists(sf):
with open(sf) as f:
state = json.load(f)
# Backward compat: populate source_files from legacy source_file
if state.get("source_file") and not state.get("source_files"):
path = state["source_file"]
if os.path.exists(path):
try:
dur_result = subprocess.run(
["ffprobe", "-v", "quiet", "-show_entries", "format=duration", "-of", "csv=p=0", path],
capture_output=True, text=True)
duration = float(dur_result.stdout.strip())
except Exception:
duration = 0
state["source_files"] = [{
"filename": state.get("filename", os.path.basename(path)),
"path": path, "offset": 0, "duration": duration
}]
# Auto-detect phase for legacy projects that predate the phase system
if "phase" not in state:
status = state.get("status", "")
if status in ("assembled",):
state["phase"] = 3
elif status in ("clips_ready", "narration_ready", "narration_cut"):
state["phase"] = 2 if state.get("narration_transcript") else 1
else:
state["phase"] = 1
return state
return {"transcript": [], "words": [], "clips": [], "text_clips": [],
"narration_transcript": [], "narration_words": [], "narr_text_clips": [],
"narration": [], "assembly": [], "source_file": None, "source_files": [], "phase": 1}
def save_state(state):
with open(state_file(), "w") as f:
json.dump(state, f, ensure_ascii=False, indent=2)
def merge_segments(raw_segments, pause_threshold=1.0, sentence_gap=0.4, max_duration=45):
"""Merge short Whisper segments into longer passages based on pauses, punctuation, and max duration."""
SENTENCE_ENDERS = set('.?!。؟')
passages = []
current = None
for seg in raw_segments:
if current is None:
current = {**seg}
continue
gap = seg["start"] - current["end"]
cur_duration = current["end"] - current["start"]
prev_ends_sentence = current["text"] and current["text"][-1] in SENTENCE_ENDERS
if (gap >= pause_threshold
or (gap >= sentence_gap and prev_ends_sentence)
or (cur_duration >= max_duration and gap >= 0.2)):
passages.append(current)
current = {**seg}
else:
current["end"] = seg["end"]
current["text"] += " " + seg["text"]
if current:
passages.append(current)
return passages
# ─── ROUTES ───────────────────────────────────────────────
@app.route("/")
def index():
return render_template("index.html")
@app.route("/state")
def get_state():
resp = jsonify(load_state())
resp.headers["Cache-Control"] = "no-store"
return resp
# ─── STEP 1: TRANSCRIBE ───────────────────────────────────
def transcribe_single_file(filepath, whisper_lang, diarize, file_index, total_files):
"""Transcribe a single audio file and return (segments, words, duration).
Updates the global ``progress`` dict with per-file status messages.
Raises on failure so the caller can handle partial errors.
"""
prefix = f"file {file_index + 1}/{total_files}: " if total_files > 1 else ""
# ── Get audio duration via ffprobe ──
duration = 0
try:
dur_result = subprocess.run(
["ffprobe", "-v", "quiet", "-show_entries", "format=duration", "-of", "csv=p=0", filepath],
capture_output=True, text=True)
duration = float(dur_result.stdout.strip())
except Exception:
pass
# ── Compress if file > 25 MB ──
upload_path = filepath
if os.path.getsize(filepath) > 25 * 1024 * 1024:
progress.update(message=f"{prefix}compressing audio…")
compressed = filepath.rsplit(".", 1)[0] + "_compressed.mp3"
target_bits = 24 * 1024 * 1024 * 8
bitrate_kbps = max(8, min(64, int(target_bits / (duration or 1) / 1000)))
subprocess.run([
"ffmpeg", "-y", "-i", filepath,
"-ac", "1", "-ar", "16000", "-b:a", f"{bitrate_kbps}k",
compressed
], capture_output=True, check=True)
upload_path = compressed
# ── Send to Whisper API ──
progress.update(message=f"{prefix}sending to Whisper…")
whisper_kwargs = {
"model": "whisper-1",
"response_format": "verbose_json",
"timestamp_granularities": ["word", "segment"],
}
if whisper_lang:
whisper_kwargs["language"] = whisper_lang
with open(upload_path, "rb") as audio_file:
whisper_kwargs["file"] = audio_file
result = client.audio.transcriptions.create(**whisper_kwargs)
# ── Extract words ──
words = []
if hasattr(result, 'words') and result.words:
for w in result.words:
words.append({"word": w.word.strip(), "start": w.start, "end": w.end})
# ── Extract and merge segments ──
raw = [{"start": seg.start, "end": seg.end, "text": seg.text.strip()} for seg in result.segments]
passages = merge_segments(raw)
segments = []
for i, p in enumerate(passages):
segments.append({
"id": i,
"start": p["start"],
"end": p["end"],
"text": p["text"],
"speaker": "S1",
})
# ── Diarization (optional) ──
if diarize and os.environ.get("HUGGINGFACE_TOKEN"):
progress.update(message=f"{prefix}detecting speakers…")
segments = assign_speakers(segments, filepath)
return segments, words, duration
@app.route("/transcribe", methods=["POST"])
def transcribe():
if not client:
return jsonify({"error": "OPENAI_API_KEY not set"}), 500
if "file" not in request.files:
return jsonify({"error": "No file uploaded"}), 400
files = request.files.getlist("file")
whisper_lang = request.form.get("language", "he")
diarize = request.form.get("diarize") == "1"
if whisper_lang == "auto":
whisper_lang = None
# Save all uploaded files to the uploads directory
saved_files = [] # list of (filename, filepath)
for f in files:
filepath = os.path.join(pdir("uploads"), f.filename)
f.save(filepath)
saved_files.append((f.filename, filepath))
def do_transcribe():
state = load_state()
state["status"] = "transcribing"
state["source_file"] = saved_files[0][1] # backward compat
save_state(state)
total_files = len(saved_files)
progress.update(phase="transcribe", current=0, total=total_files + 1,
message="starting transcription…")
# Transcribe files in parallel
results = [None] * total_files # indexed by position
errors = [None] * total_files
warnings = []
def _transcribe_one(idx):
filename, filepath = saved_files[idx]
try:
return idx, transcribe_single_file(filepath, whisper_lang, diarize, idx, total_files)
except Exception as e:
return idx, e
max_workers = min(total_files, 4)
try:
with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor:
futures = [executor.submit(_transcribe_one, i) for i in range(total_files)]
for future in concurrent.futures.as_completed(futures):
idx, result = future.result()
if isinstance(result, Exception):
errors[idx] = result
warnings.append(f"{saved_files[idx][0]}: {friendly_error(result)}")
else:
results[idx] = result # (segments, words, duration)
# Update progress count
done_count = sum(1 for r in results if r is not None) + sum(1 for e in errors if e is not None)
progress.update(current=done_count, message=f"transcribed {done_count}/{total_files} files…")
# Check if ALL files failed
if all(r is None for r in results):
err_msg = "; ".join(warnings) if warnings else "all files failed"
raise Exception(err_msg)
# ── Merge results with cumulative time offsets ──
progress.update(message="merging transcripts…")
merged_segments = []
merged_words = []
source_files_info = []
cumulative_offset = 0.0
global_seg_id = 0
speaker_offset = 0
for idx in range(total_files):
filename, filepath = saved_files[idx]
if results[idx] is None:
# This file failed — skip it but record in source_files
source_files_info.append({
"filename": filename,
"path": filepath,
"offset": cumulative_offset,
"duration": 0,
"error": friendly_error(errors[idx]) if errors[idx] else "unknown error",
})
continue
segments, words, duration = results[idx]
source_files_info.append({
"filename": filename,
"path": filepath,
"offset": cumulative_offset,
"duration": duration,
})
# Build speaker ID mapping: offset speakers so each file gets unique IDs
file_speakers = set()
for seg in segments:
file_speakers.add(seg.get("speaker", "S1"))
# Sort to get deterministic mapping
file_speakers = sorted(file_speakers, key=lambda s: int(s[1:]) if s[1:].isdigit() else 0)
speaker_map = {}
for spk in file_speakers:
old_num = int(spk[1:]) if spk[1:].isdigit() else 1
speaker_map[spk] = f"S{old_num + speaker_offset}"
# Shift timestamps, remap speakers, and add source_index
for seg in segments:
seg["id"] = global_seg_id
seg["start"] += cumulative_offset
seg["end"] += cumulative_offset
seg["source_index"] = idx
seg["speaker"] = speaker_map.get(seg.get("speaker", "S1"), seg.get("speaker", "S1"))
merged_segments.append(seg)
global_seg_id += 1
for w in words:
w["start"] += cumulative_offset
w["end"] += cumulative_offset
w["source_index"] = idx
merged_words.append(w)
speaker_offset += len(file_speakers)
cumulative_offset += duration
# Build speaker_names from merged segments
seen = []
for seg in merged_segments:
spk = seg.get("speaker", "S1")
if spk not in seen:
seen.append(spk)
speaker_names = {spk: spk for spk in seen}
# Save state
state["transcript"] = merged_segments
state["words"] = merged_words
state["text_clips"] = []
state["clips"] = []
state["status"] = "transcribed"
state["source_file"] = saved_files[0][1] # backward compat
state["source_files"] = source_files_info
state["filename"] = ", ".join(fn for fn, _ in saved_files)
state["transcription_language"] = whisper_lang or "auto"
state["speaker_names"] = speaker_names
if warnings:
state["transcription_warnings"] = warnings
save_state(state)
progress.update(current=progress["total"], message="done", phase=None)
except Exception as e:
state["status"] = f"error: {friendly_error(e)}"
save_state(state)
progress.update(phase=None, current=0, total=0, message="")
threading.Thread(target=do_transcribe).start()
return jsonify({"message": "Transcription started"})
@app.route("/status")
def status():
state = load_state()
return jsonify({
"status": state.get("status", "idle"),
"segment_count": len(state.get("transcript", [])),
"filename": state.get("filename", "")
})
@app.route("/progress")
def get_progress():
return jsonify(progress)
# ─── STEP 2: TEXT-BASED CLIP MARKING ──────────────────────
@app.route("/add_clip", methods=["POST"])
def add_clip():
"""Add a clip from text selection with word-level timestamps."""
data = request.json
start = data["start"]
end = data["end"]
text = data.get("text", "")
source = data.get("source", "interview") # "interview" or "narration"
state = load_state()
if source == "narration":
clips = state.get("narr_text_clips", [])
prefix = "narr"
else:
clips = state.get("text_clips", [])
prefix = "clip"
# Auto-number
clip_id = f"{prefix}_{len(clips) + 1:02d}"
clips.append({
"id": clip_id,
"start": round(start, 3),
"end": round(end, 3),
"text": text,
"source": source
})
# Sort by start time and renumber
clips.sort(key=lambda c: c["start"])
for i, c in enumerate(clips):
c["id"] = f"{prefix}_{i + 1:02d}"
if source == "narration":
state["narr_text_clips"] = clips
else:
state["text_clips"] = clips
save_state(state)
return jsonify({"ok": True, "clip_id": clip_id, "clips": clips})
@app.route("/trim_clip", methods=["POST"])
def trim_clip():
"""Fine-tune start/end time of a marked clip."""
data = request.json
clip_id = data["id"]
source = data.get("source", "interview")
new_start = data.get("start")
new_end = data.get("end")
state = load_state()
clips = state.get("narr_text_clips" if source == "narration" else "text_clips", [])
for c in clips:
if c["id"] == clip_id:
if new_start is not None:
c["start"] = round(max(0, float(new_start)), 3)
if new_end is not None:
c["end"] = round(float(new_end), 3)
# Ensure start < end with at least 0.1s
if c["start"] >= c["end"]:
c["end"] = c["start"] + 0.1
break
if source == "narration":
state["narr_text_clips"] = clips
else:
state["text_clips"] = clips
save_state(state)
return jsonify({"ok": True})
@app.route("/remove_clip", methods=["POST"])
def remove_clip():
"""Remove a clip by ID."""
data = request.json
clip_id = data["id"]
source = data.get("source", "interview")
state = load_state()
if source == "narration":
clips = state.get("narr_text_clips", [])
prefix = "narr"
else:
clips = state.get("text_clips", [])
prefix = "clip"
clips = [c for c in clips if c["id"] != clip_id]
# Renumber
for i, c in enumerate(clips):
c["id"] = f"{prefix}_{i + 1:02d}"
if source == "narration":
state["narr_text_clips"] = clips
else:
state["text_clips"] = clips
save_state(state)
return jsonify({"ok": True, "clips": clips})
# ─── STEP 3: CUT CLIPS ────────────────────────────────────
@app.route("/cut_clips", methods=["POST"])
def cut_clips():
state = load_state()
source_files = state.get("source_files", [])
source = state.get("source_file")
# Validate we have at least one source file available
if source_files:
has_valid = any(os.path.exists(sf["path"]) for sf in source_files)
if not has_valid:
return jsonify({"error": "Source audio file not found"}), 400
elif not source or not os.path.exists(source):
return jsonify({"error": "Source audio file not found"}), 400
text_clips = state.get("text_clips", [])
if not text_clips:
return jsonify({"error": "No clips marked"}), 400
state["status"] = "cutting"
save_state(state)
def do_cut():
try:
st = load_state()
# Validate source availability
sf_list = st.get("source_files", [])
legacy_source = st.get("source_file", "")
if not sf_list and (not legacy_source or not os.path.exists(legacy_source)):
st["status"] = f"error: source file not found — {legacy_source}"
save_state(st)
progress.update(phase=None, message="")
return
clips = st.get("text_clips", [])
progress.update(phase="cut", current=0, total=len(clips), message=f"cutting 0/{len(clips)} clips…")
cut_files = []
for i, clip in enumerate(clips):
progress.update(current=i, message=f"cutting {clip['id']}… ({i+1}/{len(clips)})")
source_path, real_start, real_end = resolve_source_for_clip(clip, st)
if not source_path or not os.path.exists(source_path):
continue
out_path = os.path.join(pdir("clips"), f"{clip['id']}.wav")
duration = real_end - real_start
cmd = [
"ffmpeg", "-y",
"-i", source_path,
"-ss", str(real_start),
"-t", str(duration),
"-c:a", "pcm_s16le", "-ar", "44100", "-ac", "1",
out_path
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
cut_files.append({
"id": clip["id"],
"path": out_path,
"start": clip["start"],
"end": clip["end"],
"duration": round(duration, 2)
})
st["clips"] = cut_files
st["status"] = "clips_ready"
save_state(st)
# Auto-generate transcript Word doc
try:
import docx as docx_lib
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
def set_rtl_doc(paragraph):
pPr = paragraph._p.get_or_add_pPr()
pPr.append(docx_lib.oxml.OxmlElement('w:bidi'))
for run in paragraph.runs:
rPr = run._r.get_or_add_rPr()
rPr.append(docx_lib.oxml.OxmlElement('w:rtl'))
doc = docx_lib.Document()
style = doc.styles['Normal']
style.font.name = 'David'
style.font.size = Pt(13)
title = doc.add_heading(st.get("filename", "תמלול"), level=1)
title.alignment = WD_ALIGN_PARAGRAPH.RIGHT
set_rtl_doc(title)
transcript = st.get("transcript", [])
speaker_names = st.get("speaker_names", {})
multi_spk = len(set(s.get("speaker", "S1") for s in transcript)) > 1
for clip in st.get("text_clips", []):
start_fmt = f"{int(clip['start']//60):02d}:{int(clip['start']%60):02d}"
end_fmt = f"{int(clip['end']//60):02d}:{int(clip['end']%60):02d}"
spk = get_clip_speaker(clip, transcript) if multi_spk else None
p = doc.add_paragraph()
header = f"{clip['id']} ({start_fmt} – {end_fmt})"
if spk:
header += f" [{speaker_names.get(spk, spk)}]"
run = p.add_run(header)
run.bold = True
run.font.size = Pt(14)
r, g, b = SPK_COLORS_RGB.get(spk, (0x33, 0x99, 0x66)) if spk else (0x33, 0x99, 0x66)
run.font.color.rgb = RGBColor(r, g, b)
set_rtl_doc(p)
tp = doc.add_paragraph(clip.get("text", ""))
set_rtl_doc(tp)
doc.add_paragraph("")
base = os.path.splitext(st.get("filename", "transcript"))[0]
docx_path = os.path.join(pdir("output"), f"{base}.docx")
doc.save(docx_path)
copy_to_export_folder(docx_path)
except Exception:
pass # Word doc generation is best-effort
progress.update(phase=None, current=len(clips), total=len(clips), message="done")
except Exception as e:
st = load_state()
st["status"] = f"error: {friendly_error(e)}"
save_state(st)
progress.update(phase=None, message="")
threading.Thread(target=do_cut).start()
return jsonify({"message": "Cutting started"})
@app.route("/export_transcript", methods=["GET"])
def export_transcript():
import docx
from docx.shared import Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
def set_rtl(paragraph):
"""Set proper RTL on a paragraph (bidi) and all its runs (rtl)."""
pPr = paragraph._p.get_or_add_pPr()
pPr.append(docx.oxml.OxmlElement('w:bidi'))
for run in paragraph.runs:
rPr = run._r.get_or_add_rPr()
rPr.append(docx.oxml.OxmlElement('w:rtl'))
state = load_state()
text_clips = state.get("text_clips", [])
if not text_clips:
return jsonify({"error": "No clips to export"}), 400
doc = docx.Document()
# Set default font for Hebrew
style = doc.styles['Normal']
style.font.name = 'David'
style.font.size = Pt(13)
title = doc.add_heading(state.get("filename", "תמלול"), level=1)
title.alignment = WD_ALIGN_PARAGRAPH.RIGHT
set_rtl(title)
transcript = state.get("transcript", [])
speaker_names = state.get("speaker_names", {})
multi_spk = len(set(s.get("speaker", "S1") for s in transcript)) > 1
for clip in text_clips:
start_fmt = f"{int(clip['start']//60):02d}:{int(clip['start']%60):02d}"
end_fmt = f"{int(clip['end']//60):02d}:{int(clip['end']%60):02d}"
spk = get_clip_speaker(clip, transcript) if multi_spk else None
p = doc.add_paragraph()
header = f"{clip['id']} ({start_fmt} – {end_fmt})"
if spk:
header += f" [{speaker_names.get(spk, spk)}]"
run = p.add_run(header)
run.bold = True
run.font.size = Pt(14)
r, g, b = SPK_COLORS_RGB.get(spk, (0x33, 0x99, 0x66)) if spk else (0x33, 0x99, 0x66)
run.font.color.rgb = RGBColor(r, g, b)
set_rtl(p)
tp = doc.add_paragraph(clip.get("text", ""))
set_rtl(tp)
doc.add_paragraph("") # spacer
base = os.path.splitext(state.get("filename", "transcript"))[0]
docx_name = f"{base}.docx"
out_path = os.path.join(pdir("output"), docx_name)
doc.save(out_path)
copy_to_export_folder(out_path)
return send_file(out_path, as_attachment=True, download_name=docx_name)
# ─── STEP 4: NARRATION ────────────────────────────────────
@app.route("/upload_narration_audio", methods=["POST"])
def upload_narration_audio():
if "file" not in request.files:
return jsonify({"error": "No file uploaded"}), 400
f = request.files["file"]
filepath = os.path.join(pdir("narration"), f.filename)
f.save(filepath)
state = load_state()
state["narration_source"] = filepath
state["narration_filename"] = f.filename
save_state(state)
return jsonify({"ok": True, "filename": f.filename})
@app.route("/import_script", methods=["POST"])
def import_script():
if "file" not in request.files:
return jsonify({"error": "No file uploaded"}), 400
f = request.files["file"]
filename = f.filename.lower()
if filename.endswith(".docx"):
import docx
tmp = tempfile.mktemp(suffix=".docx")
f.save(tmp)
doc = docx.Document(tmp)
text = "\n".join(p.text for p in doc.paragraphs if p.text.strip())
os.unlink(tmp)
elif filename.endswith(".txt"):
text = f.read().decode("utf-8")
else:
return jsonify({"error": "Unsupported format. Use .docx or .txt"}), 400
return jsonify({"text": text})
@app.route("/process_narration", methods=["POST"])
def process_narration():
"""Transcribe already-uploaded narration audio with optional script text."""
if not client:
return jsonify({"error": "OPENAI_API_KEY not set"}), 500
data = request.json or {}
script_text = data.get("script", "").strip()
state = load_state()
filepath = state.get("narration_source")
if not filepath or not os.path.exists(filepath):
return jsonify({"error": "Upload narration audio first"}), 400
state["status"] = "processing_narration"
save_state(state)
def do_process():
st = load_state()
try:
upload_path = filepath
if os.path.getsize(filepath) > 25 * 1024 * 1024:
progress.update(phase="narration", current=0, total=3, message="compressing narration…")
compressed = filepath.rsplit(".", 1)[0] + "_compressed.mp3"
try:
dur_result = subprocess.run(
["ffprobe", "-v", "quiet", "-show_entries", "format=duration", "-of", "csv=p=0", filepath],
capture_output=True, text=True)
narr_duration = float(dur_result.stdout.strip()) or 1
except Exception:
narr_duration = 1
target_bits = 24 * 1024 * 1024 * 8
bitrate_kbps = max(8, min(64, int(target_bits / narr_duration / 1000)))
subprocess.run([
"ffmpeg", "-y", "-i", filepath,
"-ac", "1", "-ar", "16000", "-b:a", f"{bitrate_kbps}k",
compressed
], capture_output=True, check=True)
upload_path = compressed
progress.update(current=1, message="transcribing narration…")
else:
progress.update(phase="narration", current=0, total=2, message="transcribing narration…")
narr_lang = st.get("transcription_language", "he")
whisper_kwargs = {
"model": "whisper-1",
"response_format": "verbose_json",
"timestamp_granularities": ["word", "segment"],
}
if narr_lang and narr_lang != "auto":
whisper_kwargs["language"] = narr_lang
if script_text:
whisper_kwargs["prompt"] = script_text[:500]
with open(upload_path, "rb") as audio_file:
whisper_kwargs["file"] = audio_file
result = client.audio.transcriptions.create(**whisper_kwargs)
# Word-level timestamps
words = []
if hasattr(result, 'words') and result.words:
for w in result.words:
words.append({"word": w.word.strip(), "start": w.start, "end": w.end})
raw = [{"start": seg.start, "end": seg.end, "text": seg.text.strip()} for seg in result.segments]
passages = merge_segments(raw)
st["narration_transcript"] = []
for i, p in enumerate(passages):
st["narration_transcript"].append({
"id": i,
"start": p["start"],
"end": p["end"],
"text": p["text"],
})
st["narration_words"] = words
st["narr_text_clips"] = []
st["narration"] = []
st["narration_source"] = filepath
st["status"] = "narration_ready"
save_state(st)
progress.update(phase=None, current=progress["total"], total=progress["total"], message="done")
except Exception as e:
st["status"] = f"error: {friendly_error(e)}"
save_state(st)
progress.update(phase=None, current=0, total=0, message="")
threading.Thread(target=do_process).start()
return jsonify({"message": "Processing narration…"})
@app.route("/cut_narration", methods=["POST"])
def cut_narration():
state = load_state()
source = state.get("narration_source")
if not source or not os.path.exists(source):
return jsonify({"error": "Narration source not found"}), 400
narr_clips = state.get("narr_text_clips", [])
if not narr_clips:
return jsonify({"error": "No narration clips marked"}), 400
state["status"] = "cutting_narration"
save_state(state)
def do_cut():
st = load_state()
clips = st.get("narr_text_clips", [])
progress.update(phase="cut_narr", current=0, total=len(clips),
message=f"cutting 0/{len(clips)} narration clips…")
narration_files = []