-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert_files.py
275 lines (224 loc) · 11.1 KB
/
convert_files.py
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
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 13 14:27:14 2020
@author: niels
"""
import os
import sys
import re
import zipfile
from shutil import rmtree
from scroll_pdf import save_jpg,save_pycode_jpg
import matplotlib.pyplot as plt
def sstr(s):
return s.encode('ascii', errors='ignore').decode('utf-8')
class convert_pdfs():
def __init__(self, path, py_files = None):
self.path = path
self.names = []
self.py_files = py_files #contains tags of the py files that are needed
def check_if_dir_exists(self):
if os.path.isdir(self.path):
if input(f"You want to remake '{self.path}'? (yes/no):\n") == "yes":
rmtree(self.path)
else:
return True
if os.path.isfile(self.path+".zip"):
self.unzip_files()
return True
else:
sys.exit(f"File {self.path}.zip not found")
def unzip_files(self):
with zipfile.ZipFile(self.path+".zip", 'r') as zip_ref:
zip_ref.extractall(self.path)
gen_obj = os.walk(self.path);
_,upper_dirnames,_ = next(gen_obj)
print(upper_dirnames)
submissions = dict()
for dirname in upper_dirnames:
name = re.findall(r" - ([\w -]*) -",dirname)[0]
lastname = re.findall(r"[^\ ]* (.*)", name)[0]
lastname = sstr(lastname).lower()
if lastname not in submissions.keys():
submissions[lastname] = 1
else:
submissions[lastname] += 1
print(submissions)
py_files = [];
pdf_files = [];
if self.py_files != None:
print(f"Multiple py files will be searched with tags: {self.py_files}")
number_of_files_found = dict()
for a in gen_obj:
(dirpath,dirnames,filenames) = a
name = re.findall(r" - ([\w -]*) -",dirpath)[0]
lastname = re.findall(r"[^\ ]* (.*)", name)[0]
lastname = sstr(lastname).lower()
submissions[lastname] -= 1
if lastname not in number_of_files_found.keys():
number_of_files_found[lastname] = 0
print(lastname)
if self.py_files == None: #single python file
try:
py_file = list(filter(lambda x : x.endswith(".py"), filenames))[0]
py_files.append([lastname,dirpath,py_file])
# print(py_file)
except IndexError:
print(f"\tpython file not found for {lastname}")
else:
for tag in self.py_files:
try:
files_found = list(filter(lambda x : x.endswith(".py"), filenames))
py_file = list(filter(lambda x : tag in x.lower(), files_found))[0]
py_files.append([lastname,dirpath,py_file,tag])
number_of_files_found[lastname] += 1
# print(py_file)
except IndexError:
print(f"\tpython file {tag} not found for {lastname}")
print(number_of_files_found[lastname])
#check if all files found
while number_of_files_found[lastname] < len(self.py_files):
if submissions[lastname] > 0:
break
for tag in self.py_files:
print(f"Wrong format detected in {lastname}")
files_found = list(filter(lambda x : x.endswith(".py"), filenames))
files_found = list(filter(lambda x : tag in x.lower(), files_found))
if files_found == []:
print(f"No files found... {tag} --> create blank file for structure:")
blank_path = self.path+"\\"+ lastname + '_' + tag + ".py"
try:
with open(blank_path, "w+"):
pass
except:
print(f"Couldn't create blank file {blank_path}")
print(f"{blank_path}")
py_files.append([lastname,dirpath,py_file,tag])
number_of_files_found[lastname] += 1
continue
selection_string = "\n".join([str(i+1) + ") " + files_found[i] for i in range(len(files_found))])
index = int(input(f"Which is {tag}? (give number) \n{selection_string}\n")) - 1
py_file = files_found[index]
selection_string = "\n".join([str(i+1) + ") " + self.py_files[i] for i in range(len(self.py_files))])
index = int(input(f"For which py file tag? (give number) \n{selection_string}\n")) - 1
py_files.append([lastname,dirpath,py_file,tag])
number_of_files_found[lastname] += 1
try:
pdf_file = list(filter(lambda x : x.endswith(".pdf"), filenames))[0]
if pdf_file == "answers.pdf":
print("answers found in wrong directory - move this file 1 directory up")
else:
pdf_files.append([lastname,dirpath,pdf_file])
# print(pdf_file)
except IndexError:
print(f"\tpdf file not found for {lastname}")
#make sure spaces have priority
for i,files in enumerate([py_files, pdf_files]):
j = 0
for name,*_ in files:
if i == 0: #py_files
py_files[j][0] = py_files[j][0].replace(' ',"AAA")
if i == 1: #pdf_files
pdf_files[j][0] = pdf_files[j][0].replace(' ',"AAA")
j+=1
#sort
py_files.sort(key = lambda x: x[0])
pdf_files.sort(key = lambda x: x[0])
# print(py_files)
# print(pdf_files)
#remove AAA's for spaces
for i,files in enumerate([py_files, pdf_files]):
j = 0
for name,*_ in files:
if i == 0: #py_files
py_files[j][0] = py_files[j][0].replace("AAA",' ')
if i == 1: #pdf_files
pdf_files[j][0] = pdf_files[j][0].replace("AAA",' ')
j+=1
if self.py_files == None: #single python file
for name,dirpath,file in py_files:
old_filename = dirpath+"\\"+file
new_filename = self.path+"\\"+name+".py"
if os.path.isfile(new_filename):
inplace_file_dirpath = [dirpath for inplace_name,dirpath,_ in py_files if inplace_name == name][0]
if (input(f"{new_filename} already exists. You want to change file from:\n{inplace_file_dirpath}\nto\n{dirpath}? (yes/no)\n") == "yes"):
os.remove(new_filename)
else:
continue
os.rename(old_filename,new_filename)
pass
else:
for tag in self.py_files:
for name,dirpath,file,file_tag in py_files:
if file_tag == tag:
old_filename = dirpath+"\\"+file
new_filename = self.path+"\\"+name+'_'+tag+".py"
if os.path.isfile(new_filename):
inplace_file_dirpath = [dirpath for inplace_name,dirpath,_,_ in py_files if inplace_name == name][0]
if (input(f"{new_filename} '{tag}' already exists. You want to change file from:\n{inplace_file_dirpath}\nto\n{dirpath}? (yes/no)\n") == "yes"):
os.remove(new_filename)
else:
continue
os.rename(old_filename,new_filename)
pass
for name,dirpath,file in pdf_files:
old_filename = dirpath+"\\"+file
new_filename = self.path+"\\"+name+".pdf"
if os.path.isfile(new_filename):
inplace_file_dirpath = [dirpath for inplace_name,dirpath,_ in pdf_files if inplace_name == name][0]
if (input(f"{new_filename} already exists. You want to change file from:\n{inplace_file_dirpath}\nto\n{dirpath}? (yes/no)\n") == "yes"):
os.remove(new_filename)
else:
continue
else:
self.names.append(name)
os.rename(old_filename,new_filename)
def check_files(self):
removal = []
for name in self.names:
if (not os.path.isfile(self.path+"\\"+name+".pdf")
or not os.path.isfile(self.path+"\\"+name+".py")
or not os.path.isfile(self.path+"\\"+name+".jpg")):
print("NOTE: incomplete files\n" +name+ " has not completed their hand-in")
removal.append(name)
for name in removal:
self.names.remove(name)
if removal == [] and self.names != []:
print("All files complete")
return True
else:
return False
def convert(self):
if not self.check_files():
self.check_if_dir_exists()
self.make_jpgs()
self.check_files()
if self.names == []:
gen_obj = os.walk(self.path);
for a in gen_obj:
(dirpath,dirnames,filenames) = a
for filename in filenames:
if filename[-3:] == "pdf" and filename[-11:] != "_pycode.pdf":
name = filename[:-4]
self.names.append(sstr(name))
self.names.sort()
print("Files were already converted")
return(self.names)
def make_jpgs(self):
print("Converting ---------")
for name in self.names:
if not os.path.isfile(self.path+"\\"+name+".jpg"):
print(name, "report...")
save_jpg(self.path+"\\"+name+".pdf")
print(name, "code...")
if self.py_files == None: #single python file
save_pycode_jpg(self.path+"\\"+name+".py")
else:
for tag in self.py_files:
save_pycode_jpg(self.path+"\\"+name+'_'+tag+".py")
print("Finished converting to jpg")
if __name__ == "__main__":
path = r"C:\Users\niels\OneDrive\OneDriveDocs\TA\Numerical Methods\student results\assignment3\Assignment 3 Download 15 October, 2020 1511"
obj = convert_pdfs(path)
names = obj.convert()
print(names)