| 1 |
|
| 2 |
|
| 3 |
""" |
| 4 |
This script should be opened within tmux and no other tmux sessions should be |
| 5 |
running. |
| 6 |
|
| 7 |
Author: Gertjan van den Burg |
| 8 |
|
| 9 |
""" |
| 10 |
|
| 11 |
import argparse |
| 12 |
import codecs |
| 13 |
import gzip |
| 14 |
import io |
| 15 |
import json |
| 16 |
import os |
| 17 |
import time |
| 18 |
import unicodedata |
| 19 |
|
| 20 |
import chardet |
| 21 |
import libtmux |
| 22 |
|
| 23 |
|
| 24 |
def get_encoding(filename): |
| 25 |
detector = chardet.UniversalDetector() |
| 26 |
final_chunk = False |
| 27 |
blk_size = 65536 |
| 28 |
with open(filename, "rb") as fid: |
| 29 |
while (not final_chunk) and (not detector.done): |
| 30 |
chunk = fid.read(blk_size) |
| 31 |
if len(chunk) < blk_size: |
| 32 |
final_chunk = True |
| 33 |
detector.feed(chunk) |
| 34 |
detector.close() |
| 35 |
encoding = detector.result.get("encoding", None) |
| 36 |
return encoding |
| 37 |
|
| 38 |
|
| 39 |
def load_file(filename, encoding="unknown"): |
| 40 |
if encoding == "unknown": |
| 41 |
encoding = get_encoding(filename) |
| 42 |
with open(filename, "r", newline="", encoding=encoding) as fid: |
| 43 |
try: |
| 44 |
return fid.read() |
| 45 |
except UnicodeDecodeError: |
| 46 |
print( |
| 47 |
"UnicodeDecodeError occurred for file: %s. " |
| 48 |
"This means the encoding was determined incorrectly " |
| 49 |
"or the file is corrupt." % filename |
| 50 |
) |
| 51 |
return None |
| 52 |
|
| 53 |
|
| 54 |
def is_potential_escapechar(char, encoding): |
| 55 |
as_unicode = codecs.decode(bytes(char, encoding), encoding=encoding) |
| 56 |
ctr = unicodedata.category(as_unicode) |
| 57 |
block = ["!", "?", '"', "'", ".", ",", ";", ":", "%", "*", "&", "#", "/"] |
| 58 |
if ctr == "Po": |
| 59 |
if as_unicode in block: |
| 60 |
return False |
| 61 |
return True |
| 62 |
return False |
| 63 |
|
| 64 |
|
| 65 |
def get_quotechar_options(data): |
| 66 |
if data is None: |
| 67 |
return set(["q", "a", "b", "t", "n"]) |
| 68 |
options = set() |
| 69 |
for x in data: |
| 70 |
if x == '"': |
| 71 |
options.add("q") |
| 72 |
elif x == "'": |
| 73 |
options.add("a") |
| 74 |
elif x == "`": |
| 75 |
options.add("b") |
| 76 |
elif x == "~": |
| 77 |
options.add("t") |
| 78 |
options.add("n") |
| 79 |
return options |
| 80 |
|
| 81 |
|
| 82 |
def has_initial_space(data, delim): |
| 83 |
if data is None: |
| 84 |
return True |
| 85 |
return "%s " % delim in data |
| 86 |
|
| 87 |
|
| 88 |
def pairwise(iterable): |
| 89 |
"s - > (s0, s1), (s1, s2), (s2, s3), ..." |
| 90 |
a = iter(iterable) |
| 91 |
b = iter(iterable) |
| 92 |
next(b, None) |
| 93 |
return zip(a, b) |
| 94 |
|
| 95 |
|
| 96 |
def get_escapechar_options(data, encoding, delim, quotechar): |
| 97 |
if data is None or encoding is None: |
| 98 |
return set(["\\"]) |
| 99 |
escapes = set() |
| 100 |
for u, v in pairwise(data): |
| 101 |
if not is_potential_escapechar(u, encoding): |
| 102 |
continue |
| 103 |
if v in [delim, quotechar] and not u in [delim, quotechar]: |
| 104 |
escapes.add(u) |
| 105 |
return escapes |
| 106 |
|
| 107 |
|
| 108 |
class Asker(object): |
| 109 |
def __init__(self, filename, pane): |
| 110 |
self.filename = filename |
| 111 |
self.opened_vim = False |
| 112 |
self.opened_less = False |
| 113 |
self.pane = pane |
| 114 |
self.note = None |
| 115 |
self.dialect = { |
| 116 |
"delimiter": None, |
| 117 |
"quotechar": None, |
| 118 |
"escapechar": None, |
| 119 |
"skipinitialspace": None, |
| 120 |
"header_idx": None, |
| 121 |
} |
| 122 |
self.skip = False |
| 123 |
self.encoding = None |
| 124 |
self.data = None |
| 125 |
self.decompressed_file = None |
| 126 |
|
| 127 |
if filename.endswith(".gz"): |
| 128 |
self.decompressed_file = os.path.splitext(filename)[0] |
| 129 |
with open(filename, "rb") as fid: |
| 130 |
with open(self.decompressed_file, "wb") as oid: |
| 131 |
oid.write(gzip.decompress(fid.read())) |
| 132 |
self.filename = self.decompressed_file |
| 133 |
|
| 134 |
def load_file(self): |
| 135 |
self.encoding = get_encoding(self.filename) |
| 136 |
self.data = load_file(self.filename, encoding=self.encoding) |
| 137 |
|
| 138 |
def ask_question( |
| 139 |
self, prompt, key, options=None, highlight_char=None, max_length=1 |
| 140 |
): |
| 141 |
if not self.opened_vim and not self.opened_less: |
| 142 |
self.open_less() |
| 143 |
self.highlight_char(highlight_char) |
| 144 |
prompt = prompt + " " if not prompt.endswith(" ") else prompt |
| 145 |
while True: |
| 146 |
if options is None: |
| 147 |
ans = input(prompt) |
| 148 |
else: |
| 149 |
ans = input("%s[%s] " % (prompt, "/".join(sorted(options)))) |
| 150 |
if ans == "quit": |
| 151 |
self.quit() |
| 152 |
elif ans == "less": |
| 153 |
self.close(clean=False) |
| 154 |
self.open_less() |
| 155 |
elif ans in ["vi", "vim"]: |
| 156 |
self.close(clean=False) |
| 157 |
self.open_vim() |
| 158 |
elif ans in ["hlt", "hltab"]: |
| 159 |
self.pane.send_keys("/\\t") |
| 160 |
elif ans in ["hls", "hlspace"]: |
| 161 |
self.pane.send_keys("/\\ ") |
| 162 |
elif ans == "skip": |
| 163 |
self.skip = True |
| 164 |
break |
| 165 |
elif ans == "note": |
| 166 |
self.note = input("Enter note: ").strip() |
| 167 |
elif ans == "none" or ans == "no": |
| 168 |
self.dialect[key] = None |
| 169 |
break |
| 170 |
elif ans == "\\t": |
| 171 |
self.dialect[key] = "\t" |
| 172 |
break |
| 173 |
elif len(ans.strip()) > max_length: |
| 174 |
print("Only length %i answers are allowed." % max_length) |
| 175 |
elif (not options is None) and (not ans.rstrip("\n") in options): |
| 176 |
print("Only these options are allowed: %r" % options) |
| 177 |
else: |
| 178 |
self.dialect[key] = ans.rstrip("\n") |
| 179 |
break |
| 180 |
|
| 181 |
def process(self): |
| 182 |
print("Annotating file: %s" % self.filename) |
| 183 |
self.ask_question("What is the delimiter?", "delimiter") |
| 184 |
if self.skip: |
| 185 |
return None |
| 186 |
|
| 187 |
self.load_file() |
| 188 |
if has_initial_space(self.data, self.dialect["delimiter"]): |
| 189 |
hval = "%s " % self.dialect["delimiter"] |
| 190 |
self.ask_question( |
| 191 |
"What is skipinitialspace?", |
| 192 |
"skipinitialspace", |
| 193 |
options=["t", "f"], |
| 194 |
highlight_char=hval, |
| 195 |
) |
| 196 |
if self.skip: |
| 197 |
return None |
| 198 |
self.dialect["skipinitialspace"] = {"t": True, "f": False}[ |
| 199 |
self.dialect["skipinitialspace"] |
| 200 |
] |
| 201 |
else: |
| 202 |
self.dialect["skipinitialspace"] = False |
| 203 |
|
| 204 |
q_options = get_quotechar_options(self.data) |
| 205 |
if list(q_options) == ["n"]: |
| 206 |
self.dialect["quotechar"] = None |
| 207 |
else: |
| 208 |
q_options.remove("n") |
| 209 |
hval = None |
| 210 |
if "q" in q_options: |
| 211 |
hval = '"' |
| 212 |
elif "a" in q_options: |
| 213 |
hval = "'" |
| 214 |
self.ask_question( |
| 215 |
"What is the quotation mark", |
| 216 |
"quotechar", |
| 217 |
options=q_options, |
| 218 |
highlight_char=hval, |
| 219 |
) |
| 220 |
if not self.dialect["quotechar"] is None: |
| 221 |
self.dialect["quotechar"] = { |
| 222 |
"Q": '"', |
| 223 |
"A": "'", |
| 224 |
"B": "`", |
| 225 |
"T": "~", |
| 226 |
}[self.dialect["quotechar"].upper()] |
| 227 |
if self.skip: |
| 228 |
return None |
| 229 |
|
| 230 |
e_options = get_escapechar_options( |
| 231 |
self.data, |
| 232 |
self.encoding, |
| 233 |
self.dialect["delimiter"], |
| 234 |
self.dialect["quotechar"], |
| 235 |
) |
| 236 |
if "n" in e_options: |
| 237 |
raise ValueError("'n' shouldn't be an option in escapechars") |
| 238 |
if len(e_options) == 1 and "\\" in e_options: |
| 239 |
hval = "\\\\" |
| 240 |
else: |
| 241 |
hval = None |
| 242 |
if e_options: |
| 243 |
self.ask_question( |
| 244 |
"What is the escape character?", |
| 245 |
"escapechar", |
| 246 |
options=e_options, |
| 247 |
highlight_char=hval, |
| 248 |
) |
| 249 |
if self.skip: |
| 250 |
return None |
| 251 |
|
| 252 |
n_lines = sum((1 for l in io.StringIO(self.data))) |
| 253 |
self.pane.send_keys("gg", enter=False, suppress_history=False) |
| 254 |
self.ask_question( |
| 255 |
"Where is the header?", "header_idx", max_length=max(1, n_lines) |
| 256 |
) |
| 257 |
if not self.dialect["header_idx"] is None: |
| 258 |
self.dialect["header_idx"] = int(self.dialect["header_idx"]) |
| 259 |
if self.skip: |
| 260 |
return None |
| 261 |
|
| 262 |
if self.dialect["delimiter"] is None: |
| 263 |
self.dialect["delimiter"] = "" |
| 264 |
if self.dialect["quotechar"] is None: |
| 265 |
self.dialect["quotechar"] = "" |
| 266 |
if self.dialect["escapechar"] is None: |
| 267 |
self.dialect["escapechar"] = "" |
| 268 |
|
| 269 |
return True |
| 270 |
|
| 271 |
def highlight_char(self, char=None): |
| 272 |
if char is None: |
| 273 |
return |
| 274 |
self.pane.send_keys("/%s" % char) |
| 275 |
self.pane.send_keys("gg", enter=False, suppress_history=False) |
| 276 |
self.pane.send_keys("n", enter=False, suppress_history=False) |
| 277 |
|
| 278 |
def open_vim(self): |
| 279 |
self.pane.send_keys("vim %s" % self.filename) |
| 280 |
self.opened_vim = True |
| 281 |
|
| 282 |
def open_less(self): |
| 283 |
self.pane.send_keys("less -N -f %s" % self.filename) |
| 284 |
self.opened_less = True |
| 285 |
|
| 286 |
def close(self, clean=True): |
| 287 |
if self.opened_less: |
| 288 |
self.close_less() |
| 289 |
elif self.opened_vim: |
| 290 |
self.close_vim() |
| 291 |
self.pane.clear() |
| 292 |
if clean and not self.decompressed_file is None: |
| 293 |
os.unlink(self.decompressed_file) |
| 294 |
|
| 295 |
def close_vim(self): |
| 296 |
self.pane.send_keys(":q", suppress_history=False) |
| 297 |
time.sleep(0.5) |
| 298 |
self.opened_vim = False |
| 299 |
|
| 300 |
def close_less(self): |
| 301 |
self.pane.send_keys("q", suppress_history=False) |
| 302 |
time.sleep(0.1) |
| 303 |
self.opened_less = False |
| 304 |
|
| 305 |
def quit(self): |
| 306 |
self.close() |
| 307 |
self.pane.send_keys("exit") |
| 308 |
print("Thank you.") |
| 309 |
raise SystemExit |
| 310 |
|
| 311 |
|
| 312 |
def annotate_file(filename, name, tmux_pane): |
| 313 |
print() |
| 314 |
asker = Asker(filename, tmux_pane) |
| 315 |
res = asker.process() |
| 316 |
out = {"filename": name + ".csv", "status": "ok"} |
| 317 |
if not asker.note is None: |
| 318 |
out["note"] = asker.note |
| 319 |
|
| 320 |
if res is None: |
| 321 |
out["status"] = "skip" |
| 322 |
asker.close() |
| 323 |
return out |
| 324 |
out["dialect"] = asker.dialect |
| 325 |
out["encoding"] = asker.encoding |
| 326 |
asker.close() |
| 327 |
return out |
| 328 |
|
| 329 |
|
| 330 |
def dump_result(output_file, res): |
| 331 |
with open(output_file, "a") as fid: |
| 332 |
json.dump(res, fid, indent=2, sort_keys=True) |
| 333 |
|
| 334 |
|
| 335 |
def init_tmux(): |
| 336 |
tmux_server = libtmux.Server() |
| 337 |
tmux_sess = tmux_server.list_sessions()[-1] |
| 338 |
tmux_win = tmux_sess.attached_window |
| 339 |
less_pane = tmux_win.split_window(attach=False) |
| 340 |
|
| 341 |
return less_pane |
| 342 |
|
| 343 |
|
| 344 |
def process(input_dir, output_dir): |
| 345 |
input_files = os.listdir(input_dir) |
| 346 |
input_files.sort() |
| 347 |
input_paths = [os.path.join(input_dir, f) for f in input_files] |
| 348 |
output_files = os.listdir(output_dir) |
| 349 |
output_paths = [os.path.join(output_dir, f) for f in output_files] |
| 350 |
|
| 351 |
data = [] |
| 352 |
for ipath in input_paths: |
| 353 |
base, ext = os.path.splitext(os.path.basename(ipath)) |
| 354 |
md5, base_ext = os.path.splitext(base) |
| 355 |
if not (ext == ".csv" or (ext == ".gz" and base_ext == ".csv")): |
| 356 |
print("Warning: non-csv file found in input directory: %s" % ipath) |
| 357 |
continue |
| 358 |
opath = os.path.join(output_dir, md5 + ".json") |
| 359 |
if opath in output_paths: |
| 360 |
|
| 361 |
continue |
| 362 |
name = base if base_ext == "" else os.path.splitext(base)[0] |
| 363 |
data.append((ipath, opath, name)) |
| 364 |
|
| 365 |
if not data: |
| 366 |
return |
| 367 |
|
| 368 |
less_pane = init_tmux() |
| 369 |
start_time = time.time() |
| 370 |
|
| 371 |
count = 0 |
| 372 |
for ipath, opath, name in data: |
| 373 |
res = annotate_file(ipath, name, less_pane) |
| 374 |
dump_result(opath, res) |
| 375 |
count += 1 |
| 376 |
|
| 377 |
if count % 10 == 0: |
| 378 |
print( |
| 379 |
"\nProgress: %i done out of %i. " |
| 380 |
"This session: %i (%.2f seconds per file)" |
| 381 |
% ( |
| 382 |
count, |
| 383 |
len(data), |
| 384 |
count, |
| 385 |
((time.time() - start_time) / count), |
| 386 |
) |
| 387 |
) |
| 388 |
|
| 389 |
|
| 390 |
def parse_args(): |
| 391 |
parser = argparse.ArgumentParser() |
| 392 |
parser.add_argument("input_dir", help="Input directory of csv files") |
| 393 |
parser.add_argument("output_dir", help="Output directory of json files") |
| 394 |
return parser.parse_args() |
| 395 |
|
| 396 |
|
| 397 |
def main(): |
| 398 |
args = parse_args() |
| 399 |
process(args.input_dir, args.output_dir) |
| 400 |
|
| 401 |
|
| 402 |
if __name__ == "__main__": |
| 403 |
main() |