]> git.treefish.org Git - photosort.git/blob - src/misc.py
4d39b3382cfcfac732dcbb8a28fbac5bc201b3d2
[photosort.git] / src / misc.py
1 import datetime
2 import mimetypes
3 import os
4 import PIL.Image
5 import shutil
6
7 def walk_media_files(dir_path):
8     for root, dirs, files in os.walk(dir_path):
9         for f in files:
10             file_path = os.path.join(root, f)
11             if _is_media_file(file_path):
12                 yield (f, file_path)
13
14 def extract_timestamp(file_path, use_exif=False):
15     if use_exif:
16         try:
17             with PIL.Image.open(file_path) as image:
18                 exif = image._getexif()
19                 if exif and 36867 in exif:
20                     return int( datetime.datetime
21                                 .strptime(exif[36867], '%Y:%m:%d %H:%M:%S')
22                                 .timestamp() )
23         except PIL.UnidentifiedImageError:
24             pass
25     return os.path.getmtime(file_path)
26
27 def find_file(dir_path, file_name, file_size, exclude_dir):
28     for root, dirs, files in os.walk(dir_path):
29         if root == exclude_dir:
30             continue
31         for f in files:
32             if f == file_name:
33                 full_path = os.path.join(root, f)
34                 if os.path.getsize(full_path) == file_size:
35                     return root
36     return None
37
38 def import_file(src_file_path, dst_file_path, move=False):
39     shutil.copyfile(src_file_path, dst_file_path)
40     src_stat = os.stat(src_file_path)
41     dst_stat = os.stat(dst_file_path)
42     os.utime( dst_file_path, ns=(dst_stat.st_atime_ns, src_stat.st_mtime_ns) )
43
44 def delete_dir_contents(dir_path):
45     for file_name in os.listdir(dir_path):
46         file_path = os.path.join(dir_path, file_name)
47         if os.path.isfile(file_path) or os.path.islink(file_path):
48             os.unlink(file_path)
49         elif os.path.isdir(file_path):
50             shutil.rmtree(file_path)
51
52 def _is_media_file(file_path):
53     if not os.path.isfile(file_path):
54         return False
55     mime_type = mimetypes.guess_type(file_path)[0]
56     if not mime_type:
57         return False
58     if not mime_type.split('/')[0] in ['image', 'video']:
59         return False
60     return True