-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathextract_dataset.py
233 lines (165 loc) · 5.75 KB
/
extract_dataset.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
#!/usr/bin/env python3
"""
Created on Tue Nov 05 09:53:17 2019
@author: Douzon
@mail: [email protected]
"""
import os
import re
import tarfile
import time
from collections import defaultdict
from concurrent.futures import ThreadPoolExecutor
from functools import partial
from pathlib import Path
from multiprocessing import Pool
from typing import Dict, List, IO, Union, Optional, Tuple
import tqdm
class_names = ["email", "form", "handwritten", "invoice", "advertisement"]
class_to_idx = {
"letter": 0,
"form": 1,
"email": 2,
"handwritten": 3,
"advertisement": 4,
"scientific report": 5,
"scientific publication": 6,
"specification": 7,
"file folder": 8,
"news article": 9,
"budget": 10,
"invoice": 11,
"presentation": 12,
"questionnaire": 13,
"resume": 14,
"memo": 15,
}
fst = ("a", "a")
fst = (fst[0], *fst)
lst = ("d", "j")
lst = (lst[0], *lst)
def timeit(f):
def wrap(*args, **kwargs):
t = time.time()
f(*args, **kwargs)
print(f"Elapsed time: {time.time() - t:0.3f}s")
return wrap
def parse_labels(label_path: Path, data_filter_f=None) -> Dict[int, List[str]]:
label_d = defaultdict(list)
with label_path.open("r") as label_file:
for line in label_file:
filename, label = line.split()
label = int(label)
if data_filter_f and data_filter_f(filename, label):
label_d[label].append(filename)
return label_d
def filter_data(filename: str, label: int):
if "images{}/{}/{}".format(*fst) <= filename < "images{}/{}/{}".format(
*lst
) and label in [class_to_idx[c] for c in class_names]:
return True
return False
def get_all_labels(dir_path: Path) -> Dict[int, List[str]]:
merge_d = defaultdict(list)
for file in dir_path.iterdir():
if file.suffix.endswith("txt"):
file_d = parse_labels(file, filter_data)
for k, v in file_d.items():
merge_d[k].extend(v)
for l in merge_d.values():
l.sort()
return merge_d
def get_xml_name(tif_name: str) -> str:
assert tif_name.endswith("tif")
new_filename = os.path.split(os.path.split(tif_name)[0])[-1] + ".xml"
return os.path.split(tif_name)[0] + "/" + new_filename
cpio_re = re.compile(r"images./([a-z])/([a-z]).*")
def get_cpio_name(file_name: str) -> Optional[str]:
match = cpio_re.match(file_name)
if match is not None:
return "images.{}.{}.cpio".format(*match.groups())
else:
return None
def get_stored_file_name(file_in_archive_name: str) -> Tuple[Path, Path]:
inter_dir = ""
suffix = ".unk"
if file_in_archive_name.endswith("xml"):
inter_dir = "ocr"
suffix = ".xml"
elif file_in_archive_name.endswith("tif"):
inter_dir = "image"
suffix = ".tif"
assert inter_dir
assert suffix in ".xml .tif".split()
inter_dir = Path(inter_dir)
return (
inter_dir,
Path(os.path.split(os.path.split(file_in_archive_name)[0])[-1] + suffix),
)
def extract_file(file_name: str, dataset_dir: Union[Path, str]) -> Optional[IO]:
if isinstance(dataset_dir, str):
dataset_dir = Path(dataset_dir)
assert dataset_dir.is_dir()
cpio_name = get_cpio_name(file_name)
if cpio_name is None:
return None
try:
archive = tarfile.open(dataset_dir / Path(cpio_name), "r")
except FileNotFoundError:
return None
return archive, archive.extractfile(file_name)
def write_file(
archive: tarfile.TarFile, file: IO, name: str, dataset_dir: Union[Path, str]
):
if isinstance(dataset_dir, str):
dataset_dir = Path(dataset_dir)
assert dataset_dir.is_dir()
inter_dir, short_file_name = get_stored_file_name(name)
file_path = dataset_dir / inter_dir / short_file_name
with file_path.open("wb") as out_file:
out_file.write(file.read())
file.close()
archive.close()
def extract_and_write(
file: str, dataset_dir_src: Union[Path, str], dataset_dir_dst: Union[Path, str]
):
streams = extract_file(file, dataset_dir_src)
if streams is None:
return
archive, file_stream = streams
write_file(archive, file_stream, file, dataset_dir_dst)
@timeit
def process_all_files(
file_l: List[str],
dataset_dir_src: Union[Path, str],
dataset_dir_dst: Union[Path, str],
max_executors=6,
):
mp_extract_and_write = partial(
extract_and_write,
dataset_dir_src=dataset_dir_src,
dataset_dir_dst=dataset_dir_dst,
)
# list(tqdm.tqdm(map(mp_extract_and_write, file_l), total=len(file_l)))
with Pool(max_executors) as executor:
# # executor.map(mp_extract_and_write, file_l)
list(tqdm.tqdm(executor.imap(mp_extract_and_write, file_l), total=len(file_l)))
if __name__ == "__main__":
tobacco_path = Path(r"D:\Tobacco\\")
seminaire_path = Path(r"F:\tobacco_dataset2\\")
label_path = Path(r"F:\labels\\")
all_tif_per_label = get_all_labels(label_path)
all_xml_per_label = {
k: list(map(get_xml_name, v)) for k, v in all_tif_per_label.items()
}
all_xml_file = sorted(sum(all_xml_per_label.values(), []))
all_tif_file = sorted(sum(all_tif_per_label.values(), []))
# print(all_xml_file[4565:4568])
# print({k: len(v) for k, v in all_xml_per_label.items()})
# aa_files = [i for i in sum(all_xml_per_label.values(), []) if fil(get_stored_file_name(i)[1])]
# print(aa_files)
# z = tarfile.open(tobacco_path / Path(get_cpio_name(aa_files[0])), 'r')
# aa_archive_xml = [z.getmember(i) for i in aa_files]
# assert all(t.isfile() for t in aa_archive_xml)
process_all_files(all_xml_file, tobacco_path, seminaire_path)
process_all_files(all_tif_file, tobacco_path, seminaire_path)