-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathdetect.py
190 lines (146 loc) · 5.06 KB
/
detect.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
from threading import Thread
import json
from queue import Queue
import os
from openai import OpenAI
from .parsers import extract_json, extract_list, rectangle_corners
from .ocr_engines import (
job_easy_ocr,
job_easy_ocr_boxes,
job_tesseract,
job_tesseract_boxes,
)
def wrapper(func, args, queue):
queue.put(func(args))
# custom error
class NoTextDetectedError(Exception):
pass
def detect():
"""Unimplemented"""
raise NotImplementedError
def detect_async():
"""Unimplemented"""
raise NotImplementedError
def detect_text(
image_path: str,
lang: list[str],
context: str = "",
tesseract: dict = {},
openai: dict = {"model": "gpt-4"},
):
"""Detect text from an image using EasyOCR and Tesseract, then combine and correct the results using OpenAI's LLM."""
q1, q2 = Queue(), Queue()
options = {
"path": image_path, # "demo.png",
"lang": lang, # ["ko", "en"]
"context": context,
"tesseract": tesseract,
"openai": openai,
}
Thread(target=wrapper, args=(job_easy_ocr, options, q1)).start()
Thread(target=wrapper, args=(job_tesseract, options, q2)).start()
q1 = q1.get()
q2 = q2.get()
optional_context_prompt = (
f"[context]: {options['context']}" if options["context"] else ""
)
prompt = f"""Combine and correct OCR results [0] and [1], using \\n for line breaks. Langauge is in {'+'.join(options['lang'])}. Remove unintended noise. Refer to the [context] keywords. Answer in the JSON format {{data:<output:string>}}:
[0]: {q1}
[1]: {q2}
{optional_context_prompt}"""
prompt = prompt.strip()
print("=====")
print(prompt)
api_key = os.environ["OPENAI_API_KEY"]
if "API_KEY" in options["openai"] and options["openai"]["API_KEY"] != "":
api_key = options["openai"]["API_KEY"]
client = OpenAI(
api_key=api_key,
)
print("=====")
completion = client.chat.completions.create(
messages=[
{"role": "user", "content": prompt},
],
**options["openai"],
)
output = completion.choices[0].message.content
print("[*] LLM", output)
result = extract_json(output)
print(result)
if "data" in result:
return result["data"]
if isinstance(result, str):
return result
raise NoTextDetectedError("No text detected")
def detect_text_async():
"""Unimplemented"""
raise NotImplementedError
def detect_boxes(
image_path: str,
lang: list[str],
context: str = "",
tesseract: dict = {},
openai: dict = {"model": "gpt-4"},
):
q1, q2 = Queue(), Queue()
options = {
"path": image_path, # "demo.png",
"lang": lang, # ["ko", "en"]
"context": context,
"tesseract": tesseract,
"openai": openai,
}
Thread(target=wrapper, args=(job_easy_ocr_boxes, options, q1)).start()
Thread(target=wrapper, args=(job_tesseract_boxes, options, q2)).start()
boxes_1 = q1.get()
boxes_2 = q2.get()
optional_context_prompt = (
" " + "Please refer to the keywords and spelling in [context]"
if options["context"]
else ""
)
optional_context_prompt_data = (
f"[context]: {options['context']}" if options["context"] else ""
)
boxes_1_json = json.dumps(boxes_1, ensure_ascii=False, default=int)
boxes_2_json = json.dumps(boxes_2, ensure_ascii=False, default=int)
prompt = f"""Combine and correct OCR data [0] and [1]. Include many items as possible. Langauge is in {'+'.join(options['lang'])} (Avoid arbitrary translations). Remove unintended noise.{optional_context_prompt} Answer in the JSON format. Ensure coordinates are integers (round based on confidence if necessary) and output in the same JSON format (indent=0): Array({{box:[[x,y],[x+w,y],[x+w,y+h],[x,y+h]],text:str}}):
[0]: {boxes_1_json}
[1]: {boxes_2_json}
{optional_context_prompt_data}"""
prompt = prompt.strip()
print("=====")
print(prompt)
api_key = os.environ["OPENAI_API_KEY"]
if "API_KEY" in options["openai"] and options["openai"]["API_KEY"] != "":
api_key = options["openai"]["API_KEY"]
client = OpenAI(
api_key=api_key,
)
print("=====")
completion = client.chat.completions.create(
messages=[
{"role": "user", "content": prompt},
],
**options["openai"],
)
output = completion.choices[0].message.content
output = output.replace("\n", "")
print("[*] LLM", output)
items = extract_list(output)
for idx, item in enumerate(items):
box = item["box"]
# [x,y,w,h]
if len(box) == 4 and isinstance(box[0], int):
rect = rectangle_corners(box)
items[idx]["box"] = rect
# [[x,y],[w,h]]
elif len(box) == 2 and isinstance(box[0], list) and len(box[0]) == 2:
flattened = [i for sublist in box for i in sublist]
rect = rectangle_corners(flattened)
items[idx]["box"] = rect
return items
def detect_boxes_async():
"""Unimplemented"""
raise NotImplementedError