AliJabbarpour commited on
Commit
e66d32e
·
verified ·
1 Parent(s): 93067e1

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -505
app.py DELETED
@@ -1,505 +0,0 @@
1
- import os
2
- import time
3
- import uuid
4
- import asyncio
5
- import tempfile
6
- import shutil
7
- import threading
8
- import logging
9
- import torch
10
- import torchaudio
11
- from fastapi import FastAPI, Request, HTTPException, BackgroundTasks
12
- from fastapi.middleware.cors import CORSMiddleware
13
- from faster_whisper import WhisperModel
14
- from df.enhance import enhance, init_df, load_audio, save_audio
15
- from pyannote.audio import Pipeline as DiarizationPipeline
16
- from pipeline.postprocess import process
17
-
18
-
19
- class HealthAndStatusFilter(logging.Filter):
20
- """جلوی چاپ لاگ‌های /status/ و /health رو می‌گیره تا کنسول شلوغ نشه (خودِ درخواست‌ها عادی پردازش میشن)"""
21
- def filter(self, record):
22
- message = record.getMessage()
23
- return "/status/" not in message and "/health" not in message
24
-
25
-
26
- logging.getLogger("uvicorn.access").addFilter(HealthAndStatusFilter())
27
-
28
- torch.set_num_threads(2) # جلوی رقابت بی‌فایده‌ی رشته‌ها روی CPU محدود رو می‌گیره
29
-
30
- app = FastAPI()
31
-
32
- app.add_middleware(
33
- CORSMiddleware,
34
- allow_origins=["*"],
35
- allow_methods=["*"],
36
- allow_headers=["*"],
37
- )
38
-
39
- print("Loading Whisper model...", flush=True)
40
- model = WhisperModel("large-v3", device="cpu", compute_type="int8")
41
- print("Whisper model ready!")
42
-
43
- print("Loading DeepFilterNet model...", flush=True)
44
- df_model, df_state, _ = init_df()
45
- print("DeepFilterNet model ready!")
46
-
47
- USE_DEEPFILTERNET = False # غیرفعال - شواهد نشون داد کمکی نمی‌کنه و بعضی صداها رو خراب می‌کنه
48
-
49
- print("Loading word-alignment model...", flush=True)
50
- align_bundle = torchaudio.pipelines.MMS_FA
51
- align_model = align_bundle.get_model().to("cpu")
52
- align_labels = align_bundle.get_labels()
53
- align_dictionary = {c: i for i, c in enumerate(align_labels)}
54
- print("Word-alignment model ready!")
55
-
56
- print("Loading speaker-diarization model...", flush=True)
57
- HF_TOKEN = os.environ.get("HF_TOKEN")
58
- diarize_pipeline = DiarizationPipeline.from_pretrained(
59
- "pyannote/speaker-diarization-3.1", use_auth_token=HF_TOKEN
60
- )
61
- print("Speaker-diarization model ready!")
62
-
63
- MIN_NOISE_BLOCK_SEC = 1.0
64
- JOB_TTL_SECONDS = 3 * 60 * 60 # کارهای قدیمی بعد از ۳ ساعت پاک میشن (برای فایل‌های سنگین که ممکنه پردازششون طولانی بشه)
65
- STAGE_TIMEOUT_SEC = 1200 # سقف زمانی برای هر مرحله‌ی سنگین (۲۰ دقیقه - فقط محافظ آخر در برابر گیرکردن واقعی)
66
-
67
- # ─── نگهداری وضعیت کارها (Jobs) توی حافظه ───────────────────────────────────
68
- jobs = {}
69
- jobs_lock = threading.Lock()
70
-
71
-
72
- def new_job(single_speaker_mode=False):
73
- job_id = uuid.uuid4().hex
74
- tmp_dir = tempfile.mkdtemp(prefix=f"subflow_{job_id}_")
75
- with jobs_lock:
76
- jobs[job_id] = {
77
- "status": "uploading",
78
- "detail": "در انتظار دریافت فایل...",
79
- "created_at": time.time(),
80
- "tmp_dir": tmp_dir,
81
- "chunk_paths": [],
82
- "srt": None,
83
- "language": None,
84
- "duration": None,
85
- "error": None,
86
- "single_speaker_mode": single_speaker_mode,
87
- }
88
- return job_id
89
-
90
-
91
- def get_job(job_id):
92
- with jobs_lock:
93
- job = jobs.get(job_id)
94
- if job is None:
95
- raise HTTPException(status_code=404, detail="این کار پیدا نشد یا منقضی شده")
96
- return job
97
-
98
-
99
- def update_job(job_id, **kwargs):
100
- with jobs_lock:
101
- if job_id in jobs:
102
- jobs[job_id].update(kwargs)
103
-
104
-
105
- def cleanup_expired_jobs():
106
- now = time.time()
107
- with jobs_lock:
108
- expired = [jid for jid, j in jobs.items() if now - j["created_at"] > JOB_TTL_SECONDS]
109
- for jid in expired:
110
- with jobs_lock:
111
- job = jobs.pop(jid, None)
112
- if job and os.path.isdir(job["tmp_dir"]):
113
- shutil.rmtree(job["tmp_dir"], ignore_errors=True)
114
- print(f"[cleanup] removed expired job {jid}")
115
-
116
-
117
- # ─── منطق تشخیص گوینده و هم‌ترازی ────────────────────────────────────────────
118
-
119
- def build_speaker_lookup(diarization):
120
- """
121
- لیست بازه‌های گوینده‌ها رو یه‌بار مرتب می‌کنه تا جست‌وجوی «این لحظه مال کدوم
122
- گوینده‌ست» برای هر جمله، به‌جای گشتن کامل لیست، سریع (با جست‌وجوی دودویی) انجام بشه.
123
- """
124
- turns = sorted(
125
- [(turn.start, turn.end, speaker) for turn, _, speaker in diarization.itertracks(yield_label=True)],
126
- key=lambda x: x[0],
127
- )
128
- return turns
129
-
130
-
131
- def get_speaker_at(turns, time_sec):
132
- import bisect
133
- starts = [t[0] for t in turns]
134
- idx = bisect.bisect_right(starts, time_sec) - 1
135
- if idx >= 0:
136
- start, end, speaker = turns[idx]
137
- if start <= time_sec <= end:
138
- return speaker
139
- return None
140
-
141
-
142
- def get_speaker_for_segment(turns, seg_start, seg_end):
143
- """
144
- به‌جای اعتماد به یه لحظه‌ی تنها، چند نقطه در طول جمله رو چک می‌کنه
145
- و گوینده‌ای که بیشترین رأی رو آورده برمی‌گردونه.
146
- """
147
- duration = seg_end - seg_start
148
- if duration <= 0:
149
- return get_speaker_at(turns, seg_start)
150
-
151
- sample_points = [seg_start + duration * frac for frac in (0.2, 0.4, 0.5, 0.6, 0.8)]
152
- votes = {}
153
- for t in sample_points:
154
- speaker = get_speaker_at(turns, t)
155
- if speaker is not None:
156
- votes[speaker] = votes.get(speaker, 0) + 1
157
-
158
- if not votes:
159
- return None
160
- return max(votes, key=votes.get)
161
-
162
-
163
- def find_leading_noise_cutoff(turns, whisper_start, search_back_sec=4.0):
164
- STABLE_SPEAKER_SEC = 0.2
165
- window_start = max(0, whisper_start - search_back_sec)
166
- step = 0.05
167
- t = whisper_start
168
- noise_end = None
169
- noise_start = None
170
- speaker_run_start = None
171
-
172
- while t > window_start:
173
- speaker = get_speaker_at(turns, t)
174
-
175
- if speaker is None:
176
- speaker_run_start = None
177
- if noise_end is None:
178
- noise_end = t
179
- noise_start = t
180
- else:
181
- if speaker_run_start is None:
182
- speaker_run_start = t
183
- run_len = speaker_run_start - t
184
- if run_len >= STABLE_SPEAKER_SEC:
185
- break
186
- if noise_end is None:
187
- noise_end = t
188
- noise_start = t
189
-
190
- t -= step
191
-
192
- if noise_start is not None and noise_end is not None:
193
- block_len = noise_end - noise_start
194
- if block_len >= MIN_NOISE_BLOCK_SEC:
195
- return noise_end
196
- return None
197
-
198
-
199
- def realign_word_timestamps(waveform_16k, words, whisper_start, whisper_end, cutoff_start=None):
200
- try:
201
- margin = 0.5
202
- raw_start = whisper_start - margin
203
- effective_start = max(raw_start, cutoff_start) if cutoff_start is not None else raw_start
204
-
205
- start_sample = max(0, int(effective_start * 16000))
206
- end_sample = int((whisper_end + margin) * 16000)
207
- clip = waveform_16k[:, start_sample:end_sample]
208
-
209
- clean_words = []
210
- for w in words:
211
- token = "".join(ch for ch in w["word"].lower() if ch in align_dictionary)
212
- if token:
213
- clean_words.append((w, token))
214
-
215
- if not clean_words:
216
- return words
217
-
218
- transcript = "".join(tok for _, tok in clean_words)
219
- tokens = [align_dictionary[c] for c in transcript]
220
-
221
- with torch.inference_mode():
222
- emission, _ = align_model(clip)
223
-
224
- targets = torch.tensor([tokens], dtype=torch.int32)
225
- input_lengths = torch.tensor([emission.shape[1]])
226
- target_lengths = torch.tensor([len(tokens)])
227
-
228
- aligned_tokens, scores = torchaudio.functional.forced_align(
229
- emission, targets, input_lengths, target_lengths, blank=0
230
- )
231
- spans = torchaudio.functional.merge_tokens(aligned_tokens[0], scores[0])
232
-
233
- ratio = clip.shape[1] / emission.shape[1] / 16000
234
- new_words = []
235
- span_idx = 0
236
- for w, tok in clean_words:
237
- n_chars = len(tok)
238
- matched = [s for s in spans[span_idx:] if s.token != 0][:n_chars]
239
- if len(matched) < n_chars:
240
- new_words.append(w)
241
- continue
242
- w_start = matched[0].start * ratio + effective_start
243
- w_end = matched[-1].end * ratio + effective_start
244
- new_words.append({"word": w["word"], "start": round(max(0, w_start), 3), "end": round(max(0, w_end), 3)})
245
- span_idx += n_chars
246
-
247
- return new_words if len(new_words) == len(words) else words
248
- except Exception as e:
249
- print(f" [align] skipped due to: {type(e).__name__}: {e}")
250
- return words
251
-
252
-
253
- def run_transcription(audio_path):
254
- """
255
- نکته‌ی مهم: model.transcribe فوراً برنمی‌گرده - یه نتیجه‌ی "تنبل" میده که کار
256
- واقعیش رو دیر انجام میده. برای اینکه کل زمان واقعی پردازش زیر نظارت سقف زمانی و
257
- پیام‌های زنده باشه، همینجا مجبورش می‌کنیم کارش رو کامل انجام بده (list کردن).
258
- """
259
- segments_raw, info = model.transcribe(
260
- audio_path,
261
- language="en",
262
- word_timestamps=True,
263
- vad_filter=True,
264
- vad_parameters=dict(
265
- min_silence_duration_ms=300,
266
- speech_pad_ms=200,
267
- threshold=0.3,
268
- ),
269
- )
270
- segments_list = list(segments_raw)
271
- return segments_list, info
272
-
273
-
274
- class SingleSpeakerResult:
275
- """
276
- یه نتیجه‌ی «قلابی» که همون شکل خروجی diarize_pipeline رو تقلید می‌کنه (متد itertracks داره)
277
- ولی هیچ پردازش واقعی‌ای روی کل فایل انجام نداده - فقط می‌گه «همه‌جا همون یه گوینده‌ست».
278
- فقط وقتی استفاده میشه که خودِ کاربر صراحتاً بگه فایل تک‌گوینده‌ست.
279
- """
280
- def __init__(self, duration):
281
- self.duration = duration
282
-
283
- def itertracks(self, yield_label=False):
284
- class FakeTurn:
285
- def __init__(self, start, end):
286
- self.start = start
287
- self.end = end
288
- yield FakeTurn(0, self.duration), None, "SPEAKER_00"
289
-
290
-
291
- def run_diarization(audio_path, single_speaker_mode=False, job_id=None):
292
- if single_speaker_mode:
293
- print(" [diarization] single-speaker mode selected by user — skipping full diarization entirely")
294
- info = torchaudio.info(audio_path)
295
- duration = info.num_frames / info.sample_rate
296
- return SingleSpeakerResult(duration)
297
-
298
- return diarize_pipeline(audio_path, max_speakers=8)
299
-
300
-
301
- def run_alignment_pass(segments_raw, align_waveform, diarization):
302
- turns = build_speaker_lookup(diarization)
303
- segments = []
304
- for seg in segments_raw:
305
- words = list(seg.words)
306
- if not words:
307
- continue
308
- word_dicts = [{"word": w.word, "start": w.start, "end": w.end} for w in words]
309
-
310
- cutoff = find_leading_noise_cutoff(turns, word_dicts[0]["start"])
311
- if cutoff is not None:
312
- print(f" [noise-trim] '{seg.text.strip()[:40]}...' cutoff moved from {word_dicts[0]['start']:.2f}s to {cutoff:.2f}s")
313
-
314
- realigned = realign_word_timestamps(
315
- align_waveform, word_dicts, word_dicts[0]["start"], word_dicts[-1]["end"], cutoff_start=cutoff
316
- )
317
-
318
- speaker = get_speaker_for_segment(turns, realigned[0]["start"], realigned[-1]["end"])
319
-
320
- segments.append({
321
- "text": seg.text.strip(),
322
- "start": realigned[0]["start"],
323
- "end": realigned[-1]["end"],
324
- "words": realigned,
325
- "speaker": speaker,
326
- })
327
- return segments
328
-
329
-
330
- class ProcessingTimeout(Exception):
331
- pass
332
-
333
-
334
- def run_blocking_with_timeout(job_id, blocking_fn, *args, status, detail, max_seconds=STAGE_TIMEOUT_SEC):
335
- """
336
- یه تابع سنگین و بلاک‌کننده رو توی یه thread جدا اجرا می‌کنه، و تا وقتی تموم بشه،
337
- هر چند ثانیه یه پیام "هنوز کار می‌کنم" روی همون status می‌فرسته - این هم جلوی
338
- قطع‌شدن اتصال به‌خاطر سکوت طولانی رو می‌گیره، هم UI رو زنده نگه می‌داره.
339
- اگه از max_seconds بیشتر طول بکشه، به‌جای قفل ابدی، خطای مشخص میده.
340
- """
341
- result_holder = {}
342
- error_holder = {}
343
-
344
- def runner():
345
- try:
346
- result_holder["value"] = blocking_fn(*args)
347
- except Exception as e:
348
- error_holder["error"] = e
349
-
350
- update_job(job_id, status=status, detail=detail)
351
- t = threading.Thread(target=runner, daemon=True)
352
- t.start()
353
-
354
- elapsed = 0
355
- while t.is_alive():
356
- t.join(timeout=3)
357
- if t.is_alive():
358
- elapsed += 3
359
- if elapsed >= max_seconds:
360
- raise ProcessingTimeout(f"مرحله‌ی «{detail}» بیشتر از {max_seconds} ثانیه طول کشید و متوقف شد.")
361
- update_job(job_id, status=status, detail=f"{detail} ({elapsed} ثانیه)")
362
-
363
- if "error" in error_holder:
364
- raise error_holder["error"]
365
- return result_holder.get("value")
366
-
367
-
368
- def process_job(job_id):
369
- """کل پایپلاین پردازش - این تابع توی یه thread پس‌زمینه اجرا میشه، نه توی درخواست HTTP."""
370
- job = get_job(job_id)
371
- tmp_dir = job["tmp_dir"]
372
- single_speaker_mode = job.get("single_speaker_mode", False)
373
- tmp_path = os.path.join(tmp_dir, "input.wav")
374
- enhanced_path = None
375
-
376
- try:
377
- with open(tmp_path, "wb") as f:
378
- for chunk_path in job["chunk_paths"]:
379
- with open(chunk_path, "rb") as c:
380
- f.write(c.read())
381
- print(f"Job {job_id}: assembled {len(job['chunk_paths'])} chunks into {tmp_path}")
382
-
383
- audio_to_transcribe = tmp_path
384
-
385
- if USE_DEEPFILTERNET:
386
- update_job(job_id, status="cleaning", detail="در حال حذف نویز پس‌زمینه")
387
- audio_data, _ = load_audio(tmp_path, sr=df_state.sr())
388
- enhanced_audio = enhance(df_model, df_state, audio_data, atten_lim_db=20)
389
- enhanced_path = os.path.join(tmp_dir, "enhanced.wav")
390
- save_audio(enhanced_path, enhanced_audio, df_state.sr())
391
- audio_to_transcribe = enhanced_path
392
-
393
- segments_raw_list, info = run_blocking_with_timeout(
394
- job_id, run_transcription, audio_to_transcribe,
395
- status="transcribing", detail="مدل large-v3 در حال شنیدن صداست",
396
- )
397
- update_job(job_id, detail=f"{len(segments_raw_list)} جمله تشخیص داده شد")
398
-
399
- align_waveform, sr = torchaudio.load(audio_to_transcribe)
400
- if sr != 16000:
401
- align_waveform = torchaudio.functional.resample(align_waveform, sr, 16000)
402
- if align_waveform.shape[0] > 1:
403
- align_waveform = align_waveform.mean(dim=0, keepdim=True)
404
-
405
- if single_speaker_mode:
406
- diarization = run_diarization(audio_to_transcribe, single_speaker_mode=True)
407
- update_job(job_id, status="aligning", detail="تشخیص گوینده رد شد (حالت تک‌گوینده)")
408
- else:
409
- diarization = run_blocking_with_timeout(
410
- job_id, run_diarization, audio_to_transcribe, False, job_id,
411
- status="aligning", detail="در حال تشخیص گوینده‌ها",
412
- )
413
- update_job(job_id, detail="گوینده‌ها شناسایی شدند")
414
-
415
- segments = run_blocking_with_timeout(
416
- job_id, run_alignment_pass, segments_raw_list, align_waveform, diarization,
417
- status="aligning", detail=f"در حال هماهنگ‌سازی زمان‌بندی {len(segments_raw_list)} جمله",
418
- )
419
- update_job(job_id, detail=f"{len(segments)} خط شناسایی شد")
420
-
421
- print(f"Job {job_id}: got {len(segments)} segments")
422
- for i, seg in enumerate(segments):
423
- print(f" seg[{i}]: '{seg['text']}' | speaker={seg['speaker']} | dur={seg['end']-seg['start']:.2f}s")
424
-
425
- update_job(job_id, status="processing", detail=f"در حال چیدمان {len(segments)} خط زیرنویس")
426
- srt_content = process(segments)
427
- update_job(job_id, detail="زیرنویس ساخته شد")
428
-
429
- update_job(
430
- job_id,
431
- status="done",
432
- detail="زیرنویس آماده شد",
433
- srt=srt_content,
434
- language=info.language,
435
- duration=info.duration,
436
- )
437
- print(f"Job {job_id}: done!")
438
-
439
- except ProcessingTimeout as e:
440
- print(f"Job {job_id}: TIMEOUT: {e}")
441
- update_job(job_id, status="error", error=str(e))
442
- except Exception as e:
443
- print(f"Job {job_id}: ERROR: {type(e).__name__}: {e}")
444
- import traceback
445
- traceback.print_exc()
446
- update_job(job_id, status="error", error=str(e))
447
- finally:
448
- pass # پاک‌سازی جداگانه و فقط موقع شروع کارهای جدید انجام میشه، نه بلافاصله بعد از اتمام همین کار
449
-
450
-
451
- @app.get("/health")
452
- async def health():
453
- return {"status": "ok", "message": "SubFlow backend is running"}
454
-
455
-
456
- @app.post("/upload/start")
457
- async def upload_start(request: Request):
458
- cleanup_expired_jobs()
459
- body = {}
460
- try:
461
- body = await request.json()
462
- except Exception:
463
- pass
464
- single_speaker_mode = bool(body.get("single_speaker_mode", False))
465
- job_id = new_job(single_speaker_mode)
466
- return {"job_id": job_id}
467
-
468
-
469
- @app.post("/upload/chunk/{job_id}")
470
- async def upload_chunk(job_id: str, request: Request):
471
- job = get_job(job_id)
472
- chunk_bytes = await request.body()
473
- chunk_index = len(job["chunk_paths"])
474
- chunk_path = os.path.join(job["tmp_dir"], f"chunk_{chunk_index:06d}.bin")
475
- with open(chunk_path, "wb") as f:
476
- f.write(chunk_bytes)
477
- with jobs_lock:
478
- jobs[job_id]["chunk_paths"].append(chunk_path)
479
- return {"received": chunk_index}
480
-
481
-
482
- @app.post("/upload/finish/{job_id}")
483
- async def upload_finish(job_id: str, background_tasks: BackgroundTasks):
484
- job = get_job(job_id)
485
- total_bytes = sum(os.path.getsize(p) for p in job["chunk_paths"])
486
- print(f"Job {job_id}: upload finished, {len(job['chunk_paths'])} chunks, {total_bytes} bytes total")
487
- update_job(job_id, status="receiving", detail="فایل آماده‌ی پردازش شد")
488
- background_tasks.add_task(process_job, job_id)
489
- return {"status": "processing_started"}
490
-
491
-
492
- @app.get("/status/{job_id}")
493
- async def status(job_id: str):
494
- job = get_job(job_id)
495
- response = {
496
- "status": job["status"],
497
- "detail": job["detail"],
498
- }
499
- if job["status"] == "done":
500
- response["srt"] = job["srt"]
501
- response["language"] = job["language"]
502
- response["duration"] = job["duration"]
503
- elif job["status"] == "error":
504
- response["message"] = job["error"]
505
- return response