-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdo-ocr.py
More file actions
67 lines (51 loc) · 2.1 KB
/
Copy pathdo-ocr.py
File metadata and controls
67 lines (51 loc) · 2.1 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
#!/usr/bin/env python3
from pathlib import Path
import subprocess
import json
import sys
import threading
from concurrent.futures import ThreadPoolExecutor
lock = threading.Lock()
def ocr_file(image):
bucket_key = image.stem.replace("snap_", '')
try:
lock.acquire()
# check if the file name is already in the dictionary, and skip it if so
if bucket_key in ocr_dict:
lock.release()
return
lock.release()
# run the ocr command on the file, and capture the output from stdout
# !! mac m1/m2 only: use the version from https://github.com/glowinthedark/macOCR/releases or the OCR binary in this repo
# let (language, fastmode, languageCorrection, src, dst) = (args[1], args[2],args[3],args[4],args[5])
# https://github.com/xulihang/macOCR/blob/main/OCR/main.swift
proc = subprocess.run(["./OCR", "en-US", "false", "true", image.absolute()],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
recognized_text = proc.stdout.decode()
err = proc.stderr.decode()
if err:
print("😱", err)
else:
lock.acquire()
print(bucket_key, recognized_text)
ocr_dict[bucket_key] = recognized_text
sorted_data = {k: ocr_dict[k] for k in sorted(ocr_dict)}
with open(results_file, "w") as f:
json.dump(sorted_data, f, ensure_ascii=False, indent=1)
finally:
lock.release()
if __name__ == '__main__':
folder_name = sys.argv[1]
results_file = sys.argv[2]
# load the existing dictionary from json file, or create an empty one
res_file = Path(results_file)
if res_file.exists():
ocr_dict = json.load(res_file.open(encoding='utf-8'))
else:
ocr_dict = {}
##### TODO: tweak the threadpool size to your liking depending on available system resources
with ThreadPoolExecutor(max_workers=20) as executor:
img: Path
for img in Path(folder_name).glob("*.png"):
executor.submit(ocr_file, img)