-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
250 lines (184 loc) · 8.3 KB
/
app.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
import click
import json
import os
import sys
from cli.core import OcrInferencer
from cli.core import utils
import gradio as gr
from PIL import Image
import shutil
import zipfile
from pathlib import Path
from pdf2image import convert_from_path
class OcrProcess:
def __init__(self):
self.tmp_dir = '/root/ocr_cli/tmp'
self.img_dir = os.path.join(self.tmp_dir, 'img')
# 入出力ファイルを格納する一時ディレクトリの作成
def make_tmp_dir(self):
os.makedirs(self.tmp_dir, exist_ok=True)
os.makedirs(self.img_dir, exist_ok=True)
# 一時ディレクトリの削除
def remove_tmp_dir(self):
shutil.rmtree(self.tmp_dir)
# 単一画像の保存
def save_single_image(self, input_image):
# 受け取った画像を /root/ocr_cli/tmp/img に保存する
image = Image.fromarray(input_image.astype('uint8'), 'RGB')
self.image_name = 'image.jpg'
self.image_path = os.path.join(self.img_dir, self.image_name)
image.save(self.image_path)
print(f'Image is saved: {self.image_path}')
# 複数画像の保存
def save_multiple_image(self, input_images):
for i, input_image in enumerate(input_images):
image_name = os.path.basename(input_image.name)
image_path = os.path.join(self.img_dir, image_name)
with open(input_image.name, 'rb') as image_file:
image = Image.open(image_file)
image.save(image_path)
print(f'Images are saved: {self.img_dir}')
# pdfから画像に変換し画像を保存
def save_image_from_pdf(self, input_pdf):
images = convert_from_path(input_pdf.name)
for i, image in enumerate(images):
output_file = os.path.join(self.img_dir, f'{os.path.basename(input_pdf.name)}_{str(i+1).zfill(4)}.jpg')
image.save(output_file, 'JPEG')
print(f'PDF is converted and images are saved: {self.img_dir}')
def infer(self, config_file, proc_range, save_image, save_xml, input_structure, dump):
if input_structure == 'f':
input_root = self.image_path
elif input_structure == 's':
input_root = self.tmp_dir
self.output_root = os.path.join(self.tmp_dir, 'output')
cfg = {
'input_root': input_root,
'output_root': self.output_root,
'config_file': config_file,
'proc_range': proc_range,
'save_image': save_image,
'save_xml': save_xml,
'dump': dump,
'input_structure': input_structure
}
# check if input_root exists
if not os.path.exists(input_root):
print('INPUT_ROOT not found :{0}'.format(input_root), file=sys.stderr)
exit(0)
# parse command line option
infer_cfg = utils.parse_cfg(cfg)
if infer_cfg is None:
print('[ERROR] Config parse error :{0}'.format(input_root), file=sys.stderr)
exit(1)
# prepare output root derectory
infer_cfg['output_root'] = utils.mkdir_with_duplication_check(infer_cfg['output_root'])
# save inference option
with open(os.path.join(infer_cfg['output_root'], 'opt.json'), 'w') as fp:
json.dump(infer_cfg, fp, ensure_ascii=False, indent=4,
sort_keys=True, separators=(',', ': '))
# do inference
inferencer = OcrInferencer(infer_cfg)
inferencer.run()
def get_text(self):
pid = os.path.splitext(os.path.basename(self.image_name))[0]
txt_path = os.path.join(self.output_root, pid, 'txt', f'{pid}_main.txt')
with open(txt_path, 'r', encoding='utf-8') as f:
text = f.read()
return text
def zip_directory(self, zip_file):
with zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, _, files in os.walk(self.output_root):
for file in files:
file_path = os.path.join(root, file)
zipf.write(file_path, os.path.relpath(file_path, self.output_root))
def ocr_single_image(input_image, config_file, proc_range, save_image, save_xml, dump):
ocr = OcrProcess()
ocr.make_tmp_dir()
ocr.save_single_image(input_image)
# infer
input_structure = 'f'
ocr.infer(config_file, proc_range, save_image, save_xml, input_structure, dump)
# outputs
text = ocr.get_text()
ocr.zip_directory('result.zip')
ocr.remove_tmp_dir()
return text, 'result.zip'
def ocr_multiple_image(input_images, config_file, proc_range, save_image, save_xml, dump):
ocr = OcrProcess()
ocr.make_tmp_dir()
ocr.save_multiple_image(input_images)
input_structure = 's'
ocr.infer(config_file, proc_range, save_image, save_xml, input_structure, dump)
ocr.zip_directory('result.zip')
ocr.remove_tmp_dir()
return 'result.zip'
def ocr_pdf(input_pdf, config_file, proc_range, save_image, save_xml, dump):
ocr = OcrProcess()
ocr.make_tmp_dir()
ocr.save_image_from_pdf(input_pdf)
input_structure = 's'
ocr.infer(config_file, proc_range, save_image, save_xml, input_structure, dump)
ocr.zip_directory('result.zip')
ocr.remove_tmp_dir()
return 'result.zip'
def main():
with gr.Blocks() as interface:
gr.Markdown('入力形式を選んでください')
with gr.Tabs():
with gr.TabItem('単一画像'):
i2t_inputs = [
# input_image
gr.Image(label='入力画像'),
# config_file
gr.Textbox(label='設定ファイル', value='config.yml'),
# proc_range
gr.Textbox(label='部分実行(0: ノド元分割, 1: 傾き補正, 2: レイアウト抽出, 3: 文字認識(OCR))', value='0..3'),
# save_image
gr.Checkbox(label='画像保存'),
# save_xml
gr.Checkbox(label='XML保存'),
# dump
gr.Checkbox(label='dump')
]
i2t_outputs = [gr.Textbox(label='結果'), gr.File(label='出力ファイル (ZIP)')]
i2t_button = gr.Button('OCR開始')
with gr.TabItem('複数画像'):
d2t_inputs = [
# input_image
gr.File(label='入力画像', file_count='multiple', file_types=['image']),
# config_file
gr.Textbox(label='設定ファイル', value='config.yml'),
# proc_range
gr.Textbox(label='部分実行(0: ノド元分割, 1: 傾き補正, 2: レイアウト抽出, 3: 文字認識(OCR))', value='0..3'),
# save_image
gr.Checkbox(label='画像保存'),
# save_xml
gr.Checkbox(label='XML保存'),
# dump
gr.Checkbox(label='dump')
]
d2t_outputs = gr.File(label='出力ファイル (ZIP)')
d2t_button = gr.Button('OCR開始')
with gr.TabItem('PDF'):
p2t_inputs = [
# input_pdf
gr.File(label='入力PDF', file_types=[".pdf"]),
# config_file
gr.Textbox(label='設定ファイル', value='config.yml'),
# proc_range
gr.Textbox(label='部分実行(0: ノド元分割, 1: 傾き補正, 2: レイアウト抽出, 3: 文字認識(OCR))', value='0..3'),
# save_image
gr.Checkbox(label='画像保存'),
# save_xml
gr.Checkbox(label='XML保存'),
# dump
gr.Checkbox(label='dump')
]
p2t_outputs = gr.File(label='出力ファイル (ZIP)')
p2t_button = gr.Button('OCR開始')
i2t_button.click(ocr_single_image, inputs=i2t_inputs, outputs=i2t_outputs)
d2t_button.click(ocr_multiple_image, inputs=d2t_inputs, outputs=d2t_outputs)
p2t_button.click(ocr_pdf, inputs=p2t_inputs, outputs=p2t_outputs)
interface.launch()
if __name__ == '__main__':
main()