ndlocr-lite 1.4.0.dev0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cli.py +15 -0
- config/NDLmoji.yaml +4 -0
- config/__init__.py +0 -0
- config/ndl.yaml +21 -0
- deim.py +169 -0
- model/__init__.py +0 -0
- model_download.py +87 -0
- ndl_parser.py +1083 -0
- ndlocr_lite-1.4.0.dev0.dist-info/METADATA +182 -0
- ndlocr_lite-1.4.0.dev0.dist-info/RECORD +43 -0
- ndlocr_lite-1.4.0.dev0.dist-info/WHEEL +5 -0
- ndlocr_lite-1.4.0.dev0.dist-info/entry_points.txt +2 -0
- ndlocr_lite-1.4.0.dev0.dist-info/licenses/LICENCE +395 -0
- ndlocr_lite-1.4.0.dev0.dist-info/licenses/LICENCE_DEPENDENCEIES +1891 -0
- ndlocr_lite-1.4.0.dev0.dist-info/top_level.txt +16 -0
- ndlocr_lite_gui/__init__.py +12 -0
- ndlocr_lite_gui/assets/icon.png +0 -0
- ndlocr_lite_gui/gui_config.py +21 -0
- ndlocr_lite_gui/main.py +2105 -0
- ocr.py +1425 -0
- optional_features/__init__.py +52 -0
- parseq.py +74 -0
- pdf_output_utils.py +71 -0
- reading_order/__init__.py +0 -0
- reading_order/order/__init__.py +0 -0
- reading_order/order/parse_xml.py +143 -0
- reading_order/order/reorder.py +211 -0
- reading_order/order/smooth_order.py +110 -0
- reading_order/order/warichu_block.py +178 -0
- reading_order/order/wrap_dataset.py +13 -0
- reading_order/utils/__init__.py +0 -0
- reading_order/utils/file.py +21 -0
- reading_order/utils/logger.py +29 -0
- reading_order/utils/time.py +63 -0
- reading_order/utils/xml.py +97 -0
- reading_order/xy_cut/__init__.py +0 -0
- reading_order/xy_cut/block_xy_cut.py +366 -0
- reading_order/xy_cut/eval.py +55 -0
- tcy_wrapper.py +202 -0
- tools/ndlkoten2tei.py +115 -0
- uicomponent/localelabel.py +118 -0
- uicomponent/textdaisy.py +1093 -0
- version.py +3 -0
ndlocr_lite_gui/main.py
ADDED
|
@@ -0,0 +1,2105 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
# logging.basicConfig(filename='debug.log', encoding='utf-8', level=logging.DEBUG)
|
|
3
|
+
import asyncio
|
|
4
|
+
import flet as ft
|
|
5
|
+
from typing import List, Dict, Tuple
|
|
6
|
+
import sys
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import threading
|
|
10
|
+
|
|
11
|
+
APP_DIR = Path(__file__).resolve().parent
|
|
12
|
+
SOURCE_DIR = APP_DIR / 'src'
|
|
13
|
+
if __package__ == 'ndlocr_lite_gui':
|
|
14
|
+
SOURCE_DIR = APP_DIR.parent
|
|
15
|
+
elif not SOURCE_DIR.is_dir():
|
|
16
|
+
# Source checkout: CI/builds copy src beside main.py, while local development
|
|
17
|
+
# uses the repository's top-level src directory directly.
|
|
18
|
+
SOURCE_DIR = APP_DIR.parent / 'src'
|
|
19
|
+
sys.path.append(str(SOURCE_DIR))
|
|
20
|
+
|
|
21
|
+
import xml.etree.ElementTree as ET
|
|
22
|
+
import time
|
|
23
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
24
|
+
import json
|
|
25
|
+
import shutil
|
|
26
|
+
import argparse
|
|
27
|
+
import yaml
|
|
28
|
+
import io
|
|
29
|
+
import glob
|
|
30
|
+
import ctypes
|
|
31
|
+
from io import BytesIO
|
|
32
|
+
if __package__ == 'ndlocr_lite_gui':
|
|
33
|
+
from .gui_config import build_default_config
|
|
34
|
+
else:
|
|
35
|
+
from gui_config import build_default_config
|
|
36
|
+
from uicomponent.localelabel import TRANSLATIONS
|
|
37
|
+
from uicomponent.textdaisy import TextDaisyExporter
|
|
38
|
+
from collections import Counter
|
|
39
|
+
from optional_features import load_optional_features
|
|
40
|
+
from pdf_output_utils import should_output_pdf_pages_separately, write_pdf_page_outputs
|
|
41
|
+
from version import __version__
|
|
42
|
+
|
|
43
|
+
name = 'NDLOCR-Lite-GUI'
|
|
44
|
+
|
|
45
|
+
_feature_modules = load_optional_features()
|
|
46
|
+
DATA_POOL_FEATURE = (
|
|
47
|
+
_feature_modules.data_pool.create_feature()
|
|
48
|
+
if _feature_modules.data_pool is not None
|
|
49
|
+
else None
|
|
50
|
+
)
|
|
51
|
+
LLM_FEATURE = (
|
|
52
|
+
_feature_modules.llm.create_feature()
|
|
53
|
+
if _feature_modules.llm is not None
|
|
54
|
+
else None
|
|
55
|
+
)
|
|
56
|
+
TABLE_STRUCTURE_FEATURE = (
|
|
57
|
+
_feature_modules.table_structure.create_feature()
|
|
58
|
+
if _feature_modules.table_structure is not None
|
|
59
|
+
else None
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
np = None
|
|
63
|
+
Image = None
|
|
64
|
+
ImageGrab = None
|
|
65
|
+
ocr = None
|
|
66
|
+
pypdfium2 = None
|
|
67
|
+
convert_tei = None
|
|
68
|
+
categories_org_name_index = None
|
|
69
|
+
_runtime_modules_lock = threading.Lock()
|
|
70
|
+
_runtime_modules_ready = False
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def load_runtime_modules():
|
|
74
|
+
"""Load OCR/native dependencies after the first GUI frame is available."""
|
|
75
|
+
global np, Image, ImageGrab, ocr, pypdfium2
|
|
76
|
+
global convert_tei, categories_org_name_index
|
|
77
|
+
global _runtime_modules_ready
|
|
78
|
+
|
|
79
|
+
if _runtime_modules_ready:
|
|
80
|
+
return
|
|
81
|
+
with _runtime_modules_lock:
|
|
82
|
+
if _runtime_modules_ready:
|
|
83
|
+
return
|
|
84
|
+
|
|
85
|
+
import numpy as numpy_module
|
|
86
|
+
from PIL import Image as pil_image_module
|
|
87
|
+
from PIL import ImageFile as pil_image_file_module
|
|
88
|
+
from PIL import ImageGrab as pil_image_grab_module
|
|
89
|
+
import ocr as ocr_module
|
|
90
|
+
import pypdfium2 as pypdfium2_module
|
|
91
|
+
from tools.ndlkoten2tei import convert_tei as convert_tei_function
|
|
92
|
+
from ndl_parser import categories_org_name_index as category_mapping
|
|
93
|
+
|
|
94
|
+
pil_image_file_module.MAXBLOCK = 1024 * 1024 * 128
|
|
95
|
+
np = numpy_module
|
|
96
|
+
Image = pil_image_module
|
|
97
|
+
ImageGrab = pil_image_grab_module
|
|
98
|
+
ocr = ocr_module
|
|
99
|
+
pypdfium2 = pypdfium2_module
|
|
100
|
+
convert_tei = convert_tei_function
|
|
101
|
+
categories_org_name_index = category_mapping
|
|
102
|
+
_runtime_modules_ready = True
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def build_gui_result_markdown(page_result, page_tables=None):
|
|
106
|
+
"""Build ft.Markdown content in layout order for one OCR page."""
|
|
107
|
+
table_fragments = (
|
|
108
|
+
TABLE_STRUCTURE_FEATURE.markdown_fragments(page_tables)
|
|
109
|
+
if TABLE_STRUCTURE_FEATURE is not None
|
|
110
|
+
else []
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
rendered = ocr.build_markdown_text_from_xml(
|
|
114
|
+
str(page_result.get('page_xml', '')),
|
|
115
|
+
table_markdowns=table_fragments,
|
|
116
|
+
)
|
|
117
|
+
if rendered:
|
|
118
|
+
return rendered
|
|
119
|
+
return str(page_result.get('markdown_text') or page_result.get('text') or '')
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
ASSETS_DIR = APP_DIR / 'assets'
|
|
123
|
+
DEFAULT_IMAGE_SRC = str(ASSETS_DIR / 'dummy.dat')
|
|
124
|
+
APP_DATA_DIR = Path(os.environ.get('FLET_APP_STORAGE_DATA', os.getcwd())).resolve()
|
|
125
|
+
APP_TEMP_DIR = Path(
|
|
126
|
+
os.environ.get('FLET_APP_STORAGE_TEMP', str(APP_DATA_DIR / 'tmp'))
|
|
127
|
+
).resolve()
|
|
128
|
+
PDFTMPPATH = str(APP_TEMP_DIR / '4ab7ecc3-53fb-b3e7-64e8-a809b5a483d2')
|
|
129
|
+
USER_CONFIG_PATH = APP_DATA_DIR / 'userconf.yaml'
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def get_windows_scale_factor():
|
|
133
|
+
try:
|
|
134
|
+
ctypes.windll.user32.SetProcessDPIAware()
|
|
135
|
+
hdc = ctypes.windll.user32.GetDC(0)
|
|
136
|
+
dpi = ctypes.windll.gdi32.GetDeviceCaps(hdc, 88)
|
|
137
|
+
ctypes.windll.user32.ReleaseDC(0, hdc)
|
|
138
|
+
return dpi / 96.0
|
|
139
|
+
except Exception:
|
|
140
|
+
return 1.0
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
class RecogLine:
|
|
144
|
+
def __init__(self, npimg: 'np.ndarray', idx: float, pred_char_cnt: int, pred_str: str = ''):
|
|
145
|
+
self.npimg = npimg
|
|
146
|
+
self.idx = idx
|
|
147
|
+
self.pred_char_cnt = pred_char_cnt
|
|
148
|
+
self.pred_str = pred_str
|
|
149
|
+
|
|
150
|
+
def __lt__(self, other):
|
|
151
|
+
return self.idx < other.idx
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def process_cascade(alllineobj: RecogLine, recognizer30, recognizer50, recognizer100, is_cascade=True):
|
|
155
|
+
targetdflist30, targetdflist50, targetdflist100 = [], [], []
|
|
156
|
+
for lineobj in alllineobj:
|
|
157
|
+
if lineobj.pred_char_cnt == 3 and is_cascade:
|
|
158
|
+
targetdflist30.append(lineobj)
|
|
159
|
+
elif lineobj.pred_char_cnt == 2 and is_cascade:
|
|
160
|
+
targetdflist50.append(lineobj)
|
|
161
|
+
else:
|
|
162
|
+
targetdflist100.append(lineobj)
|
|
163
|
+
targetdflistall = []
|
|
164
|
+
with ThreadPoolExecutor(thread_name_prefix='recognizer') as executor:
|
|
165
|
+
jobs30 = [(lineobj, executor.submit(recognizer30.read, lineobj.npimg)) for lineobj in targetdflist30]
|
|
166
|
+
jobs50 = [(lineobj, executor.submit(recognizer50.read, lineobj.npimg)) for lineobj in targetdflist50]
|
|
167
|
+
jobs100 = [(lineobj, executor.submit(recognizer100.read, lineobj.npimg)) for lineobj in targetdflist100]
|
|
168
|
+
|
|
169
|
+
for lineobj, future in jobs30:
|
|
170
|
+
pred_str = future.result()
|
|
171
|
+
if len(pred_str) >= 25:
|
|
172
|
+
jobs50.append((lineobj, executor.submit(recognizer50.read, lineobj.npimg)))
|
|
173
|
+
else:
|
|
174
|
+
lineobj.pred_str = pred_str
|
|
175
|
+
targetdflistall.append(lineobj)
|
|
176
|
+
|
|
177
|
+
for lineobj, future in jobs50:
|
|
178
|
+
pred_str = future.result()
|
|
179
|
+
if len(pred_str) >= 45:
|
|
180
|
+
jobs100.append((lineobj, executor.submit(recognizer100.read, lineobj.npimg)))
|
|
181
|
+
else:
|
|
182
|
+
lineobj.pred_str = pred_str
|
|
183
|
+
targetdflistall.append(lineobj)
|
|
184
|
+
|
|
185
|
+
targetdflist200 = []
|
|
186
|
+
for lineobj, future in jobs100:
|
|
187
|
+
pred_str = future.result()
|
|
188
|
+
lineobj.pred_str = pred_str
|
|
189
|
+
if len(pred_str) >= 98 and lineobj.npimg.shape[0] < lineobj.npimg.shape[1]:
|
|
190
|
+
baseimg = lineobj.npimg
|
|
191
|
+
tmplineobj_1 = RecogLine(npimg=baseimg[:, :baseimg.shape[1] // 2, :], idx=lineobj.idx, pred_char_cnt=100)
|
|
192
|
+
tmplineobj_2 = RecogLine(npimg=baseimg[:, baseimg.shape[1] // 2:, :], idx=lineobj.idx, pred_char_cnt=100)
|
|
193
|
+
targetdflist200.append(tmplineobj_1)
|
|
194
|
+
targetdflist200.append(tmplineobj_2)
|
|
195
|
+
else:
|
|
196
|
+
targetdflistall.append(lineobj)
|
|
197
|
+
|
|
198
|
+
jobs200 = [(lineobj, executor.submit(recognizer100.read, lineobj.npimg)) for lineobj in targetdflist200]
|
|
199
|
+
resultlines200 = [future.result() for _, future in jobs200]
|
|
200
|
+
for i in range(0, len(targetdflist200) - 1, 2):
|
|
201
|
+
ia = targetdflist200[i]
|
|
202
|
+
lineobj = RecogLine(npimg=None, idx=ia.idx, pred_char_cnt=100, pred_str=resultlines200[i] + resultlines200[i + 1])
|
|
203
|
+
targetdflistall.append(lineobj)
|
|
204
|
+
|
|
205
|
+
targetdflistall = sorted(targetdflistall)
|
|
206
|
+
return [t.pred_str for t in targetdflistall]
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def load_ocr_models(args, *, download_models=False):
|
|
210
|
+
"""Create the four independent ONNX sessions concurrently."""
|
|
211
|
+
if download_models:
|
|
212
|
+
from model_download import resolve_model_paths
|
|
213
|
+
resolve_model_paths(args, SOURCE_DIR / 'model')
|
|
214
|
+
load_runtime_modules()
|
|
215
|
+
if hasattr(ocr, '_load_charlist'):
|
|
216
|
+
ocr._load_charlist(os.path.abspath(args.rec_classes))
|
|
217
|
+
with ThreadPoolExecutor(max_workers=4, thread_name_prefix='model-init') as executor:
|
|
218
|
+
detector_future = executor.submit(ocr.get_detector, args)
|
|
219
|
+
recognizer100_future = executor.submit(ocr.get_recognizer, args)
|
|
220
|
+
recognizer30_future = executor.submit(ocr.get_recognizer, args, args.rec_weights30)
|
|
221
|
+
recognizer50_future = executor.submit(ocr.get_recognizer, args, args.rec_weights50)
|
|
222
|
+
return (
|
|
223
|
+
detector_future.result(),
|
|
224
|
+
recognizer100_future.result(),
|
|
225
|
+
recognizer30_future.result(),
|
|
226
|
+
recognizer50_future.result(),
|
|
227
|
+
)
|
|
228
|
+
|
|
229
|
+
|
|
230
|
+
def load_rgb_image_array(input_path: str) -> 'np.ndarray':
|
|
231
|
+
load_runtime_modules()
|
|
232
|
+
with Image.open(input_path) as pil_image:
|
|
233
|
+
return np.asarray(pil_image.convert('RGB'))
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def render_pdf_page_array(pdf_path: str, page_index: int, scale: float) -> 'np.ndarray':
|
|
237
|
+
"""Render one PDF page without sharing PDFium objects between threads."""
|
|
238
|
+
load_runtime_modules()
|
|
239
|
+
pdf_doc = pypdfium2.PdfDocument(pdf_path)
|
|
240
|
+
try:
|
|
241
|
+
rendered_pages = pdf_doc.render(
|
|
242
|
+
pypdfium2.PdfBitmap.to_pil,
|
|
243
|
+
page_indices=[page_index],
|
|
244
|
+
scale=scale,
|
|
245
|
+
)
|
|
246
|
+
return np.asarray(next(iter(rendered_pages)).convert('RGB'))
|
|
247
|
+
finally:
|
|
248
|
+
pdf_doc.close()
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class ImageSelector:
|
|
252
|
+
def __init__(self, page: ft.Page, config_obj: Dict, detector=None, recognizer30=None, recognizer50=None, recognizer100=None, table_feature=None, table_recognizer=None, outputdirpath=None, width: int = 600, height: int = 600):
|
|
253
|
+
self.cnt = 0
|
|
254
|
+
self.page = page
|
|
255
|
+
self.config_obj = config_obj
|
|
256
|
+
self.langcode = config_obj['langcode']
|
|
257
|
+
self.inputpathlist = []
|
|
258
|
+
self.outputdirpath = outputdirpath
|
|
259
|
+
|
|
260
|
+
self.image_src = DEFAULT_IMAGE_SRC
|
|
261
|
+
self.dialog_width = width
|
|
262
|
+
self.dialog_height = height
|
|
263
|
+
self.page_index = 0
|
|
264
|
+
self.detector = detector
|
|
265
|
+
self.recognizer30 = recognizer30
|
|
266
|
+
self.recognizer50 = recognizer50
|
|
267
|
+
self.recognizer100 = recognizer100
|
|
268
|
+
self.table_feature = table_feature
|
|
269
|
+
self.table_recognizer = table_recognizer
|
|
270
|
+
|
|
271
|
+
self.start_x = 0
|
|
272
|
+
self.start_y = 0
|
|
273
|
+
|
|
274
|
+
self.selection_box = ft.Container(
|
|
275
|
+
left=0,
|
|
276
|
+
top=0,
|
|
277
|
+
width=0,
|
|
278
|
+
height=0,
|
|
279
|
+
border=ft.Border.all(2, ft.Colors.BLUE),
|
|
280
|
+
bgcolor=ft.Colors.TRANSPARENT,
|
|
281
|
+
)
|
|
282
|
+
|
|
283
|
+
self.overlay = ft.GestureDetector(
|
|
284
|
+
content=ft.Container(
|
|
285
|
+
width=self.dialog_width,
|
|
286
|
+
height=self.dialog_height,
|
|
287
|
+
bgcolor=ft.Colors.TRANSPARENT,
|
|
288
|
+
),
|
|
289
|
+
on_pan_start=self.pan_start,
|
|
290
|
+
on_pan_update=self.pan_update,
|
|
291
|
+
on_pan_end=self.pan_end,
|
|
292
|
+
)
|
|
293
|
+
self.img = ft.Image(src=self.image_src, width=self.dialog_width, height=self.dialog_height, fit=ft.BoxFit.CONTAIN)
|
|
294
|
+
self.imgzm = ft.Image(src=self.image_src, width=self.dialog_width, height=self.dialog_height, fit=ft.BoxFit.CONTAIN)
|
|
295
|
+
self.image_stack = ft.Stack(
|
|
296
|
+
width=self.dialog_width,
|
|
297
|
+
height=self.dialog_height,
|
|
298
|
+
controls=[
|
|
299
|
+
self.img,
|
|
300
|
+
self.selection_box,
|
|
301
|
+
self.overlay,
|
|
302
|
+
],
|
|
303
|
+
)
|
|
304
|
+
self.cropocr_btn = ft.Button(TRANSLATIONS['imageselector_cropocr_btn'][self.langcode], on_click=self.crop_region)
|
|
305
|
+
self.dialog = ft.AlertDialog(
|
|
306
|
+
modal=True,
|
|
307
|
+
content=self.image_stack,
|
|
308
|
+
actions=[
|
|
309
|
+
ft.Button(TRANSLATIONS['imageselector_zoom_btn'][self.langcode], icon=ft.Icons.ZOOM_IN, on_click=self.open_zoom_page),
|
|
310
|
+
ft.Button(TRANSLATIONS['imageselector_prev_btn'][self.langcode], on_click=self.prev_page),
|
|
311
|
+
ft.Button(TRANSLATIONS['imageselector_next_btn'][self.langcode], on_click=self.next_page),
|
|
312
|
+
self.cropocr_btn,
|
|
313
|
+
ft.Button(TRANSLATIONS['common_cancel'][self.langcode], on_click=self.close_dialog),
|
|
314
|
+
],
|
|
315
|
+
)
|
|
316
|
+
zoom_img = ft.InteractiveViewer(
|
|
317
|
+
min_scale=1,
|
|
318
|
+
max_scale=10,
|
|
319
|
+
boundary_margin=ft.Margin.all(20),
|
|
320
|
+
content=self.imgzm,
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
self.zoom_dialog = ft.AlertDialog(
|
|
324
|
+
modal=True,
|
|
325
|
+
content=zoom_img,
|
|
326
|
+
actions=[
|
|
327
|
+
ft.Button(TRANSLATIONS['common_cancel'][self.langcode], on_click=self.close_zoom_page),
|
|
328
|
+
],
|
|
329
|
+
)
|
|
330
|
+
self.resulttext = ft.Markdown(
|
|
331
|
+
value='',
|
|
332
|
+
selectable=True,
|
|
333
|
+
extension_set=ft.MarkdownExtensionSet.GITHUB_WEB,
|
|
334
|
+
soft_line_break=True,
|
|
335
|
+
visible=bool(self.config_obj.get('result_markdown_display', False)),
|
|
336
|
+
)
|
|
337
|
+
self.result_plain_text = ft.Text(
|
|
338
|
+
value='',
|
|
339
|
+
selectable=True,
|
|
340
|
+
visible=not bool(self.config_obj.get('result_markdown_display', False)),
|
|
341
|
+
)
|
|
342
|
+
self.result_view_switch = ft.Switch(
|
|
343
|
+
label='整形表示(Markdown)',
|
|
344
|
+
value=bool(self.config_obj.get('result_markdown_display', False)),
|
|
345
|
+
on_change=self.change_result_view_mode,
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
self.crop_image = ft.Image(src=self.image_src, width=300, height=300, fit=ft.BoxFit.CONTAIN)
|
|
349
|
+
crop_image_col = ft.Column(
|
|
350
|
+
controls=[self.crop_image],
|
|
351
|
+
width=300,
|
|
352
|
+
height=300,
|
|
353
|
+
expand=False,
|
|
354
|
+
)
|
|
355
|
+
self.crop_image_int = ft.InteractiveViewer(
|
|
356
|
+
min_scale=1,
|
|
357
|
+
max_scale=5,
|
|
358
|
+
boundary_margin=ft.Margin.all(20),
|
|
359
|
+
content=crop_image_col,
|
|
360
|
+
)
|
|
361
|
+
self.result_text_col = ft.Column(
|
|
362
|
+
controls=[self.result_view_switch, self.result_plain_text, self.resulttext],
|
|
363
|
+
scroll=ft.ScrollMode.ALWAYS,
|
|
364
|
+
width=800,
|
|
365
|
+
height=300,
|
|
366
|
+
expand=False,
|
|
367
|
+
)
|
|
368
|
+
|
|
369
|
+
self.result_dialog = ft.AlertDialog(
|
|
370
|
+
title=ft.Text(TRANSLATIONS['imageselector_result_title'][self.langcode]),
|
|
371
|
+
modal=True,
|
|
372
|
+
content=ft.Row([self.crop_image_int, self.result_text_col]),
|
|
373
|
+
actions=[
|
|
374
|
+
ft.Button('OK', on_click=self.close_result_page),
|
|
375
|
+
],
|
|
376
|
+
)
|
|
377
|
+
|
|
378
|
+
def change_result_view_mode(self, e=None):
|
|
379
|
+
use_markdown = bool(self.result_view_switch.value)
|
|
380
|
+
self.config_obj['result_markdown_display'] = use_markdown
|
|
381
|
+
self.resulttext.visible = use_markdown
|
|
382
|
+
self.result_plain_text.visible = not use_markdown
|
|
383
|
+
self.page.update()
|
|
384
|
+
|
|
385
|
+
def open_result_page(self):
|
|
386
|
+
if self.dialog.open:
|
|
387
|
+
self.page.pop_dialog()
|
|
388
|
+
self.page.show_dialog(self.result_dialog)
|
|
389
|
+
|
|
390
|
+
def close_result_page(self, e):
|
|
391
|
+
if self.result_dialog.open:
|
|
392
|
+
self.page.pop_dialog()
|
|
393
|
+
self.page.show_dialog(self.dialog)
|
|
394
|
+
|
|
395
|
+
def set_image(self, inputpathlist):
|
|
396
|
+
self.cnt = 0
|
|
397
|
+
self.inputpathlist = inputpathlist
|
|
398
|
+
self.page_index = 0
|
|
399
|
+
if not inputpathlist:
|
|
400
|
+
return
|
|
401
|
+
self.image_src = inputpathlist[self.page_index]
|
|
402
|
+
self.img.src = inputpathlist[self.page_index]
|
|
403
|
+
self.imgzm.src = inputpathlist[self.page_index]
|
|
404
|
+
self.page.update()
|
|
405
|
+
|
|
406
|
+
def set_outputdir(self, outputdirpath):
|
|
407
|
+
self.outputdirpath = outputdirpath
|
|
408
|
+
|
|
409
|
+
def open_zoom_page(self, e):
|
|
410
|
+
if self.dialog.open:
|
|
411
|
+
self.page.pop_dialog()
|
|
412
|
+
self.page.show_dialog(self.zoom_dialog)
|
|
413
|
+
|
|
414
|
+
def close_zoom_page(self, e):
|
|
415
|
+
if self.zoom_dialog.open:
|
|
416
|
+
self.page.pop_dialog()
|
|
417
|
+
self.page.show_dialog(self.dialog)
|
|
418
|
+
|
|
419
|
+
def pan_start(self, e: ft.DragStartEvent):
|
|
420
|
+
self.start_x = e.local_position.x
|
|
421
|
+
self.start_y = e.local_position.y
|
|
422
|
+
self.selection_box.left = self.start_x
|
|
423
|
+
self.selection_box.top = self.start_y
|
|
424
|
+
self.selection_box.width = 0
|
|
425
|
+
self.selection_box.height = 0
|
|
426
|
+
self.page.update()
|
|
427
|
+
|
|
428
|
+
def pan_update(self, e: ft.DragUpdateEvent):
|
|
429
|
+
cur_x, cur_y = e.local_position.x, e.local_position.y
|
|
430
|
+
left = min(self.start_x, cur_x)
|
|
431
|
+
top = min(self.start_y, cur_y)
|
|
432
|
+
width = abs(cur_x - self.start_x)
|
|
433
|
+
height = abs(cur_y - self.start_y)
|
|
434
|
+
self.selection_box.left = left
|
|
435
|
+
self.selection_box.top = top
|
|
436
|
+
self.selection_box.width = width
|
|
437
|
+
self.selection_box.height = height
|
|
438
|
+
self.page.update()
|
|
439
|
+
|
|
440
|
+
def pan_end(self, e: ft.DragEndEvent):
|
|
441
|
+
self.page.update()
|
|
442
|
+
|
|
443
|
+
def open_dialog(self, e):
|
|
444
|
+
if not self.dialog.open:
|
|
445
|
+
self.page.show_dialog(self.dialog)
|
|
446
|
+
|
|
447
|
+
def prev_page(self, e):
|
|
448
|
+
if not self.inputpathlist:
|
|
449
|
+
return
|
|
450
|
+
if self.page_index > 0:
|
|
451
|
+
self.page_index -= 1
|
|
452
|
+
else:
|
|
453
|
+
self.page_index = len(self.inputpathlist) - 1
|
|
454
|
+
self.img.src = self.inputpathlist[self.page_index]
|
|
455
|
+
self.imgzm.src = self.inputpathlist[self.page_index]
|
|
456
|
+
self.page.update()
|
|
457
|
+
|
|
458
|
+
def next_page(self, e):
|
|
459
|
+
if not self.inputpathlist:
|
|
460
|
+
return
|
|
461
|
+
if self.page_index < len(self.inputpathlist) - 1:
|
|
462
|
+
self.page_index += 1
|
|
463
|
+
else:
|
|
464
|
+
self.page_index = 0
|
|
465
|
+
self.img.src = self.inputpathlist[self.page_index]
|
|
466
|
+
self.imgzm.src = self.inputpathlist[self.page_index]
|
|
467
|
+
self.page.update()
|
|
468
|
+
|
|
469
|
+
def crop_region(self, e):
|
|
470
|
+
pilimg = Image.open(self.img.src)
|
|
471
|
+
pilimg = pilimg.convert('RGB')
|
|
472
|
+
rwidth, rheight = pilimg.size
|
|
473
|
+
if rheight < rwidth:
|
|
474
|
+
window_h = self.dialog_height * rheight / rwidth
|
|
475
|
+
window_w = self.dialog_width
|
|
476
|
+
offset_h = (window_w - window_h) / 2
|
|
477
|
+
offset_w = 0
|
|
478
|
+
else:
|
|
479
|
+
window_h = self.dialog_height
|
|
480
|
+
window_w = self.dialog_width * rwidth / rheight
|
|
481
|
+
offset_w = (window_h - window_w) / 2
|
|
482
|
+
offset_h = 0
|
|
483
|
+
hratio = rheight / window_h
|
|
484
|
+
wratio = rwidth / window_w
|
|
485
|
+
cropx = int((self.selection_box.left - offset_w) * wratio)
|
|
486
|
+
cropy = int((self.selection_box.top - offset_h) * hratio)
|
|
487
|
+
cropw = int(self.selection_box.width * wratio)
|
|
488
|
+
croph = int(self.selection_box.height * hratio)
|
|
489
|
+
if cropx > 0 and cropy > 0 and cropw > 10 and croph > 0:
|
|
490
|
+
im_crop = pilimg.crop((cropx, cropy, cropx + cropw, cropy + croph))
|
|
491
|
+
else:
|
|
492
|
+
return
|
|
493
|
+
buff = BytesIO()
|
|
494
|
+
im_crop.save(buff, 'png')
|
|
495
|
+
self.crop_image.src = buff.getvalue()
|
|
496
|
+
self.outputcroppedpath = os.path.join(PDFTMPPATH, os.path.splitext(os.path.basename(self.image_src))[0] + '_cropped_{}.jpg'.format(self.cnt))
|
|
497
|
+
self.page.run_task(self.mini_ocr, im_crop, self.outputcroppedpath)
|
|
498
|
+
self.cnt += 1
|
|
499
|
+
self.page.update()
|
|
500
|
+
|
|
501
|
+
async def mini_ocr(self, im_crop, outputcroppedpath=None):
|
|
502
|
+
self.cropocr_btn.disabled = True
|
|
503
|
+
self.page.update()
|
|
504
|
+
inputname = os.path.basename(outputcroppedpath or self.outputcroppedpath)
|
|
505
|
+
|
|
506
|
+
npimg = np.array(im_crop)
|
|
507
|
+
try:
|
|
508
|
+
page_result = await asyncio.to_thread(
|
|
509
|
+
ocr._run_ocr_on_image_array,
|
|
510
|
+
detector=self.detector,
|
|
511
|
+
recognizer30=self.recognizer30,
|
|
512
|
+
recognizer50=self.recognizer50,
|
|
513
|
+
recognizer100=self.recognizer100,
|
|
514
|
+
inputname=inputname,
|
|
515
|
+
img=npimg,
|
|
516
|
+
outputpath=self.outputdirpath or os.getcwd(),
|
|
517
|
+
save_viz=False,
|
|
518
|
+
)
|
|
519
|
+
page_tables = []
|
|
520
|
+
if (
|
|
521
|
+
self.table_feature is not None
|
|
522
|
+
and self.config_obj.get('table_structure', True)
|
|
523
|
+
and self.table_recognizer is not None
|
|
524
|
+
):
|
|
525
|
+
page_result, page_tables = await asyncio.to_thread(
|
|
526
|
+
self.table_feature.infer,
|
|
527
|
+
npimg,
|
|
528
|
+
page_result,
|
|
529
|
+
self.table_recognizer,
|
|
530
|
+
)
|
|
531
|
+
alltextlist = [page_result['text']]
|
|
532
|
+
display_markdown = build_gui_result_markdown(page_result, page_tables)
|
|
533
|
+
if page_result['line_count'] == 0 or (
|
|
534
|
+
page_result['line_count'] > 0 and page_result['vertical_line_count'] / page_result['line_count'] > 0.5
|
|
535
|
+
):
|
|
536
|
+
alltextlist = alltextlist[::-1]
|
|
537
|
+
os.makedirs(self.outputdirpath or os.getcwd(), exist_ok=True)
|
|
538
|
+
if page_tables:
|
|
539
|
+
tables_path = os.path.join(
|
|
540
|
+
self.outputdirpath or os.getcwd(),
|
|
541
|
+
os.path.splitext(os.path.basename(inputname))[0] + '_tables.html',
|
|
542
|
+
)
|
|
543
|
+
with open(tables_path, 'w', encoding='utf-8') as wf:
|
|
544
|
+
wf.write(self.table_feature.build_html(inputname, page_tables))
|
|
545
|
+
with open(os.path.join(self.outputdirpath or os.getcwd(), os.path.splitext(os.path.basename(inputname))[0] + '.txt'), 'w', encoding='utf-8') as wtf:
|
|
546
|
+
wtf.write('\n'.join(alltextlist))
|
|
547
|
+
self.result_plain_text.value = page_result['text']
|
|
548
|
+
self.resulttext.value = display_markdown
|
|
549
|
+
except Exception as ex:
|
|
550
|
+
self.result_plain_text.value = f'エラーが発生しました: {ex}'
|
|
551
|
+
self.resulttext.value = f'エラーが発生しました: {ex}'
|
|
552
|
+
finally:
|
|
553
|
+
self.cropocr_btn.disabled = False
|
|
554
|
+
self.open_result_page()
|
|
555
|
+
self.page.update()
|
|
556
|
+
|
|
557
|
+
def close_dialog(self, e):
|
|
558
|
+
if self.dialog.open:
|
|
559
|
+
self.page.pop_dialog()
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
class CaptureTool:
|
|
563
|
+
def __init__(self, page: ft.Page, config_obj: Dict, detector=None, recognizer30=None, recognizer50=None, recognizer100=None, table_feature=None, table_recognizer=None, width: int = 400, height: int = 300):
|
|
564
|
+
self.page = page
|
|
565
|
+
self.config_obj = config_obj
|
|
566
|
+
self.langcode = config_obj['langcode']
|
|
567
|
+
self.detector = detector
|
|
568
|
+
self.recognizer30 = recognizer30
|
|
569
|
+
self.recognizer50 = recognizer50
|
|
570
|
+
self.recognizer100 = recognizer100
|
|
571
|
+
self.table_feature = table_feature
|
|
572
|
+
self.table_recognizer = table_recognizer
|
|
573
|
+
self.dialog_width = width
|
|
574
|
+
self.dialog_height = height
|
|
575
|
+
self.im_crop = None
|
|
576
|
+
self.img_str = ''
|
|
577
|
+
self.result_jsonstr = ''
|
|
578
|
+
self.outputdirpath = os.getcwd()
|
|
579
|
+
self.scale_factor = get_windows_scale_factor()
|
|
580
|
+
self.start_x = 0
|
|
581
|
+
self.start_y = 0
|
|
582
|
+
self.current_x = 0
|
|
583
|
+
self.current_y = 0
|
|
584
|
+
|
|
585
|
+
self.original_width = 0
|
|
586
|
+
self.original_height = 0
|
|
587
|
+
self.original_left = 0
|
|
588
|
+
self.original_top = 0
|
|
589
|
+
self.original_bgcolor = None
|
|
590
|
+
|
|
591
|
+
self.selection_box = ft.Container(
|
|
592
|
+
border=ft.Border.all(2, ft.Colors.RED),
|
|
593
|
+
bgcolor=ft.Colors.with_opacity(0.2, ft.Colors.RED),
|
|
594
|
+
visible=False,
|
|
595
|
+
)
|
|
596
|
+
self.img_control = ft.Image(
|
|
597
|
+
src=b'',
|
|
598
|
+
width=self.dialog_width,
|
|
599
|
+
height=self.dialog_height,
|
|
600
|
+
fit=ft.BoxFit.CONTAIN,
|
|
601
|
+
gapless_playback=True,
|
|
602
|
+
)
|
|
603
|
+
self.retry_btn = ft.Button(TRANSLATIONS['capturetool_retry_btn'][self.langcode], on_click=self.start_capture)
|
|
604
|
+
self.cboc_fixed = ft.Checkbox(label=TRANSLATIONS['capturetool_fixregion'][self.langcode], value=False, disabled=True)
|
|
605
|
+
self.cb_table_structure = (
|
|
606
|
+
self.table_feature.create_capture_control(self.config_obj)
|
|
607
|
+
if self.table_feature is not None
|
|
608
|
+
else None
|
|
609
|
+
)
|
|
610
|
+
self.ocr_btn = ft.Button(TRANSLATIONS['capturetool_ocr_button'][self.langcode], on_click=self.mini_ocr)
|
|
611
|
+
|
|
612
|
+
self.errorlog = ft.Text('')
|
|
613
|
+
self.dialog_content = ft.Column(
|
|
614
|
+
controls=[
|
|
615
|
+
self.errorlog,
|
|
616
|
+
ft.Container(
|
|
617
|
+
content=self.img_control,
|
|
618
|
+
border=ft.Border.all(1, ft.Colors.GREY),
|
|
619
|
+
alignment=ft.Alignment.CENTER,
|
|
620
|
+
),
|
|
621
|
+
],
|
|
622
|
+
alignment=ft.MainAxisAlignment.CENTER,
|
|
623
|
+
horizontal_alignment=ft.CrossAxisAlignment.CENTER,
|
|
624
|
+
tight=True,
|
|
625
|
+
)
|
|
626
|
+
|
|
627
|
+
self.dialog = ft.AlertDialog(
|
|
628
|
+
modal=True,
|
|
629
|
+
title=ft.Text(TRANSLATIONS['capturetool_result_title'][self.langcode]),
|
|
630
|
+
content=self.dialog_content,
|
|
631
|
+
actions=[
|
|
632
|
+
ft.Row([
|
|
633
|
+
self.retry_btn,
|
|
634
|
+
ft.Column(
|
|
635
|
+
controls=[
|
|
636
|
+
self.cboc_fixed,
|
|
637
|
+
*(
|
|
638
|
+
[self.cb_table_structure]
|
|
639
|
+
if self.cb_table_structure is not None
|
|
640
|
+
else []
|
|
641
|
+
),
|
|
642
|
+
],
|
|
643
|
+
spacing=0,
|
|
644
|
+
tight=True,
|
|
645
|
+
),
|
|
646
|
+
self.ocr_btn,
|
|
647
|
+
ft.Button(TRANSLATIONS['common_close'][self.langcode], on_click=self.close_dialog),
|
|
648
|
+
]),
|
|
649
|
+
],
|
|
650
|
+
actions_alignment=ft.MainAxisAlignment.END,
|
|
651
|
+
)
|
|
652
|
+
self.resulttext = ft.Markdown(
|
|
653
|
+
value='',
|
|
654
|
+
selectable=True,
|
|
655
|
+
extension_set=ft.MarkdownExtensionSet.GITHUB_WEB,
|
|
656
|
+
soft_line_break=True,
|
|
657
|
+
visible=bool(self.config_obj.get('result_markdown_display', False)),
|
|
658
|
+
)
|
|
659
|
+
self.result_plain_text = ft.Text(
|
|
660
|
+
value='',
|
|
661
|
+
selectable=True,
|
|
662
|
+
visible=not bool(self.config_obj.get('result_markdown_display', False)),
|
|
663
|
+
)
|
|
664
|
+
self.result_view_switch = ft.Switch(
|
|
665
|
+
label='整形表示(Markdown)',
|
|
666
|
+
value=bool(self.config_obj.get('result_markdown_display', False)),
|
|
667
|
+
on_change=self.change_result_view_mode,
|
|
668
|
+
)
|
|
669
|
+
self.resultsmessage = ft.Text(value='', selectable=True)
|
|
670
|
+
self.result_crop_image = ft.Image(src=b'', width=300, height=300, fit=ft.BoxFit.CONTAIN)
|
|
671
|
+
|
|
672
|
+
self.crop_image_int = ft.InteractiveViewer(
|
|
673
|
+
min_scale=1,
|
|
674
|
+
max_scale=5,
|
|
675
|
+
boundary_margin=ft.Margin.all(20),
|
|
676
|
+
content=ft.Column([self.result_crop_image], width=300, height=300),
|
|
677
|
+
)
|
|
678
|
+
|
|
679
|
+
self.result_text_col = ft.Column(
|
|
680
|
+
controls=[self.result_view_switch, self.result_plain_text, self.resulttext],
|
|
681
|
+
scroll=ft.ScrollMode.ALWAYS,
|
|
682
|
+
width=600,
|
|
683
|
+
height=300,
|
|
684
|
+
)
|
|
685
|
+
self.result_dialog = ft.AlertDialog(
|
|
686
|
+
title=ft.Text(TRANSLATIONS['capturetool_resultocr_title'][self.langcode]),
|
|
687
|
+
modal=True,
|
|
688
|
+
content=ft.Row(
|
|
689
|
+
controls=[self.crop_image_int, self.result_text_col],
|
|
690
|
+
alignment=ft.MainAxisAlignment.START,
|
|
691
|
+
vertical_alignment=ft.CrossAxisAlignment.START,
|
|
692
|
+
),
|
|
693
|
+
actions=[
|
|
694
|
+
self.resultsmessage,
|
|
695
|
+
ft.Button(TRANSLATIONS['common_close'][self.langcode], on_click=self.close_result_page),
|
|
696
|
+
],
|
|
697
|
+
)
|
|
698
|
+
self.overlay_stack = ft.Stack(
|
|
699
|
+
controls=[
|
|
700
|
+
ft.GestureDetector(
|
|
701
|
+
on_pan_start=self._on_pan_start,
|
|
702
|
+
on_pan_update=self._on_pan_update,
|
|
703
|
+
on_pan_end=self._on_pan_end,
|
|
704
|
+
drag_interval=10,
|
|
705
|
+
),
|
|
706
|
+
self.selection_box,
|
|
707
|
+
],
|
|
708
|
+
expand=True,
|
|
709
|
+
visible=False,
|
|
710
|
+
)
|
|
711
|
+
|
|
712
|
+
self.page.overlay.append(self.overlay_stack)
|
|
713
|
+
|
|
714
|
+
def start_capture(self, e=None):
|
|
715
|
+
if self.dialog.open:
|
|
716
|
+
self.close_dialog(e)
|
|
717
|
+
if self.cboc_fixed.value:
|
|
718
|
+
self._capture_and_restore(self.x1_phys, self.y1_phys, self.x2_phys, self.y2_phys)
|
|
719
|
+
return
|
|
720
|
+
self.scale_factor = get_windows_scale_factor()
|
|
721
|
+
self.original_width = self.page.window.width
|
|
722
|
+
self.original_height = self.page.window.height
|
|
723
|
+
self.original_left = self.page.window.left
|
|
724
|
+
self.original_top = self.page.window.top
|
|
725
|
+
self.original_bgcolor = self.page.bgcolor
|
|
726
|
+
|
|
727
|
+
self.page.window.maximized = True
|
|
728
|
+
self.page.window.title_bar_hidden = True
|
|
729
|
+
self.page.window.title_bar_buttons_hidden = True
|
|
730
|
+
self.page.window.always_on_top = True
|
|
731
|
+
self.page.window.opacity = 0.3
|
|
732
|
+
self.page.window.bgcolor = ft.Colors.TRANSPARENT
|
|
733
|
+
self.page.bgcolor = ft.Colors.with_opacity(0.3, ft.Colors.BLACK)
|
|
734
|
+
|
|
735
|
+
self.overlay_stack.visible = True
|
|
736
|
+
self.page.update()
|
|
737
|
+
|
|
738
|
+
def _on_pan_start(self, e: ft.DragStartEvent):
|
|
739
|
+
self.start_x = e.local_position.x
|
|
740
|
+
self.start_y = e.local_position.y
|
|
741
|
+
self.current_x = e.local_position.x
|
|
742
|
+
self.current_y = e.local_position.y
|
|
743
|
+
self.selection_box.visible = True
|
|
744
|
+
self.selection_box.left = self.start_x
|
|
745
|
+
self.selection_box.top = self.start_y
|
|
746
|
+
self.selection_box.width = 0
|
|
747
|
+
self.selection_box.height = 0
|
|
748
|
+
self.page.update()
|
|
749
|
+
|
|
750
|
+
def _on_pan_update(self, e: ft.DragUpdateEvent):
|
|
751
|
+
self.current_x = e.local_position.x
|
|
752
|
+
self.current_y = e.local_position.y
|
|
753
|
+
|
|
754
|
+
left = min(self.start_x, self.current_x)
|
|
755
|
+
top = min(self.start_y, self.current_y)
|
|
756
|
+
width = abs(self.current_x - self.start_x)
|
|
757
|
+
height = abs(self.current_y - self.start_y)
|
|
758
|
+
|
|
759
|
+
self.selection_box.left = left
|
|
760
|
+
self.selection_box.top = top
|
|
761
|
+
self.selection_box.width = width
|
|
762
|
+
self.selection_box.height = height
|
|
763
|
+
self.page.update()
|
|
764
|
+
|
|
765
|
+
def _on_pan_end(self, e: ft.DragEndEvent):
|
|
766
|
+
x1_local = min(self.start_x, self.current_x)
|
|
767
|
+
y1_local = min(self.start_y, self.current_y)
|
|
768
|
+
x2_local = max(self.start_x, self.current_x)
|
|
769
|
+
y2_local = max(self.start_y, self.current_y)
|
|
770
|
+
|
|
771
|
+
offset_x = self.page.window.left or 0
|
|
772
|
+
offset_y = self.page.window.top or 0
|
|
773
|
+
|
|
774
|
+
x1_global = x1_local + offset_x
|
|
775
|
+
y1_global = y1_local + offset_y
|
|
776
|
+
x2_global = x2_local + offset_x
|
|
777
|
+
y2_global = y2_local + offset_y
|
|
778
|
+
|
|
779
|
+
self.x1_phys = int(x1_global * self.scale_factor)
|
|
780
|
+
self.y1_phys = int(y1_global * self.scale_factor)
|
|
781
|
+
self.x2_phys = int(x2_global * self.scale_factor)
|
|
782
|
+
self.y2_phys = int(y2_global * self.scale_factor)
|
|
783
|
+
|
|
784
|
+
self._capture_and_restore(self.x1_phys, self.y1_phys, self.x2_phys, self.y2_phys)
|
|
785
|
+
|
|
786
|
+
def _capture_and_restore(self, x1, y1, x2, y2):
|
|
787
|
+
self.page.window.opacity = 0
|
|
788
|
+
self.page.update()
|
|
789
|
+
time.sleep(0.2)
|
|
790
|
+
|
|
791
|
+
if (x2 - x1) > 5 and (y2 - y1) > 5:
|
|
792
|
+
try:
|
|
793
|
+
self.im_crop = ImageGrab.grab(bbox=(x1, y1, x2, y2)).convert('RGB')
|
|
794
|
+
self.cboc_fixed.disabled = False
|
|
795
|
+
buffered = io.BytesIO()
|
|
796
|
+
self.im_crop.save(buffered, format='png')
|
|
797
|
+
image_bytes = buffered.getvalue()
|
|
798
|
+
self.img_control.src = image_bytes
|
|
799
|
+
self.result_crop_image.src = image_bytes
|
|
800
|
+
self.page.show_dialog(self.dialog)
|
|
801
|
+
except Exception as ex:
|
|
802
|
+
print(f'Capture failed: {ex}')
|
|
803
|
+
|
|
804
|
+
self.overlay_stack.visible = False
|
|
805
|
+
self.selection_box.visible = False
|
|
806
|
+
|
|
807
|
+
self.page.window.opacity = 1
|
|
808
|
+
self.page.window.maximized = False
|
|
809
|
+
self.page.window.title_bar_hidden = False
|
|
810
|
+
self.page.window.title_bar_buttons_hidden = False
|
|
811
|
+
self.page.window.always_on_top = False
|
|
812
|
+
self.page.window.bgcolor = ft.Colors.WHITE
|
|
813
|
+
self.page.bgcolor = self.original_bgcolor
|
|
814
|
+
self.page.update()
|
|
815
|
+
time.sleep(0.2)
|
|
816
|
+
|
|
817
|
+
self.page.window.width = self.original_width
|
|
818
|
+
self.page.window.height = self.original_height
|
|
819
|
+
self.page.window.left = self.original_left
|
|
820
|
+
self.page.window.top = self.original_top
|
|
821
|
+
self.page.update()
|
|
822
|
+
|
|
823
|
+
def change_result_view_mode(self, e=None):
|
|
824
|
+
use_markdown = bool(self.result_view_switch.value)
|
|
825
|
+
self.config_obj['result_markdown_display'] = use_markdown
|
|
826
|
+
self.resulttext.visible = use_markdown
|
|
827
|
+
self.result_plain_text.visible = not use_markdown
|
|
828
|
+
self.page.update()
|
|
829
|
+
|
|
830
|
+
async def mini_ocr(self, e):
|
|
831
|
+
if self.im_crop is None:
|
|
832
|
+
return
|
|
833
|
+
self.ocr_btn.disabled = True
|
|
834
|
+
self.resultsmessage.value = ''
|
|
835
|
+
self.page.update()
|
|
836
|
+
try:
|
|
837
|
+
allstart = time.time()
|
|
838
|
+
filename_base = 'captureimg'
|
|
839
|
+
npimg = np.array(self.im_crop)
|
|
840
|
+
|
|
841
|
+
page_result = await asyncio.to_thread(
|
|
842
|
+
ocr._run_ocr_on_image_array,
|
|
843
|
+
detector=self.detector,
|
|
844
|
+
recognizer30=self.recognizer30,
|
|
845
|
+
recognizer50=self.recognizer50,
|
|
846
|
+
recognizer100=self.recognizer100,
|
|
847
|
+
inputname=filename_base,
|
|
848
|
+
img=npimg,
|
|
849
|
+
outputpath=self.outputdirpath,
|
|
850
|
+
save_viz=False,
|
|
851
|
+
)
|
|
852
|
+
page_tables = []
|
|
853
|
+
if (
|
|
854
|
+
self.table_feature is not None
|
|
855
|
+
and self.cb_table_structure is not None
|
|
856
|
+
and self.cb_table_structure.value
|
|
857
|
+
and self.table_recognizer is not None
|
|
858
|
+
):
|
|
859
|
+
page_result, page_tables = await asyncio.to_thread(
|
|
860
|
+
self.table_feature.infer,
|
|
861
|
+
npimg,
|
|
862
|
+
page_result,
|
|
863
|
+
self.table_recognizer,
|
|
864
|
+
)
|
|
865
|
+
|
|
866
|
+
final_text = build_gui_result_markdown(page_result, page_tables)
|
|
867
|
+
self.resultsmessage.value = '{:.2f} sec'.format(time.time() - allstart)
|
|
868
|
+
self.result_plain_text.value = page_result['text']
|
|
869
|
+
self.resulttext.value = final_text
|
|
870
|
+
self.result_jsonstr = json.dumps(page_result['json_lines'], ensure_ascii=False)
|
|
871
|
+
self.open_result_page()
|
|
872
|
+
|
|
873
|
+
except Exception as e:
|
|
874
|
+
print(f'OCR Error: {e}')
|
|
875
|
+
self.result_plain_text.value = f'エラーが発生しました: {e}'
|
|
876
|
+
self.resulttext.value = f'エラーが発生しました: {e}'
|
|
877
|
+
self.open_result_page()
|
|
878
|
+
finally:
|
|
879
|
+
self.ocr_btn.disabled = False
|
|
880
|
+
self.page.update()
|
|
881
|
+
|
|
882
|
+
def open_dialog(self, e=None):
|
|
883
|
+
self.start_capture()
|
|
884
|
+
|
|
885
|
+
def close_dialog(self, e):
|
|
886
|
+
if self.dialog.open:
|
|
887
|
+
self.page.pop_dialog()
|
|
888
|
+
|
|
889
|
+
def open_result_page(self):
|
|
890
|
+
if self.dialog.open:
|
|
891
|
+
self.page.pop_dialog()
|
|
892
|
+
self.page.show_dialog(self.result_dialog)
|
|
893
|
+
|
|
894
|
+
def close_result_page(self, e):
|
|
895
|
+
if self.result_dialog.open:
|
|
896
|
+
self.page.pop_dialog()
|
|
897
|
+
self.page.show_dialog(self.dialog)
|
|
898
|
+
|
|
899
|
+
def parse_gui_args(argv=None, *, download_models=False):
|
|
900
|
+
parser = argparse.ArgumentParser(description='Argument for Inference using ONNXRuntime')
|
|
901
|
+
parser.add_argument('--det-weights', type=str, required=False, help='Path to rtmdet onnx file', default=None if download_models else str(SOURCE_DIR / 'model' / 'deim-s-1024x1024.onnx'))
|
|
902
|
+
parser.add_argument('--det-classes', type=str, required=False, help='Path to list of class in yaml file', default=str(SOURCE_DIR / 'config' / 'ndl.yaml'))
|
|
903
|
+
parser.add_argument('--det-score-threshold', type=float, required=False, default=0.2)
|
|
904
|
+
parser.add_argument('--det-conf-threshold', type=float, required=False, default=0.25)
|
|
905
|
+
parser.add_argument('--det-iou-threshold', type=float, required=False, default=0.2)
|
|
906
|
+
parser.add_argument('--rec-weights30', type=str, required=False, help='Path to parseq-tiny onnx file', default=None if download_models else str(SOURCE_DIR / 'model' / 'parseq-ndl-24x256-30-tiny-189epoch-tegaki3-r8data-202604.onnx'))
|
|
907
|
+
parser.add_argument('--rec-weights50', type=str, required=False, help='Path to parseq-tiny onnx file', default=None if download_models else str(SOURCE_DIR / 'model' / 'parseq-ndl-24x384-50-tiny-300epoch-tegaki3-r8data-202604.onnx'))
|
|
908
|
+
parser.add_argument('--rec-weights', type=str, required=False, help='Path to parseq-tiny onnx file', default=None if download_models else str(SOURCE_DIR / 'model' / 'parseq-ndl-24x768-100-tiny-153epoch-tegaki3-r8data-202604.onnx'))
|
|
909
|
+
parser.add_argument('--rec-classes', type=str, required=False, help='Path to list of class in yaml file', default=str(SOURCE_DIR / 'config' / 'NDLmoji.yaml'))
|
|
910
|
+
parser.add_argument('--device', type=str, required=False, help='Device use (cpu or cuda)', choices=['cpu', 'cuda'], default='cpu')
|
|
911
|
+
if TABLE_STRUCTURE_FEATURE is not None:
|
|
912
|
+
TABLE_STRUCTURE_FEATURE.add_arguments(parser, SOURCE_DIR)
|
|
913
|
+
if download_models:
|
|
914
|
+
return parser.parse_args(argv)
|
|
915
|
+
# Flet may append its own process arguments to the desktop entry point.
|
|
916
|
+
args, _ = parser.parse_known_args(argv)
|
|
917
|
+
return args
|
|
918
|
+
|
|
919
|
+
|
|
920
|
+
def main(page: ft.Page, *, args=None, download_models=False):
|
|
921
|
+
if args is None:
|
|
922
|
+
args = parse_gui_args()
|
|
923
|
+
page.title = 'NDLOCR-Lite-GUI v{}'.format(__version__)
|
|
924
|
+
page.theme_mode = ft.ThemeMode.SYSTEM
|
|
925
|
+
page.window.icon = str(ASSETS_DIR / 'icon.png')
|
|
926
|
+
page.window.width = 1024
|
|
927
|
+
page.window.height = 900
|
|
928
|
+
page.window.min_width = 1024
|
|
929
|
+
page.window.min_height = 900
|
|
930
|
+
default_config = build_default_config()
|
|
931
|
+
for feature in (DATA_POOL_FEATURE, LLM_FEATURE, TABLE_STRUCTURE_FEATURE):
|
|
932
|
+
if feature is not None:
|
|
933
|
+
default_config.update(feature.default_config())
|
|
934
|
+
load_obj = {}
|
|
935
|
+
if USER_CONFIG_PATH.exists():
|
|
936
|
+
with USER_CONFIG_PATH.open(encoding='utf-8') as f:
|
|
937
|
+
load_obj = yaml.safe_load(f)
|
|
938
|
+
if load_obj is None:
|
|
939
|
+
load_obj = {}
|
|
940
|
+
|
|
941
|
+
config_obj = default_config | load_obj
|
|
942
|
+
|
|
943
|
+
page.locale_configuration = ft.LocaleConfiguration(
|
|
944
|
+
supported_locales=[
|
|
945
|
+
ft.Locale('ja', 'JP'),
|
|
946
|
+
ft.Locale('en', 'US'),
|
|
947
|
+
],
|
|
948
|
+
current_locale=ft.Locale('ja', 'JP') if config_obj['langcode'] == 'ja' else ft.Locale('en', 'US'),
|
|
949
|
+
)
|
|
950
|
+
|
|
951
|
+
def save_config():
|
|
952
|
+
APP_DATA_DIR.mkdir(parents=True, exist_ok=True)
|
|
953
|
+
with USER_CONFIG_PATH.open('w', encoding='utf-8') as wf:
|
|
954
|
+
yaml.dump(config_obj, wf, default_flow_style=False, allow_unicode=True)
|
|
955
|
+
|
|
956
|
+
def handle_locale_change(e):
|
|
957
|
+
index = e.control.selected_index
|
|
958
|
+
if index == 0:
|
|
959
|
+
page.locale_configuration.current_locale = ft.Locale('ja', 'JP')
|
|
960
|
+
elif index == 1:
|
|
961
|
+
page.locale_configuration.current_locale = ft.Locale('en', 'US')
|
|
962
|
+
config_obj['langcode'] = page.locale_configuration.current_locale.language_code
|
|
963
|
+
save_config()
|
|
964
|
+
page.update()
|
|
965
|
+
renderui()
|
|
966
|
+
|
|
967
|
+
origin_detector = None
|
|
968
|
+
origin_recognizer = None
|
|
969
|
+
origin_recognizer30 = None
|
|
970
|
+
origin_recognizer50 = None
|
|
971
|
+
origin_table_recognizer = None
|
|
972
|
+
model_state = {'loading': False, 'error': None, 'table_error': None, 'elapsed': None}
|
|
973
|
+
|
|
974
|
+
def renderui():
|
|
975
|
+
page.clean()
|
|
976
|
+
page.overlay.clear()
|
|
977
|
+
page.services.clear()
|
|
978
|
+
page.update()
|
|
979
|
+
inputpathlist = []
|
|
980
|
+
visualizepathlist = []
|
|
981
|
+
outputtxtlist = []
|
|
982
|
+
outputplaintextlist = []
|
|
983
|
+
ocr_cancel_event=threading.Event()
|
|
984
|
+
pdf_job_list = []
|
|
985
|
+
|
|
986
|
+
def create_pdf_func(outputpath: str, img: object, bboxlistobj: list, viztxtflag: bool, resolution: int = 300):
|
|
987
|
+
from reportlab.pdfgen import canvas
|
|
988
|
+
from reportlab.pdfbase import pdfmetrics
|
|
989
|
+
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
|
|
990
|
+
from reportlab.lib.utils import ImageReader
|
|
991
|
+
from reportlab.lib.colors import blue
|
|
992
|
+
|
|
993
|
+
img_h, img_w = img.shape[:2]
|
|
994
|
+
dpi = max(float(resolution), 1.0)
|
|
995
|
+
page_w = img_w * 72.0 / dpi
|
|
996
|
+
page_h = img_h * 72.0 / dpi
|
|
997
|
+
|
|
998
|
+
pdfmetrics.registerFont(UnicodeCIDFont('HeiseiMin-W3', isVertical=True))
|
|
999
|
+
pdfmetrics.registerFont(UnicodeCIDFont('HeiseiKakuGo-W5', isVertical=False))
|
|
1000
|
+
|
|
1001
|
+
c = canvas.Canvas(outputpath, pagesize=(page_w, page_h))
|
|
1002
|
+
|
|
1003
|
+
pilimg_data = io.BytesIO()
|
|
1004
|
+
pilimg=Image.fromarray(img)
|
|
1005
|
+
if pilimg.mode in ("RGBA", "LA", "P"):
|
|
1006
|
+
pilimg = pilimg.convert("RGB")
|
|
1007
|
+
#Image.fromarray(img).save(pilimg_data, format='PNG')
|
|
1008
|
+
try:
|
|
1009
|
+
pilimg.save(pilimg_data, format='JPEG')
|
|
1010
|
+
except:
|
|
1011
|
+
pilimg.save(pilimg_data, format='PNG')
|
|
1012
|
+
pilimg_data.seek(0)
|
|
1013
|
+
|
|
1014
|
+
c.drawImage(
|
|
1015
|
+
ImageReader(pilimg_data),
|
|
1016
|
+
0,
|
|
1017
|
+
0,
|
|
1018
|
+
width=page_w,
|
|
1019
|
+
height=page_h,
|
|
1020
|
+
preserveAspectRatio=False,
|
|
1021
|
+
mask=None,
|
|
1022
|
+
)
|
|
1023
|
+
|
|
1024
|
+
if viztxtflag:
|
|
1025
|
+
c.setFillAlpha(1)
|
|
1026
|
+
c.setFillColor(blue)
|
|
1027
|
+
else:
|
|
1028
|
+
c.setFillAlpha(0)
|
|
1029
|
+
|
|
1030
|
+
for bboxobj in bboxlistobj:
|
|
1031
|
+
text = bboxobj.get('text', '')
|
|
1032
|
+
if not text:
|
|
1033
|
+
continue
|
|
1034
|
+
bbox = bboxobj['boundingBox']
|
|
1035
|
+
xmin = bbox[0][0]
|
|
1036
|
+
ymin = bbox[0][1]
|
|
1037
|
+
line_w = bbox[2][0] - bbox[0][0]
|
|
1038
|
+
line_h = bbox[1][1] - bbox[0][1]
|
|
1039
|
+
line = {
|
|
1040
|
+
'x': xmin,
|
|
1041
|
+
'y': ymin,
|
|
1042
|
+
'width': line_w,
|
|
1043
|
+
'height': line_h,
|
|
1044
|
+
'text': text,
|
|
1045
|
+
'is_vertical': line_h > line_w,
|
|
1046
|
+
}
|
|
1047
|
+
ocr._draw_text_layer_line(
|
|
1048
|
+
canvas_obj=c,
|
|
1049
|
+
line=line,
|
|
1050
|
+
img_width=img_w,
|
|
1051
|
+
img_height=img_h,
|
|
1052
|
+
page_width=page_w,
|
|
1053
|
+
page_height=page_h,
|
|
1054
|
+
visible=viztxtflag,
|
|
1055
|
+
)
|
|
1056
|
+
c.save()
|
|
1057
|
+
|
|
1058
|
+
def is_pdf_tmp_path(path: str) -> bool:
|
|
1059
|
+
try:
|
|
1060
|
+
tmp_dir = os.path.abspath(PDFTMPPATH)
|
|
1061
|
+
return os.path.abspath(path).startswith(tmp_dir + os.sep)
|
|
1062
|
+
except Exception:
|
|
1063
|
+
return False
|
|
1064
|
+
|
|
1065
|
+
def render_pdf_preview(pdf_path: str, filestem: str):
|
|
1066
|
+
load_runtime_modules()
|
|
1067
|
+
os.makedirs(PDFTMPPATH, exist_ok=True)
|
|
1068
|
+
doc = pypdfium2.PdfDocument(pdf_path)
|
|
1069
|
+
try:
|
|
1070
|
+
pdfarray = doc.render(
|
|
1071
|
+
pypdfium2.PdfBitmap.to_pil,
|
|
1072
|
+
page_indices=[i for i in range(len(doc))],
|
|
1073
|
+
scale=100 / 72,
|
|
1074
|
+
)
|
|
1075
|
+
for ix, image in enumerate(list(pdfarray)):
|
|
1076
|
+
outputtmppath = os.path.join(PDFTMPPATH, '{}_{:05}.jpg'.format(filestem, ix))
|
|
1077
|
+
inputpathlist.append(outputtmppath)
|
|
1078
|
+
image = image.convert('RGB')
|
|
1079
|
+
image.save(outputtmppath)
|
|
1080
|
+
finally:
|
|
1081
|
+
doc.close()
|
|
1082
|
+
|
|
1083
|
+
def models_are_ready():
|
|
1084
|
+
return all((
|
|
1085
|
+
origin_detector,
|
|
1086
|
+
origin_recognizer,
|
|
1087
|
+
origin_recognizer30,
|
|
1088
|
+
origin_recognizer50,
|
|
1089
|
+
))
|
|
1090
|
+
|
|
1091
|
+
def parts_control(flag:bool,allow_ocr_cancel:bool=False):
|
|
1092
|
+
file_upload_btn.disabled = flag
|
|
1093
|
+
directory_upload_btn.disabled = flag
|
|
1094
|
+
directory_output_btn.disabled = flag
|
|
1095
|
+
chkbx_visualize.disabled = flag
|
|
1096
|
+
customize_btn.disabled = flag
|
|
1097
|
+
preview_prev_btn.disabled = flag or not outputtxtlist
|
|
1098
|
+
preview_next_btn.disabled = flag or not outputtxtlist
|
|
1099
|
+
has_input = bool(inputpathlist or pdf_job_list)
|
|
1100
|
+
has_output = bool(selected_output_path.value)
|
|
1101
|
+
ocr_btn.disabled = flag or not (models_are_ready() and has_input and has_output)
|
|
1102
|
+
crop_btn.disabled = flag or not (models_are_ready() and inputpathlist and has_output)
|
|
1103
|
+
cap_btn.disabled = flag or not models_are_ready()
|
|
1104
|
+
localebutton.disabled = flag or model_state['loading']
|
|
1105
|
+
stop_ocr_btn.disabled=not (flag and allow_ocr_cancel)
|
|
1106
|
+
if chkbx_table_structure is not None:
|
|
1107
|
+
chkbx_table_structure.disabled = flag or origin_table_recognizer is None
|
|
1108
|
+
|
|
1109
|
+
async def process_pdf_with_original_layer(pdf_path: str, outputpath: str, alljsonobjlist: list, pdf_outpath_list: list, allsum: int):
|
|
1110
|
+
pdf_path_obj = Path(pdf_path)
|
|
1111
|
+
output_stem = pdf_path_obj.stem
|
|
1112
|
+
render_dpi = max(float(pdf_resolution_textfield.value), 1.0)
|
|
1113
|
+
render_scale = render_dpi / 72.0
|
|
1114
|
+
|
|
1115
|
+
pdf_doc = pypdfium2.PdfDocument(str(pdf_path_obj))
|
|
1116
|
+
page_results = []
|
|
1117
|
+
all_json_contents = []
|
|
1118
|
+
page_infos = []
|
|
1119
|
+
all_text_pages = []
|
|
1120
|
+
all_markdown_pages = []
|
|
1121
|
+
all_page_xml = []
|
|
1122
|
+
all_table_results = []
|
|
1123
|
+
tei_jsonobjlist = []
|
|
1124
|
+
|
|
1125
|
+
try:
|
|
1126
|
+
page_count = len(pdf_doc)
|
|
1127
|
+
separate_page_outputs = should_output_pdf_pages_separately(
|
|
1128
|
+
page_count,
|
|
1129
|
+
config_obj.get('pdf_page_output', True),
|
|
1130
|
+
)
|
|
1131
|
+
for page_index in range(page_count):
|
|
1132
|
+
if ocr_cancel_event.is_set():
|
|
1133
|
+
return page_index, False, tei_jsonobjlist
|
|
1134
|
+
page_name = f'{output_stem}_{page_index + 1:05}.png'
|
|
1135
|
+
progressmessage.value = f'{pdf_path_obj.name} page {page_index + 1}/{page_count}'
|
|
1136
|
+
progressmessage.update()
|
|
1137
|
+
|
|
1138
|
+
img = await asyncio.to_thread(
|
|
1139
|
+
render_pdf_page_array,
|
|
1140
|
+
str(pdf_path_obj),
|
|
1141
|
+
page_index,
|
|
1142
|
+
render_scale,
|
|
1143
|
+
)
|
|
1144
|
+
|
|
1145
|
+
page_result = await asyncio.to_thread(
|
|
1146
|
+
ocr._run_ocr_on_image_array,
|
|
1147
|
+
detector=origin_detector,
|
|
1148
|
+
recognizer30=origin_recognizer30,
|
|
1149
|
+
recognizer50=origin_recognizer50,
|
|
1150
|
+
recognizer100=origin_recognizer,
|
|
1151
|
+
inputname=page_name,
|
|
1152
|
+
img=img,
|
|
1153
|
+
outputpath=outputpath,
|
|
1154
|
+
save_viz=False,
|
|
1155
|
+
)
|
|
1156
|
+
|
|
1157
|
+
page_tables = []
|
|
1158
|
+
if (
|
|
1159
|
+
TABLE_STRUCTURE_FEATURE is not None
|
|
1160
|
+
and chkbx_table_structure is not None
|
|
1161
|
+
and chkbx_table_structure.value
|
|
1162
|
+
and origin_table_recognizer is not None
|
|
1163
|
+
):
|
|
1164
|
+
page_result, page_tables = await asyncio.to_thread(
|
|
1165
|
+
TABLE_STRUCTURE_FEATURE.infer,
|
|
1166
|
+
img,
|
|
1167
|
+
page_result,
|
|
1168
|
+
origin_table_recognizer,
|
|
1169
|
+
args.table_crop_padding,
|
|
1170
|
+
)
|
|
1171
|
+
for table_item in page_tables:
|
|
1172
|
+
table_item['page_index'] = page_index
|
|
1173
|
+
all_table_results.extend(page_tables)
|
|
1174
|
+
|
|
1175
|
+
page_results.append(page_result)
|
|
1176
|
+
all_json_contents.append(page_result['json_lines'])
|
|
1177
|
+
page_infos.append({
|
|
1178
|
+
'page_index': page_index,
|
|
1179
|
+
'img_width': page_result['img_width'],
|
|
1180
|
+
'img_height': page_result['img_height'],
|
|
1181
|
+
'img_name': page_result['img_name'],
|
|
1182
|
+
})
|
|
1183
|
+
all_text_pages.append(page_result['text'])
|
|
1184
|
+
page_markdown = build_gui_result_markdown(page_result, page_tables)
|
|
1185
|
+
all_markdown_pages.append(page_markdown)
|
|
1186
|
+
outputplaintextlist.append(page_result['text'])
|
|
1187
|
+
outputtxtlist.append(page_markdown)
|
|
1188
|
+
all_page_xml.append(page_result['page_xml'])
|
|
1189
|
+
|
|
1190
|
+
page_json_obj = write_pdf_page_outputs(
|
|
1191
|
+
outputpath,
|
|
1192
|
+
output_stem,
|
|
1193
|
+
page_index,
|
|
1194
|
+
page_result,
|
|
1195
|
+
source_path=str(pdf_path_obj),
|
|
1196
|
+
write_json=separate_page_outputs and chkbx_json.value,
|
|
1197
|
+
write_xml=separate_page_outputs and chkbx_xml.value,
|
|
1198
|
+
write_txt=separate_page_outputs and chkbx_txt.value,
|
|
1199
|
+
write_tei=separate_page_outputs and chkbx_tei.value,
|
|
1200
|
+
convert_tei_func=convert_tei if chkbx_tei.value else None,
|
|
1201
|
+
include_xml_in_json=True,
|
|
1202
|
+
)
|
|
1203
|
+
alljsonobjlist.append(page_json_obj)
|
|
1204
|
+
if not separate_page_outputs:
|
|
1205
|
+
tei_jsonobjlist.append(page_json_obj)
|
|
1206
|
+
|
|
1207
|
+
if chkbx_visualize.value:
|
|
1208
|
+
viz_path = os.path.join(outputpath, f'viz_{page_name}')
|
|
1209
|
+
await asyncio.to_thread(
|
|
1210
|
+
origin_detector.drawxml_detections,
|
|
1211
|
+
npimg=img,
|
|
1212
|
+
xmlstr='<OCRDATASET>\n' + page_result['page_xml'] + '\n</OCRDATASET>',
|
|
1213
|
+
categories=categories_org_name_index,
|
|
1214
|
+
outputimgpath=viz_path,
|
|
1215
|
+
)
|
|
1216
|
+
if os.path.exists(viz_path):
|
|
1217
|
+
visualizepathlist.append(viz_path)
|
|
1218
|
+
|
|
1219
|
+
progressbar.value += 1 / max(allsum, 1)
|
|
1220
|
+
page.update()
|
|
1221
|
+
finally:
|
|
1222
|
+
pdf_doc.close()
|
|
1223
|
+
|
|
1224
|
+
if chkbx_xml.value and not separate_page_outputs:
|
|
1225
|
+
with open(os.path.join(outputpath, output_stem + '.xml'), 'w', encoding='utf-8') as wf:
|
|
1226
|
+
wf.write('<OCRDATASET>\n')
|
|
1227
|
+
wf.write('\n'.join(all_page_xml))
|
|
1228
|
+
wf.write('\n</OCRDATASET>')
|
|
1229
|
+
|
|
1230
|
+
if chkbx_txt.value and not separate_page_outputs:
|
|
1231
|
+
with open(os.path.join(outputpath, output_stem + '.txt'), 'w', encoding='utf-8') as wf:
|
|
1232
|
+
wf.write('\n\n'.join(all_text_pages))
|
|
1233
|
+
|
|
1234
|
+
if chkbx_markdown.value:
|
|
1235
|
+
with open(os.path.join(outputpath, output_stem + '.md'), 'w', encoding='utf-8') as wf:
|
|
1236
|
+
wf.write('\n\n---\n\n'.join(all_markdown_pages))
|
|
1237
|
+
|
|
1238
|
+
pdf_json_obj = {
|
|
1239
|
+
'contents': all_json_contents,
|
|
1240
|
+
'pdfinfo': {
|
|
1241
|
+
'pdf_path': str(pdf_path_obj),
|
|
1242
|
+
'pdf_name': pdf_path_obj.name,
|
|
1243
|
+
'page_count': len(page_results),
|
|
1244
|
+
'render_dpi': render_dpi,
|
|
1245
|
+
},
|
|
1246
|
+
'pages': page_infos,
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
if chkbx_json.value and not separate_page_outputs:
|
|
1250
|
+
with open(os.path.join(outputpath, output_stem + '.json'), 'w', encoding='utf-8') as wf:
|
|
1251
|
+
wf.write(json.dumps(pdf_json_obj, ensure_ascii=False, indent=2))
|
|
1252
|
+
|
|
1253
|
+
if all_table_results:
|
|
1254
|
+
tables_html_path = os.path.join(outputpath, output_stem + '_tables.html')
|
|
1255
|
+
tables_html = TABLE_STRUCTURE_FEATURE.build_html(
|
|
1256
|
+
pdf_path_obj.name,
|
|
1257
|
+
all_table_results,
|
|
1258
|
+
)
|
|
1259
|
+
with open(tables_html_path, 'w', encoding='utf-8') as wf:
|
|
1260
|
+
wf.write(tables_html)
|
|
1261
|
+
|
|
1262
|
+
if chkbx_pdf.value:
|
|
1263
|
+
output_pdf = os.path.join(outputpath, output_stem + '_text.pdf')
|
|
1264
|
+
ocr.embed_text_layer_pdf(
|
|
1265
|
+
input_pdf=str(pdf_path_obj),
|
|
1266
|
+
output_pdf=output_pdf,
|
|
1267
|
+
page_results=page_results,
|
|
1268
|
+
visible_text=chkbx_pdf_viztxt.value,
|
|
1269
|
+
)
|
|
1270
|
+
pdf_outpath_list.append(output_pdf)
|
|
1271
|
+
|
|
1272
|
+
return page_count, True, tei_jsonobjlist
|
|
1273
|
+
|
|
1274
|
+
def request_ocr_cancel(e):
|
|
1275
|
+
if ocr_cancel_event.is_set():
|
|
1276
|
+
return
|
|
1277
|
+
ocr_cancel_event.set()
|
|
1278
|
+
stop_ocr_btn.disabled=True
|
|
1279
|
+
progressmessage.value=TRANSLATIONS["main_ocr_cancel_requested"][config_obj["langcode"]]
|
|
1280
|
+
page.update()
|
|
1281
|
+
|
|
1282
|
+
async def ocr_button_result(e):
|
|
1283
|
+
ocr_cancel_event.clear()
|
|
1284
|
+
progressbar.value = 0
|
|
1285
|
+
outputpath = selected_output_path.value
|
|
1286
|
+
nonlocal inputpathlist, outputtxtlist, visualizepathlist, preview_index, args
|
|
1287
|
+
nonlocal origin_recognizer, origin_recognizer30, origin_recognizer50
|
|
1288
|
+
nonlocal origin_detector
|
|
1289
|
+
|
|
1290
|
+
if not outputpath:
|
|
1291
|
+
progressmessage.value = 'Output directory is not selected.'
|
|
1292
|
+
progressmessage.update()
|
|
1293
|
+
return
|
|
1294
|
+
|
|
1295
|
+
preview_index = 0
|
|
1296
|
+
parts_control(True,allow_ocr_cancel=True)
|
|
1297
|
+
page.update()
|
|
1298
|
+
progressmessage.value = 'Start'
|
|
1299
|
+
progressmessage.update()
|
|
1300
|
+
|
|
1301
|
+
try:
|
|
1302
|
+
allstart = time.time()
|
|
1303
|
+
progressbar.value = 0
|
|
1304
|
+
progressbar.update()
|
|
1305
|
+
outputtxtlist.clear()
|
|
1306
|
+
outputplaintextlist.clear()
|
|
1307
|
+
visualizepathlist.clear()
|
|
1308
|
+
alljsonobjlist = []
|
|
1309
|
+
tei_jsonobjlist = []
|
|
1310
|
+
pdf_outpath_list = []
|
|
1311
|
+
completed_count=0
|
|
1312
|
+
cancelled=False
|
|
1313
|
+
standalone_inputpathlist = [p for p in inputpathlist if not is_pdf_tmp_path(p)]
|
|
1314
|
+
|
|
1315
|
+
allsum = len(standalone_inputpathlist)
|
|
1316
|
+
for pdf_path in pdf_job_list:
|
|
1317
|
+
try:
|
|
1318
|
+
pdf_doc_tmp = pypdfium2.PdfDocument(pdf_path)
|
|
1319
|
+
allsum += len(pdf_doc_tmp)
|
|
1320
|
+
pdf_doc_tmp.close()
|
|
1321
|
+
except Exception:
|
|
1322
|
+
allsum += 1
|
|
1323
|
+
|
|
1324
|
+
if allsum == 0:
|
|
1325
|
+
progressmessage.value = 'Images are not found.'
|
|
1326
|
+
progressmessage.update()
|
|
1327
|
+
return
|
|
1328
|
+
|
|
1329
|
+
for pdf_path in pdf_job_list:
|
|
1330
|
+
processed_pages, pdf_completed, pdf_tei_jsonobjlist = await process_pdf_with_original_layer(
|
|
1331
|
+
pdf_path,
|
|
1332
|
+
outputpath,
|
|
1333
|
+
alljsonobjlist,
|
|
1334
|
+
pdf_outpath_list,
|
|
1335
|
+
allsum,
|
|
1336
|
+
)
|
|
1337
|
+
tei_jsonobjlist.extend(pdf_tei_jsonobjlist)
|
|
1338
|
+
completed_count += processed_pages
|
|
1339
|
+
if not pdf_completed:
|
|
1340
|
+
cancelled = True
|
|
1341
|
+
break
|
|
1342
|
+
|
|
1343
|
+
for idx, inputpath in enumerate(standalone_inputpathlist):
|
|
1344
|
+
if ocr_cancel_event.is_set():
|
|
1345
|
+
cancelled=True
|
|
1346
|
+
break
|
|
1347
|
+
progressmessage.value = inputpath
|
|
1348
|
+
progressmessage.update()
|
|
1349
|
+
img = await asyncio.to_thread(load_rgb_image_array, inputpath)
|
|
1350
|
+
start = time.time()
|
|
1351
|
+
img_h, img_w = img.shape[:2]
|
|
1352
|
+
imgname = os.path.basename(inputpath)
|
|
1353
|
+
|
|
1354
|
+
page_result = await asyncio.to_thread(
|
|
1355
|
+
ocr._run_ocr_on_image_array,
|
|
1356
|
+
detector=origin_detector,
|
|
1357
|
+
recognizer30=origin_recognizer30,
|
|
1358
|
+
recognizer50=origin_recognizer50,
|
|
1359
|
+
recognizer100=origin_recognizer,
|
|
1360
|
+
inputname=imgname,
|
|
1361
|
+
img=img,
|
|
1362
|
+
outputpath=outputpath,
|
|
1363
|
+
save_viz=False,
|
|
1364
|
+
)
|
|
1365
|
+
|
|
1366
|
+
page_tables = []
|
|
1367
|
+
if (
|
|
1368
|
+
TABLE_STRUCTURE_FEATURE is not None
|
|
1369
|
+
and chkbx_table_structure is not None
|
|
1370
|
+
and chkbx_table_structure.value
|
|
1371
|
+
and origin_table_recognizer is not None
|
|
1372
|
+
):
|
|
1373
|
+
page_result, page_tables = await asyncio.to_thread(
|
|
1374
|
+
TABLE_STRUCTURE_FEATURE.infer,
|
|
1375
|
+
img,
|
|
1376
|
+
page_result,
|
|
1377
|
+
origin_table_recognizer,
|
|
1378
|
+
args.table_crop_padding,
|
|
1379
|
+
)
|
|
1380
|
+
|
|
1381
|
+
allxmlstr = '<OCRDATASET>\n' + page_result['page_xml'] + '\n</OCRDATASET>'
|
|
1382
|
+
alltextlist = [page_result['text']]
|
|
1383
|
+
resjsonarray = page_result['json_lines']
|
|
1384
|
+
page_markdown = build_gui_result_markdown(page_result, page_tables)
|
|
1385
|
+
outputplaintextlist.append(page_result['text'])
|
|
1386
|
+
outputtxtlist.append(page_markdown)
|
|
1387
|
+
|
|
1388
|
+
alljsonobj = {
|
|
1389
|
+
'contents': [resjsonarray],
|
|
1390
|
+
'imginfo': {
|
|
1391
|
+
'img_width': img_w,
|
|
1392
|
+
'img_height': img_h,
|
|
1393
|
+
'img_path': inputpath,
|
|
1394
|
+
'img_name': os.path.basename(inputpath),
|
|
1395
|
+
},
|
|
1396
|
+
'xml': allxmlstr,
|
|
1397
|
+
}
|
|
1398
|
+
alljsonobjlist.append(alljsonobj)
|
|
1399
|
+
tei_jsonobjlist.append(alljsonobj)
|
|
1400
|
+
|
|
1401
|
+
output_stem = os.path.splitext(os.path.basename(inputpath))[0]
|
|
1402
|
+
if page_tables:
|
|
1403
|
+
tables_html_path = os.path.join(outputpath, output_stem + '_tables.html')
|
|
1404
|
+
tables_html = TABLE_STRUCTURE_FEATURE.build_html(
|
|
1405
|
+
os.path.basename(inputpath),
|
|
1406
|
+
page_tables,
|
|
1407
|
+
)
|
|
1408
|
+
with open(tables_html_path, 'w', encoding='utf-8') as wf:
|
|
1409
|
+
wf.write(tables_html)
|
|
1410
|
+
|
|
1411
|
+
if chkbx_xml.value:
|
|
1412
|
+
with open(os.path.join(outputpath, output_stem + '.xml'), 'w', encoding='utf-8') as wf:
|
|
1413
|
+
wf.write(allxmlstr)
|
|
1414
|
+
|
|
1415
|
+
if chkbx_visualize.value:
|
|
1416
|
+
output_vizpath = os.path.join(outputpath, 'viz_' + os.path.basename(inputpath))
|
|
1417
|
+
if output_vizpath.split('.')[-1] == 'jp2':
|
|
1418
|
+
output_vizpath = output_vizpath[:-4] + '.jpg'
|
|
1419
|
+
visualizepathlist.append(output_vizpath)
|
|
1420
|
+
await asyncio.to_thread(
|
|
1421
|
+
origin_detector.drawxml_detections,
|
|
1422
|
+
npimg=img,
|
|
1423
|
+
xmlstr=allxmlstr,
|
|
1424
|
+
categories=categories_org_name_index,
|
|
1425
|
+
outputimgpath=output_vizpath,
|
|
1426
|
+
)
|
|
1427
|
+
|
|
1428
|
+
if chkbx_json.value:
|
|
1429
|
+
with open(os.path.join(outputpath, output_stem + '.json'), 'w', encoding='utf-8') as wf:
|
|
1430
|
+
wf.write(json.dumps(alljsonobj, ensure_ascii=False, indent=2))
|
|
1431
|
+
|
|
1432
|
+
if chkbx_txt.value:
|
|
1433
|
+
with open(os.path.join(outputpath, output_stem + '.txt'), 'w', encoding='utf-8') as wtf:
|
|
1434
|
+
wtf.write('\n'.join(alltextlist))
|
|
1435
|
+
|
|
1436
|
+
if chkbx_markdown.value:
|
|
1437
|
+
with open(os.path.join(outputpath, output_stem + '.md'), 'w', encoding='utf-8') as wf:
|
|
1438
|
+
wf.write(page_markdown)
|
|
1439
|
+
|
|
1440
|
+
if chkbx_pdf.value:
|
|
1441
|
+
pdf_outpath = os.path.join(outputpath, output_stem + '.pdf')
|
|
1442
|
+
await asyncio.to_thread(
|
|
1443
|
+
create_pdf_func,
|
|
1444
|
+
pdf_outpath,
|
|
1445
|
+
img,
|
|
1446
|
+
resjsonarray,
|
|
1447
|
+
chkbx_pdf_viztxt.value,
|
|
1448
|
+
resolution=int(pdf_resolution_textfield.value),
|
|
1449
|
+
)
|
|
1450
|
+
pdf_outpath_list.append(pdf_outpath)
|
|
1451
|
+
|
|
1452
|
+
print('Total calculation time (Detection + Recognition):', time.time() - start)
|
|
1453
|
+
completed_count+=1
|
|
1454
|
+
progressbar.value += 1 / max(allsum, 1)
|
|
1455
|
+
preview_prev_btn.disabled = False
|
|
1456
|
+
preview_next_btn.disabled = False
|
|
1457
|
+
if outputtxtlist:
|
|
1458
|
+
preview_plain_text.value = outputplaintextlist[preview_index] if preview_index < len(outputplaintextlist) else ''
|
|
1459
|
+
preview_text.value = outputtxtlist[preview_index]
|
|
1460
|
+
if len(visualizepathlist) > 0:
|
|
1461
|
+
preview_image.src = visualizepathlist[min(preview_index, len(visualizepathlist) - 1)]
|
|
1462
|
+
elif inputpathlist:
|
|
1463
|
+
preview_image.src = inputpathlist[min(preview_index, len(inputpathlist) - 1)]
|
|
1464
|
+
if inputpathlist:
|
|
1465
|
+
current_visualizeimgname.value = os.path.basename(inputpathlist[min(preview_index, len(inputpathlist) - 1)])
|
|
1466
|
+
preview_image.update()
|
|
1467
|
+
page.update()
|
|
1468
|
+
if cancelled:
|
|
1469
|
+
break
|
|
1470
|
+
if cancelled:
|
|
1471
|
+
progressmessage.value=TRANSLATIONS["main_ocr_cancelled"][config_obj["langcode"]].format(
|
|
1472
|
+
completed=completed_count,total=allsum,elapsed=time.time()-allstart
|
|
1473
|
+
)
|
|
1474
|
+
elif config_obj['langcode'] == 'ja':
|
|
1475
|
+
progressmessage.value = '{} 件OCR完了 / 所要時間 {:.2f} 秒'.format(allsum, time.time() - allstart)
|
|
1476
|
+
else:
|
|
1477
|
+
progressmessage.value = '{} items completed / Total time {:.2f} sec'.format(allsum, time.time() - allstart)
|
|
1478
|
+
progressmessage.update()
|
|
1479
|
+
|
|
1480
|
+
if chkbx_tei.value and len(tei_jsonobjlist)>0:
|
|
1481
|
+
tei_base_path = inputpathlist[0] if inputpathlist else tei_jsonobjlist[0]['imginfo']['img_name']
|
|
1482
|
+
with open(os.path.join(outputpath, os.path.splitext(os.path.basename(tei_base_path))[0] + '_tei.xml'), 'wb') as wf:
|
|
1483
|
+
allxmlstrtei = convert_tei(tei_jsonobjlist)
|
|
1484
|
+
wf.write(allxmlstrtei)
|
|
1485
|
+
|
|
1486
|
+
if chkbx_text_daisy.value and alljsonobjlist:
|
|
1487
|
+
first_name = alljsonobjlist[0].get('imginfo', {}).get('img_name', 'ocr')
|
|
1488
|
+
book_stem = os.path.splitext(os.path.basename(first_name))[0] or 'ocr'
|
|
1489
|
+
text_daisy_result = TextDaisyExporter(
|
|
1490
|
+
title=book_stem,
|
|
1491
|
+
language=config_obj['langcode'],
|
|
1492
|
+
producer='NDLOCR-Lite',
|
|
1493
|
+
).export(
|
|
1494
|
+
alljsonobjlist,
|
|
1495
|
+
outputpath,
|
|
1496
|
+
folder_name=book_stem + '_textdaisy',
|
|
1497
|
+
make_zip=True,
|
|
1498
|
+
)
|
|
1499
|
+
daisy_path = text_daisy_result.zip_path or text_daisy_result.directory
|
|
1500
|
+
progressmessage.value += f' / Text DAISY: {os.path.basename(daisy_path)}'
|
|
1501
|
+
|
|
1502
|
+
if chkbx_pdf.value and chkbx_pdf_merge.value and len(pdf_outpath_list) > 1:
|
|
1503
|
+
from pypdf import PdfReader, PdfWriter
|
|
1504
|
+
|
|
1505
|
+
writer = PdfWriter()
|
|
1506
|
+
for p in pdf_outpath_list:
|
|
1507
|
+
reader = PdfReader(p)
|
|
1508
|
+
for page_obj in reader.pages:
|
|
1509
|
+
writer.add_page(page_obj)
|
|
1510
|
+
|
|
1511
|
+
merged_pdf_path = os.path.join(
|
|
1512
|
+
outputpath,
|
|
1513
|
+
os.path.splitext(os.path.basename(inputpathlist[0]))[0] + '_merged.pdf',
|
|
1514
|
+
)
|
|
1515
|
+
with open(merged_pdf_path, 'wb') as wf:
|
|
1516
|
+
writer.write(wf)
|
|
1517
|
+
|
|
1518
|
+
for p in pdf_outpath_list:
|
|
1519
|
+
try:
|
|
1520
|
+
os.remove(p)
|
|
1521
|
+
except OSError:
|
|
1522
|
+
pass
|
|
1523
|
+
|
|
1524
|
+
if outputtxtlist:
|
|
1525
|
+
preview_plain_text.value = outputplaintextlist[0] if outputplaintextlist else ''
|
|
1526
|
+
preview_text.value = outputtxtlist[0]
|
|
1527
|
+
if len(visualizepathlist) > 0:
|
|
1528
|
+
preview_image.src = visualizepathlist[0]
|
|
1529
|
+
current_visualizeimgname.value = os.path.basename(visualizepathlist[0])
|
|
1530
|
+
elif inputpathlist:
|
|
1531
|
+
preview_image.src = inputpathlist[0]
|
|
1532
|
+
current_visualizeimgname.value = os.path.basename(inputpathlist[0])
|
|
1533
|
+
preview_image.update()
|
|
1534
|
+
preview_plain_text.update()
|
|
1535
|
+
preview_text.update()
|
|
1536
|
+
|
|
1537
|
+
except Exception as e:
|
|
1538
|
+
print(e)
|
|
1539
|
+
progressmessage.value = str(e)
|
|
1540
|
+
progressmessage.update()
|
|
1541
|
+
finally:
|
|
1542
|
+
ocr_cancel_event.clear()
|
|
1543
|
+
parts_control(False)
|
|
1544
|
+
page.update()
|
|
1545
|
+
|
|
1546
|
+
async def pick_files_result(e):
|
|
1547
|
+
files = await file_picker.pick_files(allow_multiple=False)
|
|
1548
|
+
if files and files[0].path:
|
|
1549
|
+
selected_file_path = files[0].path
|
|
1550
|
+
selected_input_path.value = selected_file_path
|
|
1551
|
+
nonlocal inputpathlist, outputtxtlist, pdf_job_list
|
|
1552
|
+
inputpathlist.clear()
|
|
1553
|
+
outputtxtlist.clear()
|
|
1554
|
+
outputplaintextlist.clear()
|
|
1555
|
+
pdf_job_list.clear()
|
|
1556
|
+
ext = selected_file_path.split('.')[-1].lower()
|
|
1557
|
+
if ext == 'pdf':
|
|
1558
|
+
pdf_job_list.append(selected_file_path)
|
|
1559
|
+
filestem = os.path.basename(selected_file_path)[:-4]
|
|
1560
|
+
if config_obj['langcode'] == 'ja':
|
|
1561
|
+
progressmessage.value = 'pdfファイルの前処理中…… {} '.format(selected_file_path)
|
|
1562
|
+
else:
|
|
1563
|
+
progressmessage.value = 'preprocessing pdf…… {} '.format(selected_file_path)
|
|
1564
|
+
parts_control(True)
|
|
1565
|
+
page.update()
|
|
1566
|
+
for p in glob.glob(os.path.join(PDFTMPPATH, '*.jpg')):
|
|
1567
|
+
if os.path.isfile(p):
|
|
1568
|
+
os.remove(p)
|
|
1569
|
+
os.makedirs(PDFTMPPATH, exist_ok=True)
|
|
1570
|
+
await asyncio.to_thread(render_pdf_preview, selected_file_path, filestem)
|
|
1571
|
+
if config_obj['langcode'] == 'ja':
|
|
1572
|
+
progressmessage.value = 'pdfファイルの前処理完了'
|
|
1573
|
+
else:
|
|
1574
|
+
progressmessage.value = 'Preprocessing of pdf complete'
|
|
1575
|
+
parts_control(False)
|
|
1576
|
+
page.update()
|
|
1577
|
+
else:
|
|
1578
|
+
inputpathlist.append(selected_file_path)
|
|
1579
|
+
selector.set_image(inputpathlist)
|
|
1580
|
+
if selected_output_path.value is not None:
|
|
1581
|
+
parts_control(False)
|
|
1582
|
+
selected_input_path.update()
|
|
1583
|
+
page.update()
|
|
1584
|
+
|
|
1585
|
+
async def pick_directory_result(e):
|
|
1586
|
+
selected_directory = await file_picker.get_directory_path()
|
|
1587
|
+
if selected_directory:
|
|
1588
|
+
selected_input_path.value = selected_directory
|
|
1589
|
+
nonlocal inputpathlist, outputtxtlist, pdf_job_list
|
|
1590
|
+
inputpathlist.clear()
|
|
1591
|
+
outputtxtlist.clear()
|
|
1592
|
+
outputplaintextlist.clear()
|
|
1593
|
+
pdf_job_list.clear()
|
|
1594
|
+
|
|
1595
|
+
for p in glob.glob(os.path.join(PDFTMPPATH, '*.jpg')):
|
|
1596
|
+
if os.path.isfile(p):
|
|
1597
|
+
try:
|
|
1598
|
+
os.remove(p)
|
|
1599
|
+
except Exception:
|
|
1600
|
+
pass
|
|
1601
|
+
os.makedirs(PDFTMPPATH, exist_ok=True)
|
|
1602
|
+
|
|
1603
|
+
parts_control(True)
|
|
1604
|
+
crop_btn.disabled = True
|
|
1605
|
+
ocr_btn.disabled = True
|
|
1606
|
+
page.update()
|
|
1607
|
+
|
|
1608
|
+
all_files_to_process = []
|
|
1609
|
+
pdf_filename_counter = Counter()
|
|
1610
|
+
|
|
1611
|
+
for root, dirs, files in os.walk(selected_directory):
|
|
1612
|
+
dirs.sort()
|
|
1613
|
+
files.sort()
|
|
1614
|
+
for filename in files:
|
|
1615
|
+
full_path = os.path.join(root, filename)
|
|
1616
|
+
ext = filename.split('.')[-1].lower()
|
|
1617
|
+
|
|
1618
|
+
if ext in ['jpg', 'png', 'tiff', 'jp2', 'tif', 'jpeg', 'bmp', 'webp']:
|
|
1619
|
+
all_files_to_process.append((full_path, 'image'))
|
|
1620
|
+
elif ext == 'pdf':
|
|
1621
|
+
all_files_to_process.append((full_path, 'pdf'))
|
|
1622
|
+
pdf_filename_counter[filename] += 1
|
|
1623
|
+
|
|
1624
|
+
all_files_to_process.sort(key=lambda x: x[0])
|
|
1625
|
+
|
|
1626
|
+
for inputpath, filetype in all_files_to_process:
|
|
1627
|
+
if filetype == 'image':
|
|
1628
|
+
inputpathlist.append(inputpath)
|
|
1629
|
+
elif filetype == 'pdf':
|
|
1630
|
+
pdf_job_list.append(inputpath)
|
|
1631
|
+
filename = os.path.basename(inputpath)
|
|
1632
|
+
if pdf_filename_counter[filename] > 1:
|
|
1633
|
+
rel_path = os.path.relpath(inputpath, start=selected_directory)
|
|
1634
|
+
filestem = os.path.splitext(rel_path)[0].replace(os.sep, '-')
|
|
1635
|
+
else:
|
|
1636
|
+
filestem = os.path.splitext(filename)[0]
|
|
1637
|
+
|
|
1638
|
+
if config_obj['langcode'] == 'ja':
|
|
1639
|
+
progressmessage.value = 'pdfファイルの前処理中…… {} '.format(inputpath)
|
|
1640
|
+
else:
|
|
1641
|
+
progressmessage.value = 'preprocessing pdf…… {} '.format(inputpath)
|
|
1642
|
+
page.update()
|
|
1643
|
+
|
|
1644
|
+
try:
|
|
1645
|
+
await asyncio.to_thread(render_pdf_preview, inputpath, filestem)
|
|
1646
|
+
except Exception as err:
|
|
1647
|
+
print(f'Error processing {inputpath}: {err}')
|
|
1648
|
+
|
|
1649
|
+
if config_obj['langcode'] == 'ja':
|
|
1650
|
+
progressmessage.value = '処理完了'
|
|
1651
|
+
else:
|
|
1652
|
+
progressmessage.value = 'Processing complete'
|
|
1653
|
+
|
|
1654
|
+
selector.set_image(inputpathlist)
|
|
1655
|
+
|
|
1656
|
+
if len(inputpathlist) > 0:
|
|
1657
|
+
parts_control(False)
|
|
1658
|
+
|
|
1659
|
+
selected_input_path.update()
|
|
1660
|
+
page.update()
|
|
1661
|
+
|
|
1662
|
+
async def pick_output_result(e):
|
|
1663
|
+
nonlocal inputpathlist
|
|
1664
|
+
selected_directory = await file_picker.get_directory_path()
|
|
1665
|
+
if selected_directory:
|
|
1666
|
+
selected_output_path.value = selected_directory
|
|
1667
|
+
selected_output_path.update()
|
|
1668
|
+
config_obj['selected_output_path'] = selected_directory
|
|
1669
|
+
save_config()
|
|
1670
|
+
selector.set_outputdir(selected_directory)
|
|
1671
|
+
capture_tool.outputdirpath = selected_directory
|
|
1672
|
+
if len(inputpathlist) > 0:
|
|
1673
|
+
parts_control(False)
|
|
1674
|
+
page.update()
|
|
1675
|
+
|
|
1676
|
+
preview_index = 0
|
|
1677
|
+
|
|
1678
|
+
def next_image(e):
|
|
1679
|
+
nonlocal inputpathlist, outputtxtlist, preview_index
|
|
1680
|
+
if not outputtxtlist:
|
|
1681
|
+
return
|
|
1682
|
+
if preview_index < min(len(inputpathlist) - 1, len(outputtxtlist) - 1):
|
|
1683
|
+
preview_index += 1
|
|
1684
|
+
else:
|
|
1685
|
+
preview_index = 0
|
|
1686
|
+
|
|
1687
|
+
if len(visualizepathlist) > 0:
|
|
1688
|
+
preview_image.src = visualizepathlist[min(preview_index, len(visualizepathlist) - 1)]
|
|
1689
|
+
current_visualizeimgname.value = os.path.basename(preview_image.src)
|
|
1690
|
+
elif 0 <= preview_index < len(inputpathlist):
|
|
1691
|
+
preview_image.src = inputpathlist[preview_index]
|
|
1692
|
+
current_visualizeimgname.value = os.path.basename(inputpathlist[preview_index])
|
|
1693
|
+
if 0 <= preview_index < len(outputtxtlist):
|
|
1694
|
+
preview_plain_text.value = outputplaintextlist[preview_index] if preview_index < len(outputplaintextlist) else ''
|
|
1695
|
+
preview_text.value = outputtxtlist[preview_index]
|
|
1696
|
+
preview_image.update()
|
|
1697
|
+
preview_plain_text.update()
|
|
1698
|
+
preview_text.update()
|
|
1699
|
+
page.update()
|
|
1700
|
+
|
|
1701
|
+
def prev_image(e):
|
|
1702
|
+
nonlocal inputpathlist, outputtxtlist, preview_index
|
|
1703
|
+
if not outputtxtlist:
|
|
1704
|
+
return
|
|
1705
|
+
if preview_index > 0:
|
|
1706
|
+
preview_index -= 1
|
|
1707
|
+
else:
|
|
1708
|
+
preview_index = min(len(inputpathlist) - 1, len(outputtxtlist) - 1)
|
|
1709
|
+
|
|
1710
|
+
if len(visualizepathlist) > 0:
|
|
1711
|
+
preview_image.src = visualizepathlist[min(preview_index, len(visualizepathlist) - 1)]
|
|
1712
|
+
current_visualizeimgname.value = os.path.basename(preview_image.src)
|
|
1713
|
+
elif 0 <= preview_index < len(inputpathlist):
|
|
1714
|
+
preview_image.src = inputpathlist[preview_index]
|
|
1715
|
+
current_visualizeimgname.value = os.path.basename(inputpathlist[preview_index])
|
|
1716
|
+
if 0 <= preview_index < len(outputtxtlist):
|
|
1717
|
+
preview_plain_text.value = outputplaintextlist[preview_index] if preview_index < len(outputplaintextlist) else ''
|
|
1718
|
+
preview_text.value = outputtxtlist[preview_index]
|
|
1719
|
+
preview_image.update()
|
|
1720
|
+
preview_plain_text.update()
|
|
1721
|
+
preview_text.update()
|
|
1722
|
+
page.update()
|
|
1723
|
+
|
|
1724
|
+
def change_preview_view_mode(e=None):
|
|
1725
|
+
use_markdown = bool(preview_view_switch.value)
|
|
1726
|
+
config_obj['result_markdown_display'] = use_markdown
|
|
1727
|
+
save_config()
|
|
1728
|
+
preview_text.visible = use_markdown
|
|
1729
|
+
preview_plain_text.visible = not use_markdown
|
|
1730
|
+
# Keep the crop/capture result viewers on the same mode when available.
|
|
1731
|
+
for viewer in (selector, capture_tool):
|
|
1732
|
+
viewer.result_view_switch.value = use_markdown
|
|
1733
|
+
viewer.resulttext.visible = use_markdown
|
|
1734
|
+
viewer.result_plain_text.visible = not use_markdown
|
|
1735
|
+
page.update()
|
|
1736
|
+
|
|
1737
|
+
def handle_customize_dlg_modal_close(e):
|
|
1738
|
+
updated_config = {
|
|
1739
|
+
'json': chkbx_json.value,
|
|
1740
|
+
'txt': chkbx_txt.value,
|
|
1741
|
+
'markdown': chkbx_markdown.value,
|
|
1742
|
+
'xml': chkbx_xml.value,
|
|
1743
|
+
'tei': chkbx_tei.value,
|
|
1744
|
+
'pdf': chkbx_pdf.value,
|
|
1745
|
+
'pdf_viztxt': chkbx_pdf_viztxt.value,
|
|
1746
|
+
'pdf_merge': chkbx_pdf_merge.value,
|
|
1747
|
+
'pdf_page_output': chkbx_pdf_page_output.value,
|
|
1748
|
+
'pdf_resolution': int(pdf_resolution_textfield.value),
|
|
1749
|
+
'text_daisy': chkbx_text_daisy.value,
|
|
1750
|
+
}
|
|
1751
|
+
if chkbx_table_structure is not None:
|
|
1752
|
+
updated_config['table_structure'] = chkbx_table_structure.value
|
|
1753
|
+
config_obj.update(updated_config)
|
|
1754
|
+
save_config()
|
|
1755
|
+
if customize_dlg_modal.open:
|
|
1756
|
+
page.pop_dialog()
|
|
1757
|
+
|
|
1758
|
+
def change_pdfstatus(e):
|
|
1759
|
+
chkbx_pdf_viztxt.disabled = not chkbx_pdf.value
|
|
1760
|
+
chkbx_pdf_viztxt.update()
|
|
1761
|
+
chkbx_pdf_merge.disabled = not chkbx_pdf.value
|
|
1762
|
+
chkbx_pdf_merge.update()
|
|
1763
|
+
pdf_resolution_textfield.disabled = not chkbx_pdf.value
|
|
1764
|
+
pdf_resolution_textfield.update()
|
|
1765
|
+
|
|
1766
|
+
def change_visualizestatus(e):
|
|
1767
|
+
config_obj['visualize'] = chkbx_visualize.value
|
|
1768
|
+
save_config()
|
|
1769
|
+
|
|
1770
|
+
preview_image = ft.Image(src=DEFAULT_IMAGE_SRC, width=400, height=300, gapless_playback=True)
|
|
1771
|
+
preview_text = ft.Markdown(
|
|
1772
|
+
value='',
|
|
1773
|
+
selectable=True,
|
|
1774
|
+
extension_set=ft.MarkdownExtensionSet.GITHUB_WEB,
|
|
1775
|
+
soft_line_break=True,
|
|
1776
|
+
visible=bool(config_obj.get('result_markdown_display', False)),
|
|
1777
|
+
)
|
|
1778
|
+
preview_plain_text = ft.Text(
|
|
1779
|
+
value='',
|
|
1780
|
+
selectable=True,
|
|
1781
|
+
visible=not bool(config_obj.get('result_markdown_display', False))
|
|
1782
|
+
)
|
|
1783
|
+
preview_view_switch = ft.Switch(
|
|
1784
|
+
label='整形表示(Markdown)',
|
|
1785
|
+
value=bool(config_obj.get('result_markdown_display', False)),
|
|
1786
|
+
on_change=change_preview_view_mode,
|
|
1787
|
+
)
|
|
1788
|
+
|
|
1789
|
+
file_picker = ft.FilePicker()
|
|
1790
|
+
page.services.append(file_picker)
|
|
1791
|
+
progressbar = ft.ProgressBar(width=200, value=0)
|
|
1792
|
+
selected_input_path = ft.Text(selectable=True)
|
|
1793
|
+
selected_output_path = ft.Text(config_obj['selected_output_path'], selectable=True)
|
|
1794
|
+
current_visualizeimgname = ft.Text(selectable=True)
|
|
1795
|
+
progressmessage = ft.Text(width=400, selectable=True)
|
|
1796
|
+
chkbx_visualize = ft.Checkbox(label=TRANSLATIONS['main_visualize_label'][config_obj['langcode']], value=config_obj.get('visualize', True), on_change=change_visualizestatus, key='visualize')
|
|
1797
|
+
chkbx_json = ft.Checkbox(label='JSON形式', value=config_obj['json'], key='output_json')
|
|
1798
|
+
chkbx_txt = ft.Checkbox(label='TXT形式', value=config_obj['txt'], key='output_txt')
|
|
1799
|
+
chkbx_markdown = ft.Checkbox(label='Markdown形式(.md)', value=config_obj.get('markdown', False), key='output_markdown')
|
|
1800
|
+
chkbx_xml = ft.Checkbox(label='XML形式', value=config_obj['xml'], key='output_xml')
|
|
1801
|
+
chkbx_tei = ft.Checkbox(label='TEI形式', value=config_obj['tei'], key='output_tei')
|
|
1802
|
+
chkbx_pdf = ft.Checkbox(label='透明テキスト付PDF', value=config_obj['pdf'], on_change=change_pdfstatus, key='output_pdf')
|
|
1803
|
+
chkbx_pdf_viztxt = ft.Checkbox(label='PDFに青色で文字を重ねる', value=config_obj['pdf_viztxt'], disabled=not chkbx_pdf.value, key='output_pdf_visible_text')
|
|
1804
|
+
chkbx_pdf_merge = ft.Checkbox(label='出力ファイルを1つのpdfにまとめる', value=config_obj['pdf_merge'], disabled=not chkbx_pdf.value, key='output_pdf_merge')
|
|
1805
|
+
chkbx_pdf_page_output = ft.Checkbox(label='複数ページPDFを入力とする時はTXT/JSON/XML/TEIをページ毎に出力する', value=config_obj.get('pdf_page_output', True), key='output_pdf_page_output')
|
|
1806
|
+
pdf_resolution_textfield = ft.TextField(label='pdfの出力解像度を指定する', value=str(config_obj['pdf_resolution']), width=200, disabled=not chkbx_pdf.value, key='output_pdf_resolution')
|
|
1807
|
+
chkbx_text_daisy = ft.Checkbox(
|
|
1808
|
+
label='テキストDAISY形式(DAISY 3)',
|
|
1809
|
+
value=config_obj['text_daisy'],
|
|
1810
|
+
key='output_text_daisy',
|
|
1811
|
+
)
|
|
1812
|
+
chkbx_table_structure = (
|
|
1813
|
+
TABLE_STRUCTURE_FEATURE.create_output_control(config_obj)
|
|
1814
|
+
if TABLE_STRUCTURE_FEATURE is not None
|
|
1815
|
+
else None
|
|
1816
|
+
)
|
|
1817
|
+
file_upload_btn = ft.Button(
|
|
1818
|
+
TRANSLATIONS['main_file_upload_btn'][config_obj['langcode']],
|
|
1819
|
+
icon=ft.Icons.UPLOAD_FILE,
|
|
1820
|
+
on_click=pick_files_result,
|
|
1821
|
+
key='select_input_file',
|
|
1822
|
+
)
|
|
1823
|
+
directory_upload_btn = ft.Button(
|
|
1824
|
+
TRANSLATIONS['main_directory_upload_btn'][config_obj['langcode']],
|
|
1825
|
+
icon=ft.Icons.FOLDER_OPEN,
|
|
1826
|
+
on_click=pick_directory_result,
|
|
1827
|
+
key='select_input_directory',
|
|
1828
|
+
)
|
|
1829
|
+
directory_output_btn = ft.Button(
|
|
1830
|
+
TRANSLATIONS['main_directory_output_btn'][config_obj['langcode']],
|
|
1831
|
+
on_click=pick_output_result,
|
|
1832
|
+
key='select_output_directory',
|
|
1833
|
+
)
|
|
1834
|
+
ocr_btn = ft.Button(
|
|
1835
|
+
content='OCR',
|
|
1836
|
+
on_click=ocr_button_result,
|
|
1837
|
+
style=ft.ButtonStyle(
|
|
1838
|
+
padding=30,
|
|
1839
|
+
shape=ft.RoundedRectangleBorder(radius=10),
|
|
1840
|
+
),
|
|
1841
|
+
disabled=True,
|
|
1842
|
+
key='run_ocr',
|
|
1843
|
+
)
|
|
1844
|
+
stop_ocr_btn=ft.Button(
|
|
1845
|
+
content=TRANSLATIONS["main_stop_ocr_btn"][config_obj["langcode"]],
|
|
1846
|
+
on_click=request_ocr_cancel,
|
|
1847
|
+
disabled=True,
|
|
1848
|
+
key='stop_ocr')
|
|
1849
|
+
preview_image_col = ft.Column(
|
|
1850
|
+
controls=[preview_image],
|
|
1851
|
+
width=400,
|
|
1852
|
+
height=300,
|
|
1853
|
+
expand=False,
|
|
1854
|
+
)
|
|
1855
|
+
|
|
1856
|
+
preview_image_int = ft.InteractiveViewer(
|
|
1857
|
+
min_scale=1,
|
|
1858
|
+
max_scale=10,
|
|
1859
|
+
boundary_margin=ft.Margin.all(20),
|
|
1860
|
+
content=preview_image_col,
|
|
1861
|
+
)
|
|
1862
|
+
preview_text_col = ft.Column(
|
|
1863
|
+
#controls=[preview_view_switch, preview_plain_text, preview_text],
|
|
1864
|
+
controls=[preview_plain_text, preview_text],
|
|
1865
|
+
scroll=ft.ScrollMode.ALWAYS,
|
|
1866
|
+
height=300,
|
|
1867
|
+
expand=True,
|
|
1868
|
+
)
|
|
1869
|
+
preview_prev_btn = ft.Button(content=TRANSLATIONS['main_prev_btn'][config_obj['langcode']], on_click=prev_image, disabled=True)
|
|
1870
|
+
preview_next_btn = ft.Button(content=TRANSLATIONS['main_next_btn'][config_obj['langcode']], on_click=next_image, disabled=True)
|
|
1871
|
+
customize_btn = ft.Button(
|
|
1872
|
+
TRANSLATIONS['main_customize_btn'][config_obj['langcode']],
|
|
1873
|
+
on_click=lambda e: page.show_dialog(customize_dlg_modal),
|
|
1874
|
+
key='customize_output',
|
|
1875
|
+
)
|
|
1876
|
+
customize_dlg_modal = ft.AlertDialog(
|
|
1877
|
+
modal=True,
|
|
1878
|
+
title=ft.Text(TRANSLATIONS['customize_dlg_modal_title'][config_obj['langcode']]),
|
|
1879
|
+
content=ft.Text(TRANSLATIONS['customize_dlg_modal_explain'][config_obj['langcode']]),
|
|
1880
|
+
actions=[
|
|
1881
|
+
ft.Row([chkbx_txt,chkbx_json]),
|
|
1882
|
+
#chkbx_markdown,
|
|
1883
|
+
ft.Row([chkbx_xml, chkbx_tei]),
|
|
1884
|
+
ft.Row([chkbx_pdf, chkbx_pdf_viztxt]),
|
|
1885
|
+
ft.Row([chkbx_pdf_merge, pdf_resolution_textfield]),
|
|
1886
|
+
chkbx_pdf_page_output,
|
|
1887
|
+
#chkbx_text_daisy,
|
|
1888
|
+
*([chkbx_table_structure] if chkbx_table_structure is not None else []),
|
|
1889
|
+
ft.TextButton('OK', on_click=handle_customize_dlg_modal_close, key='customize_output_ok'),
|
|
1890
|
+
],
|
|
1891
|
+
actions_alignment=ft.MainAxisAlignment.END,
|
|
1892
|
+
key='customize_output_dialog',
|
|
1893
|
+
)
|
|
1894
|
+
selector = ImageSelector(
|
|
1895
|
+
page,
|
|
1896
|
+
config_obj,
|
|
1897
|
+
detector=origin_detector,
|
|
1898
|
+
recognizer30=origin_recognizer30,
|
|
1899
|
+
recognizer50=origin_recognizer50,
|
|
1900
|
+
recognizer100=origin_recognizer,
|
|
1901
|
+
table_feature=TABLE_STRUCTURE_FEATURE,
|
|
1902
|
+
table_recognizer=origin_table_recognizer,
|
|
1903
|
+
outputdirpath=selected_output_path.value,
|
|
1904
|
+
)
|
|
1905
|
+
|
|
1906
|
+
capture_tool = CaptureTool(
|
|
1907
|
+
page,
|
|
1908
|
+
config_obj,
|
|
1909
|
+
detector=origin_detector,
|
|
1910
|
+
recognizer30=origin_recognizer30,
|
|
1911
|
+
recognizer50=origin_recognizer50,
|
|
1912
|
+
recognizer100=origin_recognizer,
|
|
1913
|
+
table_feature=TABLE_STRUCTURE_FEATURE,
|
|
1914
|
+
table_recognizer=origin_table_recognizer,
|
|
1915
|
+
)
|
|
1916
|
+
if selected_output_path.value:
|
|
1917
|
+
capture_tool.outputdirpath = selected_output_path.value
|
|
1918
|
+
|
|
1919
|
+
llm_capture_extension = (
|
|
1920
|
+
LLM_FEATURE.attach_capture_tool(capture_tool, config_obj, save_config)
|
|
1921
|
+
if LLM_FEATURE is not None
|
|
1922
|
+
else None
|
|
1923
|
+
)
|
|
1924
|
+
datapool_capture_extension = (
|
|
1925
|
+
DATA_POOL_FEATURE.attach_capture_tool(
|
|
1926
|
+
capture_tool,
|
|
1927
|
+
llm_capture_extension,
|
|
1928
|
+
config_obj,
|
|
1929
|
+
Path(PDFTMPPATH),
|
|
1930
|
+
)
|
|
1931
|
+
if DATA_POOL_FEATURE is not None
|
|
1932
|
+
else None
|
|
1933
|
+
)
|
|
1934
|
+
datapool_header_controls = (
|
|
1935
|
+
DATA_POOL_FEATURE.build_auth_controls(
|
|
1936
|
+
page,
|
|
1937
|
+
config_obj,
|
|
1938
|
+
save_config,
|
|
1939
|
+
datapool_capture_extension,
|
|
1940
|
+
)
|
|
1941
|
+
if DATA_POOL_FEATURE is not None
|
|
1942
|
+
else []
|
|
1943
|
+
)
|
|
1944
|
+
|
|
1945
|
+
crop_btn = ft.Button(
|
|
1946
|
+
content='Crop&OCR',
|
|
1947
|
+
on_click=selector.open_dialog,
|
|
1948
|
+
style=ft.ButtonStyle(
|
|
1949
|
+
padding=10,
|
|
1950
|
+
shape=ft.RoundedRectangleBorder(radius=10),
|
|
1951
|
+
),
|
|
1952
|
+
disabled=True,
|
|
1953
|
+
key='crop_ocr',
|
|
1954
|
+
)
|
|
1955
|
+
cap_btn = ft.Button(
|
|
1956
|
+
content=TRANSLATIONS['main_cap_btn'][config_obj['langcode']],
|
|
1957
|
+
on_click=capture_tool.start_capture,
|
|
1958
|
+
style=ft.ButtonStyle(
|
|
1959
|
+
padding=10,
|
|
1960
|
+
shape=ft.RoundedRectangleBorder(radius=10),
|
|
1961
|
+
),
|
|
1962
|
+
disabled=True,
|
|
1963
|
+
key='capture_ocr',
|
|
1964
|
+
)
|
|
1965
|
+
explain_label = ft.Text(TRANSLATIONS['main_explain'][config_obj['langcode']])
|
|
1966
|
+
localebutton = ft.CupertinoSlidingSegmentedButton(
|
|
1967
|
+
selected_index=0 if config_obj['langcode'] == 'ja' else 1,
|
|
1968
|
+
thumb_color=ft.Colors.BLUE_400,
|
|
1969
|
+
on_change=handle_locale_change,
|
|
1970
|
+
controls=[ft.Text('日本語'), ft.Text('English')],
|
|
1971
|
+
key='locale',
|
|
1972
|
+
)
|
|
1973
|
+
page.add(
|
|
1974
|
+
ft.Row([
|
|
1975
|
+
localebutton,
|
|
1976
|
+
*datapool_header_controls,
|
|
1977
|
+
]),
|
|
1978
|
+
ft.Row([
|
|
1979
|
+
explain_label,
|
|
1980
|
+
cap_btn,
|
|
1981
|
+
]),
|
|
1982
|
+
ft.Divider(),
|
|
1983
|
+
ft.Row([
|
|
1984
|
+
file_upload_btn,
|
|
1985
|
+
directory_upload_btn,
|
|
1986
|
+
ft.Text(TRANSLATIONS['main_target_label'][config_obj['langcode']]),
|
|
1987
|
+
selected_input_path,
|
|
1988
|
+
]),
|
|
1989
|
+
ft.Divider(),
|
|
1990
|
+
ft.Row([
|
|
1991
|
+
directory_output_btn,
|
|
1992
|
+
ft.Text(TRANSLATIONS['main_output_label'][config_obj['langcode']]),
|
|
1993
|
+
selected_output_path,
|
|
1994
|
+
]),
|
|
1995
|
+
ft.Divider(),
|
|
1996
|
+
ft.Row([
|
|
1997
|
+
ocr_btn,
|
|
1998
|
+
stop_ocr_btn,
|
|
1999
|
+
crop_btn,
|
|
2000
|
+
ft.Column([
|
|
2001
|
+
chkbx_visualize,
|
|
2002
|
+
ft.Row([
|
|
2003
|
+
customize_btn,
|
|
2004
|
+
ft.Column([progressmessage, progressbar], width=400),
|
|
2005
|
+
]),
|
|
2006
|
+
]),
|
|
2007
|
+
]),
|
|
2008
|
+
ft.Divider(),
|
|
2009
|
+
ft.Row([ft.Text(TRANSLATIONS['main_preview_label'][config_obj['langcode']]), preview_prev_btn, preview_next_btn, current_visualizeimgname]),
|
|
2010
|
+
ft.Row([preview_image_int, preview_text_col]),
|
|
2011
|
+
)
|
|
2012
|
+
page.update()
|
|
2013
|
+
|
|
2014
|
+
async def initialize_models():
|
|
2015
|
+
nonlocal origin_detector, origin_recognizer
|
|
2016
|
+
nonlocal origin_recognizer30, origin_recognizer50
|
|
2017
|
+
nonlocal origin_table_recognizer
|
|
2018
|
+
|
|
2019
|
+
started_at = time.perf_counter()
|
|
2020
|
+
try:
|
|
2021
|
+
(
|
|
2022
|
+
origin_detector,
|
|
2023
|
+
origin_recognizer,
|
|
2024
|
+
origin_recognizer30,
|
|
2025
|
+
origin_recognizer50,
|
|
2026
|
+
) = await asyncio.to_thread(load_ocr_models, args, download_models=download_models)
|
|
2027
|
+
origin_table_recognizer = None
|
|
2028
|
+
model_state['table_error'] = None
|
|
2029
|
+
if TABLE_STRUCTURE_FEATURE is not None:
|
|
2030
|
+
try:
|
|
2031
|
+
table_recognizer = TABLE_STRUCTURE_FEATURE.create_recognizer(args)
|
|
2032
|
+
await asyncio.to_thread(table_recognizer.load)
|
|
2033
|
+
origin_table_recognizer = table_recognizer
|
|
2034
|
+
except Exception as table_ex:
|
|
2035
|
+
model_state['table_error'] = table_ex
|
|
2036
|
+
print(f'[WARN] Table structure initialization failed: {table_ex}')
|
|
2037
|
+
|
|
2038
|
+
model_state['elapsed'] = time.perf_counter() - started_at
|
|
2039
|
+
model_state['error'] = None
|
|
2040
|
+
|
|
2041
|
+
for tool in (selector, capture_tool):
|
|
2042
|
+
tool.detector = origin_detector
|
|
2043
|
+
tool.recognizer30 = origin_recognizer30
|
|
2044
|
+
tool.recognizer50 = origin_recognizer50
|
|
2045
|
+
tool.recognizer100 = origin_recognizer
|
|
2046
|
+
tool.table_recognizer = origin_table_recognizer
|
|
2047
|
+
|
|
2048
|
+
progressbar.value = 0
|
|
2049
|
+
if config_obj['langcode'] == 'ja':
|
|
2050
|
+
if TABLE_STRUCTURE_FEATURE is None:
|
|
2051
|
+
progressmessage.value = f'OCRモデル準備完了 ({model_state["elapsed"]:.1f}秒)'
|
|
2052
|
+
elif model_state.get('table_error') is None:
|
|
2053
|
+
progressmessage.value = f'OCR / 表推定モデル準備完了 ({model_state["elapsed"]:.1f}秒)'
|
|
2054
|
+
else:
|
|
2055
|
+
progressmessage.value = f'OCRモデル準備完了 / 表推定初期化失敗 ({model_state["elapsed"]:.1f}秒)'
|
|
2056
|
+
else:
|
|
2057
|
+
if TABLE_STRUCTURE_FEATURE is None:
|
|
2058
|
+
progressmessage.value = f'OCR models ready ({model_state["elapsed"]:.1f} sec)'
|
|
2059
|
+
elif model_state.get('table_error') is None:
|
|
2060
|
+
progressmessage.value = f'OCR / TableInfer models ready ({model_state["elapsed"]:.1f} sec)'
|
|
2061
|
+
else:
|
|
2062
|
+
progressmessage.value = f'OCR models ready / TableInfer models unavailable ({model_state["elapsed"]:.1f} sec)'
|
|
2063
|
+
except Exception as ex:
|
|
2064
|
+
model_state['error'] = ex
|
|
2065
|
+
progressbar.value = 0
|
|
2066
|
+
progressmessage.value = f'OCR model initialization failed: {ex}'
|
|
2067
|
+
finally:
|
|
2068
|
+
model_state['loading'] = False
|
|
2069
|
+
parts_control(False)
|
|
2070
|
+
page.update()
|
|
2071
|
+
|
|
2072
|
+
if models_are_ready():
|
|
2073
|
+
parts_control(False)
|
|
2074
|
+
if model_state['elapsed'] is not None:
|
|
2075
|
+
if config_obj['langcode'] == 'ja':
|
|
2076
|
+
if TABLE_STRUCTURE_FEATURE is None:
|
|
2077
|
+
progressmessage.value = f'OCRモデル準備完了 ({model_state["elapsed"]:.1f}秒)'
|
|
2078
|
+
elif model_state.get('table_error') is None:
|
|
2079
|
+
progressmessage.value = f'OCR / 表推定モデル準備完了 ({model_state["elapsed"]:.1f}秒)'
|
|
2080
|
+
else:
|
|
2081
|
+
progressmessage.value = f'OCRモデル準備完了 / 表推定初期化失敗 ({model_state["elapsed"]:.1f}秒)'
|
|
2082
|
+
else:
|
|
2083
|
+
if TABLE_STRUCTURE_FEATURE is None:
|
|
2084
|
+
progressmessage.value = f'OCR models ready ({model_state["elapsed"]:.1f} sec)'
|
|
2085
|
+
elif model_state.get('table_error') is None:
|
|
2086
|
+
progressmessage.value = f'OCR / TableInfer models ready ({model_state["elapsed"]:.1f} sec)'
|
|
2087
|
+
else:
|
|
2088
|
+
progressmessage.value = f'OCR models ready / TableInfer models unavailable ({model_state["elapsed"]:.1f} sec)'
|
|
2089
|
+
page.update()
|
|
2090
|
+
elif not model_state['loading']:
|
|
2091
|
+
model_state['loading'] = True
|
|
2092
|
+
progressbar.value = None
|
|
2093
|
+
if config_obj['langcode'] == 'ja':
|
|
2094
|
+
progressmessage.value = 'OCRモデルを読み込み中…'
|
|
2095
|
+
else:
|
|
2096
|
+
progressmessage.value = 'Loading OCR models…'
|
|
2097
|
+
localebutton.disabled = True
|
|
2098
|
+
page.update()
|
|
2099
|
+
page.run_task(initialize_models)
|
|
2100
|
+
|
|
2101
|
+
renderui()
|
|
2102
|
+
|
|
2103
|
+
|
|
2104
|
+
if __name__ == '__main__':
|
|
2105
|
+
ft.run(main, assets_dir=str(ASSETS_DIR))
|