mirror of
https://github.com/shadoll/moma.git
synced 2026-08-28 03:27:34 +00:00
Refactor extractors and formatters for improved structure and functionality
- Converted static methods to instance methods in FileInfoExtractor and FilenameExtractor for better encapsulation. - Enhanced MediaInfoExtractor to initialize with file path and extract media information upon instantiation. - Updated MetadataExtractor to handle metadata extraction with improved error handling and added methods for meta type detection. - Introduced ColorFormatter for consistent text formatting across the application. - Refactored MediaFormatter to utilize the new extractor structure and improve output formatting. - Removed redundant utility functions and replaced them with direct calls in extractors. - Added ProposedNameFormatter for better handling of proposed filename formatting. - Updated extension handling to use MEDIA_TYPES for descriptions instead of VIDEO_EXT_DESCRIPTIONS.
This commit is contained in:
@@ -4,22 +4,29 @@ from pathlib import Path
|
||||
class FileInfoExtractor:
|
||||
"""Class to extract file information"""
|
||||
|
||||
@staticmethod
|
||||
def extract_size(file_path: Path) -> int:
|
||||
def __init__(self, file_path: Path):
|
||||
self.file_path = file_path
|
||||
self._size = file_path.stat().st_size
|
||||
self._modification_time = file_path.stat().st_mtime
|
||||
self._file_name = file_path.name
|
||||
self._file_path = str(file_path)
|
||||
|
||||
def extract_size(self) -> int:
|
||||
"""Extract file size in bytes"""
|
||||
return file_path.stat().st_size
|
||||
return self._size
|
||||
|
||||
@staticmethod
|
||||
def extract_modification_time(file_path: Path) -> float:
|
||||
def extract_modification_time(self) -> float:
|
||||
"""Extract file modification time"""
|
||||
return file_path.stat().st_mtime
|
||||
return self._modification_time
|
||||
|
||||
@staticmethod
|
||||
def extract_file_name(file_path: Path) -> str:
|
||||
def extract_file_name(self) -> str:
|
||||
"""Extract file name"""
|
||||
return file_path.name
|
||||
return self._file_name
|
||||
|
||||
@staticmethod
|
||||
def extract_file_path(file_path: Path) -> str:
|
||||
def extract_file_path(self) -> str:
|
||||
"""Extract full file path as string"""
|
||||
return str(file_path)
|
||||
return self._file_path
|
||||
|
||||
def extract_extension(self) -> str:
|
||||
"""Extract file extension without the dot"""
|
||||
return self.file_path.suffix.lower().lstrip('.')
|
||||
@@ -6,40 +6,37 @@ from ..constants import SOURCE_DICT, FRAME_CLASSES
|
||||
class FilenameExtractor:
|
||||
"""Class to extract information from filename"""
|
||||
|
||||
@staticmethod
|
||||
def _get_frame_class_from_height(height: int) -> str:
|
||||
def __init__(self, file_path: Path):
|
||||
self.file_path = file_path
|
||||
self.file_name = file_path.name
|
||||
|
||||
def _get_frame_class_from_height(self, height: int) -> str:
|
||||
"""Get frame class from video height using FRAME_CLASSES constant"""
|
||||
for frame_class, info in FRAME_CLASSES.items():
|
||||
if height == info['nominal_height']:
|
||||
return frame_class
|
||||
return 'Unclassified'
|
||||
|
||||
@staticmethod
|
||||
def extract_title(file_path: Path) -> str | None:
|
||||
def extract_title(self) -> str | None:
|
||||
"""Extract movie title from filename"""
|
||||
file_name = file_path.name
|
||||
temp_name = re.sub(r'\s*\(\d{4}\)\s*|\s*\d{4}\s*|\.\d{4}\.', '', file_name)
|
||||
temp_name = re.sub(r'\s*\(\d{4}\)\s*|\s*\d{4}\s*|\.\d{4}\.', '', self.file_name)
|
||||
|
||||
# Find and remove source
|
||||
source = FilenameExtractor.extract_source(file_path)
|
||||
source = self.extract_source()
|
||||
if source:
|
||||
for alias in SOURCE_DICT[source]:
|
||||
temp_name = re.sub(r'\b' + re.escape(alias) + r'\b', '', temp_name, flags=re.IGNORECASE)
|
||||
|
||||
return temp_name.rsplit('.', 1)[0].strip()
|
||||
|
||||
@staticmethod
|
||||
def extract_year(file_path: Path) -> str | None:
|
||||
def extract_year(self) -> str | None:
|
||||
"""Extract year from filename"""
|
||||
file_name = file_path.name
|
||||
year_match = re.search(r'\((\d{4})\)|(\d{4})', file_name)
|
||||
year_match = re.search(r'\((\d{4})\)|(\d{4})', self.file_name)
|
||||
return (year_match.group(1) or year_match.group(2)) if year_match else None
|
||||
|
||||
@staticmethod
|
||||
def extract_source(file_path: Path) -> str | None:
|
||||
def extract_source(self) -> str | None:
|
||||
"""Extract video source from filename"""
|
||||
file_name = file_path.name
|
||||
temp_name = re.sub(r'\s*\(\d{4}\)\s*|\s*\d{4}\s*|\.\d{4}\.', '', file_name)
|
||||
temp_name = re.sub(r'\s*\(\d{4}\)\s*|\s*\d{4}\s*|\.\d{4}\.', '', self.file_name)
|
||||
|
||||
for src, aliases in SOURCE_DICT.items():
|
||||
for alias in aliases:
|
||||
@@ -47,12 +44,10 @@ class FilenameExtractor:
|
||||
return src
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def extract_frame_class(file_path: Path) -> str | None:
|
||||
def extract_frame_class(self) -> str | None:
|
||||
"""Extract frame class from filename (480p, 720p, 1080p, 2160p, etc.)"""
|
||||
file_name = file_path.name
|
||||
match = re.search(r'(\d{3,4})[pi]', file_name, re.IGNORECASE)
|
||||
match = re.search(r'(\d{3,4})[pi]', self.file_name, re.IGNORECASE)
|
||||
if match:
|
||||
height = int(match.group(1))
|
||||
return FilenameExtractor._get_frame_class_from_height(height)
|
||||
return self._get_frame_class_from_height(height)
|
||||
return 'Unclassified'
|
||||
@@ -2,17 +2,24 @@ from pathlib import Path
|
||||
from pymediainfo import MediaInfo
|
||||
from collections import Counter
|
||||
from ..constants import FRAME_CLASSES
|
||||
from ..formatters.color_formatter import ColorFormatter
|
||||
|
||||
|
||||
class MediaInfoExtractor:
|
||||
"""Class to extract information from MediaInfo"""
|
||||
|
||||
def __init__(self):
|
||||
self.lang_map = {
|
||||
'en': 'eng', 'fr': 'fre', 'de': 'ger', 'uk': 'ukr', 'ru': 'rus',
|
||||
'es': 'spa', 'it': 'ita', 'pt': 'por', 'ja': 'jpn', 'ko': 'kor',
|
||||
'zh': 'chi', 'und': 'und'
|
||||
}
|
||||
def __init__(self, file_path: Path):
|
||||
self.file_path = file_path
|
||||
try:
|
||||
self.media_info = MediaInfo.parse(file_path)
|
||||
self.video_tracks = [t for t in self.media_info.tracks if t.track_type == 'Video']
|
||||
self.audio_tracks = [t for t in self.media_info.tracks if t.track_type == 'Audio']
|
||||
self.sub_tracks = [t for t in self.media_info.tracks if t.track_type == 'Text']
|
||||
except Exception:
|
||||
self.media_info = None
|
||||
self.video_tracks = []
|
||||
self.audio_tracks = []
|
||||
self.sub_tracks = []
|
||||
|
||||
def _get_frame_class_from_height(self, height: int) -> str:
|
||||
"""Get frame class from video height using FRAME_CLASSES constant"""
|
||||
@@ -21,82 +28,113 @@ class MediaInfoExtractor:
|
||||
return frame_class
|
||||
return 'Unclassified'
|
||||
|
||||
def extract_frame_class(self, file_path: Path) -> str | None:
|
||||
def extract_frame_class(self) -> str | None:
|
||||
"""Extract frame class from media info (480p, 720p, 1080p, etc.)"""
|
||||
try:
|
||||
media_info = MediaInfo.parse(file_path)
|
||||
video_tracks = [t for t in media_info.tracks if t.track_type == 'Video']
|
||||
if video_tracks:
|
||||
height = getattr(video_tracks[0], 'height', None)
|
||||
if height:
|
||||
return self._get_frame_class_from_height(height)
|
||||
except:
|
||||
pass
|
||||
if not self.video_tracks:
|
||||
return 'Unclassified'
|
||||
height = getattr(self.video_tracks[0], 'height', None)
|
||||
if height:
|
||||
return self._get_frame_class_from_height(height)
|
||||
return 'Unclassified'
|
||||
|
||||
def extract_resolution(self, file_path: Path) -> str | None:
|
||||
def extract_resolution(self) -> str | None:
|
||||
"""Extract actual video resolution (WIDTHxHEIGHT) from media info"""
|
||||
try:
|
||||
media_info = MediaInfo.parse(file_path)
|
||||
video_tracks = [t for t in media_info.tracks if t.track_type == 'Video']
|
||||
if video_tracks:
|
||||
width = getattr(video_tracks[0], 'width', None)
|
||||
height = getattr(video_tracks[0], 'height', None)
|
||||
if width and height:
|
||||
return f"{width}x{height}"
|
||||
except:
|
||||
pass
|
||||
if not self.video_tracks:
|
||||
return None
|
||||
width = getattr(self.video_tracks[0], 'width', None)
|
||||
height = getattr(self.video_tracks[0], 'height', None)
|
||||
if width and height:
|
||||
return f"{width}x{height}"
|
||||
return None
|
||||
|
||||
def extract_aspect_ratio(self, file_path: Path) -> str | None:
|
||||
def extract_aspect_ratio(self) -> str | None:
|
||||
"""Extract video aspect ratio from media info"""
|
||||
try:
|
||||
media_info = MediaInfo.parse(file_path)
|
||||
video_tracks = [t for t in media_info.tracks if t.track_type == 'Video']
|
||||
if video_tracks:
|
||||
aspect_ratio = getattr(video_tracks[0], 'display_aspect_ratio', None)
|
||||
if aspect_ratio:
|
||||
return str(aspect_ratio)
|
||||
except:
|
||||
pass
|
||||
if not self.video_tracks:
|
||||
return None
|
||||
aspect_ratio = getattr(self.video_tracks[0], 'display_aspect_ratio', None)
|
||||
if aspect_ratio:
|
||||
return str(aspect_ratio)
|
||||
return None
|
||||
|
||||
def extract_hdr(self, file_path: Path) -> str | None:
|
||||
def extract_hdr(self) -> str | None:
|
||||
"""Extract HDR info from media info"""
|
||||
try:
|
||||
media_info = MediaInfo.parse(file_path)
|
||||
video_tracks = [t for t in media_info.tracks if t.track_type == 'Video']
|
||||
if video_tracks:
|
||||
profile = getattr(video_tracks[0], 'format_profile', '')
|
||||
if 'HDR' in profile.upper():
|
||||
return 'HDR'
|
||||
except:
|
||||
pass
|
||||
if not self.video_tracks:
|
||||
return None
|
||||
profile = getattr(self.video_tracks[0], 'format_profile', '')
|
||||
if 'HDR' in profile.upper():
|
||||
return 'HDR'
|
||||
return None
|
||||
|
||||
def extract_audio_langs(self, file_path: Path) -> str:
|
||||
def extract_audio_langs(self) -> str:
|
||||
"""Extract audio languages from media info"""
|
||||
try:
|
||||
media_info = MediaInfo.parse(file_path)
|
||||
audio_tracks = [t for t in media_info.tracks if t.track_type == 'Audio']
|
||||
langs = [getattr(a, 'language', 'und').lower()[:3] for a in audio_tracks]
|
||||
langs = [self.lang_map.get(lang, lang) for lang in langs]
|
||||
lang_counts = Counter(langs)
|
||||
audio_langs = [f"{count}{lang}" if count > 1 else lang for lang, count in lang_counts.items()]
|
||||
return ','.join(audio_langs)
|
||||
except:
|
||||
if not self.audio_tracks:
|
||||
return ''
|
||||
lang_map = {
|
||||
'en': 'eng', 'fr': 'fre', 'de': 'ger', 'uk': 'ukr', 'ru': 'rus',
|
||||
'es': 'spa', 'it': 'ita', 'pt': 'por', 'ja': 'jpn', 'ko': 'kor',
|
||||
'zh': 'chi', 'und': 'und'
|
||||
}
|
||||
langs = [getattr(a, 'language', 'und').lower()[:3] for a in self.audio_tracks]
|
||||
langs = [lang_map.get(lang, lang) for lang in langs]
|
||||
lang_counts = Counter(langs)
|
||||
audio_langs = [f"{count}{lang}" if count > 1 else lang for lang, count in lang_counts.items()]
|
||||
return ','.join(audio_langs)
|
||||
|
||||
def extract_video_dimensions(self, file_path: Path) -> tuple[int, int] | None:
|
||||
def extract_video_dimensions(self) -> tuple[int, int] | None:
|
||||
"""Extract video width and height"""
|
||||
if not self.video_tracks:
|
||||
return None
|
||||
width = getattr(self.video_tracks[0], 'width', None)
|
||||
height = getattr(self.video_tracks[0], 'height', None)
|
||||
if width and height:
|
||||
return width, height
|
||||
return None
|
||||
|
||||
def extract_tracks(self) -> str:
|
||||
"""Extract compact media track information"""
|
||||
tracks_info = []
|
||||
try:
|
||||
media_info = MediaInfo.parse(file_path)
|
||||
video_tracks = [t for t in media_info.tracks if t.track_type == 'Video']
|
||||
if video_tracks:
|
||||
width = getattr(video_tracks[0], 'width', None)
|
||||
height = getattr(video_tracks[0], 'height', None)
|
||||
if width and height:
|
||||
return width, height
|
||||
except:
|
||||
pass
|
||||
return None
|
||||
# Video tracks
|
||||
for i, v in enumerate(self.video_tracks[:2]): # Up to 2 videos
|
||||
codec = getattr(v, 'format', None) or getattr(v, 'codec', None) or 'unknown'
|
||||
width = getattr(v, 'width', None) or '?'
|
||||
height = getattr(v, 'height', None) or '?'
|
||||
bitrate = getattr(v, 'bit_rate', None)
|
||||
fps = getattr(v, 'frame_rate', None)
|
||||
profile = getattr(v, 'format_profile', None)
|
||||
|
||||
video_str = f"{codec} {width}x{height}"
|
||||
if bitrate:
|
||||
video_str += f" {bitrate}bps"
|
||||
if fps:
|
||||
video_str += f" {fps}fps"
|
||||
if profile:
|
||||
video_str += f" ({profile})"
|
||||
|
||||
tracks_info.append(ColorFormatter.green(f"Video {i+1}: {video_str}"))
|
||||
|
||||
# Audio tracks
|
||||
for i, a in enumerate(self.audio_tracks[:3]): # Up to 3 audios
|
||||
codec = getattr(a, 'format', None) or getattr(a, 'codec', None) or 'unknown'
|
||||
channels = getattr(a, 'channel_s', None) or '?'
|
||||
lang = getattr(a, 'language', None) or 'und'
|
||||
bitrate = getattr(a, 'bit_rate', None)
|
||||
|
||||
audio_str = f"{codec} {channels}ch {lang}"
|
||||
if bitrate:
|
||||
audio_str += f" {bitrate}bps"
|
||||
|
||||
tracks_info.append(ColorFormatter.yellow(f"Audio {i+1}: {audio_str}"))
|
||||
|
||||
# Subtitle tracks
|
||||
for i, s in enumerate(self.sub_tracks[:3]): # Up to 3 subs
|
||||
lang = getattr(s, 'language', None) or 'und'
|
||||
format = getattr(s, 'format', None) or getattr(s, 'codec', None) or 'unknown'
|
||||
|
||||
sub_str = f"{lang} ({format})"
|
||||
tracks_info.append(ColorFormatter.magenta(f"Sub {i+1}: {sub_str}"))
|
||||
|
||||
except Exception as e:
|
||||
tracks_info.append(ColorFormatter.red(f"Track info error: {str(e)}"))
|
||||
|
||||
return "\n".join(tracks_info) if tracks_info else ""
|
||||
@@ -1,48 +1,63 @@
|
||||
import mutagen
|
||||
from pathlib import Path
|
||||
from ..constants import MEDIA_TYPES
|
||||
|
||||
|
||||
class MetadataExtractor:
|
||||
"""Class to extract information from file metadata"""
|
||||
|
||||
@staticmethod
|
||||
def extract_title(file_path: Path) -> str | None:
|
||||
def __init__(self, file_path: Path):
|
||||
self.file_path = file_path
|
||||
try:
|
||||
self.info = mutagen.File(file_path) # type: ignore
|
||||
except Exception:
|
||||
self.info = None
|
||||
|
||||
def extract_title(self) -> str | None:
|
||||
"""Extract title from metadata"""
|
||||
try:
|
||||
info = mutagen.File(file_path)
|
||||
if info:
|
||||
return getattr(info, 'title', None) or getattr(info, 'get', lambda x, default=None: default)('title', [None])[0]
|
||||
except:
|
||||
pass
|
||||
if self.info:
|
||||
return getattr(self.info, 'title', None) or getattr(self.info, 'get', lambda x, default=None: default)('title', [None])[0] # type: ignore
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def extract_duration(file_path: Path) -> float | None:
|
||||
def extract_duration(self) -> float | None:
|
||||
"""Extract duration from metadata"""
|
||||
try:
|
||||
info = mutagen.File(file_path)
|
||||
if info:
|
||||
return getattr(info, 'length', None)
|
||||
except:
|
||||
pass
|
||||
if self.info:
|
||||
return getattr(self.info, 'length', None)
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def extract_artist(file_path: Path) -> str | None:
|
||||
def extract_artist(self) -> str | None:
|
||||
"""Extract artist from metadata"""
|
||||
try:
|
||||
info = mutagen.File(file_path)
|
||||
if info:
|
||||
return getattr(info, 'artist', None) or getattr(info, 'get', lambda x, default=None: default)('artist', [None])[0]
|
||||
except:
|
||||
pass
|
||||
if self.info:
|
||||
return getattr(self.info, 'artist', None) or getattr(self.info, 'get', lambda x, default=None: default)('artist', [None])[0] # type: ignore
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def extract_all_metadata(file_path: Path) -> dict:
|
||||
def extract_all_metadata(self) -> dict:
|
||||
"""Extract all metadata"""
|
||||
return {
|
||||
'title': MetadataExtractor.extract_title(file_path),
|
||||
'duration': MetadataExtractor.extract_duration(file_path),
|
||||
'artist': MetadataExtractor.extract_artist(file_path)
|
||||
}
|
||||
'title': self.extract_title(),
|
||||
'duration': self.extract_duration(),
|
||||
'artist': self.extract_artist()
|
||||
}
|
||||
|
||||
def extract_meta_type(self) -> str:
|
||||
"""Extract meta type from metadata"""
|
||||
if self.info:
|
||||
return type(self.info).__name__
|
||||
return self._detect_by_mime()
|
||||
|
||||
def extract_meta_description(self) -> str:
|
||||
"""Extract meta description"""
|
||||
meta_type = self.extract_meta_type()
|
||||
return {info['meta_type']: info['description'] for info in MEDIA_TYPES.values()}.get(meta_type, f'Unknown type {meta_type}')
|
||||
|
||||
def _detect_by_mime(self) -> str:
|
||||
"""Detect meta type by MIME"""
|
||||
try:
|
||||
import magic
|
||||
mime = magic.from_file(str(self.file_path), mime=True)
|
||||
for ext, info in MEDIA_TYPES.items():
|
||||
if info['mime'] == mime:
|
||||
return info['meta_type']
|
||||
return 'Unknown'
|
||||
except Exception:
|
||||
return 'Unknown'
|
||||
Reference in New Issue
Block a user