]> git.treefish.org Git - photosort.git/blob - src/misc.py
move dateless files to na subdir
[photosort.git] / src / misc.py
1 import datetime
2 import mimetypes
3 import os
4 import PIL.Image
5 import re
6 import shutil
7 import subprocess
8
9 def walk_media_files(dir_path):
10     for root, dirs, files in os.walk(dir_path):
11         for f in files:
12             file_path = os.path.join(root, f)
13             if is_media_file(file_path):
14                 yield (f, file_path)
15
16 def extract_meta_time(file_path):
17     if is_media_file(file_path, types=['image']):
18         return _extract_image_timestamp(file_path)
19     elif is_media_file(file_path, types=['video']):
20         return _extract_video_timestamp(file_path)
21
22 def find_file(dir_path, file_name, file_size, exclude_dir):
23     for root, dirs, files in os.walk(dir_path):
24         if root.startswith(exclude_dir):
25             continue
26         for f in files:
27             if f == file_name:
28                 full_path = os.path.join(root, f)
29                 if os.path.getsize(full_path) == file_size:
30                     return root
31     return None
32
33 def import_file(src_file_path, dst_file_path):
34     shutil.copyfile(src_file_path, dst_file_path)
35     src_stat = os.stat(src_file_path)
36     dst_stat = os.stat(dst_file_path)
37     os.utime( dst_file_path, ns=(dst_stat.st_atime_ns, src_stat.st_mtime_ns) )
38
39 def is_media_file(file_path, types=['image', 'video']):
40     if not os.path.isfile(file_path):
41         return False
42     mime_type = mimetypes.guess_type(file_path)[0]
43     if not mime_type:
44         return False
45     if not mime_type.split('/')[0] in types:
46         return False
47     return True
48
49 def _extract_image_timestamp(file_path):
50     time = None
51     try:
52         with PIL.Image.open(file_path) as image:
53             exif = image._getexif()
54             if exif and 36867 in exif:
55                 time = datetime.datetime\
56                                .strptime(exif[36867], '%Y:%m:%d %H:%M:%S')\
57                                .timestamp()
58     except Exception as e:
59         logging.warn("Error extracting exif for %s: %s", file_path, str(e))
60     return time
61
62 def _extract_video_timestamp(file_path):
63     p = subprocess.run(['ffmpeg', '-i', file_path],
64                        capture_output=True, encoding='UTF-8')
65     for line in p.stderr.splitlines():
66         m = re.search('^.*creation_time.*: ([^ ]+)$', line)
67         if m:
68             return datetime.datetime\
69                            .strptime(m.group(1), '%Y-%m-%dT%H:%M:%S.%fZ')\
70                            .timestamp()
71     return None