-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
917 lines (773 loc) · 39 KB
/
Copy pathapp.py
File metadata and controls
917 lines (773 loc) · 39 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
import os
import subprocess
import re
import shutil
import uuid
import logging
import sys
import threading
import time
import json
import hashlib
import gc
import requests
from concurrent.futures import ThreadPoolExecutor
from collections import Counter
from flask import Flask, request, jsonify, render_template, send_from_directory
from werkzeug.utils import secure_filename
from faster_whisper import WhisperModel
from pydub import AudioSegment
from pydub.generators import Sine
# --- CONFIGURATION ---
FFMPEG_PATH = r"C:\ProgramData\chocolatey\bin\ffmpeg.exe" if os.name == 'nt' else "ffmpeg"
FFPROBE_PATH = r"C:\ProgramData\chocolatey\bin\ffprobe.exe" if os.name == 'nt' else "ffprobe"
UPLOAD_FOLDER = 'uploads'
OUTPUT_FOLDER = 'processed'
TEMP_FOLDER = 'temp_chunks'
CACHE_FOLDER = 'cache_transcripts'
MODEL_SIZE = "models/medium"
MAX_WORKERS = 4 # Оптимально для 2.5ч файлов
if os.path.exists(os.path.dirname(FFMPEG_PATH)) and os.path.dirname(FFMPEG_PATH) != '':
os.environ["PATH"] += os.pathsep + os.path.dirname(FFMPEG_PATH)
AudioSegment.converter = FFMPEG_PATH
AudioSegment.ffprobe = FFPROBE_PATH
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['OUTPUT_FOLDER'] = OUTPUT_FOLDER
app.config['TEMP_FOLDER'] = TEMP_FOLDER
app.config['CACHE_FOLDER'] = CACHE_FOLDER
for folder in [UPLOAD_FOLDER, OUTPUT_FOLDER, TEMP_FOLDER, CACHE_FOLDER]:
os.makedirs(folder, exist_ok=True)
logging.basicConfig(level=logging.INFO, stream=sys.stdout, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
jobs = {}
# --- MODEL & HELPERS ---
def load_model():
import torch
device = "cpu"
compute_type = "int8"
if torch.cuda.is_available():
try:
device = "cuda"
compute_type = "float16"
except: pass
local_path = os.path.join(os.getcwd(), MODEL_SIZE)
if os.path.exists(local_path):
model_path = local_path
local_files = True
else:
model_path = "medium"
local_files = False
logger.info(f"Loading Whisper from {model_path} on {device}...")
return WhisperModel(model_path, device=device, compute_type=compute_type, local_files_only=local_files)
model = load_model()
def normalize_text(text):
# Убираем все кроме букв и цифр, переводим в нижний регистр
return re.sub(r'[^\w\s]', '', text).lower().strip()
def format_timestamp(seconds):
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
millis = int((seconds - int(seconds)) * 1000)
return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"
def calculate_file_hash(file_path):
hash_md5 = hashlib.md5()
with open(file_path, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_md5.update(chunk)
return hash_md5.hexdigest()
def create_srt(segments, output_path):
with open(output_path, 'w', encoding='utf-8') as f:
for i, segment in enumerate(segments):
start = format_timestamp(segment['start'])
end = format_timestamp(segment['end'])
text = segment['text'].strip()
f.write(f"{i+1}\n{start} --> {end}\n{text}\n\n")
def create_txt(segments, output_path):
with open(output_path, 'w', encoding='utf-8') as f:
full_text = " ".join([seg['text'].strip() for seg in segments])
f.write(full_text)
def summarize_transcript(segments, model_name="qwen3:8b", chunk_size=4000):
"""
Генерирует сводку текста через Ollama.
segments: список сегментов транскрипта {'text': ...}
Возвращает строку сводки.
"""
import requests
import time
# Извлечение полного текста
full_text = " ".join([seg['text'].strip() for seg in segments])
if not full_text.strip():
return "Текст отсутствует."
# Простой разбивщик по символам (можно улучшить)
# Примерно 4 символа на токен, chunk_size в токенах -> символы
char_limit = chunk_size * 4
chunks = []
start = 0
while start < len(full_text):
end = start + char_limit
if end >= len(full_text):
chunks.append(full_text[start:])
break
# Ищем ближайший конец предложения
sentence_end = max(
full_text.rfind('.', start, end),
full_text.rfind('!', start, end),
full_text.rfind('?', start, end),
full_text.rfind('\n', start, end)
)
if sentence_end == -1 or sentence_end < start + char_limit // 2:
sentence_end = end
chunks.append(full_text[start:sentence_end + 1].strip())
start = sentence_end + 1
logger.info(f"Разбивка текста на {len(chunks)} чанков")
summaries = []
for i, chunk in enumerate(chunks):
logger.info(f"Обработка чанка {i+1}/{len(chunks)}")
prompt = f"Сделай краткий пересказ следующего текста, сохраняя важные детали:\n\n{chunk}"
payload = {
"model": model_name,
"prompt": prompt,
"stream": False,
"options": {"temperature": 0.3}
}
try:
response = requests.post("http://localhost:11434/api/generate", json=payload, timeout=60)
if response.status_code == 200:
result = response.json()
summary = result.get("response", "").strip()
if summary:
summaries.append(summary)
else:
summaries.append("(Пустой ответ)")
else:
logger.error(f"Ошибка Ollama: {response.status_code}")
summaries.append(f"(Ошибка: {response.status_code})")
except Exception as e:
logger.error(f"Ошибка соединения с Ollama: {e}")
summaries.append(f"(Ошибка соединения)")
# Небольшая пауза между запросами
time.sleep(0.5)
if not summaries:
return "Не удалось получить сводку."
# Если чанк один, вернем его как есть
if len(summaries) == 1:
return summaries[0]
# Иначе сделаем финальное суммаризирование объединенных сводок
combined = " ".join(summaries)
# Если объединенный текст слишком длинный, рекурсивно суммаризируем
if len(combined) > char_limit:
# Создаем искусственные сегменты для рекурсивного вызова
fake_segments = [{'text': combined}]
return summarize_transcript(fake_segments, model_name, chunk_size)
else:
# Запрос финальной сводки
prompt = f"Сделай итоговый краткий пересказ, объединив следующие части:\n\n{combined}"
payload = {
"model": model_name,
"prompt": prompt,
"stream": False,
"options": {"temperature": 0.3}
}
try:
response = requests.post("http://localhost:11434/api/generate", json=payload, timeout=60)
if response.status_code == 200:
result = response.json()
return result.get("response", "").strip()
else:
logger.error(f"Ошибка финальной сводки: {response.status_code}")
return combined[:500] + "..."
except Exception as e:
logger.error(f"Ошибка соединения при финальной сводке: {e}")
return combined[:500] + "..."
def cleanup_temp(unique_id):
target_dir = os.path.join(app.config['TEMP_FOLDER'], unique_id)
if os.path.exists(target_dir):
try:
shutil.rmtree(target_dir)
except Exception as e:
logger.error(f"Failed to cleanup temp {target_dir}: {e}")
def update_job(task_id, status, percent, **kwargs):
if task_id in jobs:
jobs[task_id]['status'] = status
jobs[task_id]['percent'] = percent
for k, v in kwargs.items():
jobs[task_id][k] = v
def get_duration(file_path):
try:
cmd = [FFPROBE_PATH, '-v', 'error', '-show_entries', 'format=duration',
'-of', 'default=noprint_wrappers=1:nokey=1', file_path]
return float(subprocess.check_output(cmd).decode().strip())
except:
return 0.0
def convert_to_format(input_path, output_path, output_ext):
"""
Конвертирует файл целиком, если слов не найдено.
Важно: ffmpeg корректно переделает видео в аудио (mp3), если требуется.
"""
logger.info(f"Converting full file {input_path} to {output_path}")
cmd = [FFMPEG_PATH, '-y', '-i', input_path]
if output_ext == 'mp3':
cmd.extend(['-vn', '-acodec', 'libmp3lame', '-q:a', '2'])
elif output_ext == 'mp4':
cmd.extend(['-c:v', 'copy', '-c:a', 'aac']) # Просто копируем потоки
else:
cmd.extend(['-vn', '-acodec', 'aac'])
cmd.append(output_path)
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# --- CORE LOGIC ---
def get_transcript_and_matches(input_path, filename, target_words):
"""
Возвращает данные транскрипции и совпадения для одного файла
в локальном времени (начинается с 0).
"""
file_hash = calculate_file_hash(input_path)
cache_path = os.path.join(app.config['CACHE_FOLDER'], f"{file_hash}.json")
segments_data = []
file_duration = 0.0
if os.path.exists(cache_path):
logger.info(f"Using cached transcript for {filename}")
with open(cache_path, 'r', encoding='utf-8') as f:
cached_data = json.load(f)
segments_data = cached_data['segments']
file_duration = cached_data.get('duration', get_duration(input_path))
else:
logger.info(f"Transcribing new file {filename}")
file_duration = get_duration(input_path)
segments_gen, info = model.transcribe(input_path, word_timestamps=True)
if info.duration:
file_duration = info.duration
for seg in segments_gen:
words_list = []
if seg.words:
for w in seg.words:
words_list.append({
'word': w.word,
'start': w.start,
'end': w.end
})
segments_data.append({
'start': seg.start,
'end': seg.end,
'text': seg.text,
'words': words_list
})
with open(cache_path, 'w', encoding='utf-8') as f:
json.dump({'duration': file_duration, 'segments': segments_data}, f, ensure_ascii=False)
matches = []
full_transcript = []
found_words_list = []
target_words_set = set(target_words)
for segment in segments_data:
full_transcript.append({'start': segment['start'], 'end': segment['end'], 'text': segment['text']})
for word in segment['words']:
w_clean = normalize_text(word['word'])
if w_clean in target_words_set:
matches.append({'start': word['start'], 'end': word['end'], 'word': word['word']})
found_words_list.append(w_clean)
word_counts = dict(Counter(found_words_list))
return segments_data, matches, full_transcript, word_counts, file_duration
def process_task(task_id, input_path, filename, target_words, mode, settings):
try:
update_job(task_id, "Вычисление хеша...", 5)
file_hash = calculate_file_hash(input_path)
cache_path = os.path.join(app.config['CACHE_FOLDER'], f"{file_hash}.json")
segments_data = []
total_duration = 0.0
if os.path.exists(cache_path):
update_job(task_id, "Загрузка из кэша...", 10)
logger.info(f"Using cached transcript for {filename}")
with open(cache_path, 'r', encoding='utf-8') as f:
cached_data = json.load(f)
segments_data = cached_data['segments']
total_duration = cached_data.get('duration', get_duration(input_path))
else:
update_job(task_id, "Транскрибация...", 10)
logger.info(f"Transcribing new file {filename}")
total_duration = get_duration(input_path)
segments_gen, info = model.transcribe(input_path, word_timestamps=True)
if info.duration: total_duration = info.duration
for seg in segments_gen:
words_list = []
if seg.words:
for w in seg.words:
words_list.append({
'word': w.word,
'start': w.start,
'end': w.end
})
segments_data.append({
'start': seg.start,
'end': seg.end,
'text': seg.text,
'words': words_list
})
with open(cache_path, 'w', encoding='utf-8') as f:
json.dump({'duration': total_duration, 'segments': segments_data}, f, ensure_ascii=False)
update_job(task_id, "Анализ текста...", 40)
matches = []
full_transcript = []
found_words_list = []
target_words_set = set(target_words)
for segment in segments_data:
full_transcript.append({'start': segment['start'], 'end': segment['end'], 'text': segment['text']})
for word in segment['words']:
w_clean = normalize_text(word['word'])
if w_clean in target_words_set:
matches.append({'start': word['start'], 'end': word['end'], 'word': word['word']})
found_words_list.append(w_clean)
word_counts = dict(Counter(found_words_list))
logger.info(f"Task {task_id}: Found {len(matches)} matches. Mode: {mode}")
base_name = f"result_{uuid.uuid4().hex[:6]}"
srt_filename = f"{base_name}.srt"
txt_filename = f"{base_name}.txt"
create_srt(segments_data, os.path.join(app.config['OUTPUT_FOLDER'], srt_filename))
create_txt(segments_data, os.path.join(app.config['OUTPUT_FOLDER'], txt_filename))
# Определение типа входного файла (видео/аудио)
is_video_input = filename.lower().endswith(('.mp4', '.mov', '.avi', '.mkv', '.webm'))
# Режим пересказа
if mode == 'summarize':
update_job(task_id, "Генерация сводки...", 60)
summary_text = summarize_transcript(segments_data)
summary_filename = f"{base_name}_summary.txt"
summary_path = os.path.join(app.config['OUTPUT_FOLDER'], summary_filename)
with open(summary_path, 'w', encoding='utf-8') as f:
f.write(summary_text)
jobs[task_id] = {
'status': 'completed',
'percent': 100,
'summary_url': f"/download/{summary_filename}",
'download_url': f"/download/{summary_filename}",
'summary_text': summary_text,
'srt_url': f"/download/{srt_filename}",
'txt_url': f"/download/{txt_filename}",
'filename': summary_filename,
'match_count': len(matches),
'is_video': False,
'matches_list': matches,
'full_transcript': full_transcript,
'word_counts': word_counts
}
gc.collect()
return
output_ext = settings.get('format', 'mp3')
# Если просят mp3, значит это аудио (даже если вход видео)
final_ext = output_ext
if is_video_input and output_ext == 'mp4':
final_ext = 'mp4'
output_filename = f"{base_name}_cut.{final_ext}"
output_path = os.path.join(app.config['OUTPUT_FOLDER'], output_filename)
padding_sec = int(settings.get('padding', 0)) / 1000.0
processed_matches = []
for m in matches:
processed_matches.append({
'start': max(0, m['start'] - padding_sec),
'end': min(total_duration, m['end'] + padding_sec)
})
# --- LOGIC BRANCHING ---
if not matches:
if mode == 'save':
jobs[task_id] = {'status': 'completed', 'percent': 100, 'error': 'Совпадений не найдено (файл пуст)'}
return
else:
# ВАЖНО: Если слов нет, но режим remove/replace - отдаем оригинал в НУЖНОМ формате
# Используем ffmpeg для конвертации, а не shutil.copy, чтобы не сломать контейнер
logger.info(f"No matches found. Converting original to {final_ext}")
update_job(task_id, "Конвертация...", 80)
convert_to_format(input_path, output_path, final_ext)
else:
# СЛОВА НАЙДЕНЫ
update_job(task_id, f"Рендеринг: {mode}...", 50)
task_temp_dir = os.path.join(app.config['TEMP_FOLDER'], task_id)
os.makedirs(task_temp_dir, exist_ok=True)
if mode == 'replace':
process_replace_chunked(input_path, output_path, processed_matches, is_video_input, settings, task_id, total_duration)
else:
# Режимы 'remove' или 'cut'
keep_segments = calculate_keep_segments(processed_matches, total_duration, mode)
logger.info(f"Task {task_id}: Keep segments count: {len(keep_segments)}")
if not keep_segments and mode in ['remove', 'cut']:
# Если вдруг удалили ВЕСЬ файл (очень много мата), создаем тишину
logger.warning("All content removed. Generating silence.")
AudioSegment.silent(duration=1000).export(output_path, format=final_ext)
else:
parallel_media_cut(input_path, output_path, keep_segments, is_video_input, task_id, final_ext)
cleanup_temp(task_id)
jobs[task_id] = {
'status': 'completed',
'percent': 100,
'download_url': f"/download/{output_filename}",
'srt_url': f"/download/{srt_filename}",
'txt_url': f"/download/{txt_filename}",
'filename': output_filename,
'match_count': len(matches),
'is_video': is_video_input,
'matches_list': matches,
'full_transcript': full_transcript,
'word_counts': word_counts
}
gc.collect()
except Exception as e:
logger.error(f"Error in task {task_id}: {e}", exc_info=True)
jobs[task_id] = {'status': 'error', 'percent': 100, 'error': str(e)}
cleanup_temp(task_id)
def process_task_multiple(task_id, input_paths, filenames, target_words, mode, settings):
try:
update_job(task_id, "Обработка списка файлов...", 5)
all_segments = []
all_matches = []
all_full_transcript = []
all_word_counts = {}
# Переменная для подсчета сдвига времени для ОБЩЕГО SRT
total_offset_accumulator = 0.0
processed_files = []
is_video_input_global = any(f.lower().endswith(('.mp4', '.mov', '.avi', '.mkv', '.webm')) for f in filenames)
# Создаем временную директорию
task_temp_dir = os.path.join(app.config['TEMP_FOLDER'], task_id)
os.makedirs(task_temp_dir, exist_ok=True)
total_files = len(input_paths)
# --- ЭТАП 1: Обработка каждого файла по отдельности ---
for idx, (input_path, filename) in enumerate(zip(input_paths, filenames)):
update_job(task_id, f"Файл {idx+1}/{total_files}: Анализ и обработка...", 10 + int(80 * idx / total_files))
# 1. Получаем чистые данные (время начинается с 0)
segments, matches, full_trans, w_counts, duration = get_transcript_and_matches(input_path, filename, target_words)
# 2. Собираем статистику для итогового отчета (добавляем Offset только сюда!)
for seg in segments:
# Копируем объект, чтобы не менять исходник
seg_copy = seg.copy()
seg_copy['start'] += total_offset_accumulator
seg_copy['end'] += total_offset_accumulator
all_segments.append(seg_copy)
for m in matches:
m_copy = m.copy()
m_copy['start'] += total_offset_accumulator
m_copy['end'] += total_offset_accumulator
all_matches.append(m_copy)
for ft in full_trans:
ft_copy = ft.copy()
ft_copy['start'] += total_offset_accumulator
ft_copy['end'] += total_offset_accumulator
all_full_transcript.append(ft_copy)
for w, c in w_counts.items():
all_word_counts[w] = all_word_counts.get(w, 0) + c
# 3. Физическая обработка файла (передаем ЧИСТЫЕ matches без офсета)
# В режиме summarize нарезку делать не нужно
if mode != 'summarize':
temp_file_path = process_single_file_to_temp(
input_path, filename, matches, duration, mode, settings, task_id, task_temp_dir
)
if temp_file_path:
processed_files.append(temp_file_path)
# Увеличиваем общий счетчик времени на длительность ОРИГИНАЛЬНОГО файла
# (Если файлы режутся, SRT может рассинхронизироваться с итогом,
# но это стандартное поведение для объединения транскриптов)
total_offset_accumulator += duration
# --- ЭТАП 2: Генерация результатов ---
base_name = f"result_{uuid.uuid4().hex[:6]}"
# 1. Если режим сводки (Summarize)
if mode == 'summarize':
update_job(task_id, "Генерация сводки...", 90)
summary_text = summarize_transcript(all_segments)
summary_filename = f"{base_name}_summary.txt"
with open(os.path.join(app.config['OUTPUT_FOLDER'], summary_filename), 'w', encoding='utf-8') as f:
f.write(summary_text)
# Также создаем SRT исходника
create_srt(all_segments, os.path.join(app.config['OUTPUT_FOLDER'], f"{base_name}.srt"))
create_txt(all_segments, os.path.join(app.config['OUTPUT_FOLDER'], f"{base_name}.txt"))
jobs[task_id] = {
'status': 'completed', 'percent': 100,
'download_url': f"/download/{summary_filename}",
'summary_text': summary_text,
'match_count': len(all_matches),
'is_video': False
}
cleanup_temp(task_id)
gc.collect()
return
# 2. Склейка файлов (Concat)
update_job(task_id, "Финальная склейка файлов...", 95)
output_ext = settings.get('format', 'mp3')
final_ext = output_ext
if is_video_input_global and output_ext == 'mp4':
final_ext = 'mp4'
output_filename = f"{base_name}_cut.{final_ext}"
output_path = os.path.join(app.config['OUTPUT_FOLDER'], output_filename)
if not processed_files:
# Если файлов нет (например, save mode и ничего не нашлось), создаем тишину
AudioSegment.silent(duration=1000).export(output_path, format=final_ext)
elif len(processed_files) == 1:
shutil.move(processed_files[0], output_path)
else:
# Concat через ffmpeg list
concat_list_path = os.path.join(task_temp_dir, "concat_list_final.txt")
with open(concat_list_path, 'w', encoding='utf-8') as f:
for pf in processed_files:
f.write(f"file '{os.path.abspath(pf)}'\n")
subprocess.run(
[FFMPEG_PATH, '-y', '-f', 'concat', '-safe', '0', '-i', concat_list_path, '-c', 'copy', output_path],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
# Создание SRT/TXT
srt_filename = f"{base_name}.srt"
txt_filename = f"{base_name}.txt"
create_srt(all_segments, os.path.join(app.config['OUTPUT_FOLDER'], srt_filename))
create_txt(all_segments, os.path.join(app.config['OUTPUT_FOLDER'], txt_filename))
cleanup_temp(task_id)
jobs[task_id] = {
'status': 'completed',
'percent': 100,
'download_url': f"/download/{output_filename}",
'srt_url': f"/download/{srt_filename}",
'txt_url': f"/download/{txt_filename}",
'filename': output_filename,
'match_count': len(all_matches),
'is_video': is_video_input_global,
'matches_list': all_matches,
'full_transcript': all_full_transcript,
'word_counts': all_word_counts
}
gc.collect()
except Exception as e:
logger.error(f"Error in multi-file task {task_id}: {e}", exc_info=True)
jobs[task_id] = {'status': 'error', 'percent': 100, 'error': str(e)}
cleanup_temp(task_id)
# --- MEDIA PROCESSING ---
def calculate_keep_segments(matches, total_duration, mode):
# Сортируем и объединяем перекрывающиеся интервалы удаления
matches.sort(key=lambda x: x['start'])
merged = []
if matches:
curr = matches[0]
for next_match in matches[1:]:
if next_match['start'] < curr['end']:
curr['end'] = max(curr['end'], next_match['end'])
else:
merged.append(curr)
curr = next_match
merged.append(curr)
matches = merged
segments = []
if mode == 'save':
segments = [(m['start'], m['end']) for m in matches]
elif mode == 'remove' or mode == 'cut': # ИСПРАВЛЕНИЕ: Добавлена поддержка 'cut'
current_time = 0.0
for m in matches:
if m['start'] > current_time:
segments.append((current_time, m['start']))
current_time = max(current_time, m['end'])
# Добавляем хвост, если он есть
if current_time < total_duration:
segments.append((current_time, total_duration))
# Фильтруем мусор < 0.1 сек
return [s for s in segments if (s[1] - s[0]) > 0.1]
def process_replace_chunked(input_path, output_path, matches, is_video, settings, task_id, total_duration):
temp_audio_out = os.path.join(app.config['TEMP_FOLDER'], task_id, "replaced_audio.mp3")
freq = int(settings.get('beep_freq', 1000))
gain = int(settings.get('beep_gain', -10))
matches.sort(key=lambda x: x['start'])
chunk_files = []
current_pos = 0.0
chunk_idx = 0
matches_ms = [{'start': int(m['start']*1000), 'end': int(m['end']*1000)} for m in matches]
CHUNK_SIZE_SEC = 600
while current_pos < total_duration:
chunk_end = min(current_pos + CHUNK_SIZE_SEC, total_duration)
percent = 50 + int((current_pos / total_duration) * 40)
update_job(task_id, f"Обработка аудио: {int(current_pos//60)} мин...", percent)
t_start = current_pos
t_dur = chunk_end - current_pos
# Загружаем кусок
audio_chunk = AudioSegment.from_file(input_path, start_second=t_start, duration=t_dur)
chunk_start_ms = int(t_start * 1000)
chunk_end_ms = int(chunk_end * 1000)
local_matches = [m for m in matches_ms if m['end'] > chunk_start_ms and m['start'] < chunk_end_ms]
if local_matches:
processed_chunk = AudioSegment.empty()
last_idx_in_chunk = 0
for m in local_matches:
m_start_rel = max(0, m['start'] - chunk_start_ms)
m_end_rel = min(len(audio_chunk), m['end'] - chunk_start_ms)
if m_start_rel > last_idx_in_chunk:
processed_chunk += audio_chunk[last_idx_in_chunk:m_start_rel]
beep_dur = m_end_rel - m_start_rel
if beep_dur > 0:
beep = Sine(freq).to_audio_segment(duration=beep_dur).apply_gain(gain)
processed_chunk += beep
last_idx_in_chunk = m_end_rel
if last_idx_in_chunk < len(audio_chunk):
processed_chunk += audio_chunk[last_idx_in_chunk:]
audio_chunk = processed_chunk
part_filename = os.path.join(app.config['TEMP_FOLDER'], task_id, f"part_{chunk_idx:04d}.mp3")
audio_chunk.export(part_filename, format="mp3")
chunk_files.append(part_filename)
del audio_chunk
gc.collect()
current_pos = chunk_end
chunk_idx += 1
concat_list_path = os.path.join(app.config['TEMP_FOLDER'], task_id, "concat_list.txt")
with open(concat_list_path, 'w') as f:
for cf in chunk_files:
f.write(f"file '{os.path.abspath(cf)}'\n")
subprocess.run([FFMPEG_PATH, '-y', '-f', 'concat', '-safe', '0', '-i', concat_list_path, '-c', 'copy', temp_audio_out],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if is_video and output_path.endswith('.mp4'):
update_job(task_id, "Сборка видео...", 95)
# Копируем видео, заменяем аудио
cmd = [FFMPEG_PATH, '-y', '-i', input_path, '-i', temp_audio_out, '-c:v', 'copy', '-c:a', 'aac', '-map', '0:v:0', '-map', '1:a:0', '-shortest', output_path]
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
else:
# Если выход нужен mp3 (даже если вход видео), просто отдаем аудио
shutil.move(temp_audio_out, output_path)
def parallel_media_cut(input_path, output_path, segments, is_video_input, task_id, ext):
if not segments:
return
task_dir = os.path.join(app.config['TEMP_FOLDER'], task_id)
chunk_files = [None] * len(segments)
# Определяем нужные кодеки
# Если на выходе MP4: видео перекодируем (для точности стыков), аудио AAC
# Если на выходе MP3: видео отбрасываем, аудио MP3
def process_one_segment(index, start, end):
duration = end - start
chunk_name = f"chunk_{index:04d}.{ext}"
chunk_path = os.path.join(task_dir, chunk_name)
# Fast Seek (-ss перед -i)
cmd = [FFMPEG_PATH, '-y', '-ss', f"{start:.3f}", '-t', f"{duration:.3f}", '-i', input_path]
if ext == 'mp4':
# Перекодирование x264 ultrafast для скорости
cmd.extend(['-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '23', '-c:a', 'aac'])
else:
# Только аудио
cmd.extend(['-vn', '-c:a', 'libmp3lame', '-q:a', '2'])
cmd.append(chunk_path)
try:
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return (index, chunk_path)
except Exception as e:
logger.error(f"Error cutting segment {index}: {e}")
return (index, None)
total_segs = len(segments)
completed = 0
with ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor:
futures = []
for i, (s, e) in enumerate(segments):
futures.append(executor.submit(process_one_segment, i, s, e))
for future in futures:
idx, path = future.result()
completed += 1
if completed % 5 == 0 or completed == total_segs:
percent = 50 + int((completed / total_segs) * 45)
update_job(task_id, f"Нарезка: {completed}/{total_segs}", percent)
chunk_files[idx] = path
valid_chunks = [f for f in chunk_files if f is not None]
if not valid_chunks:
raise Exception("Failed to create chunks")
update_job(task_id, "Финальная склейка...", 98)
concat_list_path = os.path.join(task_dir, "final_concat_list.txt")
with open(concat_list_path, 'w') as f:
for cf in valid_chunks:
f.write(f"file '{os.path.abspath(cf)}'\n")
subprocess.run([FFMPEG_PATH, '-y', '-f', 'concat', '-safe', '0', '-i', concat_list_path, '-c', 'copy', output_path],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
# --- SINGLE FILE PROCESSING ---
def process_single_file_to_temp(input_path, filename, matches, duration, mode, settings, task_id, temp_dir):
"""
Обрабатывает один файл на основе переданных matches.
Возвращает путь к временному файлу или None.
"""
is_video_input = filename.lower().endswith(('.mp4', '.mov', '.avi', '.mkv', '.webm'))
output_ext = settings.get('format', 'mp3')
final_ext = output_ext
if is_video_input and output_ext == 'mp4':
final_ext = 'mp4'
padding_sec = int(settings.get('padding', 0)) / 1000.0
# Добавляем паддинг к совпадениям
processed_matches = []
for m in matches:
processed_matches.append({
'start': max(0, m['start'] - padding_sec),
'end': min(duration, m['end'] + padding_sec)
})
# Логика режимов
# 1. Если совпадений нет
if not processed_matches:
if mode == 'save':
# Режим "сохранить слова", но слов нет -> файл пропускаем
return None
else:
# Режимы remove/replace/cut, но слов нет -> оставляем файл как есть (просто конвертируем)
temp_output = os.path.join(temp_dir, f"full_{uuid.uuid4().hex[:6]}.{final_ext}")
convert_to_format(input_path, temp_output, final_ext)
return temp_output
# 2. Режим replace (запикивание)
if mode == 'replace':
temp_output = os.path.join(temp_dir, f"replaced_{uuid.uuid4().hex[:6]}.{final_ext}")
process_replace_chunked(input_path, temp_output, processed_matches, is_video_input, settings, task_id, duration)
return temp_output
# 3. Режимы remove / save / cut
keep_segments = calculate_keep_segments(processed_matches, duration, mode)
if not keep_segments:
# Если удалено вообще всё -> создаем тишину 1 сек, чтобы не ломать склейку
temp_output = os.path.join(temp_dir, f"silence_{uuid.uuid4().hex[:6]}.{final_ext}")
AudioSegment.silent(duration=1000).export(temp_output, format=final_ext)
return temp_output
temp_output = os.path.join(temp_dir, f"cut_{uuid.uuid4().hex[:6]}.{final_ext}")
parallel_media_cut(input_path, temp_output, keep_segments, is_video_input, task_id, final_ext)
return temp_output
# --- ROUTES ---
@app.route('/')
def index():
return render_template('index.html')
@app.route('/download/<filename>')
def download_file(filename):
response = send_from_directory(app.config['OUTPUT_FOLDER'], filename, as_attachment=True)
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
response.headers["Pragma"] = "no-cache"
response.headers["Expires"] = "0"
return response
@app.route('/<path:filename>')
def serve_template_files(filename):
if filename.endswith(('.css', '.js')):
return send_from_directory('templates', filename)
return "Not Found", 404
@app.route('/status/<task_id>')
def job_status(task_id):
return jsonify(jobs.get(task_id, {'status': 'unknown'}))
@app.route('/process', methods=['POST'])
def handle_process():
files = request.files.getlist('file')
if not files or files[0].filename == '': return jsonify({'error': 'No file'}), 400
settings = {
'padding': int(request.form.get('padding', 0)),
'format': request.form.get('format', 'mp3'),
'beep_freq': int(request.form.get('beep_freq', 1000)),
'beep_gain': int(request.form.get('beep_gain', -10))
}
task_id = str(uuid.uuid4())
# Обработка слов
raw_words = request.form.get('words', '')
words = raw_words.split(',')
words = [normalize_text(w) for w in words if w.strip()]
# Обработка mode (дефолт remove)
mode = request.form.get('mode', 'remove')
# Сохраняем файлы
input_paths = []
filenames = []
for i, file in enumerate(files):
filename = secure_filename(file.filename)
if not filename:
continue
input_path = os.path.join(app.config['UPLOAD_FOLDER'], f"{task_id}_{i}_{filename}")
file.save(input_path)
input_paths.append(input_path)
filenames.append(filename)
# Если файлов нет (все пустые)
if not input_paths:
return jsonify({'error': 'No valid files'}), 400
# Запускаем задачу обработки
thread = threading.Thread(target=process_task_multiple, args=(task_id, input_paths, filenames, words, mode, settings))
thread.daemon = True
thread.start()
jobs[task_id] = {'status': 'queued', 'percent': 0}
return jsonify({'success': True, 'task_id': task_id})
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True, port=5000, threaded=True)