-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetadata_copier.py
More file actions
185 lines (154 loc) · 5.39 KB
/
metadata_copier.py
File metadata and controls
185 lines (154 loc) · 5.39 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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
from datetime import datetime, timedelta
import sys
import os
import re
from PyQt5 import QtGui, QtCore, uic, QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import pyexiv2
app = None
def main():
global app
app = QApplication(sys.argv)
ex = Program()
sys.exit(app.exec_())
# https://stackoverflow.com/questions/5671354/how-to-programmatically-make-a-horizontal-line-in-qt
class QHLine(QFrame):
def __init__(self):
super(QHLine, self).__init__()
self.setFrameShape(QFrame.HLine)
self.setFrameShadow(QFrame.Sunken)
class Program(QMainWindow):
def __init__(self):
super(Program, self).__init__()
# globals for processing
self.isProcessing = False
self.totalJPGs = 0
self.referenceFileCount = 0
self.processed = [0, 0, 0] # [total to process, corrected, skipped]
# set central layout and some default window options
self.mainWidget = QWidget()
self.setCentralWidget(self.mainWidget)
self.setGeometry(400, 250, 400, 300)
self.setWindowTitle('Metadata Copier')
self.mainLayout = QVBoxLayout()
self.mainWidget.setLayout(self.mainLayout)
self.pathLayout = QHBoxLayout()
self.mainLayout.addLayout(self.pathLayout)
self.pathLayout.addWidget(QLabel('path:'))
self.pathBox = QLineEdit("")
self.pathLayout.addWidget(self.pathBox)
self.pathBtn = QPushButton("Browse")
self.pathBtn.clicked.connect(self.select_path)
self.pathBox.textChanged.connect(self.verify_path)
self.pathLayout.addWidget(self.pathBtn)
# self.duplicateBox = QCheckBox('Skip files with matching names')
# self.duplicateBox.setChecked(True)
# self.duplicateBox.setToolTip('When checked, skip files when more than one matching reference file is found. This is recommended')
# self.mainLayout.addWidget(self.duplicateBox)
self.startBtnLayout = QHBoxLayout()
self.startBtnLayout.addItem(QSpacerItem(20, 20, QSizePolicy.Expanding, QSizePolicy.Fixed))
self.startBtn = QPushButton("Start")
self.startBtn.clicked.connect(self.process)
self.startBtn.setEnabled(False)
self.startBtnLayout.addWidget(self.startBtn)
self.mainLayout.addLayout(self.startBtnLayout)
self.mainLayout.addWidget(QHLine())
self.infoLabel = QLabel('')
self.mainLayout.addWidget(self.infoLabel)
self.mainLayout.addItem(QSpacerItem(20, 20, QSizePolicy.Fixed, QSizePolicy.Expanding))
self.show()
def select_path(self):
folder = QFileDialog.getExistingDirectory(self, "Select Directory")
if folder:
self.pathBox.setText(str(folder))
def verify_path(self):
if os.path.exists(str(self.pathBox.text())):
if not self.isProcessing:
self.startBtn.setEnabled(True)
self.startBtn.setText('Start')
else:
self.startBtn.setEnabled(False)
self.startBtn.setText('(invalid path)')
def update_info_text(self, stillSearching=True, stillProcessing=True):
# TODO: add info about duplicates
text = '{0} images found\n\t{1} with metadata\n\t{2} without\n'.format(
self.totalJPGs, self.referenceFileCount, self.processed[0])
if not stillSearching:
text += '{0} reference files found\n{1} files corrected\n{2} files skipped (unable to find info for)\n'.format(
self.referenceFileCount, self.processed[1], self.processed[2]
)
text += ('working...' if stillProcessing else 'done.')
self.infoLabel.setText(text)
def process(self):
self.isProcessing = True
self.startBtn.setEnabled(False)
# Reset summary data
self.totalJPGs = 0
self.referenceFileCount = 0
self.processed = [0, 0, 0]
basePath = str(self.pathBox.text())
d = {}
listToAddMeta = []
self.build_hash(basePath, d, listToAddMeta)
self.update_info_text()
self.add_meta(d, listToAddMeta)
self.update_info_text(False, False)
self.isProcessing = False
def build_hash(self, path, d, listToAddMeta):
folders = []
for i, filename in enumerate(os.listdir(path)):
if i % 100 == 1:
self.update_info_text()
app.processEvents()
filepath = os.path.join(path, filename)
if os.path.isdir(filepath):
folders.append(filepath)
elif filepath.endswith('.jpg') or filepath.endswith('.JPG'):
self.totalJPGs += 1
if self.add_to_hash(d, filepath, filename):
self.referenceFileCount += 1
else:
listToAddMeta.append((filepath, filename))
self.processed[0] += 1
for folder in folders:
self.build_hash(folder, d, listToAddMeta)
# Returns True and inserts if valid metadata, else returns False and does not insert
def add_to_hash(self, d, filepath, filename):
shortName = filename.split('.')[0]
with pyexiv2.Image(filepath) as img:
meta = img.read_exif()
if len(meta) < 1:
return False
self.trim_meta(meta)
if shortName not in d:
d[shortName] = meta
else:
pass # TODO don't go fubar
return True
def add_meta(self, d, listToAddMeta):
for i, file in enumerate(listToAddMeta):
if i % 100 == 1:
self.update_info_text(False)
app.processEvents()
filepath, filename = file
shortName = filename.split('.')[0]
if shortName in d:
with pyexiv2.Image(filepath) as img2:
img2.modify_exif(d[shortName])
self.processed[1] += 1
else:
self.processed[2] += 1
def trim_meta(self, meta):
toPop = ['Exif.Thumbnail.Compression',
'Exif.Thumbnail.XResolution',
'Exif.Thumbnail.YResolution',
'Exif.Thumbnail.ResolutionUnit',
'Exif.Thumbnail.JPEGInterchangeFormat',
'Exif.Thumbnail.JPEGInterchangeFormatLength']
for item in toPop:
if item in meta:
meta.pop(item)
if __name__ == "__main__":
main()