-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAuto Target Encoder.pyw
More file actions
6574 lines (5060 loc) · 273 KB
/
Auto Target Encoder.pyw
File metadata and controls
6574 lines (5060 loc) · 273 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 __future__ import annotations
from sklearn .linear_model import LinearRegression
from sklearn .ensemble import RandomForestRegressor
import customtkinter as ctk
from customtkinter import filedialog
import tkinter as tk
from tkinter import ttk ,messagebox
import threading
import logging
import platform
import queue
import time
import json
import uuid
import os
import sys
import gc
import subprocess
import configparser
from pathlib import Path
from datetime import datetime
from typing import Dict ,List ,Optional ,Tuple
import concurrent .futures
import numpy as np
import psutil
import itertools
import hashlib
import sqlite3
import tempfile
import re
from dataclasses import dataclass
import select
import pickle
import warnings
warnings .filterwarnings ('ignore')
ctk .set_appearance_mode ("dark")
ctk .set_default_color_theme ("blue")
SUBPROCESS_FLAGS =0
if os .name =='nt':
SUBPROCESS_FLAGS =subprocess .CREATE_NO_WINDOW
def log_to_worker (task_id ,message ):
"""Default log function for workers"""
print (f"[Worker {task_id }] {message }")
@dataclass
class EncodingSettings :
ffmpeg_path :str
ffprobe_path :str
database_path :str
encoding_log_path :str
ffvship_path :str
max_workers :int
num_parallel_vmaf_runs :int
max_iterations :int
cpu_threads :int
encoder_type :str
nvenc_preset :str
nvenc_quality_mode :str
nvenc_advanced_params :str
svt_av1_preset :int
svt_av1_advanced_params :str
quality_metric_mode :str
target_score :float
quality_tolerance_percent :float
cq_search_min :int
cq_search_max :int
vmaf_targeting_mode :str
vmaf_target_percentile :float
sampling_method :str
sample_segment_duration :int
num_samples :int
master_sample_encoder :str
min_scene_changes_required :int
min_keyframes_required :int
skip_start_seconds :int
skip_end_seconds :int
ffmpeg_scenedetect_threshold :float
min_duration_seconds :int
min_filesize_mb :int
min_bitrate_4k_kbps :int
min_bitrate_1080p_kbps :int
min_bitrate_720p_kbps :int
enable_quality_cache :bool
enable_performance_log :bool
delete_source_file :bool
output_suffix :str
output_directory :str
use_different_input_directory :bool
input_directory :str
min_size_reduction_threshold :float
rename_skipped_files :bool
skipped_file_suffix :str
skipped_file_filter_suffix: str
skip_encoding_if_target_not_reached :bool
output_bit_depth :str
ml_extra_cq_check :bool
class FeatureExtractor :
"""Centralized feature extraction for consistent ML features across the application."""
@staticmethod
def extract_video_features (media_info :dict ,complexity_data :dict =None )->dict :
"""Extract all ML-relevant features from media info and complexity data."""
features ={
'resolution_pixels':0 ,
'width':0 ,
'height':0 ,
'source_bitrate_kbps':0 ,
'bitrate_per_pixel':0 ,
'complexity_score':0.5 ,
'scenes_per_minute':0 ,
'frame_rate':30.0 ,
'duration_seconds':0 ,
'aspect_ratio':1.778 ,
'is_hdr':0 ,
'is_10bit':0
}
if not media_info :
return features
if 'format'in media_info :
format_info =media_info ['format']
features ['duration_seconds']=float (format_info .get ('duration',0 ))
if features ['duration_seconds']>0 :
file_size_bits =float (format_info .get ('bit_rate',0 ))
if file_size_bits ==0 and 'size'in format_info :
file_size_bits =float (format_info .get ('size',0 ))*8
features ['source_bitrate_kbps']=file_size_bits /1000
video_stream =next ((s for s in media_info .get ('streams',[])
if s .get ('codec_type')=='video'),None )
if video_stream :
features ['width']=video_stream .get ('width',0 )
features ['height']=video_stream .get ('height',0 )
features ['resolution_pixels']=features ['width']*features ['height']
if features ['height']>0 :
features ['aspect_ratio']=features ['width']/features ['height']
try :
frame_rate_str =video_stream .get ('avg_frame_rate','30/1')
if '/'in frame_rate_str :
num ,den =map (float ,frame_rate_str .split ('/'))
if den >0 :
features ['frame_rate']=num /den
else :
features ['frame_rate']=float (frame_rate_str )
except :
features ['frame_rate']=30.0
if features ['resolution_pixels']>0 and features ['source_bitrate_kbps']>0 :
features ['bitrate_per_pixel']=(features ['source_bitrate_kbps']*1000 )/features ['resolution_pixels']
pix_fmt =video_stream .get ('pix_fmt','')
if '10'in pix_fmt or '12'in pix_fmt :
features ['is_10bit']=1
color_transfer =video_stream .get ('color_transfer','')
if 'smpte2084'in color_transfer or 'arib-std-b67'in color_transfer :
features ['is_hdr']=1
if complexity_data :
features ['complexity_score']=complexity_data .get ('complexity_score',0.5 )
features ['scenes_per_minute']=complexity_data .get ('scenes_per_minute',0 )
features ['scene_count']=complexity_data .get ('scene_count',0 )
features ['avg_scene_duration']=complexity_data .get ('avg_scene_duration',0 )
return features
@staticmethod
def get_encoder_features (settings :EncodingSettings )->dict :
"""Extract encoder-specific features."""
features ={
'is_nvenc':1 if settings .encoder_type =='nvenc'else 0 ,
'preset_num':0 ,
'is_10bit_output':0
}
if settings .encoder_type =='nvenc':
preset_str =settings .nvenc_preset .lower ()
if preset_str .startswith ('p'):
try :
features ['preset_num']=int (preset_str [1 :])
except :
features ['preset_num']=5
else :
features ['preset_num']=5
else :
features ['preset_num']=settings .svt_av1_preset
if settings .output_bit_depth =='10bit':
features ['is_10bit_output']=1
return features
class PredictionErrorAnalyzer:
"""Analyzes and learns from ML prediction errors to improve future predictions."""
def __init__(self, database_manager=None):
self.database_manager = database_manager
self.error_patterns = {}
self.content_signatures = {}
def get_content_signature(self, features: dict) -> str:
"""Create a signature for content type based on key features."""
# Group by resolution, complexity, and bitrate ranges
resolution_bucket = "4k" if features.get('resolution_pixels', 0) > 3000000 else \
"1080p" if features.get('resolution_pixels', 0) > 1000000 else \
"720p"
complexity_bucket = "high" if features.get('complexity_score', 0.5) > 0.7 else \
"medium" if features.get('complexity_score', 0.5) > 0.3 else \
"low"
motion_bucket = "high" if features.get('scenes_per_minute', 0) > 30 else \
"medium" if features.get('scenes_per_minute', 0) > 10 else \
"low"
return f"{resolution_bucket}_{complexity_bucket}_{motion_bucket}"
def analyze_error(self, features: dict, predicted_cq: int, optimal_cq: int,
predicted_score: float, actual_score: float) -> float:
"""Analyze prediction error and return correction factor."""
signature = self.get_content_signature(features)
if signature not in self.error_patterns:
self.error_patterns[signature] = []
error_data = {
'predicted_cq': predicted_cq,
'optimal_cq': optimal_cq,
'cq_error': optimal_cq - predicted_cq,
'score_error': actual_score - predicted_score,
'timestamp': time.time()
}
self.error_patterns[signature].append(error_data)
# Keep only recent errors (last 20 per signature)
self.error_patterns[signature] = self.error_patterns[signature][-20:]
# Calculate average correction needed for this content type
if len(self.error_patterns[signature]) >= 3:
recent_errors = self.error_patterns[signature][-10:]
avg_cq_error = np.mean([e['cq_error'] for e in recent_errors])
return avg_cq_error
return 0.0
def get_correction_factor(self, features: dict) -> float:
"""Get learned correction factor for this content type."""
signature = self.get_content_signature(features)
if signature in self.error_patterns and len(self.error_patterns[signature]) >= 3:
recent_errors = self.error_patterns[signature][-10:]
return np.mean([e['cq_error'] for e in recent_errors])
return 0.0
class PerformanceErrorAnalyzer:
"""Real-time ETA correction based on recent prediction errors."""
def __init__(self):
self.error_history = {} # Keyed by content signature
self.correction_factors = {}
def get_content_signature(self, features: dict, encoder_features: dict) -> str:
"""Create signature for similar encoding scenarios."""
resolution = "4k" if features.get('resolution_pixels', 0) > 3000000 else \
"1080p" if features.get('resolution_pixels', 0) > 1000000 else "720p"
complexity = "high" if features.get('complexity_score', 0.5) > 0.7 else \
"medium" if features.get('complexity_score', 0.5) > 0.3 else "low"
encoder = "nvenc" if encoder_features.get('is_nvenc') else "svt"
preset = encoder_features.get('preset_num', 5)
return f"{encoder}_{preset}_{resolution}_{complexity}"
def record_error(self, features: dict, encoder_features: dict,
predicted_fps: float, actual_fps: float):
"""Record prediction error for learning."""
signature = self.get_content_signature(features, encoder_features)
if signature not in self.error_history:
self.error_history[signature] = []
error_ratio = actual_fps / predicted_fps if predicted_fps > 0 else 1.0
self.error_history[signature].append({
'ratio': error_ratio,
'timestamp': time.time()
})
# Keep only recent errors (last 10)
self.error_history[signature] = self.error_history[signature][-10:]
# Update correction factor if we have enough data
if len(self.error_history[signature]) >= 3:
recent_ratios = [e['ratio'] for e in self.error_history[signature][-5:]]
self.correction_factors[signature] = np.median(recent_ratios)
def get_corrected_fps(self, predicted_fps: float, features: dict,
encoder_features: dict) -> float:
"""Apply learned correction to FPS prediction."""
signature = self.get_content_signature(features, encoder_features)
if signature in self.correction_factors:
correction = self.correction_factors[signature]
# Apply correction with dampening to avoid overcorrection
dampened_correction = 1.0 + (correction - 1.0) * 0.7
corrected = predicted_fps * dampened_correction
return max(corrected, 1.0) # Ensure positive FPS
return predicted_fps
def get_vmaf_subtype(settings: EncodingSettings) -> str:
"""Get the VMAF subtype string based on current settings."""
if settings.quality_metric_mode != 'vmaf':
return None
if settings.vmaf_targeting_mode == 'average':
return 'average'
elif settings.vmaf_targeting_mode == 'percentile':
return f'percentile_{int(settings.vmaf_target_percentile)}'
else:
return 'average' # Default fallback
class ModelPersistence :
"""Handles saving and loading of trained models."""
def __init__ (self ,model_dir :str =None ):
if model_dir is None :
model_dir =os .path .join (os .path .dirname (os .path .abspath (__file__ )),'ml_models')
self .model_dir =Path (model_dir )
self .model_dir .mkdir (exist_ok =True )
def save_model (self ,model ,model_name :str ,metadata :dict =None ):
"""Save a trained model with metadata."""
model_path =self .model_dir /f"{model_name }.pkl"
meta_path =self .model_dir /f"{model_name }_meta.json"
try :
with open (model_path ,'wb')as f :
pickle .dump (model ,f )
if metadata is None :
metadata ={}
metadata ['saved_at']=time .time ()
metadata ['model_name']=model_name
with open (meta_path ,'w')as f :
json .dump (metadata ,f ,indent =2 )
return True
except Exception as e :
print (f"Error saving model {model_name }: {e }")
return False
def load_model (self ,model_name :str )->tuple :
"""Load a model and its metadata."""
model_path =self .model_dir /f"{model_name }.pkl"
meta_path =self .model_dir /f"{model_name }_meta.json"
if not model_path .exists ():
return None ,None
try :
with open (model_path ,'rb')as f :
model =pickle .load (f )
metadata ={}
if meta_path .exists ():
with open (meta_path ,'r')as f :
metadata =json .load (f )
return model ,metadata
except Exception as e :
print (f"Error loading model {model_name }: {e }")
return None ,None
def get_model_age_hours (self ,model_name :str )->float :
"""Get age of model in hours."""
meta_path =self .model_dir /f"{model_name }_meta.json"
if not meta_path .exists ():
return float ('inf')
try :
with open (meta_path ,'r')as f :
metadata =json .load (f )
saved_at =metadata .get ('saved_at',0 )
return (time .time ()-saved_at )/3600
except :
return float ('inf')
class PerformanceModel:
"""Predicts encoding speed (FPS) based on video features using RandomForest."""
def __init__(self, model_persistence: ModelPersistence = None):
self.model = None
self.is_trained = False
self.feature_order = [
'resolution_pixels', 'source_bitrate_kbps', 'bitrate_per_pixel',
'complexity_score', 'scenes_per_minute', 'is_nvenc', 'preset_num',
'frame_rate', 'is_10bit', 'is_hdr'
]
self.model_persistence = model_persistence or ModelPersistence()
self.training_metadata = {}
self._load_or_init_model()
def _load_or_init_model(self):
"""Try to load existing model or initialize new one."""
model, metadata = self.model_persistence.load_model('performance_model')
if model is not None:
self.model = model
self.training_metadata = metadata
self.is_trained = True
print(f"Loaded existing PerformanceModel trained on {metadata.get('num_samples', 0)} samples")
else:
# Changed from LinearRegression to RandomForestRegressor
self.model = RandomForestRegressor(
n_estimators=50,
random_state=42,
max_depth=10,
n_jobs=-1
)
self.is_trained = False
def train(self, db_records: list):
"""Train the model on historical performance data."""
if len(db_records) < 15:
print(f"PerformanceModel: Not enough data ({len(db_records)} records). Need at least 15.")
return
features = []
targets = []
for record in db_records:
try:
if not record.get('final_encode_fps') or record['final_encode_fps'] <= 0:
continue
if record.get('skipped_on_failure'):
continue
feature_set = {}
for feature in self.feature_order:
if feature == 'is_nvenc':
feature_set[feature] = 1 if record.get('encoder_type') == 'nvenc' else 0
elif feature == 'preset_num':
preset = str(record.get('preset', '5'))
if preset.startswith('p'):
feature_set[feature] = int(preset[1:]) if preset[1:].isdigit() else 5
else:
feature_set[feature] = int(preset) if preset.isdigit() else 5
else:
feature_set[feature] = float(record.get(feature, 0) or 0)
feature_vector = [feature_set[f] for f in self.feature_order]
features.append(feature_vector)
targets.append(record['final_encode_fps'])
except Exception as e:
continue
if len(features) < 15:
print(f"PerformanceModel: Only {len(features)} valid records after filtering.")
return
X = np.array(features)
y = np.array(targets)
# Changed from LinearRegression to RandomForestRegressor
self.model = RandomForestRegressor(
n_estimators=50,
random_state=42,
max_depth=10,
n_jobs=-1
)
self.model.fit(X, y)
self.is_trained = True
train_score = self.model.score(X, y)
self.training_metadata = {
'num_samples': len(X),
'train_score': train_score,
'mean_fps': float(np.mean(y)),
'std_fps': float(np.std(y)),
'trained_at': time.time()
}
self.model_persistence.save_model(self.model, 'performance_model', self.training_metadata)
print(f"PerformanceModel: Trained on {len(X)} samples, R² = {train_score:.3f}")
def update_model_incrementally(self, new_records: list, max_samples: int = 500):
"""Update model with recent data without full retrain."""
if len(new_records) < 5:
return False
# Get existing training data
if database_manager:
existing_records = database_manager.get_all_performance_records(limit=max_samples)
# Combine with new records (new ones first)
all_records = new_records + existing_records[:max_samples - len(new_records)]
# Retrain
self.train(all_records)
print(f"Performance model updated with {len(new_records)} new samples")
return True
return False
def predict_fps(self, file_features: dict, encoder_features: dict = None) -> tuple[float, str]:
"""Predict encoding FPS with confidence level."""
all_features = file_features.copy()
if encoder_features:
all_features.update(encoder_features)
if not self.is_trained:
base_fps = 200 if all_features.get('is_nvenc') else 50
resolution_factor = (1920 * 1080) / max(all_features.get('resolution_pixels', 1920 * 1080), 1)
complexity_factor = 1.0 - (all_features.get('complexity_score', 0.5) * 0.5)
estimated_fps = base_fps * resolution_factor * complexity_factor
return max(estimated_fps, 5.0), 'low'
try:
feature_vector = np.array([[all_features.get(f, 0) for f in self.feature_order]])
# Get predictions from all trees for confidence assessment
if hasattr(self.model, 'estimators_'):
tree_predictions = [est.predict(feature_vector)[0] for est in self.model.estimators_]
predicted_fps = np.mean(tree_predictions)
prediction_std = np.std(tree_predictions)
# Determine confidence based on prediction variance
if prediction_std < predicted_fps * 0.1: # Less than 10% variance
confidence = 'high'
elif prediction_std < predicted_fps * 0.25: # Less than 25% variance
confidence = 'medium'
else:
confidence = 'low'
else:
predicted_fps = self.model.predict(feature_vector)[0]
confidence = 'medium'
# Clip to reasonable ranges
if all_features.get('is_nvenc'):
predicted_fps = np.clip(predicted_fps, 10, 1000)
else:
predicted_fps = np.clip(predicted_fps, 1, 200)
return max(predicted_fps, 5.0), confidence
except Exception as e:
print(f"PerformanceModel prediction error: {e}")
base_fps = 200 if all_features.get('is_nvenc') else 50
return base_fps, 'low'
class SamplingTimePredictor:
"""Predicts sample creation time using a simple linear model."""
def __init__(self, model_persistence: ModelPersistence = None):
self.model = None
self.is_trained = False
self.feature_order = [
'total_sample_duration_s', 'resolution_pixels',
'source_bitrate_kbps', 'is_nvenc_sample_encoder'
]
self.model_persistence = model_persistence or ModelPersistence()
self.training_metadata = {}
self._load_or_init_model()
def _load_or_init_model(self):
model, metadata = self.model_persistence.load_model('sampling_time_model')
if model is not None:
self.model = model
self.training_metadata = metadata
self.is_trained = True
print(f"Loaded existing SamplingTimePredictor trained on {metadata.get('num_samples', 0)} samples")
else:
self.model = LinearRegression()
self.is_trained = False
def train(self, db_records: list):
if len(db_records) < 20:
print(f"SamplingTimePredictor: Not enough data ({len(db_records)} records). Need at least 20.")
return
features = []
targets = []
for record in db_records:
try:
if not record.get('sample_creation_time') or record['sample_creation_time'] <= 0:
continue
feature_set = {
'total_sample_duration_s': float(record.get('total_sample_duration_s', 0)),
'resolution_pixels': float(record.get('resolution_pixels', 0)),
'source_bitrate_kbps': float(record.get('source_bitrate_kbps', 0)),
'is_nvenc_sample_encoder': 1 if record.get('master_sample_encoder') == 'nvenc' else 0
}
feature_vector = [feature_set[f] for f in self.feature_order]
features.append(feature_vector)
targets.append(record['sample_creation_time'])
except (ValueError, TypeError):
continue
if len(features) < 20:
return
X = np.array(features)
y = np.array(targets)
self.model.fit(X, y)
self.is_trained = True
train_score = self.model.score(X, y)
self.training_metadata = {'num_samples': len(X), 'train_score': train_score}
self.model_persistence.save_model(self.model, 'sampling_time_model', self.training_metadata)
print(f"SamplingTimePredictor: Trained on {len(X)} samples, R² = {train_score:.3f}")
def predict(self, features_dict: dict) -> float:
if not self.is_trained:
# Fallback heuristic if model is not trained
return 15.0 + (features_dict.get('total_sample_duration_s', 12) * 1.5)
try:
feature_vector = np.array([[features_dict.get(f, 0) for f in self.feature_order]])
prediction = self.model.predict(feature_vector)[0]
return max(prediction, 5.0) # Ensure a minimum predicted time
except Exception:
return 30.0 # Safe fallback on error
class SearchTimePredictor:
"""Predicts CQ search time using a simple linear model."""
def __init__(self, model_persistence: ModelPersistence = None):
self.model = None
self.is_trained = False
self.feature_order = [
'search_iterations', 'resolution_pixels', 'total_sample_duration_s'
]
self.model_persistence = model_persistence or ModelPersistence()
self.training_metadata = {}
self._load_or_init_model()
def _load_or_init_model(self):
model, metadata = self.model_persistence.load_model('search_time_model')
if model is not None:
self.model = model
self.training_metadata = metadata
self.is_trained = True
print(f"Loaded existing SearchTimePredictor trained on {metadata.get('num_samples', 0)} samples")
else:
self.model = LinearRegression()
self.is_trained = False
def train(self, db_records: list):
if len(db_records) < 20:
print(f"SearchTimePredictor: Not enough data ({len(db_records)} records). Need at least 20.")
return
features = []
targets = []
for record in db_records:
try:
if not record.get('quality_search_time') or record['quality_search_time'] <= 0 or not record.get('search_iterations'):
continue
feature_set = {
'search_iterations': int(record.get('search_iterations', 0)),
'resolution_pixels': float(record.get('resolution_pixels', 0)),
'total_sample_duration_s': float(record.get('total_sample_duration_s', 0))
}
feature_vector = [feature_set[f] for f in self.feature_order]
features.append(feature_vector)
targets.append(record['quality_search_time'])
except (ValueError, TypeError):
continue
if len(features) < 20:
return
X = np.array(features)
y = np.array(targets)
self.model.fit(X, y)
self.is_trained = True
train_score = self.model.score(X, y)
self.training_metadata = {'num_samples': len(X), 'train_score': train_score}
self.model_persistence.save_model(self.model, 'search_time_model', self.training_metadata)
print(f"SearchTimePredictor: Trained on {len(X)} samples, R² = {train_score:.3f}")
def predict(self, features_dict: dict) -> float:
if not self.is_trained:
# Fallback heuristic if model is not trained
return 20.0 + (features_dict.get('search_iterations', 2) * 15.0)
try:
feature_vector = np.array([[features_dict.get(f, 0) for f in self.feature_order]])
prediction = self.model.predict(feature_vector)[0]
return max(prediction, 10.0) # Ensure a minimum predicted time
except Exception:
return 45.0 # Safe fallback on error
class QualityModel:
def __init__(self, encoder_type: str, metric_name: str = 'vmaf', metric_subtype: str = None, model_persistence: ModelPersistence = None):
self.encoder_type = encoder_type.lower()
self.metric_name = metric_name.lower()
self.metric_subtype = metric_subtype
self.model = None
self.is_trained = False
self.feature_order = [
'cq', 'resolution_pixels', 'source_bitrate_kbps',
'bitrate_per_pixel', 'complexity_score', 'scenes_per_minute',
'frame_rate', 'is_10bit', 'is_hdr',
# Added encoder-specific features
'is_nvenc', 'preset_num'
]
self.model_persistence = model_persistence or ModelPersistence()
self.training_metadata = {}
self._load_or_init_model()
def _get_model_name(self) -> str:
"""Get the model name for this specific encoder, metric, and subtype."""
base_name = f'quality_model_{self.encoder_type}_{self.metric_name}'
if self.metric_name == 'vmaf' and self.metric_subtype:
return f'{base_name}_{self.metric_subtype}'
return base_name
def _load_or_init_model(self):
"""Try to load existing model or initialize new one."""
model_name = self._get_model_name()
model, metadata = self.model_persistence.load_model(model_name)
if model is not None:
self.model = model
self.training_metadata = metadata
self.is_trained = True
subtype_info = f" ({self.metric_subtype})" if self.metric_subtype else ""
print(f"Loaded existing QualityModel for {self.encoder_type.upper()}/{self.metric_name.upper()}{subtype_info} trained on {metadata.get('num_samples', 0)} samples")
else:
self.model = RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=-1, max_depth=10)
self.is_trained = False
subtype_info = f" ({self.metric_subtype})" if self.metric_subtype else ""
print(f"Initialized new QualityModel for {self.encoder_type.upper()}/{self.metric_name.upper()}{subtype_info}")
def train(self, all_quality_records: list):
"""Train the model on historical quality test data for this specific encoder, metric, and subtype."""
# 1. Filter records for the current encoder
encoder_records = [r for r in all_quality_records if r.get('encoder_type', '').lower() == self.encoder_type]
# 2. Filter by metric and subtype
if self.metric_name == 'vmaf' and self.metric_subtype:
metric_records = [r for r in encoder_records
if r.get('metric_name', '').lower() == self.metric_name
and r.get('metric_subtype', '').lower() == self.metric_subtype.lower()]
else:
metric_records = [r for r in encoder_records
if r.get('metric_name', '').lower() == self.metric_name]
model_id = f"{self.encoder_type.upper()}/{self.metric_name.upper()}" + (f" ({self.metric_subtype})" if self.metric_subtype else "")
if len(metric_records) < 50:
print(f"QualityModel ({model_id}): Not enough data ({len(metric_records)} records). Need at least 50.")
return
features = []
targets = []
for record in metric_records:
try:
if not record.get('score') or record['score'] <= 0 or not record.get('cq'):
continue
feature_set = {k: float(v or 0) for k, v in record.items() if k in self.feature_order and k not in ['is_nvenc', 'preset_num']}
# Manually add encoder features
feature_set['is_nvenc'] = 1 if record.get('encoder_type') == 'nvenc' else 0
preset = str(record.get('preset','5'))
if preset.startswith('p'):
feature_set['preset_num'] = int(preset[1:]) if preset[1:].isdigit() else 5
else:
feature_set['preset_num'] = int(preset) if preset.isdigit() else 5
feature_vector = [feature_set.get(f, 0) for f in self.feature_order]
features.append(feature_vector)
targets.append(record['score'])
except (ValueError, TypeError):
continue
if len(features) < 50:
print(f"QualityModel ({model_id}): Only {len(features)} valid records after filtering.")
return
X = np.array(features)
y = np.array(targets)
split_idx = int(len(X) * 0.8)
X_train, X_val = X[:split_idx], X[split_idx:]
y_train, y_val = y[:split_idx], y[split_idx:]
self.model = RandomForestRegressor(n_estimators=50, random_state=42, n_jobs=-1, max_depth=10)
self.model.fit(X_train, y_train)
self.is_trained = True
train_score = self.model.score(X_train, y_train)
val_score = self.model.score(X_val, y_val) if len(X_val) > 0 else train_score
self.training_metadata = {
'num_samples': len(X), 'train_score': train_score, 'val_score': val_score,
'mean_score': float(np.mean(y)), 'std_score': float(np.std(y)),
'encoder_type': self.encoder_type, 'metric_name': self.metric_name, 'metric_subtype': self.metric_subtype,
'trained_at': time.time()
}
model_name = self._get_model_name()
self.model_persistence.save_model(self.model, model_name, self.training_metadata)
print(f"QualityModel ({model_id}): Trained on {len(X)} samples, Train R² = {train_score:.3f}, Val R² = {val_score:.3f}")
def predict_with_confidence(self, file_features: dict, encoder_features: dict,
target_score: float, tolerance: float,
cq_min: int, cq_max: int) -> tuple:
"""Predict optimal CQ with confidence assessment."""
if not self.is_trained:
return None, None, 'none', {}
try:
# Get predictions from all trees for confidence assessment
predictions = {}
all_trees_predictions = []
for cq in range(cq_min, cq_max + 1):
feature_dict = {**file_features, **encoder_features, 'cq': cq}
feature_vector = np.array([[feature_dict.get(f, 0) for f in self.feature_order]])
# Get predictions from each tree
tree_predictions = [est.predict(feature_vector)[0] for est in self.model.estimators_]
predictions[cq] = {
'mean': np.mean(tree_predictions),
'std': np.std(tree_predictions)
}
all_trees_predictions.append(tree_predictions)
# Find CQ values within tolerance
valid_cqs = []
for cq, pred in predictions.items():
if target_score - tolerance <= pred['mean'] <= target_score + tolerance:
valid_cqs.append(cq)
if not valid_cqs:
# Find closest if none in range
best_cq = min(predictions.keys(),
key=lambda x: abs(predictions[x]['mean'] - target_score))
else:
# Get highest CQ (best compression) within tolerance
best_cq = max(valid_cqs)
# Calculate confidence based on prediction variance
prediction_std = predictions[best_cq]['std']
# Also check consistency across neighboring CQs
if best_cq > cq_min and best_cq < cq_max:
neighbor_scores = [
predictions.get(best_cq - 1, {}).get('mean', 0),
predictions[best_cq]['mean'],
predictions.get(best_cq + 1, {}).get('mean', 0)
]
score_gradient = np.diff(neighbor_scores)
gradient_consistency = np.std(score_gradient)
else:
gradient_consistency = 1.0
# Determine confidence level
if prediction_std < 1.0 and gradient_consistency < 0.5:
confidence = 'high'
elif prediction_std < 2.0 and gradient_consistency < 1.0:
confidence = 'medium'
else:
confidence = 'low'
return best_cq, predictions[best_cq]['mean'], confidence, predictions
except Exception as e:
print(f"Error in predict_with_confidence: {e}")
return None, None, 'none', {}
def predict_score(self, file_features: dict, encoder_features: dict, cq: int) -> tuple[float, float]:
"""Predict quality score with confidence interval."""
if not self.is_trained:
return None, None
try:
feature_dict = {**file_features, **encoder_features, 'cq': cq}
feature_vector = np.array([[feature_dict.get(f, 0) for f in self.feature_order]])
predictions = np.array([est.predict(feature_vector)[0] for est in self.model.estimators_])
return np.mean(predictions), np.std(predictions)
except Exception as e:
model_id = f"{self.encoder_type.upper()}/{self.metric_name.upper()}"
print(f"QualityModel ({model_id}) prediction error: {e}")
return None, None
def predict_cq_curve(self, file_features: dict, encoder_features: dict, cq_min: int, cq_max: int) -> dict:
"""Predict quality scores for all CQ values in range."""
if not self.is_trained: return {}
return {cq: {'score': s, 'confidence': c} for cq in range(cq_min, cq_max + 1) if (s_c := self.predict_score(file_features, encoder_features, cq)) and (s := s_c[0]) is not None and (c := s_c[1]) is not None}
def suggest_cq_range(self, file_features: dict, encoder_features: dict, target_score: float,
tolerance: float, cq_min: int, cq_max: int) -> tuple[int, int, dict]:
"""Suggest narrowed CQ range likely to contain target score."""
if not self.is_trained:
return cq_min, cq_max, {}
predictions = self.predict_cq_curve(file_features, encoder_features, cq_min, cq_max)
if not predictions:
return cq_min, cq_max, {}
candidates = [cq for cq, pred in predictions.items() if target_score - tolerance <= pred['score'] <= target_score + tolerance]
if candidates:
suggested_min = max(cq_min, min(candidates) - 2)
suggested_max = min(cq_max, max(candidates) + 2)
else:
best_cq = min(predictions.keys(), key=lambda x: abs(predictions[x]['score'] - target_score))
suggested_min = max(cq_min, best_cq - 5)
suggested_max = min(cq_max, best_cq + 5)