-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathBatchConvertViewModel.cs
More file actions
2562 lines (2228 loc) · 97.7 KB
/
Copy pathBatchConvertViewModel.cs
File metadata and controls
2562 lines (2228 loc) · 97.7 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
using Nikse.SubtitleEdit.UiLogic.Export;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Nikse.SubtitleEdit.Core.AutoTranslate;
using Nikse.SubtitleEdit.Core.Common;
using Nikse.SubtitleEdit.Core.ContainerFormats.Matroska;
using Nikse.SubtitleEdit.Core.ContainerFormats.Mp4;
using Nikse.SubtitleEdit.Core.SubtitleFormats;
using Nikse.SubtitleEdit.Core.Translate;
using Nikse.SubtitleEdit.Features.Assa;
using Nikse.SubtitleEdit.Features.Edit.MultipleReplace;
using Nikse.SubtitleEdit.Features.Files.ExportCustomTextFormat;
using Nikse.SubtitleEdit.Features.Files.ExportEbuStl;
using Nikse.SubtitleEdit.Features.Files.Export.ExportEbuStl;
using Nikse.SubtitleEdit.Features.Files.ExportImageBased;
using Nikse.SubtitleEdit.Features.Main;
using Nikse.SubtitleEdit.Features.Ocr;
using Nikse.SubtitleEdit.Features.Ocr.Download;
using Nikse.SubtitleEdit.Features.Shared;
using Nikse.SubtitleEdit.Features.Shared.ErrorList;
using Nikse.SubtitleEdit.Features.Shared.PickSubtitleFormat;
using Nikse.SubtitleEdit.Features.Shared.PromptTextBox;
using Nikse.SubtitleEdit.Features.Tools.AdjustDuration;
using Nikse.SubtitleEdit.Features.Tools.BatchConvert.BatchErrorList;
using Nikse.SubtitleEdit.Features.Tools.FixCommonErrors;
using Nikse.SubtitleEdit.Features.Tools.RemoveTextForHearingImpaired;
using Nikse.SubtitleEdit.Features.Translate;
using Nikse.SubtitleEdit.Logic.LlamaCpp;
using Nikse.SubtitleEdit.Features.Video.SpeechToText;
using Nikse.SubtitleEdit.Features.Video.SpeechToText.Engines;
using Nikse.SubtitleEdit.Logic;
using Nikse.SubtitleEdit.Logic.Config;
using Nikse.SubtitleEdit.UiLogic.BatchConvert;
using Nikse.SubtitleEdit.Logic.Media;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Nikse.SubtitleEdit.Features.Tools.BatchConvert;
public partial class BatchConvertViewModel : ObservableObject
{
[ObservableProperty] private ObservableCollection<BatchConvertItem> _batchItems;
[ObservableProperty] private BatchConvertItem? _selectedBatchItem;
[ObservableProperty] private string _batchItemsInfo;
[ObservableProperty] private ObservableCollection<string> _targetFormats;
[ObservableProperty] private string? _selectedTargetFormat;
[ObservableProperty] private ObservableCollection<BatchConvertFunction> _batchFunctions;
[ObservableProperty] private BatchConvertFunction? _selectedBatchFunction;
[ObservableProperty] private bool _isProgressVisible;
[ObservableProperty] private bool _isConverting;
[ObservableProperty] private bool _isAddingFiles;
[ObservableProperty] private string _addingFilesStatus;
[ObservableProperty] private double _addingFilesProgressValue;
[ObservableProperty] private double _addingFilesProgressMax;
[ObservableProperty] private bool _areControlsEnabled;
[ObservableProperty] private string _outputFolderLabel;
[ObservableProperty] private string _outputFolderLinkLabel;
[ObservableProperty] private string _outputEncodingLabel;
[ObservableProperty] private string _statusText;
[ObservableProperty] private string _progressText;
[ObservableProperty] private double _progressValue;
[ObservableProperty] private double _progressMaxValue;
[ObservableProperty] private string _actionsSelected;
[ObservableProperty] private bool _isTargetFormatSettingsVisible;
[ObservableProperty] private ObservableCollection<string> _filterItems;
[ObservableProperty] private string? _selectedFilterItem;
[ObservableProperty] private string _filterText;
[ObservableProperty] private bool _isFilterTextVisible;
[ObservableProperty] private bool _isRemoveVisible;
[ObservableProperty] private bool _isOpenContainingFolderVisible;
// Add formatting
[ObservableProperty] private bool _formattingAddItalic;
[ObservableProperty] private bool _formattingAddBold;
[ObservableProperty] private bool _formattingAddUnderline;
[ObservableProperty] private bool _formattingAddAlignmentTag;
[ObservableProperty] private bool _formattingAddColor;
[ObservableProperty] private Color _formattingAddColorValue;
[ObservableProperty] private ObservableCollection<DisplayAlignment> _alignmentTagOptions;
[ObservableProperty] private DisplayAlignment? _selectedAlignmentTagOption;
// Remove formatting
[ObservableProperty] private bool _formattingRemoveAll;
[ObservableProperty] private bool _formattingRemoveItalic;
[ObservableProperty] private bool _formattingRemoveBold;
[ObservableProperty] private bool _formattingRemoveUnderline;
[ObservableProperty] private bool _formattingRemoveFontTags;
[ObservableProperty] private bool _formattingRemoveAlignmentTags;
[ObservableProperty] private bool _formattingRemoveColors;
// Remove line breaks
[ObservableProperty] private bool _removeLineBreaksOnlyShortLines;
// Offset time codes
[ObservableProperty] private bool _offsetTimeCodesForward;
[ObservableProperty] private bool _offsetTimeCodesBack;
[ObservableProperty] private TimeSpan _offsetTimeCodesTime;
// Adjust mininum gap between subtitles
[ObservableProperty] private int _minGapMs;
// Adjust display duration
[ObservableProperty] private ObservableCollection<AdjustDurationDisplay> _adjustTypes;
[ObservableProperty] private AdjustDurationDisplay _selectedAdjustType;
[ObservableProperty] private double _adjustSeconds;
[ObservableProperty] private int _adjustPercent;
[ObservableProperty] private double _adjustFixed;
[ObservableProperty] private double _adjustRecalculateMaxCharacterPerSecond;
[ObservableProperty] private double _adjustRecalculateOptimalCharacterPerSecond;
[ObservableProperty] private bool _adjustIsSecondsVisible;
[ObservableProperty] private bool _adjustIsPercentVisible;
[ObservableProperty] private bool _adjustIsFixedVisible;
[ObservableProperty] private bool _adjustIsRecalculateVisible;
// Delete lines
[ObservableProperty] private ObservableCollection<int> _deleteLineNumbers;
[ObservableProperty] private int _deleteXFirstLines;
[ObservableProperty] private int _deleteXLastLines;
[ObservableProperty] private string _deleteLinesContains;
[ObservableProperty] private string _deleteActorsOrStyles;
// Change frame rate
[ObservableProperty] private ObservableCollection<double> _fromFrameRates;
[ObservableProperty] private double _selectedFromFrameRate;
[ObservableProperty] private ObservableCollection<double> _toFrameRates;
[ObservableProperty] private double _selectedToFrameRate;
// Change speed
[ObservableProperty] private double _changeSpeedPercent;
// Change casing
[ObservableProperty] private bool _normalCasing;
[ObservableProperty] private bool _normalCasingFixNames;
[ObservableProperty] private bool _normalCasingOnlyUpper;
[ObservableProperty] private bool _fixNamesOnly;
[ObservableProperty] private bool _allUppercase;
[ObservableProperty] private bool _allLowercase;
// Auto translate
[ObservableProperty] public ObservableCollection<IAutoTranslator> _autoTranslators;
[ObservableProperty] private IAutoTranslator _selectedAutoTranslator;
[ObservableProperty] private ObservableCollection<TranslationPair> _sourceLanguages = new();
[ObservableProperty] private TranslationPair? _selectedSourceLanguage;
[ObservableProperty] private ObservableCollection<TranslationPair> _targetLanguages = new();
[ObservableProperty] private TranslationPair? _selectedTargetLanguage;
[ObservableProperty] private string _autoTranslateModel;
[ObservableProperty] private string _autoTranslateUrl;
[ObservableProperty] private string _autoTranslateApiKey;
[ObservableProperty] private bool _autoTranslateModelIsVisible;
[ObservableProperty] private bool _autoTranslateModelBrowseIsVisible;
[ObservableProperty] private bool _autoTranslateUrlIsVisible;
[ObservableProperty] private bool _autoTranslateApiKeyIsVisible;
[ObservableProperty] private ObservableCollection<SpeechToTextModelDisplay> _crispAsrModels = new();
[ObservableProperty] private SpeechToTextModelDisplay? _selectedCrispAsrModel;
[ObservableProperty] private bool _crispAsrModelComboIsVisible;
// Fix common errors
[ObservableProperty] private FixCommonErrors.ProfileDisplayItem? _fixCommonErrorsProfile;
// Merge lines with same text
[ObservableProperty] private int _mergeSameTextMaxMillisecondsBetweenLines;
[ObservableProperty] private bool _mergeSameTextIncludeIncrementingLines;
// Merge lines with same time codes
[ObservableProperty] private int _mergeSameTimeMaxMillisecondsDifference;
[ObservableProperty] private bool _mergeSameTimeMergeDialog;
[ObservableProperty] private bool _mergeSameTimeAutoBreak;
// Fix right-to-left
[ObservableProperty] private bool _rtlFixViaUniCode;
[ObservableProperty] private bool _rtlRemoveUniCode;
[ObservableProperty] private bool _rtlReverseStartEnd;
// Bride gaps
[ObservableProperty] private int _bridgeGapsSmallerThanMs;
[ObservableProperty] private int _bridgeGapsMinGapMs;
[ObservableProperty] private int _bridgeGapsPercentForLeft;
// Split/break long lines
[ObservableProperty] private bool _splitBreakSplitLongLines;
[ObservableProperty] private int _splitBreakSingleLineMaxLength;
[ObservableProperty] private int _splitBreakMaxNumberOfLines;
[ObservableProperty] private bool _splitBreakRebalanceLongLines;
// ASSA change resolution
[ObservableProperty] private int _assaChangeResolutionTargetWidth;
[ObservableProperty] private int _assaChangeResolutionTargetHeight;
[ObservableProperty] private bool _assaChangeResolutionChangeMargins;
[ObservableProperty] private bool _assaChangeResolutionChangeFontSize;
[ObservableProperty] private bool _assaChangeResolutionChangePosition;
[ObservableProperty] private bool _assaChangeResolutionChangeDrawing;
// ASSA change style
[ObservableProperty] private string _assaChangeStyleFromStyle;
[ObservableProperty] private string _assaChangeStyleToStyle;
[ObservableProperty] private string _assaChangeStyleImportFileName;
[ObservableProperty] private string _assaChangeStyleImportedStyleHeader;
[ObservableProperty] private bool _assaChangeStyleTrimUnusedStyles;
// Merge short lines
[ObservableProperty] private int _mergeShortLinesMaxCharacters;
[ObservableProperty] private int _mergeShortLinesMaxMillisecondsBetweenLines;
[ObservableProperty] private bool _mergeShortLinesOnlyContinuationLines;
// Apply duration limits
[ObservableProperty] private bool _applyDurationLimitsFixMin;
[ObservableProperty] private int _applyDurationLimitsMinDurationMs;
[ObservableProperty] private bool _applyDurationLimitsFixMax;
[ObservableProperty] private int _applyDurationLimitsMaxDurationMs;
// Sort by
[ObservableProperty] private ObservableCollection<SortByOption> _sortByOptions;
[ObservableProperty] private SortByOption? _selectedSortByOption;
[ObservableProperty] private bool _sortByDescending;
public Window? Window { get; set; }
public DataGrid FileGrid { get; set; } = new();
public bool OkPressed { get; private set; }
public ScrollViewer FunctionContainer { get; internal set; }
public string EbuHeader { get; private set; } = string.Empty;
public byte EbuJustificationCode { get; private set; } = 2;
private List<BatchConvertItem> _allBatchItems;
private readonly System.Timers.Timer _filesTimer;
private bool _isFilesDirty;
private readonly IWindowService _windowService;
private readonly IFileHelper _fileHelper;
private readonly IFolderHelper _folderHelper;
private readonly IBatchConverter _batchConverter;
private readonly IBatchConvertItemSplitter _batchConvertItemSplitter;
private CancellationToken _cancellationToken;
private CancellationTokenSource _cancellationTokenSource;
private CancellationTokenSource _addFilesCancellationTokenSource = new();
private List<string> _encodings;
private List<string> _targetFormatsWithSettings;
public BatchConvertViewModel(
IWindowService windowService,
IFileHelper fileHelper,
IBatchConverter batchConverter,
IFolderHelper folderHelper,
IBatchConvertItemSplitter batchConvertItemSplitter)
{
_windowService = windowService;
_fileHelper = fileHelper;
_batchConverter = batchConverter;
_folderHelper = folderHelper;
_batchConvertItemSplitter = batchConvertItemSplitter;
BatchItems = new ObservableCollection<BatchConvertItem>();
_allBatchItems = new List<BatchConvertItem>();
BatchFunctions = new ObservableCollection<BatchConvertFunction>();
TargetFormats = new ObservableCollection<string>(SubtitleFormatHelper.GetSubtitleFormatsWithFavoritesAtTop().Select(p => p.Name))
{
BatchConverter.FormatAyato,
BatchConverter.FormatBdnXml,
BatchConverter.FormatBluRaySup,
BatchConverter.FormatCavena890,
BatchConverter.FormatCustomTextFormat,
BatchConverter.FormatDCinemaInterop,
BatchConverter.FormatDCinemaSmpte2014,
BatchConverter.FormatDostImage,
BatchConverter.FormatFcpImage,
BatchConverter.FormatImagesWithTimeCodesInFileName,
BatchConverter.FormatPac,
BatchConverter.FormatPlainText,
BatchConverter.FormatVobSub
};
FilterItems =
[
Se.Language.General.AllFiles,
Se.Language.Tools.BatchConvert.FileNameContainsDotDotDot,
Se.Language.Tools.BatchConvert.TrackLanguageContainsDotDotDot,
];
SelectedFilterItem = FilterItems.FirstOrDefault();
FilterText = string.Empty;
DeleteLineNumbers = new ObservableCollection<int>();
BatchItemsInfo = string.Empty;
AddingFilesStatus = string.Empty;
ProgressText = string.Empty;
ActionsSelected = string.Empty;
DeleteLinesContains = string.Empty;
OutputFolderLabel = string.Empty;
OutputFolderLinkLabel = string.Empty;
OutputEncodingLabel = string.Empty;
StatusText = string.Empty;
DeleteActorsOrStyles = string.Empty;
OffsetTimeCodesForward = true;
FunctionContainer = new ScrollViewer();
FromFrameRates = new ObservableCollection<double>
{
23.976,
24,
25,
29.97,
30,
48,
59.94,
60,
120,
};
ToFrameRates = new ObservableCollection<double>
{
23.976,
24,
25,
29.97,
30,
48,
59.94,
60,
120,
};
AdjustTypes = new ObservableCollection<AdjustDurationDisplay>(AdjustDurationDisplay.ListAll());
SelectedAdjustType = AdjustTypes.First();
AlignmentTagOptions = new ObservableCollection<DisplayAlignment>(DisplayAlignment.GetAll());
SelectedAlignmentTagOption = AlignmentTagOptions[1];
SortByOptions = new ObservableCollection<SortByOption>
{
new("Number", Se.Language.Tools.SortBy.SortByNumber),
new("StartTime", Se.Language.Tools.SortBy.SortByStartTime),
new("EndTime", Se.Language.Tools.SortBy.SortByEndTime),
};
SelectedSortByOption = SortByOptions[0];
BatchFunctions = new ObservableCollection<BatchConvertFunction>(BatchConvertFunction.List(this));
_cancellationTokenSource = new CancellationTokenSource();
_cancellationToken = _cancellationTokenSource.Token;
_encodings = EncodingHelper.GetEncodings().Select(p => p.DisplayName).ToList();
_encodings.Insert(0, EncodingHelper.TryToUseSourceEncoding);
AutoTranslateModel = string.Empty;
AutoTranslateUrl = string.Empty;
AutoTranslateApiKey = string.Empty;
AutoTranslators =
[
new OllamaTranslate(),
new LibreTranslate(),
new LmStudioTranslate(),
new LlamaCppTranslate(),
new NoLanguageLeftBehindServe(),
new NoLanguageLeftBehindApi(),
new DeepLTranslate(),
new CrispAsrMadladTranslate(),
];
SelectedAutoTranslator = AutoTranslators[0];
OnAutoTranslatorChanged();
SelectedFromFrameRate = FromFrameRates[0];
SelectedToFrameRate = ToFrameRates[1];
ChangeSpeedPercent = 100;
AssaChangeResolutionTargetWidth = 1920;
AssaChangeResolutionTargetHeight = 1080;
AssaChangeResolutionChangeMargins = true;
AssaChangeResolutionChangeFontSize = true;
AssaChangeResolutionChangePosition = true;
AssaChangeResolutionChangeDrawing = true;
AssaChangeStyleFromStyle = string.Empty;
AssaChangeStyleToStyle = string.Empty;
AssaChangeStyleImportFileName = string.Empty;
AssaChangeStyleImportedStyleHeader = string.Empty;
AssaChangeStyleTrimUnusedStyles = false;
FixCommonErrorsProfile = LoadDefaultProfile();
_targetFormatsWithSettings = new List<string>
{
BatchConverter.FormatBdnXml,
BatchConverter.FormatBluRaySup,
BatchConverter.FormatCustomTextFormat,
BatchConverter.FormatDostImage,
BatchConverter.FormatEbuStl,
BatchConverter.FormatFcpImage,
BatchConverter.FormatImagesWithTimeCodesInFileName,
BatchConverter.FormatVobSub,
new AdvancedSubStationAlpha().Name,
};
LoadSettings();
FilterComboBoxChanged();
_filesTimer = new System.Timers.Timer(250);
_filesTimer.Elapsed += (sender, args) =>
{
Dispatcher.UIThread.Post(() =>
{
_filesTimer.Stop();
if (_isFilesDirty)
{
_isFilesDirty = false;
UpdateFilteredFiles();
}
_filesTimer.Start();
});
};
_filesTimer.Start();
}
private void UpdateFilteredFiles()
{
BatchItems.Clear();
foreach (var item in _allBatchItems)
{
if (PassesFilter(item))
{
BatchItems.Add(item);
}
}
}
private bool PassesFilter(BatchConvertItem item)
{
if (SelectedFilterItem == Se.Language.Tools.BatchConvert.FileNameContainsDotDotDot && !string.IsNullOrEmpty(FilterText))
{
return item.FileName.Contains(FilterText, StringComparison.InvariantCultureIgnoreCase);
}
if (SelectedFilterItem == Se.Language.Tools.BatchConvert.TrackLanguageContainsDotDotDot && !string.IsNullOrEmpty(FilterText))
{
return item.Format.Contains(FilterText, StringComparison.InvariantCultureIgnoreCase);
}
return true;
}
// Appends just-parsed items to the visible grid (respecting the active filter) so files show
// up incrementally as they load. Must run on the UI thread.
private void AddFilteredItems(IEnumerable<BatchConvertItem> items)
{
foreach (var item in items)
{
if (PassesFilter(item))
{
BatchItems.Add(item);
}
}
}
private static FixCommonErrors.ProfileDisplayItem LoadDefaultProfile()
{
var profiles = Se.Settings.Tools.FixCommonErrors.Profiles;
var displayProfiles = new List<FixCommonErrors.ProfileDisplayItem>();
var defaultName = Se.Settings.Tools.FixCommonErrors.LastProfileName;
var allFixRules = FixCommonErrorsViewModel.MakeDefaultRules();
foreach (var setting in profiles)
{
var profile = new FixCommonErrors.ProfileDisplayItem
{
Name = setting.ProfileName,
FixRules = new ObservableCollection<FixRuleDisplayItem>(allFixRules.Select(rule => new FixRuleDisplayItem(rule)
{
IsSelected = setting.SelectedRules.Contains(rule.FixCommonErrorFunctionName)
}))
};
if (defaultName == profile.Name)
{
return profile;
}
displayProfiles.Add(profile);
}
return displayProfiles.First();
}
private void SaveSettings()
{
Se.Settings.Tools.BatchConvert.TargetFormat = SelectedTargetFormat ?? TargetFormats.First();
Se.Settings.Tools.BatchConvert.ActiveFunctions = BatchFunctions
.Where(p => p.IsSelected)
.Select(p => p.Type.ToString())
.ToArray();
Se.Settings.Tools.BatchConvert.LastFilterItem = SelectedFilterItem ?? string.Empty;
Se.Settings.Tools.BatchConvert.AdjustVia = SelectedAdjustType.Name;
Se.Settings.Tools.BatchConvert.AdjustMaxCps = AdjustRecalculateMaxCharacterPerSecond;
Se.Settings.Tools.BatchConvert.AdjustOptimalCps = AdjustRecalculateOptimalCharacterPerSecond;
Se.Settings.Tools.BatchConvert.AdjustDurationFixedMilliseconds = (int)AdjustFixed;
Se.Settings.Tools.BatchConvert.AdjustDurationSeconds = AdjustSeconds;
Se.Settings.Tools.BatchConvert.AdjustDurationPercentage = AdjustPercent;
Se.Settings.Tools.BatchConvert.AutoTranslateEngine = SelectedAutoTranslator.Name;
Se.Settings.Tools.BatchConvert.AutoTranslateSourceLanguage = SelectedSourceLanguage?.TwoLetterIsoLanguageName ?? "auto";
Se.Settings.Tools.BatchConvert.AutoTranslateTargetLanguage = SelectedTargetLanguage?.TwoLetterIsoLanguageName ?? "en";
// Change casing
if (NormalCasing)
{
Se.Settings.Tools.BatchConvert.ChangeCasingType = "Normal";
}
else if (FixNamesOnly)
{
Se.Settings.Tools.BatchConvert.ChangeCasingType = "FixNamesOnly";
}
else if (AllUppercase)
{
Se.Settings.Tools.BatchConvert.ChangeCasingType = "AllUppercase";
}
else if (AllLowercase)
{
Se.Settings.Tools.BatchConvert.ChangeCasingType = "AllLowercase";
}
Se.Settings.Tools.BatchConvert.NormalCasingFixNames = NormalCasingFixNames;
Se.Settings.Tools.BatchConvert.NormalCasingOnlyUpper = NormalCasingOnlyUpper;
// Offset time codes
Se.Settings.Tools.BatchConvert.OffsetTimeCodesMilliseconds = OffsetTimeCodesTime.TotalMilliseconds;
Se.Settings.Tools.BatchConvert.OffsetTimeCodesForward = OffsetTimeCodesForward;
// Change frame rate
Se.Settings.Tools.BatchConvert.ChangeFrameRateFrom = SelectedFromFrameRate;
Se.Settings.Tools.BatchConvert.ChangeFrameRateTo = SelectedToFrameRate;
// Change speed
Se.Settings.Tools.BatchConvert.ChangeSpeedPercent = ChangeSpeedPercent;
// Delete lines
Se.Settings.Tools.BatchConvert.DeleteXFirstLines = DeleteXFirstLines;
Se.Settings.Tools.BatchConvert.DeleteXLastLines = DeleteXLastLines;
Se.Settings.Tools.BatchConvert.DeleteLinesContains = DeleteLinesContains ?? string.Empty;
Se.Settings.Tools.BatchConvert.DeleteActorsOrStyles = DeleteActorsOrStyles ?? string.Empty;
// Add formatting
Se.Settings.Tools.BatchConvert.FormattingAddItalic = FormattingAddItalic;
Se.Settings.Tools.BatchConvert.FormattingAddBold = FormattingAddBold;
Se.Settings.Tools.BatchConvert.FormattingAddUnderline = FormattingAddUnderline;
Se.Settings.Tools.BatchConvert.FormattingAddAlignmentTag = FormattingAddAlignmentTag;
Se.Settings.Tools.BatchConvert.FormattingAddAlignmentTagOption = SelectedAlignmentTagOption?.Code ?? "an2";
Se.Settings.Tools.BatchConvert.FormattingAddColor = FormattingAddColor;
Se.Settings.Tools.BatchConvert.FormattingAddColorValue = FormattingAddColorValue.ToString();
// Remove line breaks
Se.Settings.Tools.BatchConvert.RemoveLineBreaksOnlyShortLines = RemoveLineBreaksOnlyShortLines;
// ASSA change resolution
Se.Settings.Tools.BatchConvert.AssaChangeResolutionTargetWidth = AssaChangeResolutionTargetWidth;
Se.Settings.Tools.BatchConvert.AssaChangeResolutionTargetHeight = AssaChangeResolutionTargetHeight;
Se.Settings.Tools.BatchConvert.AssaChangeResolutionChangeMargins = AssaChangeResolutionChangeMargins;
Se.Settings.Tools.BatchConvert.AssaChangeResolutionChangeFontSize = AssaChangeResolutionChangeFontSize;
Se.Settings.Tools.BatchConvert.AssaChangeResolutionChangePosition = AssaChangeResolutionChangePosition;
Se.Settings.Tools.BatchConvert.AssaChangeResolutionChangeDrawing = AssaChangeResolutionChangeDrawing;
// ASSA change style
Se.Settings.Tools.BatchConvert.AssaChangeStyleFromStyle = AssaChangeStyleFromStyle ?? string.Empty;
Se.Settings.Tools.BatchConvert.AssaChangeStyleToStyle = AssaChangeStyleToStyle ?? string.Empty;
Se.Settings.Tools.BatchConvert.AssaChangeStyleTrimUnusedStyles = AssaChangeStyleTrimUnusedStyles;
// Merge short lines
Se.Settings.Tools.BatchConvert.MergeShortLinesMaxCharacters = MergeShortLinesMaxCharacters;
Se.Settings.Tools.BatchConvert.MergeShortLinesMaxMillisecondsBetweenLines = MergeShortLinesMaxMillisecondsBetweenLines;
Se.Settings.Tools.BatchConvert.MergeShortLinesOnlyContinuationLines = MergeShortLinesOnlyContinuationLines;
// Apply duration limits
Se.Settings.Tools.BatchConvert.ApplyDurationLimitsFixMinDuration = ApplyDurationLimitsFixMin;
Se.Settings.Tools.BatchConvert.ApplyDurationLimitsMinDurationMs = ApplyDurationLimitsMinDurationMs;
Se.Settings.Tools.BatchConvert.ApplyDurationLimitsFixMaxDuration = ApplyDurationLimitsFixMax;
Se.Settings.Tools.BatchConvert.ApplyDurationLimitsMaxDurationMs = ApplyDurationLimitsMaxDurationMs;
// Sort by
Se.Settings.Tools.BatchConvert.SortBy = SelectedSortByOption?.Key ?? "Number";
Se.Settings.Tools.BatchConvert.SortByDescending = SortByDescending;
// Fix right-to-left
if (RtlFixViaUniCode)
{
Se.Settings.Tools.BatchConvert.FixRtlMode = "FixViaUnicode";
}
else if (RtlRemoveUniCode)
{
Se.Settings.Tools.BatchConvert.FixRtlMode = "RemoveUnicode";
}
else
{
Se.Settings.Tools.BatchConvert.FixRtlMode = "ReverseStartEnd";
}
Se.SaveSettings();
}
private void LoadSettings()
{
var targetFormat = TargetFormats.FirstOrDefault(p => p == Se.Settings.Tools.BatchConvert.TargetFormat);
if (targetFormat == null)
{
targetFormat = TargetFormats.First();
}
SelectedTargetFormat = targetFormat;
SelectedAdjustType = AdjustTypes.First();
foreach (var adjustType in AdjustTypes)
{
if (adjustType.Name == Se.Settings.Tools.BatchConvert.AdjustVia)
{
SelectedAdjustType = adjustType;
break;
}
}
var filterItem = FilterItems.FirstOrDefault(p => p == Se.Settings.Tools.BatchConvert.LastFilterItem);
if (filterItem != null)
{
SelectedFilterItem = filterItem;
}
AdjustRecalculateMaxCharacterPerSecond = Se.Settings.Tools.BatchConvert.AdjustMaxCps;
AdjustRecalculateOptimalCharacterPerSecond = Se.Settings.Tools.BatchConvert.AdjustOptimalCps;
AdjustFixed = Se.Settings.Tools.BatchConvert.AdjustDurationFixedMilliseconds;
AdjustSeconds = Se.Settings.Tools.BatchConvert.AdjustDurationSeconds;
AdjustPercent = Se.Settings.Tools.BatchConvert.AdjustDurationPercentage;
var translator = AutoTranslators.FirstOrDefault(p => p.Name == Se.Settings.Tools.BatchConvert.AutoTranslateEngine);
if (translator != null)
{
SelectedAutoTranslator = translator;
}
var sourceLanguage = SourceLanguages.FirstOrDefault(p => p.TwoLetterIsoLanguageName == Se.Settings.Tools.BatchConvert.AutoTranslateSourceLanguage);
if (sourceLanguage != null)
{
SelectedSourceLanguage = sourceLanguage;
}
var defaultTarget = AutoTranslateViewModel.EvaluateDefaultTargetLanguageCode(string.Empty, SelectedSourceLanguage?.Code ?? string.Empty);
SelectedTargetLanguage = TargetLanguages.FirstOrDefault(p => p.TwoLetterIsoLanguageName == defaultTarget);
var targetLanguage = TargetLanguages.FirstOrDefault(p => p.TwoLetterIsoLanguageName == Se.Settings.Tools.BatchConvert.AutoTranslateTargetLanguage);
if (targetLanguage != null)
{
SelectedTargetLanguage = targetLanguage;
}
// Change casing
if (Se.Settings.Tools.BatchConvert.ChangeCasingType == "Normal")
{
NormalCasing = true;
}
else if (Se.Settings.Tools.BatchConvert.ChangeCasingType == "FixNamesOnly")
{
FixNamesOnly = true;
}
else if (Se.Settings.Tools.BatchConvert.ChangeCasingType == "AllUppercase")
{
AllUppercase = true;
}
else if (Se.Settings.Tools.BatchConvert.ChangeCasingType == "AllLowercase")
{
AllLowercase = true;
}
NormalCasingFixNames = Se.Settings.Tools.BatchConvert.NormalCasingFixNames;
NormalCasingOnlyUpper = Se.Settings.Tools.BatchConvert.NormalCasingOnlyUpper;
UpdateOutputProperties();
MergeSameTextMaxMillisecondsBetweenLines = Se.Settings.Tools.MergeSameText.MaxMillisecondsBetweenLines;
MergeSameTextIncludeIncrementingLines = Se.Settings.Tools.MergeSameText.IncludeIncrementingLines;
MergeSameTimeMaxMillisecondsDifference = Se.Settings.Tools.MergeSameTimeCode.MaxMillisecondsDifference;
MergeSameTimeMergeDialog = Se.Settings.Tools.MergeSameTimeCode.MergeDialog;
MergeSameTimeAutoBreak = Se.Settings.Tools.MergeSameTimeCode.AutoBreak;
if (Se.Settings.Tools.BatchConvert.FixRtlMode == "FixViaUnicode")
{
RtlFixViaUniCode = true;
}
else if (Se.Settings.Tools.BatchConvert.FixRtlMode == "RemoveUnicode")
{
RtlRemoveUniCode = true;
}
else
{
RtlReverseStartEnd = true;
}
BridgeGapsSmallerThanMs = Se.Settings.Tools.BridgeGaps.BridgeGapsSmallerThanMs;
BridgeGapsMinGapMs = Se.Settings.Tools.BridgeGaps.MinGapMs;
BridgeGapsPercentForLeft = Se.Settings.Tools.BridgeGaps.PercentForLeft;
SplitBreakSingleLineMaxLength = Se.Settings.General.SubtitleLineMaximumLength;
SplitBreakMaxNumberOfLines = Se.Settings.General.MaxNumberOfLines;
SplitBreakSplitLongLines = Se.Settings.Tools.SplitRebalanceLongLinesSplit;
SplitBreakRebalanceLongLines = Se.Settings.Tools.SplitRebalanceLongLinesRebalance;
// Offset time codes
OffsetTimeCodesTime = TimeSpan.FromMilliseconds(Se.Settings.Tools.BatchConvert.OffsetTimeCodesMilliseconds);
OffsetTimeCodesForward = Se.Settings.Tools.BatchConvert.OffsetTimeCodesForward;
OffsetTimeCodesBack = !OffsetTimeCodesForward;
// Change frame rate — match against the available list so binding picks up the value.
var fromRate = FromFrameRates.FirstOrDefault(p => Math.Abs(p - Se.Settings.Tools.BatchConvert.ChangeFrameRateFrom) < 0.001);
if (fromRate > 0)
{
SelectedFromFrameRate = fromRate;
}
var toRate = ToFrameRates.FirstOrDefault(p => Math.Abs(p - Se.Settings.Tools.BatchConvert.ChangeFrameRateTo) < 0.001);
if (toRate > 0)
{
SelectedToFrameRate = toRate;
}
// Change speed
ChangeSpeedPercent = Se.Settings.Tools.BatchConvert.ChangeSpeedPercent;
// Delete lines
DeleteXFirstLines = Se.Settings.Tools.BatchConvert.DeleteXFirstLines;
DeleteXLastLines = Se.Settings.Tools.BatchConvert.DeleteXLastLines;
DeleteLinesContains = Se.Settings.Tools.BatchConvert.DeleteLinesContains ?? string.Empty;
DeleteActorsOrStyles = Se.Settings.Tools.BatchConvert.DeleteActorsOrStyles ?? string.Empty;
// Add formatting
FormattingAddItalic = Se.Settings.Tools.BatchConvert.FormattingAddItalic;
FormattingAddBold = Se.Settings.Tools.BatchConvert.FormattingAddBold;
FormattingAddUnderline = Se.Settings.Tools.BatchConvert.FormattingAddUnderline;
FormattingAddAlignmentTag = Se.Settings.Tools.BatchConvert.FormattingAddAlignmentTag;
var alignment = AlignmentTagOptions.FirstOrDefault(p => p.Code == Se.Settings.Tools.BatchConvert.FormattingAddAlignmentTagOption);
if (alignment != null)
{
SelectedAlignmentTagOption = alignment;
}
FormattingAddColor = Se.Settings.Tools.BatchConvert.FormattingAddColor;
if (Color.TryParse(Se.Settings.Tools.BatchConvert.FormattingAddColorValue, out var color))
{
FormattingAddColorValue = color;
}
// Remove line breaks
RemoveLineBreaksOnlyShortLines = Se.Settings.Tools.BatchConvert.RemoveLineBreaksOnlyShortLines;
// ASSA change resolution
AssaChangeResolutionTargetWidth = Se.Settings.Tools.BatchConvert.AssaChangeResolutionTargetWidth;
AssaChangeResolutionTargetHeight = Se.Settings.Tools.BatchConvert.AssaChangeResolutionTargetHeight;
AssaChangeResolutionChangeMargins = Se.Settings.Tools.BatchConvert.AssaChangeResolutionChangeMargins;
AssaChangeResolutionChangeFontSize = Se.Settings.Tools.BatchConvert.AssaChangeResolutionChangeFontSize;
AssaChangeResolutionChangePosition = Se.Settings.Tools.BatchConvert.AssaChangeResolutionChangePosition;
AssaChangeResolutionChangeDrawing = Se.Settings.Tools.BatchConvert.AssaChangeResolutionChangeDrawing;
// ASSA change style
AssaChangeStyleFromStyle = Se.Settings.Tools.BatchConvert.AssaChangeStyleFromStyle ?? string.Empty;
AssaChangeStyleToStyle = Se.Settings.Tools.BatchConvert.AssaChangeStyleToStyle ?? string.Empty;
AssaChangeStyleTrimUnusedStyles = Se.Settings.Tools.BatchConvert.AssaChangeStyleTrimUnusedStyles;
// Merge short lines
MergeShortLinesMaxCharacters = Se.Settings.Tools.BatchConvert.MergeShortLinesMaxCharacters;
MergeShortLinesMaxMillisecondsBetweenLines = Se.Settings.Tools.BatchConvert.MergeShortLinesMaxMillisecondsBetweenLines;
MergeShortLinesOnlyContinuationLines = Se.Settings.Tools.BatchConvert.MergeShortLinesOnlyContinuationLines;
// Apply duration limits
ApplyDurationLimitsFixMin = Se.Settings.Tools.BatchConvert.ApplyDurationLimitsFixMinDuration;
ApplyDurationLimitsMinDurationMs = Se.Settings.Tools.BatchConvert.ApplyDurationLimitsMinDurationMs;
ApplyDurationLimitsFixMax = Se.Settings.Tools.BatchConvert.ApplyDurationLimitsFixMaxDuration;
ApplyDurationLimitsMaxDurationMs = Se.Settings.Tools.BatchConvert.ApplyDurationLimitsMaxDurationMs;
// Sort by
var savedSortBy = SortByOptions.FirstOrDefault(p => p.Key == Se.Settings.Tools.BatchConvert.SortBy);
if (savedSortBy != null)
{
SelectedSortByOption = savedSortBy;
}
SortByDescending = Se.Settings.Tools.BatchConvert.SortByDescending;
}
private void UpdateOutputProperties()
{
var targetEncoding =
_encodings.FirstOrDefault(p => p == Se.Settings.Tools.BatchConvert.TargetEncoding);
if (targetEncoding == null)
{
targetEncoding = _encodings.FirstOrDefault(p => p == TextEncoding.Utf8WithBom)
?? _encodings.First();
Se.Settings.Tools.BatchConvert.TargetEncoding = targetEncoding;
}
if (!Se.Settings.Tools.BatchConvert.SaveInSourceFolder &&
string.IsNullOrWhiteSpace(Se.Settings.Tools.BatchConvert.OutputFolder))
{
Se.Settings.Tools.BatchConvert.SaveInSourceFolder = true;
}
if (Se.Settings.Tools.BatchConvert.SaveInSourceFolder)
{
OutputFolderLinkLabel = string.Empty;
OutputFolderLabel = Se.Language.Tools.BatchConvert.OutputFolderSource;
}
else
{
OutputFolderLinkLabel = string.Format(Se.Language.Tools.BatchConvert.OutputFolderX, Se.Settings.Tools.BatchConvert.OutputFolder);
OutputFolderLabel = string.Empty;
}
OutputEncodingLabel = string.Format(Se.Language.Tools.BatchConvert.EncodingXOverwriteY,
Se.Settings.Tools.BatchConvert.TargetEncoding,
Se.Settings.Tools.BatchConvert.Overwrite);
}
[RelayCommand]
private async Task ShowRemoveTextForHearingImpairedSettings()
{
_ = await _windowService
.ShowDialogAsync<RemoveTextForHearingImpairedWindow, RemoveTextForHearingImpairedViewModel>(
Window!, vm => { vm.Initialize(new Subtitle()); });
}
[RelayCommand]
private void Done()
{
SaveSettings();
OkPressed = true;
Window?.Close();
}
[RelayCommand]
private void Cancel()
{
_cancellationTokenSource.Cancel();
IsConverting = false;
foreach (var batchItem in BatchItems)
{
if (batchItem.Status != "-" &&
batchItem.Status != Se.Language.General.Converted &&
batchItem.Status != Se.Language.General.Error)
{
batchItem.Status = Se.Language.General.Cancelled;
}
}
ProgressText = string.Empty;
}
[RelayCommand]
private async Task Convert()
{
if (BatchItems.Count == 0)
{
await ShowStatus(Se.Language.General.NoFilesToConvert);
return;
}
_cancellationTokenSource = new CancellationTokenSource();
_cancellationToken = _cancellationTokenSource.Token;
foreach (var batchItem in BatchItems)
{
batchItem.Status = "-";
}
SaveSettings();
var config = MakeBatchConvertConfig();
if (!await EnsurePaddleOcrAvailable(config))
{
return;
}
if (!await EnsureCrispAsrAvailable(config))
{
return;
}
if (!await EnsureLlamaCppAvailable(config))
{
return;
}
_batchConverter.Initialize(config);
var start = DateTime.UtcNow.Ticks;
IsProgressVisible = true;
IsConverting = true;
AreControlsEnabled = false;
ProgressMaxValue = BatchItems.Count;
_ = Task.Run(async () =>
{
var count = 1;
foreach (var batchItem in BatchItems)
{
var countDisplay = count;
ProgressText = string.Format(Se.Language.General.ConvertingXofYDotDoDot, countDisplay, BatchItems.Count);
ProgressValue = countDisplay / (double)BatchItems.Count;
if (batchItem.Format!.StartsWith("Transport Stream", StringComparison.Ordinal))
{
var tsResult = _batchConvertItemSplitter.LoadTransportStream(batchItem, _cancellationToken);
foreach (var bi in tsResult)
{
if (_cancellationToken.IsCancellationRequested)
{
break;
}
await _batchConverter.Convert(bi, _cancellationToken);
}
}
else
{
await _batchConverter.Convert(batchItem, _cancellationToken);
}
count++;
if (_cancellationToken.IsCancellationRequested)
{
ProgressText = string.Empty;
break;
}
}
IsProgressVisible = false;
IsConverting = false;
AreControlsEnabled = true;
ProgressText = string.Empty;
var end = DateTime.UtcNow.Ticks;
var elapsed = new TimeSpan(end - start).TotalMilliseconds;
var message = string.Format(Se.Language.General.XFilesConvertedInY, BatchItems.Count, elapsed);
if (_cancellationToken.IsCancellationRequested)
{
message += Environment.NewLine + Se.Language.General.ConversionCancelledByUser;
}
await ShowStatus(message);
}, _cancellationToken);
}
private async Task<bool> EnsurePaddleOcrAvailable(BatchConvertConfig config)
{
if (Window == null || Configuration.IsRunningOnMac)
{
return true;
}
if (config.IsTargetFormatImageBased)
{
return true;
}
if (!Se.Settings.Tools.BatchConvert.OcrEngine.Equals("PaddleOCR", StringComparison.OrdinalIgnoreCase))
{
return true;
}
if (!BatchItems.Any(IsImageBasedInput))
{
return true;
}
if (Configuration.IsRunningOnWindows && !File.Exists(Path.Combine(Se.PaddleOcrFolder, "paddleocr.exe")))
{
var answer = await MessageBox.Show(
Window,
"Download Paddle OCR?",
$"{Environment.NewLine}\"Paddle OCR\" requires downloading Paddle OCR.{Environment.NewLine}{Environment.NewLine}Download and use Paddle OCR?",
MessageBoxButtons.Cancel,
MessageBoxIcon.Question,
"CPU",
"GPU CUDA 11",
"GPU CUDA 12");
if (answer == MessageBoxResult.Cancel)
{
return false;
}
var result = await _windowService.ShowDialogAsync<DownloadPaddleOcrWindow, DownloadPaddleOcrViewModel>(Window,
vm =>
{
var engine = PaddleOcrDownloadType.EngineCpu;
if (answer == MessageBoxResult.Custom1)
{
engine = PaddleOcrDownloadType.EngineCpu;
}
else if (answer == MessageBoxResult.Custom2)