-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathmain.py
More file actions
96 lines (77 loc) · 2.97 KB
/
main.py
File metadata and controls
96 lines (77 loc) · 2.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import os
import json
import sys
from pathlib import Path
import re
stem_regex = r'.*\(\d+\)\..*'
def get_alike_regex(filename):
tokens = filename.split(".")
name = re.escape(".".join(tokens[0:len(tokens) - 1]))
ext = re.escape(tokens[len(tokens) - 1])
return fr".*{name}( (\d{{1,2}}\.){{2}}\d{{1,2}} PM)+\.{ext}\..*"
def get_alike_regex_with_duplication(filename):
return fr".*{re.escape(filename)}( (\d{{1,2}}\.){{2}}\d{{1,2}} PM)+\..*"
def move_duplication_string(path):
pattern = r"(.*)\((.*?)\)(\..*)"
match = re.search(pattern, path)
if match:
new_path = match.group(1) + match.group(3) + "(" + match.group(2) + ")"
return new_path
else:
return path
def get_alike_json(path):
dir_path = os.path.dirname(path)
file_name = os.path.basename(path)
jsons = [os.path.join(dir_path, f) for f in os.listdir(dir_path) if f.endswith('.json')]
regex = get_alike_regex(file_name)
for json in jsons:
if re.match(regex, json):
return json
# Try with duplication
file_name = os.path.basename(move_duplication_string(path))
regex = get_alike_regex_with_duplication(file_name)
for json in jsons:
if re.match(regex, json):
return json
def get_json_data(image_path):
json_path = Path(move_duplication_string(image_path) + ".json")
json_data = None
try:
with open(json_path, 'r') as f:
json_data = json.load(f)
except FileNotFoundError:
try:
with open(Path(image_path + ".json"), 'r') as f:
json_data = json.load(f)
except FileNotFoundError:
try:
# Remove the "-edited" from the file name
no_edited = image_path.replace("-edited", "")
with open(Path(no_edited + ".json"), 'r') as f:
json_data = json.load(f)
except FileNotFoundError:
try:
with open(Path(get_alike_json(image_path)), 'r') as f:
json_data = json.load(f)
except FileNotFoundError:
print(f"Could not find JSON file for {image_path}")
return
# os.remove(image_path)
return json_data
def update_image_metadata(image_path):
# Get the timestamp from the JSON file
json_data = get_json_data(image_path)
timestamp = json_data['photoTakenTime']['timestamp']
# Convert the timestamp from string to float
timestamp = float(timestamp)
# Update the image's creation time
os.utime(image_path, (timestamp, timestamp))
path = sys.argv[1]
for dirpath, dirnames, filenames in os.walk(path):
for filename in filenames:
if not filename.endswith('.json') and filename != '.DS_Store':
file_path = os.path.join(dirpath, filename)
try:
update_image_metadata(file_path)
except:
print("Could not update image creation time for " + file_path)