-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdatabase.py
More file actions
279 lines (255 loc) · 9.03 KB
/
database.py
File metadata and controls
279 lines (255 loc) · 9.03 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
try:
import Image
except ImportError:
from PIL import Image
import copy
import imghdr
import os
import re
import shutil
import pytesseract
from flickr import download_flickr_images, upload_image
# FOLDER PATHS
LOADING_ZONE = "loading_zone"
TEXT_PATH = "completed_text_files"
DEST_PATH = "completed_files"
# SPECIAL FILES
COUNT_FILE = "filecount.txt"
METADATA_FILE = "metadata.txt"
# METADATA FILES
METADATA_FILE_NAME_FIELD = "File Name"
METADATA_FIELDS = [
METADATA_FILE_NAME_FIELD,
"Name of Picture Taker (Last, First)",
"Date Added (mm/dd/yyyy)",
"Box Number",
"Folder",
"Page Number",
"Title",
"Creator",
"Subject",
"Description",
"Publisher",
"Type",
"Format",
"Source",
"Language",
"Tags and/or Keywords",
"Rights Management",
"Comments/Notes about File"
]
def indent_print(message, indent=0):
print(4 * indent * " " + message)
# DOCUMENT FUNCTIONS
class Document:
def __init__(self, image_file):
self.image_file = image_file
self.image_path = os.path.join(DEST_PATH, image_file)
self.filenumber = re.search("document(.*)image", self.image_path).group(1)
self.text_file = self.text_file_name()
self.text_path = os.path.join(TEXT_PATH, self.text_file)
if self.has_text_file():
with open(self.text_path) as file:
self.text = file.read()
else:
self.text = ""
self.metadata = {}
self.metadata_list = self.get_metadata_list()
self.search_meta_matches = {}
self.search_text_matches = []
def get_metadata_list(self):
list_from_dict = []
for field in METADATA_FIELDS:
if field in self.metadata:
list_from_dict.append([field, self.metadata[field]])
else:
list_from_dict.append([field, ''])
for field, value in sorted(self.metadata.items()):
if field not in METADATA_FIELDS:
list_from_dict.append([field, value])
return list_from_dict
def text_file_name(self):
return "document" + str(self.filenumber) + "text.txt"
def has_image_file(self):
return os.path.exists(self.image_path)
def has_text_file(self):
return os.path.exists(self.text_path)
def has_files(self):
return self.has_text_file()
def write_text_file(self):
with open(self.text_path, "w") as file:
file.write(self.text)
def metadata_string(self):
lines = []
# add all defined fields first
for field in METADATA_FIELDS:
if field in self.metadata:
lines.append(field + ": [" + self.metadata[field] + "]")
else:
lines.append(field + ": []")
# then add the remainder alphabetically
for field, value in sorted(self.metadata.items()):
if field not in METADATA_FIELDS:
lines.append(field + ": [" + value + "]")
return "\n".join(lines)
def create_new_metadata(file):
metadata = {}
for field in METADATA_FIELDS:
metadata[field] = ""
metadata[METADATA_FILE_NAME_FIELD] = file
return metadata
def metadata_to_dict(section):
metadata = {}
# FIXME assumes each line is a field
for line in section.splitlines():
line = line.strip()
if line == "":
continue
field, value = line.split(":", maxsplit=1)
# remove trailing spaces and the [brackets]
value = value.strip()[1:-1]
metadata[field] = value
return metadata
def read_documents():
documents = []
with open(METADATA_FILE) as file:
metadata_text = file.read()
for section in metadata_text.split("\n\n"):
if section.strip() == "":
continue
metadata = metadata_to_dict(section)
# create the Document using the File Name
doc = Document(metadata[METADATA_FILE_NAME_FIELD])
doc.metadata = metadata
# only add it to the list of documents if those files actually exist
if doc.has_files():
documents.append(doc)
return documents
def search_term_in_metadata_and_text(term):
matches = set()
if term:
term = term.lower()
for instance in read_documents():
index = 0
for key in instance.metadata:
if term in instance.metadata[key].lower():
if instance not in matches:
matches.add(instance)
if term in instance.text.lower():
while index < len(instance.text):
index = instance.text.lower().find(term, index)
if index == -1:
break
instance.search_text_matches.append(index)
index += len(term)
if instance not in matches:
matches.add(instance)
if not matches:
matches = "No search matches found."
return matches
# OCR FUNCTIONS
def text_file_exists(path):
for file in os.listdir(path):
if file.endswith('.txt'):
return True
return False
def read_folder_metadata(path):
text_exists = text_file_exists(path)
if text_exists:
for file in os.listdir(path):
if file.endswith('.txt'):
with open(os.path.join(path, file)) as file:
return metadata_to_dict(file.read())
def request_new_file_number():
with open(COUNT_FILE) as file:
file_number = int(file.read())
with open(COUNT_FILE, "w") as file:
file.write(str(file_number + 1))
return file_number
def rotate_image_ocr(path):
images = [Image.open(path)]
text = pytesseract.image_to_string(images[-1])
ocr_extractions = [text]
for i in range(3):
images.append(images[-1].rotate(90))
text = pytesseract.image_to_string(images[-1])
ocr_extractions.append(text)
images_zip_ocr = [list(pair) for pair in zip(images, ocr_extractions)]
return images_zip_ocr
def count_occurrences(images_zip_ocr):
occurrences = []
for img_txt_pair in images_zip_ocr:
ocr_text = img_txt_pair[1]
num_occurrences = ocr_text.lower().count('the')
occurrences.append(num_occurrences)
return occurrences
def isolate_correct_img_ocr(path):
images_zip_ocr = rotate_image_ocr(path)
occurrences_of_the = count_occurrences(images_zip_ocr)
index_of_pair = occurrences_of_the.index(max(occurrences_of_the))
img_ocr = images_zip_ocr[index_of_pair]
return img_ocr
def run_image(file, metadata):
# create the new Document
doc = Document(file)
doc.metadata = metadata
doc.metadata[METADATA_FILE_NAME_FIELD] = doc.image_file
# run OCR, update the doc, and write the file
img_ocr = isolate_correct_img_ocr(doc.image_path)
doc.text = img_ocr[1]
doc.write_text_file()
# save the image in the right place
img_ocr[0].save(doc.image_path)
# upload image to Flickr
indent_print("Uploading to Flickr...", indent=2)
flickr_dict = upload_image(doc.image_path)
doc.metadata.update(flickr_dict)
# update master metadata file
with open(METADATA_FILE, "a") as file:
file.write(doc.metadata_string())
file.write("\n")
file.write("\n")
return doc
def run_folder_images(path):
new_documents = []
metadata = read_folder_metadata(path)
for file in os.listdir(path):
old_file_path = os.path.join(path, file)
image_type = imghdr.what(old_file_path)
if image_type:
indent_print("{} is a {} file; running OCR...".format(file, image_type), indent=2)
# build the new file path
file_ext = file.split(".")[1]
count = request_new_file_number()
new_file_name = 'document' + str(count) + 'image.' + file_ext
new_file_path = os.path.join(DEST_PATH, new_file_name)
# move the file first
os.rename(old_file_path, new_file_path)
# create a document and do OCR
doc = run_image(new_file_name, copy.copy(metadata))
new_documents.append(doc)
shutil.rmtree(path)
return new_documents
def run_images():
indent_print("Running OCR on images...", indent=0)
new_documents = []
for folder in os.listdir(LOADING_ZONE):
path = os.path.join(LOADING_ZONE, folder)
if os.path.isdir(path):
indent_print("Looking at folder {}...".format(folder), indent=1)
if not text_file_exists(path):
indent_print("No metadata file found; skipping...", indent=2)
continue
metadata = read_folder_metadata(path)
if all(s == "" for s in metadata.values()):
indent_print("Metadata file is empty; skipping...", indent=2)
continue
new_documents.extend(run_folder_images(path))
return new_documents
if __name__ == "__main__":
os.chdir(os.path.dirname(os.path.realpath(__file__)))
indent_print("Initializing...", indent=0)
download_flickr_images()
run_images()
print()
indent_print("Done!", indent=0)