Move get_date_format method in media and fixes

This commit is contained in:
Cédric Leporcq 2022-01-29 08:08:30 +01:00
parent f0a7624b0f
commit e0fc31e543
4 changed files with 33 additions and 36 deletions

View File

@ -979,8 +979,7 @@ class Collection(SortMedias):
return self.summary return self.summary
def sort_files( def sort_files(
self, src_dirs, path_format, loc, self, src_dirs, path_format, loc, imp=False, remove_duplicates=False
imp=False, remove_duplicates=False
): ):
""" """
Sort files into appropriate folder Sort files into appropriate folder

View File

@ -60,7 +60,7 @@ class Config:
return { return {
'Exif': { 'Exif': {
'album_from_folder': False, 'album_from_folder': False,
'cache': False, 'cache': True,
'ignore_tags': None, 'ignore_tags': None,
'use_date_filename': False, 'use_date_filename': False,
'use_file_dates': False, 'use_file_dates': False,

View File

@ -12,7 +12,6 @@ from ordigi import utils
from ordigi import request from ordigi import request
class ExifMetadata: class ExifMetadata:
def __init__(self, file_path, ignore_tags=None): def __init__(self, file_path, ignore_tags=None):
@ -20,6 +19,7 @@ class ExifMetadata:
if ignore_tags is None: if ignore_tags is None:
ignore_tags = set() ignore_tags = set()
self.ignore_tags = ignore_tags self.ignore_tags = ignore_tags
self.log = LOG.getChild(self.__class__.__name__)
self.tags_keys = self.get_tags() self.tags_keys = self.get_tags()
def get_tags(self) -> dict: def get_tags(self) -> dict:
@ -67,6 +67,27 @@ class ExifMetadata:
return tags_keys return tags_keys
def get_date_format(self, value):
"""
Formatting date attribute.
:returns: datetime object or None
"""
# We need to parse a string to datetime format.
# EXIF DateTimeOriginal and EXIF DateTime are both stored
# in %Y:%m:%d %H:%M:%S format
if value is None:
return None
try:
# correct nasty formated date
regex = re.compile(r'(\d{4}):(\d{2}):(\d{2})')
if re.match(regex, value) is not None: # noqa
value = re.sub(regex, r'\g<1>-\g<2>-\g<3>', value)
return parser.parse(value)
except BaseException or parser._parser.ParserError as e:
self.log.warning(e.args, value)
return None
class ReadExif(ExifMetadata): class ReadExif(ExifMetadata):
"""Read exif metadata to file""" """Read exif metadata to file"""
@ -76,7 +97,7 @@ class ReadExif(ExifMetadata):
file_path, file_path,
exif_metadata=None, exif_metadata=None,
ignore_tags=None, ignore_tags=None,
): ):
super().__init__(file_path, ignore_tags) super().__init__(file_path, ignore_tags)
@ -96,7 +117,7 @@ class ReadExif(ExifMetadata):
def get_key_values(self, key): def get_key_values(self, key):
""" """
Get the first value of a tag set Get tags values of a key
:returns: str or None if no exif tag :returns: str or None if no exif tag
""" """
if self.exif_metadata is None: if self.exif_metadata is None:
@ -224,6 +245,7 @@ class WriteExif(ExifMetadata):
# TODO use tag key # TODO use tag key
return self.set_value('Album', self.file_path.parent.name) return self.set_value('Album', self.file_path.parent.name)
class Media(ReadExif): class Media(ReadExif):
""" """
Extract matadatas from exiftool and sort them to dict structure Extract matadatas from exiftool and sort them to dict structure
@ -257,7 +279,6 @@ class Media(ReadExif):
self.theme = request.load_theme() self.theme = request.load_theme()
def get_mimetype(self): def get_mimetype(self):
""" """
Get the mimetype of the file. Get the mimetype of the file.
@ -270,27 +291,6 @@ class Media(ReadExif):
return mimetype[0] return mimetype[0]
def get_date_format(self, value):
"""
Formatting date attribute.
:returns: datetime object or None
"""
# We need to parse a string to datetime format.
# EXIF DateTimeOriginal and EXIF DateTime are both stored
# in %Y:%m:%d %H:%M:%S format
if value is None:
return None
try:
# correct nasty formated date
regex = re.compile(r'(\d{4}):(\d{2}):(\d{2})')
if re.match(regex, value) is not None: # noqa
value = re.sub(regex, r'\g<1>-\g<2>-\g<3>', value)
return parser.parse(value)
except BaseException or parser._parser.ParserError as e:
self.log.warning(e.args, value)
return None
def _get_date_media_interactive(self, choices, default): def _get_date_media_interactive(self, choices, default):
print(f"Date conflict for file: {self.file_path}") print(f"Date conflict for file: {self.file_path}")
choices_list = [ choices_list = [

View File

@ -137,7 +137,7 @@ class TestCollection:
assert summary.success_table.sum('sort') == nb assert summary.success_table.sum('sort') == nb
def test_sort_files(self, tmp_path): def test_sort_files(self, tmp_path):
cli_options = {'album_from_folder': True} cli_options = {'album_from_folder': True, 'cache': False}
collection = Collection(tmp_path, cli_options=cli_options) collection = Collection(tmp_path, cli_options=cli_options)
loc = GeoLocation() loc = GeoLocation()
summary = collection.sort_files([self.src_path], summary = collection.sort_files([self.src_path],
@ -160,24 +160,22 @@ class TestCollection:
paths = Paths(filters).get_files(tmp_path) paths = Paths(filters).get_files(tmp_path)
for file_path in paths: for file_path in paths:
if '.db' not in str(file_path): if '.db' not in str(file_path):
media = Media(file_path, tmp_path, album_from_folder=True)
for value in ReadExif(file_path).get_key_values('album'): for value in ReadExif(file_path).get_key_values('album'):
assert value != '' or None assert value != '' or None
collection = Collection(tmp_path, cli_options=cli_options) collection = Collection(tmp_path, cli_options=cli_options)
# Try to change path format and sort files again # Try to change path format and sort files again
path = '{city}/{%Y}-{name}.%l{ext}' path_format = 'test_exif/{city}/{%Y}-{name}.%l{ext}'
summary = collection.sort_files([tmp_path], summary = collection.sort_files([tmp_path], path_format, loc)
self.path_format, loc)
self.assert_sort(summary, 24) self.assert_sort(summary, 27)
shutil.copytree(tmp_path / 'test_exif', tmp_path / 'test_exif_copy') shutil.copytree(tmp_path / 'test_exif', tmp_path / 'test_exif_copy')
collection.summary = Summary(tmp_path) collection.summary = Summary(tmp_path)
assert collection.summary.success_table.sum() == 0 assert collection.summary.success_table.sum() == 0
summary = collection.update(loc) summary = collection.update(loc)
assert summary.success_table.sum('update') == 2 assert summary.success_table.sum('update') == 30
assert summary.success_table.sum() == 2 assert summary.success_table.sum() == 30
assert not summary.errors assert not summary.errors
collection.summary = Summary(tmp_path) collection.summary = Summary(tmp_path)
summary = collection.update(loc) summary = collection.update(loc)