-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_app.py
More file actions
1827 lines (1535 loc) · 63.6 KB
/
main_app.py
File metadata and controls
1827 lines (1535 loc) · 63.6 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
from flask import render_template, request, jsonify, send_from_directory, url_for, send_file, after_this_request, make_response
import os
import json
import subprocess
import base64
import binascii
import logging
import threading
import uuid
import copy
import re
import tempfile
import glob
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple
import shutil
import tarfile
import zipfile
import stat
from werkzeug.utils import secure_filename
from pydub import AudioSegment
import wave
import math
from collections import OrderedDict
from app_factory import create_flask_app, register_app_routes
from services.script_catalog import (
get_script_definition as get_script_definition_service,
get_scripts_catalog as get_scripts_catalog_service,
infer_autofill_kind as infer_autofill_kind_service,
prepare_script_entry as prepare_script_entry_service,
rebuild_scripts_config_file as rebuild_scripts_config_file_service,
)
from services.script_meta import validate_script_meta
from services.project_files import (
build_audio_metadata as build_audio_metadata_service,
build_failed_generation_json_metadata as build_failed_generation_json_metadata_service,
collect_directory_entries as collect_directory_entries_service,
compute_failed_generation_highlights as compute_failed_generation_highlights_service,
get_audio_metadata_directories as get_audio_metadata_directories_service,
get_failed_generation_directories as get_failed_generation_directories_service,
get_tts_root_directory as get_tts_root_directory_service,
sanitize_storage_relative_path as sanitize_storage_relative_path_service,
should_enable_failed_move as should_enable_failed_move_service,
)
from services.workflow_jobs import (
build_log_links as build_log_links_service,
cleanup_workflow_resources as cleanup_workflow_resources_service,
get_project_jobs as get_project_jobs_service,
get_workflow_event as get_workflow_event_service,
get_workflow_job as get_workflow_job_service,
get_workflow_thread as get_workflow_thread_service,
read_log_tail as read_log_tail_service,
register_workflow_job as register_workflow_job_service,
request_workflow_cancel as request_workflow_cancel_service,
run_workflow_job as run_workflow_job_service,
set_workflow_thread as set_workflow_thread_service,
update_workflow_job as update_workflow_job_service,
)
from services.workflow_state import (
ensure_workflows_dir as ensure_workflows_dir_service,
get_project_root_path as get_project_root_path_service,
get_project_workflow_state_path as get_project_workflow_state_path_service,
list_workflow_templates as list_workflow_templates_service,
load_project_workflow_state as load_project_workflow_state_service,
load_workflow_template as load_workflow_template_service,
save_project_workflow_state as save_project_workflow_state_service,
save_workflow_template_file as save_workflow_template_file_service,
sanitize_workflow_id as sanitize_workflow_id_service,
load_workflow_file as load_workflow_file_service,
)
from services.workflow_execution import (
build_command_for_step as build_command_for_step_service,
build_masked_command_and_params as build_masked_command_and_params_service,
coerce_bool as coerce_bool_service,
mask_workflow_secret_params as mask_workflow_secret_params_service,
mask_applied_params_for_ui as mask_applied_params_for_ui_service,
mask_command_for_ui as mask_command_for_ui_service,
normalize_workflow_steps as normalize_workflow_steps_service,
run_script_command as run_script_command_service,
unmask_secret_param_value as unmask_secret_param_value_service,
)
app = create_flask_app(__name__)
logging.basicConfig(level=logging.INFO)
config_lock = threading.Lock()
workflow_lock = threading.Lock()
theme_config_lock = threading.Lock()
workflow_jobs = {}
workflow_threads = {}
workflow_events = {}
review_audio_encoding_jobs: Dict[str, Dict[str, Any]] = {}
review_audio_encoding_lock = threading.Lock()
CONFIG_FILE_PATH = Path(app.root_path) / 'config.json'
CONFIG_MTIME: Optional[float] = None
KEYHOLDER_PATH = os.path.join(app.root_path, 'keyholder.json')
CONDA_PYTHON_CACHE = {}
AUDIO_EXTENSIONS = {'.wav', '.mp3', '.ogg', '.flac', '.m4a', '.aac'}
VIDEO_EXTENSIONS = {
'.mp4', '.mkv', '.avi', '.mov', '.webm', '.wmv', '.flv', '.mts', '.m2ts', '.mpg', '.mpeg'
}
DEFAULT_UI_LANGUAGE = 'hun'
UI_LANGUAGE_COOKIE = 'ui_language'
language_cache_lock = threading.Lock()
language_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
def derive_project_prefix(name: str) -> str:
tokens = [part for part in re.split(r'[._-]+', name) if part]
if not tokens:
return name or 'Egyéb'
prefix = tokens[0]
if len(tokens) >= 2 and len(prefix) <= 3:
prefix = f"{prefix}_{tokens[1]}"
return prefix
def build_project_entries(projects: List[str], group_threshold: int = 3) -> List[Dict[str, Any]]:
grouped: "OrderedDict[str, List[str]]" = OrderedDict()
for project in projects:
key = derive_project_prefix(project)
if key not in grouped:
grouped[key] = []
grouped[key].append(project)
entries: List[Dict[str, Any]] = []
for key, names in grouped.items():
if len(names) >= group_threshold:
entries.append({
'type': 'group',
'key': key,
'projects': names,
'count': len(names)
})
else:
for name in names:
entries.append({
'type': 'project',
'name': name
})
return entries
def sanitize_segment_strings(segments: Any) -> Any:
"""
Remove stray escape sequences that break JSON loading on the front-end.
"""
if not isinstance(segments, list):
return segments
for segment in segments:
if not isinstance(segment, dict):
continue
for key in ('text', 'translated_text'):
value = segment.get(key)
if isinstance(value, str):
segment[key] = value.replace('\\"', '"')
return segments
def format_time_for_filename(time_in_seconds: Any) -> str:
"""
Convert a time value (seconds) into the HH-MM-SS-mmm pattern used for split filenames.
"""
try:
time_float = float(time_in_seconds)
except (TypeError, ValueError):
return "00-00-00-000"
total_milliseconds = int(round(time_float * 1000))
if total_milliseconds < 0:
total_milliseconds = 0
hours = total_milliseconds // 3_600_000
minutes = (total_milliseconds % 3_600_000) // 60_000
seconds = (total_milliseconds % 60_000) // 1_000
milliseconds = total_milliseconds % 1_000
return f"{hours:02d}-{minutes:02d}-{seconds:02d}-{milliseconds:03d}"
def annotate_segments_with_translated_splits(project_dir: str, segments: List[Dict[str, Any]]) -> None:
"""
Mark each segment with a flag indicating whether a translated split WAV exists.
"""
try:
project_subdirs = config.get('PROJECT_SUBDIRS') if isinstance(config, dict) else {}
except NameError:
project_subdirs = {}
translated_splits_subdir = (project_subdirs or {}).get('translated_splits')
base_dir = Path(project_dir) / translated_splits_subdir if translated_splits_subdir else None
base_dir_exists = base_dir.exists() if base_dir else False
for segment in segments:
has_split = False
if isinstance(segment, dict):
start = segment.get('start')
end = segment.get('end')
if (
base_dir_exists
and isinstance(start, (int, float))
and isinstance(end, (int, float))
):
filename = f"{format_time_for_filename(start)}_{format_time_for_filename(end)}.wav"
has_split = (base_dir / filename).is_file()
segment['has_translated_split'] = has_split
def prepare_segments_for_response(project_dir: str, segments: Any) -> List[Dict[str, Any]]:
"""
Return a sanitized, annotated copy of the segment list for front-end consumption.
"""
if not isinstance(segments, list):
return []
prepared_segments: List[Dict[str, Any]] = copy.deepcopy(segments)
sanitize_segment_strings(prepared_segments)
annotate_segments_with_translated_splits(project_dir, prepared_segments)
return prepared_segments
def collect_translated_split_progress(project_name: str, config_snapshot: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
current_config = config_snapshot or get_config_copy()
directories = current_config.get('DIRECTORIES') or {}
project_subdirs = current_config.get('PROJECT_SUBDIRS') or {}
workdir_rel = directories.get('workdir')
translated_rel = project_subdirs.get('translated')
translated_splits_rel = project_subdirs.get('translated_splits')
if not workdir_rel or not translated_rel or not translated_splits_rel:
raise WorkflowValidationError(
"Hiányzó config kulcs: DIRECTORIES.workdir, PROJECT_SUBDIRS.translated vagy PROJECT_SUBDIRS.translated_splits."
)
safe_project = secure_filename(project_name)
project_dir = Path(workdir_rel) / safe_project
if not project_dir.is_dir():
raise FileNotFoundError(f"A projekt könyvtár nem található: {project_dir}")
translated_dir = project_dir / translated_rel
if not translated_dir.is_dir():
raise FileNotFoundError(f"A translated könyvtár nem található: {translated_dir}")
translated_json_files = sorted(
path for path in translated_dir.iterdir()
if path.is_file() and path.suffix.lower() == '.json'
)
if not translated_json_files:
raise FileNotFoundError(f"Nem található JSON fájl a translated könyvtárban: {translated_dir}")
selected_json_path = translated_json_files[0]
try:
with selected_json_path.open('r', encoding='utf-8') as file:
payload = json.load(file)
except OSError as exc:
raise FileNotFoundError(f"Nem sikerült beolvasni a translated JSON fájlt: {selected_json_path}") from exc
except json.JSONDecodeError as exc:
raise WorkflowValidationError(f"Hibás JSON formátum: {selected_json_path.name}") from exc
segments = payload.get('segments')
if not isinstance(segments, list):
raise WorkflowValidationError(
f'A kiválasztott translated JSON fájl nem tartalmaz érvényes "segments" listát: {selected_json_path.name}'
)
expected_segment_stems: List[str] = []
translated_ready_segments = 0
for segment in segments:
if not isinstance(segment, dict):
continue
start = segment.get('start')
end = segment.get('end')
original_text = str(segment.get('text') or '').strip()
translated_text = str(segment.get('translated_text') or '').strip()
if not isinstance(start, (int, float)) or not isinstance(end, (int, float)):
continue
if not original_text:
continue
expected_segment_stems.append(f"{format_time_for_filename(start)}_{format_time_for_filename(end)}")
if translated_text:
translated_ready_segments += 1
translated_splits_dir = project_dir / translated_splits_rel
actual_audio_stems: Set[str] = set()
if translated_splits_dir.is_dir():
for path in translated_splits_dir.iterdir():
if path.is_file() and path.suffix.lower() in AUDIO_EXTENSIONS:
actual_audio_stems.add(path.stem)
completed_segments = sum(1 for stem in expected_segment_stems if stem in actual_audio_stems)
expected_segments = len(expected_segment_stems)
return {
'project_name': safe_project,
'json_file_name': selected_json_path.name,
'translated_dir': translated_rel,
'translated_splits_dir': translated_splits_rel,
'total_segments': len(segments),
'expected_segments': expected_segments,
'translated_ready_segments': translated_ready_segments,
'completed_segments': completed_segments,
'missing_segments': max(expected_segments - completed_segments, 0),
'actual_audio_files': len(actual_audio_stems),
'translated_splits_exists': translated_splits_dir.is_dir()
}
def resolve_project_paths(project_name: str) -> Path:
safe_project = secure_filename(project_name)
return Path('workdir') / safe_project
def resolve_source_audio_path(project_name: str, audio_file_name: str) -> Optional[Path]:
if not project_name or not audio_file_name:
return None
project_root = resolve_project_paths(project_name)
speech_subdir = (config.get('PROJECT_SUBDIRS') or {}).get('separated_audio_speech')
if not speech_subdir:
return None
candidate = project_root / speech_subdir / os.path.basename(audio_file_name)
if candidate.is_file():
return candidate
return None
def get_review_encoded_audio_path(project_name: str, audio_file_name: str) -> Optional[Path]:
temp_subdir = (config.get('PROJECT_SUBDIRS') or {}).get('temp')
if not temp_subdir or not audio_file_name:
return None
project_root = resolve_project_paths(project_name)
temp_dir = project_root / temp_subdir
try:
temp_dir.mkdir(parents=True, exist_ok=True)
except OSError as exc:
logging.error("Failed to create temp dir %s: %s", temp_dir, exc)
return None
source_stem = Path(audio_file_name).stem or Path(audio_file_name).name
encoded_name = f"{source_stem}_review_preview.mp3"
return temp_dir / encoded_name
def probe_audio_duration(audio_path: Path) -> Optional[float]:
try:
result = subprocess.run(
[
'ffprobe',
'-v',
'error',
'-show_entries',
'format=duration',
'-of',
'default=noprint_wrappers=1:nokey=1',
str(audio_path)
],
capture_output=True,
text=True,
check=True
)
return float(result.stdout.strip())
except Exception as exc:
logging.warning("Failed to probe duration for %s: %s", audio_path, exc)
return None
def _run_review_audio_encoding_job(project_name: str, source_path: Path, target_path: Path, job: Dict[str, Any]) -> None:
job['status'] = 'encoding'
job['progress'] = 0.0
duration_seconds = probe_audio_duration(source_path)
command = [
'ffmpeg',
'-y',
'-i',
str(source_path),
'-ac',
'1',
'-ar',
'44100',
'-b:a',
'128k',
'-progress',
'pipe:1',
'-nostats',
str(target_path)
]
proc = None
try:
proc = subprocess.Popen(
command,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1
)
if proc.stdout:
for line in proc.stdout:
line = line.strip()
if duration_seconds and line.startswith('out_time_ms='):
try:
current_ms = float(line.split('=')[1])
progress = (current_ms / (duration_seconds * 1000.0)) * 100.0
job['progress'] = max(0.0, min(99.0, progress))
except (ValueError, ZeroDivisionError):
continue
proc.wait()
if proc.returncode == 0 and target_path.exists():
job['progress'] = 100.0
job['status'] = 'completed'
else:
job['status'] = 'failed'
job['error'] = f"ffmpeg exited with code {proc.returncode}"
if target_path.exists():
try:
target_path.unlink()
except OSError:
pass
except Exception as exc:
job['status'] = 'failed'
job['error'] = str(exc)
if target_path.exists():
try:
target_path.unlink()
except OSError:
pass
finally:
if proc and proc.stdout:
proc.stdout.close()
with review_audio_encoding_lock:
review_audio_encoding_jobs.pop(project_name, None)
def find_matching_audio_file(base_name: str, directory: str) -> Optional[str]:
"""
Find the first audio file in directory whose stem matches base_name.
Preference order follows PREFERRED_AUDIO_EXTENSIONS.
"""
for extension in PREFERRED_AUDIO_EXTENSIONS:
candidate = base_name + extension
candidate_path = Path(directory) / candidate
if candidate_path.is_file():
return candidate
return None
def delete_translated_split_file(project_dir: str, start: Any, end: Any) -> bool:
"""
Delete the translated split WAV file for the provided time window, if it exists.
"""
try:
project_subdirs = config.get('PROJECT_SUBDIRS') if isinstance(config, dict) else {}
except NameError:
project_subdirs = {}
translated_splits_subdir = (project_subdirs or {}).get('translated_splits')
if not translated_splits_subdir:
return False
try:
start_float = float(start)
end_float = float(end)
except (TypeError, ValueError):
return False
base_dir = Path(project_dir) / translated_splits_subdir
if not base_dir.exists():
return False
filename = f"{format_time_for_filename(start_float)}_{format_time_for_filename(end_float)}.wav"
file_path = (base_dir / filename).resolve()
project_root = Path(project_dir).resolve()
if not is_subpath(str(file_path), str(project_root)):
logging.warning("Skipping translated split deletion outside project scope: %s", file_path)
return False
try:
if file_path.exists() and file_path.is_file():
file_path.unlink()
logging.info("Deleted translated split file: %s", file_path)
return True
except OSError as exc:
logging.warning("Failed to delete translated split file %s: %s", file_path, exc)
return False
AUDIO_MIME_MAP = {
'.wav': 'audio/wav',
'.mp3': 'audio/mpeg',
'.ogg': 'audio/ogg',
'.flac': 'audio/flac',
'.m4a': 'audio/mp4',
'.aac': 'audio/aac'
}
VIDEO_MIME_MAP = {
'.mp4': 'video/mp4',
'.mkv': 'video/x-matroska',
'.avi': 'video/x-msvideo',
'.mov': 'video/quicktime',
'.webm': 'video/webm',
'.wmv': 'video/x-ms-wmv',
'.flv': 'video/x-flv',
'.mts': 'video/mp2t',
'.m2ts': 'video/mp2t',
'.mpg': 'video/mpeg',
'.mpeg': 'video/mpeg'
}
PREFERRED_AUDIO_EXTENSIONS = ['.wav', '.mp3', '.ogg', '.flac']
SCRIPTS_DIR = Path(app.root_path) / 'scripts'
SCRIPTS_CONFIG_PATH = SCRIPTS_DIR / 'scripts.json'
SCRIPTS_CACHE: Dict[str, Any] = {'mtime': None, 'data': []}
SCRIPTS_CACHE_LOCK = threading.Lock()
CONDA_INFO_CACHE: Optional[dict] = None
CONDA_INFO_LOCK = threading.Lock()
WORKFLOWS_DIR = Path(app.root_path) / 'workflows'
WORKFLOW_STATE_FILENAME = 'workflow_state.json'
THEME_CONFIG_PATH = Path(app.root_path) / 'config' / 'theme_colors.json'
THEME_COLOR_KEYS = [
'primary-color',
'secondary-color',
'success-color',
'background-color',
'text-color',
'card-bg',
'border-color',
'waveform-bg',
'timeline-segment-bg',
]
DEFAULT_THEME_COLORS = {
'light': {
'primary-color': '#0d6efd',
'secondary-color': '#6c757d',
'success-color': '#198754',
'background-color': '#ffffff',
'text-color': '#212529',
'card-bg': '#f8f9fa',
'border-color': '#dee2e6',
'waveform-bg': '#f0f0f0',
'timeline-segment-bg': 'rgba(230, 230, 250, 0.8)',
},
'dark': {
'primary-color': '#0dcaf0',
'secondary-color': '#6c757d',
'success-color': '#198754',
'background-color': '#212529',
'text-color': '#f8f9fa',
'card-bg': '#2d3339',
'border-color': '#495057',
'waveform-bg': '#343a40',
'timeline-segment-bg': 'rgba(100, 100, 150, 0.8)',
},
}
SCRIPT_KEY_REQUIREMENTS = {
'translate_chatgpt_srt_easy_codex.py': {'chatgpt'},
'translate.py': {'deepl'},
'split_segments_by_speaker_codex.py': {'huggingface'},
'whisx.py': {'huggingface'},
}
SCRIPT_PARAM_KEYHOLDER = {
'translate_chatgpt_srt_easy_codex.py': {'auth_key': ('chatgpt_api_key', 'api_key')},
'translate.py': {'auth_key': ('deepL_api_key', 'deepl_api_key')},
'split_segments_by_speaker_codex.py': {'hf_token': ('hf_token',)},
'whisx.py': {'hf_token': ('hf_token',)},
}
PROJECT_AUTOFILL_OVERRIDES = {
'project_name': 'project_name',
'project': 'project_name',
'project_dir_name': 'project_name',
'project_dir': 'project_path',
'project_path': 'project_path',
}
SECRET_PARAM_NAMES = {'auth_key', 'api_key', 'hf_token'}
NEGATIVE_FLAG_NAME_PREFIXES: Tuple[str, ...] = ('no_', 'disable_', 'skip_', 'without_')
ENCODED_SECRET_PREFIX = 'base64:'
SECRET_VALUE_PLACEHOLDER = '***'
ALLOWED_WORKFLOW_WIDGETS = {'reviewContinue', 'cycleWidget', 'translatedSplitLoopWidget'}
class WorkflowValidationError(Exception):
"""Egy workflow lépés konfigurációja érvénytelen."""
def _normalize_theme_colors(data: Optional[Dict[str, Dict[str, Any]]]) -> Dict[str, Dict[str, str]]:
normalized: Dict[str, Dict[str, str]] = {}
for mode, defaults in DEFAULT_THEME_COLORS.items():
normalized[mode] = {}
mode_values = data.get(mode) if isinstance(data, dict) else {}
mode_values = mode_values if isinstance(mode_values, dict) else {}
for key, default_value in defaults.items():
value = mode_values.get(key)
if isinstance(value, str):
value = value.strip() or default_value
else:
value = default_value
normalized[mode][key] = value
return normalized
def load_theme_colors() -> Dict[str, Dict[str, str]]:
with theme_config_lock:
if THEME_CONFIG_PATH.exists():
try:
with open(THEME_CONFIG_PATH, 'r', encoding='utf-8') as file:
raw_data = json.load(file)
except (OSError, json.JSONDecodeError) as exc:
logging.warning("Nem sikerült beolvasni a témaszíneket: %s", exc)
raw_data = None
else:
raw_data = None
return _normalize_theme_colors(raw_data)
def save_theme_colors(data: Dict[str, Dict[str, Any]]) -> Dict[str, Dict[str, str]]:
normalized = _normalize_theme_colors(data)
with theme_config_lock:
try:
THEME_CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
with open(THEME_CONFIG_PATH, 'w', encoding='utf-8') as file:
json.dump(normalized, file, ensure_ascii=False, indent=2)
except OSError as exc:
logging.error("Nem sikerült elmenteni a témaszíneket: %s", exc)
raise
return normalized
@app.context_processor
def inject_theme_colors():
try:
colors = load_theme_colors()
except Exception as exc:
logging.error("Nem sikerült betölteni a témaszíneket: %s", exc)
colors = DEFAULT_THEME_COLORS
return {
'theme_colors': colors,
'default_theme_colors': DEFAULT_THEME_COLORS,
}
def is_secret_param(name: str) -> bool:
return name in SECRET_PARAM_NAMES
def mask_workflow_secret_params(steps: Optional[List[Dict[str, Any]]]) -> List[Dict[str, Any]]:
return mask_workflow_secret_params_service(
steps,
secret_param_names=SECRET_PARAM_NAMES,
encoded_secret_prefix=ENCODED_SECRET_PREFIX,
encode_keyholder_value=encode_keyholder_value,
)
def unmask_secret_param_value(value: Any) -> Any:
return unmask_secret_param_value_service(
value,
encoded_secret_prefix=ENCODED_SECRET_PREFIX,
decode_keyholder_value=decode_keyholder_value,
)
def mask_applied_params_for_ui(applied_params: Optional[List[Dict[str, Any]]]) -> List[Dict[str, Any]]:
return mask_applied_params_for_ui_service(
applied_params,
secret_param_names=SECRET_PARAM_NAMES,
secret_value_placeholder=SECRET_VALUE_PLACEHOLDER,
)
def mask_command_for_ui(command: Optional[List[str]], applied_params: Optional[List[Dict[str, Any]]], script_meta: Dict[str, Any]) -> List[str]:
return mask_command_for_ui_service(
command,
applied_params,
script_meta,
secret_param_names=SECRET_PARAM_NAMES,
secret_value_placeholder=SECRET_VALUE_PLACEHOLDER,
)
def build_masked_command_and_params(
command: Optional[List[str]],
applied_params: Optional[List[Dict[str, Any]]],
script_meta: Dict[str, Any]
) -> Tuple[List[str], List[Dict[str, Any]]]:
return build_masked_command_and_params_service(
command,
applied_params,
script_meta,
secret_param_names=SECRET_PARAM_NAMES,
secret_value_placeholder=SECRET_VALUE_PLACEHOLDER,
)
def resolve_workspace_path(path_value):
if path_value is None:
return None
if os.path.isabs(path_value):
return os.path.abspath(path_value)
return os.path.abspath(os.path.join(app.root_path, path_value))
def is_subpath(child_path, parent_path):
try:
return os.path.commonpath([child_path, parent_path]) == os.path.commonpath([parent_path])
except ValueError:
return False
def sanitize_storage_relative_path(path_value: str, *, allow_empty: bool = False) -> str:
return sanitize_storage_relative_path_service(path_value, secure_filename, allow_empty=allow_empty)
def get_tts_root_directory(config_snapshot: Dict[str, Any]) -> Optional[str]:
return get_tts_root_directory_service(config_snapshot, resolve_workspace_path)
def safe_extract_tar(archive: tarfile.TarFile, destination: str) -> None:
for member in archive.getmembers():
member_name = member.name or ''
if not member_name:
continue
member_path = os.path.abspath(os.path.join(destination, member_name))
if not is_subpath(member_path, destination):
raise ValueError('Az archívum érvénytelen elérési utakat tartalmaz.')
if member.issym() or member.islnk():
raise ValueError('Az archívum szimbolikus linkeket tartalmaz, ami nem támogatott.')
archive.extractall(path=destination)
def safe_extract_zip(archive: zipfile.ZipFile, destination: str) -> None:
for info in archive.infolist():
member_name = info.filename or ''
if not member_name:
continue
if info.create_system == 3:
permissions = info.external_attr >> 16
if stat.S_ISLNK(permissions):
raise ValueError('Az archívum szimbolikus linkeket tartalmaz, ami nem támogatott.')
member_path = os.path.abspath(os.path.join(destination, member_name))
if not is_subpath(member_path, destination):
raise ValueError('Az archívum érvénytelen elérési utakat tartalmaz.')
if info.is_dir():
os.makedirs(member_path, exist_ok=True)
continue
parent_dir = os.path.dirname(member_path)
if parent_dir:
os.makedirs(parent_dir, exist_ok=True)
with archive.open(info, 'r') as source, open(member_path, 'wb') as target:
shutil.copyfileobj(source, target)
def collect_directory_entries(
root_path: str,
target_path: str,
metadata_directories: Optional[Set[str]] = None,
highlight_map: Optional[Dict[str, str]] = None,
failed_generation_directories: Optional[Set[str]] = None
) -> List[Dict[str, Any]]:
return collect_directory_entries_service(
root_path,
target_path,
metadata_directories=metadata_directories,
highlight_map=highlight_map,
failed_generation_directories=failed_generation_directories,
)
def compute_failed_generation_highlights(
project_dir: str,
config_snapshot: Dict[str, Any]
) -> Dict[str, str]:
return compute_failed_generation_highlights_service(project_dir, config_snapshot)
def should_enable_failed_move(rel_path: str, highlight_map: Dict[str, str]) -> bool:
return should_enable_failed_move_service(rel_path, highlight_map)
FILENAME_RANGE_PATTERN = re.compile(
r'^(\d{2}-\d{2}-\d{2}-\d{3})_(\d{2}-\d{2}-\d{2}-\d{3})'
)
def get_audio_metadata_directories(config_snapshot: Dict[str, Any]) -> Set[str]:
return get_audio_metadata_directories_service(config_snapshot)
def should_collect_audio_metadata(rel_path: str, metadata_directories: Set[str]) -> bool:
if not rel_path or not metadata_directories:
return False
normalized = rel_path.replace('\\', '/')
segments = [segment for segment in normalized.split('/') if segment]
if len(segments) <= 1:
return False
parent_segments = segments[:-1]
return any(segment in metadata_directories for segment in parent_segments)
def parse_timestamp_to_seconds(value: str) -> Optional[float]:
if not value:
return None
parts = value.split('-')
if len(parts) != 4:
return None
try:
hours, minutes, seconds, milliseconds = (int(part) for part in parts)
except ValueError:
return None
total_seconds = (hours * 3600) + (minutes * 60) + seconds + (milliseconds / 1000.0)
return max(total_seconds, 0.0)
def compute_duration_from_filename(filename: str) -> Optional[float]:
if not filename:
return None
stem, _ = os.path.splitext(filename)
match = FILENAME_RANGE_PATTERN.match(stem or '')
if not match:
return None
start_seconds = parse_timestamp_to_seconds(match.group(1))
end_seconds = parse_timestamp_to_seconds(match.group(2))
if start_seconds is None or end_seconds is None:
return None
computed = end_seconds - start_seconds
if computed < 0:
return None
return computed
def read_wav_duration_seconds(file_path: str) -> Optional[float]:
try:
with wave.open(file_path, 'rb') as wav_file:
frame_rate = wav_file.getframerate()
frame_count = wav_file.getnframes()
if not frame_rate:
return None
duration = frame_count / float(frame_rate)
if math.isfinite(duration) and duration >= 0:
return duration
except (wave.Error, OSError) as exc:
logging.debug("Nem sikerült kiolvasni a wav időtartamot (%s): %s", file_path, exc)
return None
def format_seconds_hundredths(value: Optional[float]) -> Optional[str]:
if value is None:
return None
if not math.isfinite(value):
return None
rounded = round(max(value, 0) + 1e-9, 2)
return f"{rounded:.2f}"
def build_audio_metadata(
full_path: str,
rel_path: str,
metadata_directories: Set[str]
) -> Dict[str, Any]:
return build_audio_metadata_service(full_path, rel_path, metadata_directories)
def get_failed_generation_directories(config_snapshot: Dict[str, Any]) -> Set[str]:
return get_failed_generation_directories_service(config_snapshot)
def should_collect_failed_generation_text(rel_path: str, failed_directories: Set[str]) -> bool:
if not rel_path or not failed_directories:
return False
normalized = rel_path.replace('\\', '/')
segments = [segment for segment in normalized.split('/') if segment]
if len(segments) <= 1:
return False
parent_segments = segments[:-1]
return any(segment in failed_directories for segment in parent_segments)
def build_failed_generation_json_metadata(
full_path: str,
rel_path: str,
failed_directories: Set[str]
) -> Dict[str, Any]:
return build_failed_generation_json_metadata_service(full_path, rel_path, failed_directories)
def infer_autofill_kind(param_name: str) -> Optional[str]:
return infer_autofill_kind_service(param_name, PROJECT_AUTOFILL_OVERRIDES)
def load_scripts_file() -> List[Dict[str, Any]]:
entries = rebuild_scripts_config_file()
return entries
def rebuild_scripts_config_file() -> List[Dict[str, Any]]:
return rebuild_scripts_config_file_service(
SCRIPTS_DIR,
SCRIPTS_CONFIG_PATH,
validate_script_meta,
)
def prepare_script_entry(raw_entry: Dict[str, Any]) -> Optional[Dict[str, Any]]:
return prepare_script_entry_service(
raw_entry,
scripts_dir=SCRIPTS_DIR,
negative_flag_name_prefixes=NEGATIVE_FLAG_NAME_PREFIXES,
secret_param_names=SECRET_PARAM_NAMES,
script_key_requirements=SCRIPT_KEY_REQUIREMENTS,
project_autofill_overrides=PROJECT_AUTOFILL_OVERRIDES,
)
def get_scripts_catalog(force_reload: bool = False) -> List[Dict[str, Any]]:
return get_scripts_catalog_service(
force_reload=force_reload,
scripts_config_path=SCRIPTS_CONFIG_PATH,
scripts_cache=SCRIPTS_CACHE,
scripts_cache_lock=SCRIPTS_CACHE_LOCK,
load_scripts_file=load_scripts_file,
prepare_script_entry_fn=prepare_script_entry,
)
def initialize_scripts_catalog() -> None:
try:
rebuild_scripts_config_file()
except Exception as exc:
logging.error("Nem sikerült inicializálni a script katalógust: %s", exc)
def get_script_definition(script_id: str) -> Optional[Dict[str, Any]]:
return get_script_definition_service(script_id, get_scripts_catalog)
def ensure_workflows_dir() -> Path:
return ensure_workflows_dir_service(WORKFLOWS_DIR)
def sanitize_workflow_id(name: str) -> str:
return sanitize_workflow_id_service(name, secure_filename)
def _load_workflow_file(path: Path) -> Optional[Dict[str, Any]]:
return load_workflow_file_service(path, mask_workflow_secret_params)
def list_workflow_templates() -> List[Dict[str, Any]]:
return list_workflow_templates_service(WORKFLOWS_DIR, mask_workflow_secret_params)
def load_workflow_template(template_id: str) -> Optional[Dict[str, Any]]:
return load_workflow_template_service(WORKFLOWS_DIR, template_id, mask_workflow_secret_params)
def save_workflow_template_file(
name: str,
steps: List[Dict[str, Any]],
template_id: Optional[str] = None,
overwrite: bool = False,
description: Optional[str] = None
) -> Dict[str, Any]:
return save_workflow_template_file_service(
WORKFLOWS_DIR,
name,
steps,
mask_workflow_secret_params,
secure_filename,
WorkflowValidationError,
template_id=template_id,
overwrite=overwrite,
description=description,
)
def get_project_root_path(project_name: str, config_snapshot: Optional[Dict[str, Any]] = None) -> Optional[Path]:
return get_project_root_path_service(project_name, get_config_copy, secure_filename, config_snapshot=config_snapshot)
def get_project_workflow_state_path(project_name: str, config_snapshot: Optional[Dict[str, Any]] = None) -> Optional[Path]:
return get_project_workflow_state_path_service(
project_name,
WORKFLOW_STATE_FILENAME,
get_config_copy,
secure_filename,
config_snapshot=config_snapshot,
)
def load_project_workflow_state(project_name: str, config_snapshot: Optional[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
return load_project_workflow_state_service(
project_name,
WORKFLOW_STATE_FILENAME,
get_config_copy,
secure_filename,
mask_workflow_secret_params,
config_snapshot=config_snapshot,
)