Core Module¶
Core components for orchestration and configuration.
Orchestrator¶
orchestrator
¶
Orchestrator for video conversion workflow.
This module implements the central Orchestrator class that coordinates the entire video conversion workflow from discovery to completion.
SDS Reference: SDS-C01-002 SRS Reference: SRS-601 (Orchestrator Workflow)
Example
from video_converter.core.orchestrator import Orchestrator from video_converter.core import ConversionRequest
orchestrator = Orchestrator()
Convert a single file¶
result = await orchestrator.convert_single( ... input_path=Path("input.mov"), ... output_path=Path("output.mp4"), ... )
Run batch conversion with progress tracking¶
def on_progress(progress): ... print(f"Progress: {progress.overall_progress:.1%}")
report = await orchestrator.run( ... input_paths=[Path("video1.mov"), Path("video2.mov")], ... output_dir=Path("converted"), ... on_progress=on_progress, ... ) print(f"Converted: {report.successful}/{report.total_files}")
OrchestratorConfig
dataclass
¶
OrchestratorConfig(mode=HARDWARE, quality=DEFAULT_QUALITY, crf=DEFAULT_CRF, preset='medium', output_suffix='_h265', preserve_metadata=True, preserve_timestamps=True, validate_output=True, validation_strictness=STANDARD, max_concurrent=DEFAULT_CONCURRENT_CONVERSIONS, delete_original=False, move_to_processed=None, move_to_failed=None, queue_priority=FIFO, enable_retry=True, retry_config=None, check_disk_space=True, min_free_space=MIN_FREE_DISK_SPACE, pause_on_disk_full=True, enable_notifications=True, notification_config=None, auto_download_icloud=True, icloud_timeout=ICLOUD_DOWNLOAD_TIMEOUT, skip_icloud_on_timeout=True, enable_vmaf=False, vmaf_threshold=VMAF_THRESHOLD_VISUALLY_LOSSLESS, vmaf_sample_interval=VMAF_DEFAULT_SAMPLE_INTERVAL, vmaf_fail_action='warn')
Configuration for the Orchestrator.
Attributes:
| Name | Type | Description |
|---|---|---|
mode |
ConversionMode
|
Preferred conversion mode (hardware or software). |
quality |
int
|
Quality setting for encoding (1-100). |
crf |
int
|
Constant Rate Factor for software encoding. |
preset |
str
|
Encoding preset for software encoding. |
output_suffix |
str
|
Suffix to add to output filenames. |
preserve_metadata |
bool
|
Whether to copy metadata from original. |
preserve_timestamps |
bool
|
Whether to sync timestamps from original. |
validate_output |
bool
|
Whether to validate converted files. |
validation_strictness |
ValidationStrictness
|
How strictly to validate output. |
max_concurrent |
int
|
Maximum concurrent conversions. |
delete_original |
bool
|
Whether to delete original after success. |
move_to_processed |
Path | None
|
Directory to move processed originals. |
move_to_failed |
Path | None
|
Directory to move failed files. |
queue_priority |
QueuePriority
|
Priority ordering for batch queue. |
enable_retry |
bool
|
Whether to retry failed conversions. |
retry_config |
RetryConfig | None
|
Configuration for retry behavior. |
check_disk_space |
bool
|
Whether to check disk space before processing. |
min_free_space |
int
|
Minimum free disk space in bytes (default 1GB). |
pause_on_disk_full |
bool
|
Whether to pause on low disk space. |
enable_notifications |
bool
|
Whether to send macOS notifications. |
notification_config |
NotificationConfig | None
|
Configuration for notification behavior. |
auto_download_icloud |
bool
|
Whether to auto-download iCloud files for folders. |
icloud_timeout |
int
|
Maximum time to wait for iCloud downloads in seconds. |
skip_icloud_on_timeout |
bool
|
Whether to skip files if download times out. |
enable_vmaf |
bool
|
Whether to measure VMAF quality score after conversion. |
vmaf_threshold |
float
|
Minimum acceptable VMAF score (default 93.0 for visually lossless). |
vmaf_sample_interval |
int
|
Frame sampling interval for VMAF analysis (1=all, 30=faster). |
vmaf_fail_action |
str
|
Action when VMAF is below threshold ("warn", "retry", "fail"). |
ConversionTask
dataclass
¶
A single video conversion task in the queue.
Attributes:
| Name | Type | Description |
|---|---|---|
input_path |
Path
|
Path to input video. |
output_path |
Path
|
Path for output video. |
status |
ConversionStatus
|
Current status of the task. |
result |
ConversionResult | None
|
Conversion result (when complete). |
error |
str | None
|
Error message (if failed). |
Orchestrator
¶
Orchestrator(config=None, converter_factory=None, validator=None, timestamp_synchronizer=None, session_manager=None, enable_session_persistence=True, retry_manager=None, error_recovery_manager=None)
Coordinates the video conversion workflow.
The Orchestrator manages the entire conversion pipeline: 1. Discovery - Finding videos to convert 2. Queueing - Managing the conversion queue 3. Converting - Running the encoder 4. Validating - Verifying output integrity 5. Cleanup - Moving/deleting files 6. Reporting - Generating conversion reports
Attributes:
| Name | Type | Description |
|---|---|---|
config |
Orchestrator configuration. |
|
converter_factory |
Factory for creating converters. |
|
validator |
Video file validator. |
|
timestamp_synchronizer |
Timestamp synchronization handler. |
|
session_manager |
SessionStateManager | None
|
Session state manager for persistence. |
Initialize the Orchestrator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
OrchestratorConfig | None
|
Optional configuration. Uses defaults if not provided. |
None
|
converter_factory
|
ConverterFactory | None
|
Optional converter factory. |
None
|
validator
|
VideoValidator | None
|
Optional video validator. |
None
|
timestamp_synchronizer
|
TimestampSynchronizer | None
|
Optional timestamp synchronizer. |
None
|
session_manager
|
SessionStateManager | None
|
Optional session state manager. |
None
|
enable_session_persistence
|
bool
|
Whether to enable session persistence. |
True
|
retry_manager
|
RetryManager | None
|
Optional retry manager for failed conversions. |
None
|
error_recovery_manager
|
ErrorRecoveryManager | None
|
Optional error recovery manager. |
None
|
Source code in src/video_converter/core/orchestrator.py
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 | |
convert_single
async
¶
convert_single(input_path, output_path=None, on_progress=None, video_info=None, on_progress_info=None)
Convert a single video file through the full pipeline.
Handles both local files and iCloud files. For iCloud files, automatically downloads before conversion if auto_download_icloud is enabled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
Path
|
Path to the input video. |
required |
output_path
|
Path | None
|
Path for the output video. Auto-generated if None. |
None
|
on_progress
|
ProgressCallback | None
|
Optional progress callback for pipeline stage updates. |
None
|
video_info
|
FolderVideoInfo | None
|
Optional FolderVideoInfo with iCloud status. |
None
|
on_progress_info
|
Callable[[ProgressInfo], None] | None
|
Optional progress callback for detailed FFmpeg progress (percentage, speed, current size, ETA). |
None
|
Returns:
| Type | Description |
|---|---|
ConversionResult
|
ConversionResult with success status and statistics. |
Source code in src/video_converter/core/orchestrator.py
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 | |
run
async
¶
Run batch conversion on multiple files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_paths
|
list[Path]
|
List of input video paths. |
required |
output_dir
|
Path | None
|
Directory for output files. Uses original dirs if None. |
None
|
on_progress
|
ProgressCallback | None
|
Optional progress callback. |
None
|
on_complete
|
CompleteCallback | None
|
Optional completion callback. |
None
|
resume_session
|
bool
|
If True, try to resume an interrupted session. |
False
|
Returns:
| Type | Description |
|---|---|
ConversionReport
|
ConversionReport with batch statistics. |
Source code in src/video_converter/core/orchestrator.py
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 | |
resume_session
async
¶
Resume an interrupted or paused session from disk.
This method loads a previously saved session and continues processing any pending videos.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on_progress
|
ProgressCallback | None
|
Optional progress callback. |
None
|
on_complete
|
CompleteCallback | None
|
Optional completion callback. |
None
|
Returns:
| Type | Description |
|---|---|
ConversionReport | None
|
ConversionReport if resumed successfully, None if no session to resume. |
Source code in src/video_converter/core/orchestrator.py
has_resumable_session
¶
Check if there is a resumable session available.
Returns:
| Type | Description |
|---|---|
bool
|
True if a session can be resumed, False otherwise. |
Source code in src/video_converter/core/orchestrator.py
get_session_status
¶
Get the current session status.
Returns:
| Type | Description |
|---|---|
dict | None
|
Session status dictionary, or None if no session. |
Source code in src/video_converter/core/orchestrator.py
run_directory
async
¶
Run batch conversion on a directory.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dir
|
Path
|
Directory containing videos. |
required |
output_dir
|
Path | None
|
Directory for output files. |
None
|
recursive
|
bool
|
Whether to search subdirectories. |
False
|
on_progress
|
ProgressCallback | None
|
Optional progress callback. |
None
|
on_complete
|
CompleteCallback | None
|
Optional completion callback. |
None
|
Returns:
| Type | Description |
|---|---|
ConversionReport
|
ConversionReport with batch statistics. |
Source code in src/video_converter/core/orchestrator.py
cancel
¶
Cancel the current conversion operation.
Source code in src/video_converter/core/orchestrator.py
pause
¶
Pause the batch conversion.
Pauses after the current file completes.
Returns:
| Type | Description |
|---|---|
bool
|
True if paused, False if not running. |
Source code in src/video_converter/core/orchestrator.py
resume
¶
Resume a paused batch conversion.
This resumes a batch that was paused in the current session. To resume a saved session from disk, use resume_session() instead.
Returns:
| Type | Description |
|---|---|
bool
|
True if resumed, False if not paused. |
Source code in src/video_converter/core/orchestrator.py
get_batch_status
¶
is_paused
¶
Check if batch conversion is paused.
Returns:
| Type | Description |
|---|---|
bool
|
True if paused, False otherwise. |
get_pending_tasks
¶
Get list of pending tasks.
Returns:
| Type | Description |
|---|---|
list[ConversionTask]
|
List of tasks not yet completed. |
get_completed_tasks
¶
Get list of completed tasks.
Returns:
| Type | Description |
|---|---|
list[ConversionTask]
|
List of successfully completed tasks. |
Source code in src/video_converter/core/orchestrator.py
get_failed_tasks
¶
convert_single_sync
¶
Synchronous wrapper for convert_single.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_path
|
Path
|
Path to the input video. |
required |
output_path
|
Path | None
|
Path for the output video. |
None
|
on_progress
|
ProgressCallback | None
|
Optional progress callback. |
None
|
Returns:
| Type | Description |
|---|---|
ConversionResult
|
ConversionResult with success status and statistics. |
Source code in src/video_converter/core/orchestrator.py
run_sync
¶
Synchronous wrapper for run.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_paths
|
list[Path]
|
List of input video paths. |
required |
output_dir
|
Path | None
|
Directory for output files. |
None
|
on_progress
|
ProgressCallback | None
|
Optional progress callback. |
None
|
on_complete
|
CompleteCallback | None
|
Optional completion callback. |
None
|
Returns:
| Type | Description |
|---|---|
ConversionReport
|
ConversionReport with batch statistics. |
Source code in src/video_converter/core/orchestrator.py
check_disk_space
¶
Check if there is sufficient disk space for conversion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path | None
|
Path to check. Uses output directory or home if None. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[bool, dict]
|
Tuple of (has_sufficient_space, disk_info_dict). |
Source code in src/video_converter/core/orchestrator.py
get_failure_records
¶
Get list of all recorded failures.
Returns:
| Type | Description |
|---|---|
list[FailureRecord]
|
List of FailureRecord objects from this session. |
get_retryable_failures
¶
Get list of failures that can be retried.
Returns:
| Type | Description |
|---|---|
list[FailureRecord]
|
List of retryable FailureRecord objects. |
Source code in src/video_converter/core/orchestrator.py
retry_failed
async
¶
Retry a failed conversion.
This method allows manual retry of a specific failed conversion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
FailureRecord
|
The FailureRecord to retry. |
required |
on_progress
|
ProgressCallback | None
|
Optional progress callback. |
None
|
Returns:
| Type | Description |
|---|---|
ConversionResult
|
ConversionResult with retry outcome. |
Source code in src/video_converter/core/orchestrator.py
retry_all_failed
async
¶
Retry all failed conversions that are retryable.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on_progress
|
ProgressCallback | None
|
Optional progress callback. |
None
|
Returns:
| Type | Description |
|---|---|
ConversionReport
|
ConversionReport with retry results. |
Source code in src/video_converter/core/orchestrator.py
retry_failed_sync
¶
Synchronous wrapper for retry_failed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
FailureRecord
|
The FailureRecord to retry. |
required |
on_progress
|
ProgressCallback | None
|
Optional progress callback. |
None
|
Returns:
| Type | Description |
|---|---|
ConversionResult
|
ConversionResult with retry outcome. |
Source code in src/video_converter/core/orchestrator.py
retry_all_failed_sync
¶
Synchronous wrapper for retry_all_failed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
on_progress
|
ProgressCallback | None
|
Optional progress callback. |
None
|
Returns:
| Type | Description |
|---|---|
ConversionReport
|
ConversionReport with retry results. |
Source code in src/video_converter/core/orchestrator.py
get_failure_summary
¶
Get summary of all recorded failures.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary with failure statistics. |
clear_failure_records
¶
Clear all failure records.
Returns:
| Type | Description |
|---|---|
int
|
Number of records cleared. |
get_pause_reason
¶
Get the reason for pause if paused.
Returns:
| Type | Description |
|---|---|
str | None
|
Pause reason string, or None if not paused. |
send_notification
¶
Send a custom notification.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
title
|
str
|
The notification title. |
required |
body
|
str
|
The notification body text. |
required |
sound
|
bool | None
|
Whether to play sound. Uses config default if None. |
None
|
Returns:
| Type | Description |
|---|---|
bool
|
True if notification was sent successfully. |
Source code in src/video_converter/core/orchestrator.py
Config¶
config
¶
Configuration management system for video converter.
This module provides a centralized configuration system that loads, validates, and saves user preferences in JSON format. It supports both default and user-customized settings with environment variable overrides.
SDS Reference: SDS-C01-003 SRS Reference: SRS-102 (Configuration Management)
Example
from video_converter.core.config import Config config = Config.load() print(config.encoding.mode) # "hardware" config.encoding.quality = 50 config.save()
Environment variable override¶
VIDEO_CONVERTER_ENCODING__MODE=software¶
config = Config.load() print(config.encoding.mode) # "software"
EncodingConfig
¶
Bases: BaseModel
Encoding settings for video conversion.
Attributes:
| Name | Type | Description |
|---|---|---|
mode |
Literal['hardware', 'software']
|
Encoding mode - "hardware" (VideoToolbox) or "software" (libx265). |
quality |
int
|
Quality setting (1-100, higher is better). |
crf |
int
|
Constant Rate Factor for encoding (18-28, lower is better quality). |
preset |
Literal['fast', 'medium', 'slow']
|
Encoding preset affecting speed vs compression trade-off. |
bit_depth |
Literal[8, 10]
|
Output bit depth (8 or 10). 10-bit for HDR content. |
hdr |
bool
|
Enable HDR encoding parameters for 10-bit content. |
PathsConfig
¶
Bases: BaseModel
Path settings for file management.
Attributes:
| Name | Type | Description |
|---|---|---|
output |
Path
|
Directory for converted output files. |
processed |
Path
|
Directory for successfully processed original files. |
failed |
Path
|
Directory for files that failed conversion. |
expand_path
classmethod
¶
Expand user home directory in paths.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
str | Path
|
Path value (string or Path). |
required |
Returns:
| Type | Description |
|---|---|
Path
|
Path with ~ expanded to user home directory. |
Source code in src/video_converter/core/config.py
AutomationConfig
¶
Bases: BaseModel
Automation settings for scheduled conversions.
Attributes:
| Name | Type | Description |
|---|---|---|
enabled |
bool
|
Whether automation is enabled. |
schedule |
Literal['hourly', 'daily', 'weekly']
|
Schedule type ("daily", "hourly", etc.). |
time |
str
|
Time of day to run (HH:MM format). |
PhotosConfig
¶
Bases: BaseModel
Photos library settings.
Attributes:
| Name | Type | Description |
|---|---|---|
include_albums |
list[str]
|
List of album names to include (empty = all). |
exclude_albums |
list[str]
|
List of album names to exclude. |
download_from_icloud |
bool
|
Whether to download videos from iCloud. |
icloud_timeout |
int
|
Maximum time to wait for iCloud downloads in seconds. |
skip_cloud_only |
bool
|
Skip videos that are only in iCloud (don't download). |
FolderConfig
¶
Bases: BaseModel
Folder-based video scanning settings.
Settings for scanning videos from filesystem directories, including iCloud Drive folders with stub files.
SRS Reference: SRS-304 (Folder-based Video Extraction)
Attributes:
| Name | Type | Description |
|---|---|---|
recursive |
bool
|
Whether to scan subdirectories. |
auto_download_icloud |
bool
|
Whether to auto-download iCloud stub files. |
icloud_timeout |
int
|
Maximum time to wait for iCloud downloads in seconds. |
skip_icloud_on_timeout |
bool
|
Skip file if download times out. |
include_patterns |
list[str]
|
Glob patterns to include (e.g., ["vacation*"]). |
exclude_patterns |
list[str]
|
Glob patterns to exclude (e.g., [".tmp", "._"]). |
VmafConfig
¶
Bases: BaseModel
VMAF quality analysis settings.
VMAF (Video Multimethod Assessment Fusion) is a perceptual video quality assessment algorithm that predicts subjective quality scores.
Attributes:
| Name | Type | Description |
|---|---|---|
enabled |
bool
|
Whether to measure VMAF quality score after conversion. |
threshold |
float
|
Minimum acceptable VMAF score (0-100). 93.0 is visually lossless. |
sample_interval |
int
|
Frame sampling interval for VMAF analysis (1=all, 30=faster). |
fail_action |
Literal['warn', 'retry', 'fail']
|
Action when VMAF is below threshold. - "warn": Log warning but keep file. - "retry": Retry with adjusted settings. - "fail": Delete file and mark as failed. |
ProcessingConfig
¶
Bases: BaseModel
Processing settings for conversion workflow.
Attributes:
| Name | Type | Description |
|---|---|---|
max_concurrent |
int
|
Maximum concurrent conversions. |
validate_quality |
bool
|
Whether to validate output quality. |
preserve_original |
bool
|
Whether to preserve original files. |
move_processed |
bool
|
Whether to move processed originals to paths.processed. |
move_failed |
bool
|
Whether to move failed files to paths.failed. |
check_disk_space |
bool
|
Whether to check disk space before processing. |
min_free_space_gb |
float
|
Minimum free disk space in gigabytes. |
NotificationConfig
¶
Bases: BaseModel
Notification settings.
Attributes:
| Name | Type | Description |
|---|---|---|
on_complete |
bool
|
Send notification when conversion completes. |
on_error |
bool
|
Send notification on errors. |
daily_summary |
bool
|
Send daily summary notification. |
Config
¶
Bases: BaseSettings
Main configuration class for video converter.
This class manages all configuration settings for the video converter application. It supports loading from JSON files, environment variable overrides, and runtime modifications.
Attributes:
| Name | Type | Description |
|---|---|---|
version |
str
|
Configuration schema version. |
encoding |
EncodingConfig
|
Encoding settings. |
paths |
PathsConfig
|
Path settings. |
automation |
AutomationConfig
|
Automation settings. |
photos |
PhotosConfig
|
Photos library settings. |
processing |
ProcessingConfig
|
Processing settings. |
notification |
NotificationConfig
|
Notification settings. |
Example
config = Config.load() print(config.encoding.mode) 'hardware'
Modify and save¶
config.encoding.quality = 60 config.save()
Environment override (VIDEO_CONVERTER_ENCODING__MODE=software)¶
config = Config.load() print(config.encoding.mode) 'software'
settings_customise_sources
classmethod
¶
settings_customise_sources(settings_cls, init_settings, env_settings, dotenv_settings, file_secret_settings)
Customize settings sources priority.
Priority (highest to lowest): 1. init_settings (direct arguments) 2. env_settings (environment variables) 3. JSON file settings 4. Default values
This ensures environment variables override JSON file settings.
Source code in src/video_converter/core/config.py
load
classmethod
¶
Load configuration from file.
Loads configuration from the specified path, or falls back to default locations. Environment variables can override loaded values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
Path | None
|
Deprecated. Custom paths are not currently supported. Use environment variables or modify the default files. |
None
|
force_reload
|
bool
|
Force reload even if already loaded. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
Config |
Config
|
Loaded configuration instance. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If configuration file contains invalid values. |
Example
config = Config.load() # Uses default paths
Environment override: VIDEO_CONVERTER_ENCODING__MODE=software¶
Source code in src/video_converter/core/config.py
save
¶
Save configuration to file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config_path
|
Path | None
|
Optional path to save to. Defaults to loaded path. |
None
|
Raises:
| Type | Description |
|---|---|
IOError
|
If file cannot be written. |
Example
config = Config.load() config.encoding.quality = 60 config.save()
Source code in src/video_converter/core/config.py
reset
classmethod
¶
Reset the singleton instance.
This is primarily useful for testing to ensure a clean state.
Source code in src/video_converter/core/config.py
get_default_config_path
classmethod
¶
Get the default user configuration file path.
Returns:
| Type | Description |
|---|---|
Path
|
Path to user configuration file. |
get_config_dir
classmethod
¶
Get the configuration directory path.
Returns:
| Type | Description |
|---|---|
Path
|
Path to configuration directory. |
to_dict
¶
Convert configuration to dictionary.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dictionary representation of configuration. |
Types¶
types
¶
Core type definitions for video conversion workflow.
This module defines the essential data classes used throughout the video conversion pipeline, including conversion requests, results, progress tracking, and reporting structures.
SDS Reference: SDS-C01-001 SRS Reference: SRS-601 (Orchestrator Workflow)
Example
from video_converter.core.types import ConversionRequest, ConversionResult request = ConversionRequest( ... input_path=Path("input.mov"), ... output_path=Path("output.mp4"), ... mode="hardware", ... )
After conversion¶
result = ConversionResult( ... success=True, ... request=request, ... original_size=100_000_000, ... converted_size=40_000_000, ... duration_seconds=120.5, ... ) print(f"Compression ratio: {result.compression_ratio:.1%}") Compression ratio: 60.0%
ConversionMode
¶
Bases: Enum
Video conversion mode.
Attributes:
| Name | Type | Description |
|---|---|---|
HARDWARE |
Use hardware encoder (VideoToolbox on macOS). |
|
SOFTWARE |
Use software encoder (libx265). |
ErrorCategory
¶
Bases: Enum
Category of conversion error for recovery action determination.
SDS Reference: SDS-C01-004 SRS Reference: SRS-605 (Failure Isolation)
Attributes:
| Name | Type | Description |
|---|---|---|
INPUT_ERROR |
Input file issue (missing, corrupt, unsupported format). |
|
ENCODING_ERROR |
Encoder failure during conversion. |
|
VALIDATION_ERROR |
Output file failed quality validation. |
|
METADATA_ERROR |
Metadata copy/sync failure (non-fatal). |
|
DISK_SPACE_ERROR |
Insufficient disk space. |
|
PERMISSION_ERROR |
File permission or access denied. |
|
UNKNOWN_ERROR |
Unclassified error. |
RecoveryAction
¶
Bases: Enum
Recommended recovery action for an error category.
Attributes:
| Name | Type | Description |
|---|---|---|
SKIP |
Skip this file and continue with next. |
|
RETRY_WITH_FALLBACK |
Retry with alternative encoder/settings. |
|
RETRY_ONCE |
Retry one more time with same settings. |
|
KEEP_VIDEO_LOG_WARNING |
Keep converted video, log the warning. |
|
PAUSE_NOTIFY_USER |
Pause processing and notify user. |
|
ABORT |
Stop all processing. |
QueuePriority
¶
Bases: Enum
Queue priority ordering for batch processing.
Attributes:
| Name | Type | Description |
|---|---|---|
FIFO |
First-in, first-out (default). |
|
DATE_OLDEST |
Oldest files first (by modification time). |
|
DATE_NEWEST |
Newest files first (by modification time). |
|
SIZE_SMALLEST |
Smallest files first. |
|
SIZE_LARGEST |
Largest files first. |
ConversionStage
¶
Bases: Enum
Stages in the conversion pipeline.
Attributes:
| Name | Type | Description |
|---|---|---|
DISCOVERY |
Finding videos to convert. |
|
EXPORT |
Extracting from Photos library. |
|
CONVERT |
Running the encoder. |
|
VALIDATE |
Verifying output integrity. |
|
METADATA |
Copying metadata. |
|
CLEANUP |
Moving/deleting files. |
|
COMPLETE |
All stages finished. |
ConversionStatus
¶
Bases: Enum
Status of a conversion operation.
Attributes:
| Name | Type | Description |
|---|---|---|
PENDING |
Waiting to be processed. |
|
IN_PROGRESS |
Currently being processed. |
|
COMPLETED |
Successfully completed. |
|
FAILED |
Failed during processing. |
|
SKIPPED |
Skipped (already converted or filtered). |
|
CANCELLED |
Cancelled by user. |
BatchStatus
¶
Bases: Enum
Status of a batch conversion operation.
Attributes:
| Name | Type | Description |
|---|---|---|
IDLE |
No batch is running. |
|
RUNNING |
Batch is actively processing. |
|
PAUSED |
Batch is paused by user. |
|
COMPLETED |
Batch finished (success or with failures). |
|
CANCELLED |
Batch was cancelled. |
ConversionRequest
dataclass
¶
ConversionRequest(input_path, output_path, mode=HARDWARE, quality=45, crf=22, preset='medium', audio_mode='copy', preserve_metadata=True, bit_depth=8, hdr=False)
Request for video conversion.
Attributes:
| Name | Type | Description |
|---|---|---|
input_path |
Path
|
Path to the input video file. |
output_path |
Path
|
Path for the converted output file. |
mode |
ConversionMode
|
Conversion mode (hardware or software). |
quality |
int
|
Quality setting (1-100, higher is better). |
crf |
int
|
Constant Rate Factor for encoding. |
preset |
str
|
Encoding preset (speed vs compression trade-off). |
audio_mode |
str
|
How to handle audio ("copy", "aac", etc.). |
preserve_metadata |
bool
|
Whether to copy metadata from original. |
bit_depth |
int
|
Output bit depth (8 or 10). 10-bit for HDR content. |
hdr |
bool
|
Enable HDR encoding parameters for 10-bit content. |
__post_init__
¶
Validate and normalize fields.
Source code in src/video_converter/core/types.py
ConversionResult
dataclass
¶
ConversionResult(success, request, original_size=0, converted_size=0, duration_seconds=0.0, speed_ratio=0.0, error_message=None, warnings=list(), started_at=None, completed_at=None, retry_count=0, retry_strategy_used=None, retry_history=list(), vmaf_score=None, vmaf_quality_level=None)
Result of a single video conversion.
Attributes:
| Name | Type | Description |
|---|---|---|
success |
bool
|
Whether conversion completed successfully. |
request |
ConversionRequest
|
The original conversion request. |
original_size |
int
|
Size of input file in bytes. |
converted_size |
int
|
Size of output file in bytes. |
duration_seconds |
float
|
Time taken to convert in seconds. |
speed_ratio |
float
|
Conversion speed relative to realtime. |
error_message |
str | None
|
Error message if conversion failed. |
warnings |
list[str]
|
Non-critical issues encountered. |
started_at |
datetime | None
|
When conversion started. |
completed_at |
datetime | None
|
When conversion finished. |
retry_count |
int
|
Number of retry attempts made (0 if no retries). |
retry_strategy_used |
str | None
|
Final retry strategy that succeeded (or None). |
retry_history |
list[dict]
|
Detailed history of all retry attempts. |
vmaf_score |
float | None
|
VMAF quality score (0-100) if measured. |
vmaf_quality_level |
str | None
|
Quality classification based on VMAF score. |
ConversionProgress
dataclass
¶
ConversionProgress(stage, status, current_file='', current_index=0, total_files=0, stage_progress=0.0, overall_progress=0.0, bytes_processed=0, bytes_total=0, estimated_time_remaining=None, message='')
Progress information for conversion tracking.
Attributes:
| Name | Type | Description |
|---|---|---|
stage |
ConversionStage
|
Current stage in the pipeline. |
status |
ConversionStatus
|
Current status of the operation. |
current_file |
str
|
Name of the file being processed. |
current_index |
int
|
Index of current file (0-based). |
total_files |
int
|
Total number of files to process. |
stage_progress |
float
|
Progress within current stage (0.0-1.0). |
overall_progress |
float
|
Overall progress (0.0-1.0). |
bytes_processed |
int
|
Bytes processed so far. |
bytes_total |
int
|
Total bytes to process. |
estimated_time_remaining |
float | None
|
Estimated seconds remaining. |
message |
str
|
Human-readable status message. |
__post_init__
¶
ConversionReport
dataclass
¶
ConversionReport(session_id, started_at, completed_at=None, total_files=0, successful=0, failed=0, skipped=0, cancelled=False, total_original_size=0, total_converted_size=0, total_duration_seconds=0.0, results=list(), errors=list(), warnings=list())
Summary report for a conversion batch.
Attributes:
| Name | Type | Description |
|---|---|---|
session_id |
str
|
Unique identifier for this conversion session. |
started_at |
datetime
|
When the batch started. |
completed_at |
datetime | None
|
When the batch finished. |
total_files |
int
|
Total files in the batch. |
successful |
int
|
Number of successfully converted files. |
failed |
int
|
Number of failed conversions. |
skipped |
int
|
Number of skipped files. |
cancelled |
bool
|
Whether the batch was cancelled. |
total_original_size |
int
|
Sum of all original file sizes. |
total_converted_size |
int
|
Sum of all converted file sizes. |
total_duration_seconds |
float
|
Total conversion time. |
results |
list[ConversionResult]
|
Individual conversion results. |
errors |
list[str]
|
Aggregated error messages. |
warnings |
list[str]
|
Aggregated warning messages. |
add_result
¶
Add a conversion result to the report.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
ConversionResult
|
The conversion result to add. |
required |
Source code in src/video_converter/core/types.py
SessionStatus
¶
Bases: Enum
Status of a conversion session for persistence.
Attributes:
| Name | Type | Description |
|---|---|---|
ACTIVE |
Session is currently running. |
|
PAUSED |
Session was paused and can be resumed. |
|
COMPLETED |
Session finished successfully. |
|
INTERRUPTED |
Session was interrupted (crash, shutdown). |
|
CANCELLED |
Session was explicitly cancelled. |
VideoEntry
dataclass
¶
VideoEntry(path, output_path, status=PENDING, error_message=None, original_size=0, converted_size=0)
Entry for a video file in session state.
Attributes:
| Name | Type | Description |
|---|---|---|
path |
Path
|
Absolute path to the video file. |
output_path |
Path
|
Absolute path to the output file. |
status |
ConversionStatus
|
Current conversion status. |
error_message |
str | None
|
Error message if failed. |
original_size |
int
|
Size of original file in bytes. |
converted_size |
int
|
Size of converted file in bytes. |
__post_init__
¶
Validate and normalize fields.
Source code in src/video_converter/core/types.py
to_dict
¶
Convert to JSON-serializable dictionary.
Source code in src/video_converter/core/types.py
from_dict
classmethod
¶
Create from dictionary.
Source code in src/video_converter/core/types.py
SessionState
dataclass
¶
SessionState(session_id, status=ACTIVE, started_at=now(), updated_at=now(), current_index=0, pending_videos=list(), completed_videos=list(), failed_videos=list(), temporary_files=list(), output_dir=None, config_snapshot=dict())
Persistent session state for resumable conversions.
Tracks all information needed to resume an interrupted conversion session, including which files have been processed and any temporary files created.
Attributes:
| Name | Type | Description |
|---|---|---|
session_id |
str
|
Unique identifier for this session. |
status |
SessionStatus
|
Current session status. |
started_at |
datetime
|
When the session started. |
updated_at |
datetime
|
When the session was last updated. |
current_index |
int
|
Index of the file currently being processed. |
pending_videos |
list[VideoEntry]
|
List of videos waiting to be processed. |
completed_videos |
list[VideoEntry]
|
List of successfully completed videos. |
failed_videos |
list[VideoEntry]
|
List of videos that failed conversion. |
temporary_files |
list[Path]
|
List of temporary files created during conversion. |
output_dir |
Path | None
|
Output directory for converted files. |
config_snapshot |
dict
|
Snapshot of configuration at session start. |
__post_init__
¶
Validate and normalize fields.
Source code in src/video_converter/core/types.py
mark_video_completed
¶
Move a video from pending to completed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video
|
VideoEntry
|
The video entry to mark complete. |
required |
original_size
|
int
|
Size of original file in bytes. |
0
|
converted_size
|
int
|
Size of converted file in bytes. |
0
|
Source code in src/video_converter/core/types.py
mark_video_failed
¶
Move a video from pending to failed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video
|
VideoEntry
|
The video entry to mark failed. |
required |
error
|
str
|
Error message describing the failure. |
required |
Source code in src/video_converter/core/types.py
add_temporary_file
¶
Track a temporary file created during conversion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Path to the temporary file. |
required |
Source code in src/video_converter/core/types.py
remove_temporary_file
¶
Remove a temporary file from tracking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Path to the temporary file. |
required |
Source code in src/video_converter/core/types.py
to_dict
¶
Convert to JSON-serializable dictionary.
Source code in src/video_converter/core/types.py
from_dict
classmethod
¶
Create from dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Dictionary containing session state data. |
required |
Returns:
| Type | Description |
|---|---|
SessionState
|
A new SessionState instance. |
Source code in src/video_converter/core/types.py
Logger¶
logger
¶
Logging system with file and console output.
This module provides a comprehensive logging system that outputs to both file and console with configurable log levels, log rotation, and colored console output using the Rich library.
SDS Reference: SDS-C01-002 SRS Reference: SRS-101 (Logging System)
Example
from video_converter.core.logger import get_logger logger = get_logger(name) logger.info("Starting conversion") logger.debug("Processing file: %s", filename) logger.error("Conversion failed", exc_info=True)
Configure log level globally¶
from video_converter.core.logger import configure_logging configure_logging(level="DEBUG", log_dir=Path("/custom/path"))
LogLevel
¶
Log level constants for convenient access.
Attributes:
| Name | Type | Description |
|---|---|---|
DEBUG |
Detailed information for debugging. |
|
INFO |
General operational information. |
|
WARNING |
Indication of potential issues. |
|
ERROR |
Error that prevented an operation. |
|
CRITICAL |
Critical error, application may not continue. |
configure_logging
¶
Configure the global logging settings.
This function should be called once at application startup to configure the logging system. Subsequent calls will update the configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
int | str
|
Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL). Can be either an integer or string. |
DEFAULT_LOG_LEVEL
|
log_dir
|
Path | None
|
Directory for log files. Default: ~/.local/share/video_converter/logs |
None
|
console_output
|
bool
|
Whether to output logs to console. Default: True. |
True
|
file_output
|
bool
|
Whether to output logs to file. Default: True. |
True
|
Example
configure_logging(level="DEBUG") configure_logging(level=logging.WARNING, log_dir=Path("/var/log/myapp"))
Source code in src/video_converter/core/logger.py
get_logger
¶
Get a logger instance with the specified name.
This is the primary function for obtaining a logger. It returns a logger that is a child of the "video_converter" root logger, ensuring consistent configuration across the application.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The name of the logger, typically name. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Logger |
Logger
|
Configured logger instance. |
Example
logger = get_logger(name) logger.info("Starting conversion") logger.debug("Processing file: %s", filename) logger.error("Conversion failed", exc_info=True)
Source code in src/video_converter/core/logger.py
set_log_level
¶
Set the log level for all video_converter loggers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
level
|
int | str
|
Log level (DEBUG, INFO, WARNING, ERROR, CRITICAL). Can be either an integer or string. |
required |
Example
set_log_level("DEBUG") set_log_level(logging.WARNING)
Source code in src/video_converter/core/logger.py
get_log_file_path
¶
Get the path to the current log file.
Returns:
| Name | Type | Description |
|---|---|---|
Path |
Path
|
Path to the log file. |
get_log_dir
¶
Session¶
session
¶
Session state management for resumable conversions.
This module implements persistent session state tracking to enable resuming interrupted video conversions.
SDS Reference: SDS-C01-003 SRS Reference: SRS-603 (Session State Management)
Example
from video_converter.core.session import SessionStateManager from pathlib import Path
manager = SessionStateManager()
Create a new session¶
session = manager.create_session( ... video_paths=[Path("video1.mov"), Path("video2.mov")], ... output_dir=Path("converted"), ... )
Update session progress¶
manager.mark_completed(session.pending_videos[0]) manager.save()
Resume an interrupted session¶
if manager.has_resumable_session(): ... session = manager.load_session() ... # Continue processing pending_videos
SessionStateError
¶
Bases: Exception
Base exception for session state errors.
SessionNotFoundError
¶
Bases: SessionStateError
Raised when a session cannot be found.
SessionCorruptedError
¶
Bases: SessionStateError
Raised when session data is corrupted.
SessionStateManager
¶
Manages persistent session state for video conversion.
Provides functionality to: - Create and track conversion sessions - Save session state to disk periodically - Resume from saved state after restart - Handle orphaned temporary files - Query session status
Attributes:
| Name | Type | Description |
|---|---|---|
state_dir |
Directory for session state files. |
|
current_session |
SessionState | None
|
The currently active session, if any. |
Initialize the session state manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dir
|
Path | None
|
Directory for session state files. Defaults to ~/.local/share/video_converter/sessions |
None
|
auto_save_interval
|
int
|
Seconds between auto-saves. 0 disables auto-save. |
30
|
Source code in src/video_converter/core/session.py
create_session
¶
Create a new conversion session.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video_paths
|
list[Path]
|
List of video files to convert. |
required |
output_dir
|
Path | None
|
Directory for output files. |
None
|
config
|
OrchestratorConfig | None
|
Orchestrator configuration to snapshot. |
None
|
Returns:
| Type | Description |
|---|---|
SessionState
|
A new SessionState instance. |
Raises:
| Type | Description |
|---|---|
SessionStateError
|
If a session is already active. |
Source code in src/video_converter/core/session.py
save
¶
Save current session state to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
force
|
bool
|
If True, save even if not dirty or interval not reached. |
False
|
Source code in src/video_converter/core/session.py
load_session
¶
Load a session from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str | None
|
Specific session ID to load, or None for current. |
None
|
Returns:
| Type | Description |
|---|---|
SessionState
|
The loaded SessionState. |
Raises:
| Type | Description |
|---|---|
SessionNotFoundError
|
If the session does not exist. |
SessionCorruptedError
|
If the session data is corrupted. |
Source code in src/video_converter/core/session.py
has_resumable_session
¶
Check if there is a resumable session available.
Returns:
| Type | Description |
|---|---|
bool
|
True if a session can be resumed, False otherwise. |
Source code in src/video_converter/core/session.py
get_resumable_sessions
¶
Get list of all resumable sessions.
Returns:
| Type | Description |
|---|---|
list[dict]
|
List of session info dictionaries with id, status, and progress. |
Source code in src/video_converter/core/session.py
mark_video_completed
¶
Mark a video as successfully completed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video
|
VideoEntry
|
The video entry to mark complete. |
required |
original_size
|
int
|
Size of original file in bytes. |
0
|
converted_size
|
int
|
Size of converted file in bytes. |
0
|
Source code in src/video_converter/core/session.py
mark_video_failed
¶
Mark a video as failed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
video
|
VideoEntry
|
The video entry to mark failed. |
required |
error
|
str
|
Error message describing the failure. |
required |
Source code in src/video_converter/core/session.py
add_temporary_file
¶
Track a temporary file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Path to the temporary file. |
required |
Source code in src/video_converter/core/session.py
remove_temporary_file
¶
Stop tracking a temporary file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Path to the temporary file. |
required |
Source code in src/video_converter/core/session.py
pause_session
¶
Pause the current session.
Returns:
| Type | Description |
|---|---|
bool
|
True if paused successfully, False if no active session. |
Source code in src/video_converter/core/session.py
resume_session
¶
Resume a paused or interrupted session.
Returns:
| Type | Description |
|---|---|
SessionState | None
|
The resumed SessionState, or None if no resumable session. |
Source code in src/video_converter/core/session.py
complete_session
¶
Mark the current session as completed and archive it.
Source code in src/video_converter/core/session.py
cancel_session
¶
Cancel the current session and archive it.
Source code in src/video_converter/core/session.py
cleanup_orphaned_temp_files
¶
Clean up orphaned temporary files from interrupted sessions.
Returns:
| Type | Description |
|---|---|
list[Path]
|
List of files that were cleaned up. |
Source code in src/video_converter/core/session.py
get_session_status
¶
Get status summary for the current session.
Returns:
| Type | Description |
|---|---|
dict | None
|
Dictionary with session status info, or None if no session. |
Source code in src/video_converter/core/session.py
delete_session
¶
Delete a session from history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session_id
|
str
|
The session ID to delete. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if deleted, False if not found. |
Source code in src/video_converter/core/session.py
clear_history
¶
Clear old sessions from history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keep_days
|
int
|
Number of days of history to keep. |
30
|
Returns:
| Type | Description |
|---|---|
int
|
Number of sessions deleted. |
Source code in src/video_converter/core/session.py
get_session_manager
¶
Get or create the default session state manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state_dir
|
Path | None
|
Optional state directory. Only used on first call. |
None
|
Returns:
| Type | Description |
|---|---|
SessionStateManager
|
The default SessionStateManager instance. |
Source code in src/video_converter/core/session.py
History¶
history
¶
Conversion history tracking for duplicate prevention.
This module implements a conversion history tracking system to prevent re-converting videos that have already been processed. It uses file hashes or Photos UUIDs to identify videos across renames and moves.
SDS Reference: SDS-C01-003 SRS Reference: SRS-306 (Conversion History)
Example
from video_converter.core.history import ConversionHistory, ConversionRecord from pathlib import Path from datetime import datetime
history = ConversionHistory()
Check before converting¶
if not history.is_converted(video_uuid): ... # Perform conversion... ... record = ConversionRecord( ... id=video_uuid, ... source_path=str(source), ... output_path=str(output), ... source_codec="h264", ... output_codec="hevc", ... source_size=original_size, ... output_size=converted_size, ... converted_at=datetime.now().isoformat(), ... success=True, ... ) ... history.add_record(record)
StatsPeriod
¶
Bases: Enum
Time period for statistics filtering.
HistoryError
¶
Bases: Exception
Base exception for history operations.
HistoryCorruptedError
¶
Bases: HistoryError
Raised when history data is corrupted or invalid.
ConversionRecord
dataclass
¶
ConversionRecord(id, source_path, output_path, source_codec, output_codec, source_size, output_size, converted_at, success, error_message=None)
Record of a video conversion.
Stores all relevant information about a single video conversion, including paths, codecs, sizes, and success status.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier (UUID from Photos or file hash). |
source_path |
str
|
Original file path at time of conversion. |
output_path |
str | None
|
Converted file path (None if failed). |
source_codec |
str
|
Original video codec (e.g., "h264"). |
output_codec |
str
|
Target video codec (e.g., "hevc"). |
source_size |
int
|
Original file size in bytes. |
output_size |
int | None
|
Converted file size in bytes (None if failed). |
converted_at |
str
|
ISO format timestamp of conversion. |
success |
bool
|
Whether conversion completed successfully. |
error_message |
str | None
|
Error details if conversion failed. |
size_saved
property
¶
Calculate bytes saved by conversion.
Returns:
| Type | Description |
|---|---|
int
|
Bytes saved (0 if conversion failed or increased size). |
compression_ratio
property
¶
Calculate compression ratio.
Returns:
| Type | Description |
|---|---|
float
|
Compression ratio (0.0-1.0) where 0.6 means 60% size reduction. |
float
|
Returns 0.0 if conversion failed or source size is 0. |
to_dict
¶
Convert record to JSON-serializable dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary representation of the record. |
from_dict
classmethod
¶
Create a ConversionRecord from dictionary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
dict
|
Dictionary containing record data. |
required |
Returns:
| Type | Description |
|---|---|
ConversionRecord
|
A new ConversionRecord instance. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If required fields are missing. |
Source code in src/video_converter/core/history.py
HistoryStatistics
dataclass
¶
HistoryStatistics(total_converted=0, total_failed=0, total_source_bytes=0, total_output_bytes=0, total_saved_bytes=0, first_conversion=None, last_conversion=None, period='all', period_start=None, total_duration_seconds=0.0)
Statistics summary for conversion history.
Attributes:
| Name | Type | Description |
|---|---|---|
total_converted |
int
|
Number of successfully converted videos. |
total_failed |
int
|
Number of failed conversions. |
total_source_bytes |
int
|
Sum of all original file sizes. |
total_output_bytes |
int
|
Sum of all converted file sizes. |
total_saved_bytes |
int
|
Total bytes saved by compression. |
first_conversion |
str | None
|
Timestamp of earliest conversion. |
last_conversion |
str | None
|
Timestamp of most recent conversion. |
period |
str
|
The time period these statistics cover. |
period_start |
str | None
|
Start timestamp of the period. |
total_duration_seconds |
float
|
Total conversion time in seconds. |
success_rate
property
¶
Calculate success rate.
Returns:
| Type | Description |
|---|---|
float
|
Success rate as a fraction (0.0-1.0). |
average_compression_ratio
property
¶
Calculate average compression ratio.
Returns:
| Type | Description |
|---|---|
float
|
Average compression ratio (0.0-1.0). |
storage_saved_percent
property
¶
Calculate storage saved percentage.
Returns:
| Type | Description |
|---|---|
float
|
Percentage of storage saved (0.0-100.0). |
to_dict
¶
Convert statistics to dictionary.
Returns:
| Type | Description |
|---|---|
dict
|
Dictionary representation of statistics. |
Source code in src/video_converter/core/history.py
ConversionHistory
¶
Manage conversion history for duplicate prevention.
Provides functionality to: - Track converted videos by unique identifier - Store conversion metadata (date, result, output path) - Support Photos UUID and file hash identification - Persist history across application restarts - Generate statistics and reports
Thread-safe for concurrent access.
Attributes:
| Name | Type | Description |
|---|---|---|
history_path |
Path to the history JSON file. |
Example
history = ConversionHistory()
Check if already converted¶
if history.is_converted(video_id): ... print("Already converted, skipping") ...
Add conversion record¶
record = ConversionRecord(...) history.add_record(record)
Get statistics¶
stats = history.get_statistics() print(f"Converted: {stats.total_converted} videos")
Initialize the conversion history manager.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
history_path
|
Path | None
|
Path to history file. Defaults to ~/.local/share/video_converter/history.json |
None
|
Source code in src/video_converter/core/history.py
is_converted
¶
Check if a video has been successfully converted.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identifier
|
str
|
UUID (from Photos) or file hash. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if video was successfully converted before. |
Source code in src/video_converter/core/history.py
add_record
¶
Add or update a conversion record.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
record
|
ConversionRecord
|
The conversion record to add. |
required |
Source code in src/video_converter/core/history.py
get_record
¶
Get a conversion record by identifier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identifier
|
str
|
UUID or file hash. |
required |
Returns:
| Type | Description |
|---|---|
ConversionRecord | None
|
The ConversionRecord if found, None otherwise. |
Source code in src/video_converter/core/history.py
remove_record
¶
Remove a record from history.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
identifier
|
str
|
UUID or file hash. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if record was removed, False if not found. |
Source code in src/video_converter/core/history.py
clear
¶
Clear all history records.
get_records_by_period
¶
Get all conversion records filtered by time period.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
period
|
StatsPeriod
|
Time period to filter by. |
ALL
|
Returns:
| Type | Description |
|---|---|
list[ConversionRecord]
|
List of ConversionRecord instances within the period. |
Source code in src/video_converter/core/history.py
get_statistics
¶
Get aggregated statistics for conversions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
period
|
StatsPeriod
|
Time period to filter statistics by. |
ALL
|
Returns:
| Type | Description |
|---|---|
HistoryStatistics
|
HistoryStatistics with totals and averages. |
Source code in src/video_converter/core/history.py
get_all_records
¶
Get all conversion records.
Returns:
| Type | Description |
|---|---|
list[ConversionRecord]
|
List of all ConversionRecord instances. |
get_failed_records
¶
Get all failed conversion records.
Returns:
| Type | Description |
|---|---|
list[ConversionRecord]
|
List of failed ConversionRecord instances. |
Source code in src/video_converter/core/history.py
get_successful_records
¶
Get all successful conversion records.
Returns:
| Type | Description |
|---|---|
list[ConversionRecord]
|
List of successful ConversionRecord instances. |
Source code in src/video_converter/core/history.py
count
¶
Get total number of records.
Returns:
| Type | Description |
|---|---|
int
|
Number of records in history. |
export_to_json
¶
Export history to a JSON file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Path to export file. |
required |
Source code in src/video_converter/core/history.py
export_to_csv
¶
Export history to a CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Path to export file. |
required |
Source code in src/video_converter/core/history.py
compute_file_hash
staticmethod
¶
Compute a hash for file identification.
Uses SHA-256 hash of first and last 1MB of file for efficient identification of large files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
Path
|
Path to the file. |
required |
Returns:
| Type | Description |
|---|---|
str
|
16-character hex hash string. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If file does not exist. |
OSError
|
If file cannot be read. |
Source code in src/video_converter/core/history.py
get_history
¶
Get or create the default ConversionHistory instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
history_path
|
Path | None
|
Optional path. Only used on first call. |
None
|
Returns:
| Type | Description |
|---|---|
ConversionHistory
|
The default ConversionHistory instance. |
Source code in src/video_converter/core/history.py
reset_history
¶
Reset the default history instance.
Primarily useful for testing.