dinhminh20521597 commited on
Commit
8c3a770
·
1 Parent(s): d0bb85b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +16 -1380
app.py CHANGED
@@ -1,1381 +1,17 @@
1
- """This Streamlit app allows you to compare, from a given image, the results of different solutions:
2
- EasyOcr, PaddleOCR, MMOCR, Tesseract
3
- """
4
  import streamlit as st
5
- import plotly.express as px
6
- import numpy as np
7
- import math
8
- import pandas as pd
9
- from time import sleep
10
-
11
- import cv2
12
- from PIL import Image, ImageColor
13
- import PIL
14
- import easyocr
15
- from paddleocr import PaddleOCR
16
- from mmocr.utils.ocr import MMOCR
17
- import pytesseract
18
- from pytesseract import Output
19
- import os
20
- from mycolorpy import colorlist as mcp
21
-
22
-
23
- ###################################################################################################
24
- ## MAIN
25
- ###################################################################################################
26
- def app():
27
-
28
- ###################################################################################################
29
- ## FUNCTIONS
30
- ###################################################################################################
31
-
32
- @st.cache
33
- def convert_df(in_df):
34
- """Convert data frame function, used by download button
35
-
36
- Args:
37
- in_df (data frame): data frame to convert
38
-
39
- Returns:
40
- data frame: converted data frame
41
- """
42
- # IMPORTANT: Cache the conversion to prevent computation on every rerun
43
- return in_df.to_csv().encode('utf-8')
44
-
45
- ###
46
- def easyocr_coord_convert(in_list_coord):
47
- """Convert easyocr coordinates to standard format used by others functions
48
-
49
- Args:
50
- in_list_coord (list of numbers): format [x_min, x_max, y_min, y_max]
51
-
52
- Returns:
53
- list of lists: format [ [x_min, y_min], [x_max, y_min], [x_max, y_max], [x_min, y_max] ]
54
- """
55
-
56
- coord = in_list_coord
57
- return [[coord[0], coord[2]], [coord[1], coord[2]], [coord[1], coord[3]], [coord[0], coord[3]]]
58
-
59
- ###
60
- @st.cache(show_spinner=False)
61
- def initializations():
62
- """Initializations for the app
63
-
64
- Returns:
65
- list of strings : list of OCR solutions names
66
- (['EasyOCR', 'PPOCR', 'MMOCR', 'Tesseract'])
67
- dict : names and indices of the OCR solutions
68
- ({'EasyOCR': 0, 'PPOCR': 1, 'MMOCR': 2, 'Tesseract': 3})
69
- list of dicts : list of languages supported by each OCR solution
70
- list of int : columns for recognition details results
71
- dict : confidence color scale
72
- plotly figure : confidence color scale figure
73
- """
74
- # the readers considered
75
- out_reader_type_list = ['EasyOCR', 'PPOCR', 'MMOCR', 'Tesseract']
76
- out_reader_type_dict = {'EasyOCR': 0, 'PPOCR': 1, 'MMOCR': 2, 'Tesseract': 3}
77
-
78
- # Columns for recognition details results
79
- out_cols_size = [2] + [2,1]*(len(out_reader_type_list)-1) # Except Tesseract
80
-
81
- # Dicts of laguages supported by each reader
82
- out_dict_lang_easyocr = {'Abaza': 'abq', 'Adyghe': 'ady', 'Afrikaans': 'af', 'Angika': 'ang', \
83
- 'Arabic': 'ar', 'Assamese': 'as', 'Avar': 'ava', 'Azerbaijani': 'az', 'Belarusian': 'be', \
84
- 'Bulgarian': 'bg', 'Bihari': 'bh', 'Bhojpuri': 'bho', 'Bengali': 'bn', 'Bosnian': 'bs', \
85
- 'Simplified Chinese': 'ch_sim', 'Traditional Chinese': 'ch_tra', 'Chechen': 'che', \
86
- 'Czech': 'cs', 'Welsh': 'cy', 'Danish': 'da', 'Dargwa': 'dar', 'German': 'de', \
87
- 'English': 'en', 'Spanish': 'es', 'Estonian': 'et', 'Persian (Farsi)': 'fa', 'French': 'fr', \
88
- 'Irish': 'ga', 'Goan Konkani': 'gom', 'Hindi': 'hi', 'Croatian': 'hr', 'Hungarian': 'hu', \
89
- 'Indonesian': 'id', 'Ingush': 'inh', 'Icelandic': 'is', 'Italian': 'it', 'Japanese': 'ja', \
90
- 'Kabardian': 'kbd', 'Kannada': 'kn', 'Korean': 'ko', 'Kurdish': 'ku', 'Latin': 'la', \
91
- 'Lak': 'lbe', 'Lezghian': 'lez', 'Lithuanian': 'lt', 'Latvian': 'lv', 'Magahi': 'mah', \
92
- 'Maithili': 'mai', 'Maori': 'mi', 'Mongolian': 'mn', 'Marathi': 'mr', 'Malay': 'ms', \
93
- 'Maltese': 'mt', 'Nepali': 'ne', 'Newari': 'new', 'Dutch': 'nl', 'Norwegian': 'no', \
94
- 'Occitan': 'oc', 'Pali': 'pi', 'Polish': 'pl', 'Portuguese': 'pt', 'Romanian': 'ro', \
95
- 'Russian': 'ru', 'Serbian (cyrillic)': 'rs_cyrillic', 'Serbian (latin)': 'rs_latin', \
96
- 'Nagpuri': 'sck', 'Slovak': 'sk', 'Slovenian': 'sl', 'Albanian': 'sq', 'Swedish': 'sv', \
97
- 'Swahili': 'sw', 'Tamil': 'ta', 'Tabassaran': 'tab', 'Telugu': 'te', 'Thai': 'th', \
98
- 'Tajik': 'tjk', 'Tagalog': 'tl', 'Turkish': 'tr', 'Uyghur': 'ug', 'Ukranian': 'uk', \
99
- 'Urdu': 'ur', 'Uzbek': 'uz', 'Vietnamese': 'vi'}
100
-
101
- out_dict_lang_ppocr = {'Abaza': 'abq', 'Adyghe': 'ady', 'Afrikaans': 'af', 'Albanian': 'sq', \
102
- 'Angika': 'ang', 'Arabic': 'ar', 'Avar': 'ava', 'Azerbaijani': 'az', 'Belarusian': 'be', \
103
- 'Bhojpuri': 'bho','Bihari': 'bh','Bosnian': 'bs','Bulgarian': 'bg','Chinese & English': 'ch', \
104
- 'Chinese Traditional': 'chinese_cht', 'Croatian': 'hr', 'Czech': 'cs', 'Danish': 'da', \
105
- 'Dargwa': 'dar', 'Dutch': 'nl', 'English': 'en', 'Estonian': 'et', 'French': 'fr', \
106
- 'German': 'german','Goan Konkani': 'gom','Hindi': 'hi','Hungarian': 'hu','Icelandic': 'is', \
107
- 'Indonesian': 'id', 'Ingush': 'inh', 'Irish': 'ga', 'Italian': 'it', 'Japan': 'japan', \
108
- 'Kabardian': 'kbd', 'Korean': 'korean', 'Kurdish': 'ku', 'Lak': 'lbe', 'Latvian': 'lv', \
109
- 'Lezghian': 'lez', 'Lithuanian': 'lt', 'Magahi': 'mah', 'Maithili': 'mai', 'Malay': 'ms', \
110
- 'Maltese': 'mt', 'Maori': 'mi', 'Marathi': 'mr', 'Mongolian': 'mn', 'Nagpur': 'sck', \
111
- 'Nepali': 'ne', 'Newari': 'new', 'Norwegian': 'no', 'Occitan': 'oc', 'Persian': 'fa', \
112
- 'Polish': 'pl', 'Portuguese': 'pt', 'Romanian': 'ro', 'Russia': 'ru', 'Saudi Arabia': 'sa', \
113
- 'Serbian(cyrillic)': 'rs_cyrillic', 'Serbian(latin)': 'rs_latin', 'Slovak': 'sk', \
114
- 'Slovenian': 'sl', 'Spanish': 'es', 'Swahili': 'sw', 'Swedish': 'sv', 'Tabassaran': 'tab', \
115
- 'Tagalog': 'tl', 'Tamil': 'ta', 'Telugu': 'te', 'Turkish': 'tr', 'Ukranian': 'uk', \
116
- 'Urdu': 'ur', 'Uyghur': 'ug', 'Uzbek': 'uz', 'Vietnamese': 'vi', 'Welsh': 'cy'}
117
-
118
- out_dict_lang_mmocr = {'English': 'en'}
119
-
120
- out_dict_lang_tesseract = {'Afrikaans': 'afr','Albanian': 'sqi','Amharic': 'amh', \
121
- 'Arabic': 'ara', 'Armenian': 'hye','Assamese': 'asm','Azerbaijani - Cyrilic': 'aze_cyrl', \
122
- 'Azerbaijani': 'aze', 'Basque': 'eus','Belarusian': 'bel','Bengali': 'ben','Bosnian': 'bos', \
123
- 'Breton': 'bre', 'Bulgarian': 'bul','Burmese': 'mya','Catalan; Valencian': 'cat', \
124
- 'Cebuano': 'ceb', 'Central Khmer': 'khm','Cherokee': 'chr','Chinese - Simplified': 'chi_sim', \
125
- 'Chinese - Traditional': 'chi_tra','Corsican': 'cos','Croatian': 'hrv','Czech': 'ces', \
126
- 'Danish':'dan','Dutch; Flemish':'nld','Dzongkha':'dzo','English, Middle (1100-1500)':'enm', \
127
- 'English': 'eng','Esperanto': 'epo','Estonian': 'est','Faroese': 'fao', \
128
- 'Filipino (old - Tagalog)': 'fil','Finnish': 'fin','French, Middle (ca.1400-1600)': 'frm', \
129
- 'French': 'fra','Galician': 'glg','Georgian - Old': 'kat_old','Georgian': 'kat', \
130
- 'German - Fraktur': 'frk','German': 'deu','Greek, Modern (1453-)': 'ell','Gujarati': 'guj', \
131
- 'Haitian; Haitian Creole': 'hat','Hebrew': 'heb','Hindi': 'hin','Hungarian': 'hun', \
132
- 'Icelandic': 'isl','Indonesian': 'ind','Inuktitut': 'iku','Irish': 'gle', \
133
- 'Italian - Old': 'ita_old','Italian': 'ita','Japanese': 'jpn','Javanese': 'jav', \
134
- 'Kannada': 'kan','Kazakh': 'kaz','Kirghiz; Kyrgyz': 'kir','Korean (vertical)': 'kor_vert', \
135
- 'Korean': 'kor','Kurdish (Arabic Script)': 'kur_ara','Lao': 'lao','Latin': 'lat', \
136
- 'Latvian':'lav','Lithuanian':'lit','Luxembourgish':'ltz','Macedonian':'mkd','Malay':'msa', \
137
- 'Malayalam': 'mal','Maltese': 'mlt','Maori': 'mri','Marathi': 'mar','Mongolian': 'mon', \
138
- 'Nepali': 'nep','Norwegian': 'nor','Occitan (post 1500)': 'oci', \
139
- 'Orientation and script detection module':'osd','Oriya':'ori','Panjabi; Punjabi':'pan', \
140
- 'Persian':'fas','Polish':'pol','Portuguese':'por','Pushto; Pashto':'pus','Quechua':'que', \
141
- 'Romanian; Moldavian; Moldovan': 'ron','Russian': 'rus','Sanskrit': 'san', \
142
- 'Scottish Gaelic': 'gla','Serbian - Latin': 'srp_latn','Serbian': 'srp','Sindhi': 'snd', \
143
- 'Sinhala; Sinhalese': 'sin','Slovak': 'slk','Slovenian': 'slv', \
144
- 'Spanish; Castilian - Old': 'spa_old','Spanish; Castilian': 'spa','Sundanese': 'sun', \
145
- 'Swahili': 'swa','Swedish': 'swe','Syriac': 'syr','Tajik': 'tgk','Tamil': 'tam', \
146
- 'Tatar':'tat','Telugu':'tel','Thai':'tha','Tibetan':'bod','Tigrinya':'tir','Tonga':'ton', \
147
- 'Turkish': 'tur','Uighur; Uyghur': 'uig','Ukrainian': 'ukr','Urdu': 'urd', \
148
- 'Uzbek - Cyrilic': 'uzb_cyrl','Uzbek': 'uzb','Vietnamese': 'vie','Welsh': 'cym', \
149
- 'Western Frisian': 'fry','Yiddish': 'yid','Yoruba': 'yor'}
150
-
151
- out_list_dict_lang = [out_dict_lang_easyocr, out_dict_lang_ppocr, out_dict_lang_mmocr, \
152
- out_dict_lang_tesseract]
153
-
154
- # Initialization of detection form
155
- if 'columns_size' not in st.session_state:
156
- st.session_state.columns_size = [2] + [1 for x in out_reader_type_list[1:]]
157
- if 'column_width' not in st.session_state:
158
- st.session_state.column_width = [400] + [300 for x in out_reader_type_list[1:]]
159
- if 'columns_color' not in st.session_state:
160
- st.session_state.columns_color = ["rgb(228,26,28)"] + \
161
- ["rgb(0,0,0)" for x in out_reader_type_list[1:]]
162
- if 'list_coordinates' not in st.session_state:
163
- st.session_state.list_coordinates = []
164
-
165
- # Confidence color scale
166
- out_list_confid = list(np.arange(0,101,1))
167
- out_list_grad = mcp.gen_color_normalized(cmap="Greens",data_arr=np.array(out_list_confid))
168
- out_dict_back_colors = {out_list_confid[i]: out_list_grad[i] \
169
- for i in range(len(out_list_confid))}
170
-
171
- list_y = [1 for i in out_list_confid]
172
- df_confid = pd.DataFrame({'% confidence scale': out_list_confid, 'y': list_y})
173
-
174
- out_fig = px.scatter(df_confid, x='% confidence scale', y='y', \
175
- hover_data={'% confidence scale': True, 'y': False},
176
- color=out_dict_back_colors.values(), range_y=[0.9,1.1], range_x=[0,100],
177
- color_discrete_map="identity",height=50,symbol='y',symbol_sequence=['square'])
178
- out_fig.update_xaxes(showticklabels=False)
179
- out_fig.update_yaxes(showticklabels=False, range=[0.1, 1.1], visible=False)
180
- out_fig.update_traces(marker_size=50)
181
- out_fig.update_layout(paper_bgcolor="white", margin=dict(b=0,r=0,t=0,l=0), xaxis_side="top", \
182
- showlegend=False)
183
-
184
- return out_reader_type_list, out_reader_type_dict, out_list_dict_lang, \
185
- out_cols_size, out_dict_back_colors, out_fig
186
-
187
- ###
188
- @st.experimental_memo(show_spinner=False)
189
- def init_easyocr(in_params):
190
- """Initialization of easyOCR reader
191
-
192
- Args:
193
- in_params (list): list with the language
194
-
195
- Returns:
196
- easyocr reader: the easyocr reader instance
197
- """
198
- out_ocr = easyocr.Reader(in_params)
199
- return out_ocr
200
-
201
- ###
202
- @st.cache(show_spinner=False)
203
- def init_ppocr(in_params):
204
- """Initialization of PPOCR reader
205
-
206
- Args:
207
- in_params (dict): dict with parameters
208
-
209
- Returns:
210
- ppocr reader: the ppocr reader instance
211
- """
212
- out_ocr = PaddleOCR(lang=in_params[0], **in_params[1])
213
- return out_ocr
214
-
215
- ###
216
- @st.experimental_memo(show_spinner=False)
217
- def init_mmocr(in_params):
218
- """Initialization of MMOCR reader
219
-
220
- Args:
221
- in_params (dict): dict with parameters
222
-
223
- Returns:
224
- mmocr reader: the ppocr reader instance
225
- """
226
- out_ocr = MMOCR(recog=None, **in_params[1])
227
- return out_ocr
228
-
229
- ###
230
- def init_readers(in_list_params):
231
- """Initialization of the readers, and return them as list
232
-
233
- Args:
234
- in_list_params (list): list of dicts of parameters for each reader
235
-
236
- Returns:
237
- list: list of the reader's instances
238
- """
239
- # Instantiations of the readers :
240
- # - EasyOCR
241
- # with st.spinner("EasyOCR reader initialization in progress ..."):
242
- # reader_easyocr = init_easyocr([in_list_params[0][0]])
243
-
244
- # # - PPOCR
245
- # # Paddleocr
246
- # with st.spinner("PPOCR reader initialization in progress ..."):
247
- # reader_ppocr = init_ppocr(in_list_params[1])
248
-
249
- # - MMOCR
250
- with st.spinner("MMOCR reader initialization in progress ..."):
251
- reader_mmocr = init_mmocr(in_list_params[0])
252
-
253
- out_list_readers = [reader_mmocr]
254
-
255
- # out_list_readers = [reader_easyocr, reader_ppocr, reader_mmocr]
256
-
257
- return out_list_readers
258
-
259
- ###
260
- def load_image(in_image_file):
261
- """Load input file and open it
262
-
263
- Args:
264
- in_image_file (string or Streamlit UploadedFile): image to consider
265
-
266
- Returns:
267
- string : locally saved image path (img.)
268
- PIL.Image : input file opened with Pillow
269
- matrix : input file opened with Opencv
270
- """
271
-
272
- #if isinstance(in_image_file, str):
273
- # out_image_path = "img."+in_image_file.split('.')[-1]
274
- #else:
275
- # out_image_path = "img."+in_image_file.name.split('.')[-1]
276
-
277
- if isinstance(in_image_file, str):
278
- out_image_path = "tmp_"+in_image_file
279
- else:
280
- out_image_path = "tmp_"+in_image_file.name
281
-
282
- img = Image.open(in_image_file)
283
- img_saved = img.save(out_image_path)
284
-
285
- # Read image
286
- out_image_orig = Image.open(out_image_path)
287
- out_image_cv2 = cv2.cvtColor(cv2.imread(out_image_path), cv2.COLOR_BGR2RGB)
288
-
289
- return out_image_path, out_image_orig, out_image_cv2
290
-
291
- ###
292
- @st.experimental_memo(show_spinner=False)
293
- def easyocr_detect(_in_reader, in_image_path, in_params):
294
- """Detection with EasyOCR
295
-
296
- Args:
297
- _in_reader (EasyOCR reader) : the previously initialized instance
298
- in_image_path (string ) : locally saved image path
299
- in_params (list) : list with the parameters for detection
300
-
301
- Returns:
302
- list : list of the boxes coordinates
303
- exception on error, string 'OK' otherwise
304
- """
305
- try:
306
- dict_param = in_params[1]
307
- detection_result = _in_reader.detect(in_image_path,
308
- #width_ths=0.7,
309
- #mag_ratio=1.5
310
- **dict_param
311
- )
312
- easyocr_coordinates = detection_result[0][0]
313
-
314
- # The format of the coordinate is as follows: [x_min, x_max, y_min, y_max]
315
- # Format boxes coordinates for draw
316
- out_easyocr_boxes_coordinates = list(map(easyocr_coord_convert, easyocr_coordinates))
317
- out_status = 'OK'
318
- except Exception as e:
319
- out_easyocr_boxes_coordinates = []
320
- out_status = e
321
-
322
- return out_easyocr_boxes_coordinates, out_status
323
-
324
- ###
325
- @st.experimental_memo(show_spinner=False)
326
- def ppocr_detect(_in_reader, in_image_path):
327
- """Detection with PPOCR
328
-
329
- Args:
330
- _in_reader (PPOCR reader) : the previously initialized instance
331
- in_image_path (string ) : locally saved image path
332
-
333
- Returns:
334
- list : list of the boxes coordinates
335
- exception on error, string 'OK' otherwise
336
- """
337
- # PPOCR detection method
338
- try:
339
- out_ppocr_boxes_coordinates = _in_reader.ocr(in_image_path, rec=False)
340
- out_status = 'OK'
341
- except Exception as e:
342
- out_ppocr_boxes_coordinates = []
343
- out_status = e
344
-
345
- return out_ppocr_boxes_coordinates, out_status
346
-
347
- ###
348
- @st.experimental_memo(show_spinner=False)
349
- def mmocr_detect(_in_reader, in_image_path):
350
- """Detection with MMOCR
351
-
352
- Args:
353
- _in_reader (EasyORC reader) : the previously initialized instance
354
- in_image_path (string) : locally saved image path
355
- in_params (list) : list with the parameters
356
-
357
- Returns:
358
- list : list of the boxes coordinates
359
- exception on error, string 'OK' otherwise
360
- """
361
- # MMOCR detection method
362
- out_mmocr_boxes_coordinates = []
363
- try:
364
- det_result = _in_reader.readtext(in_image_path, details=True)
365
- bboxes_list = [res['boundary_result'] for res in det_result]
366
- for bboxes in bboxes_list:
367
- for bbox in bboxes:
368
- if len(bbox) > 9:
369
- min_x = min(bbox[0:-1:2])
370
- min_y = min(bbox[1:-1:2])
371
- max_x = max(bbox[0:-1:2])
372
- max_y = max(bbox[1:-1:2])
373
- #box = [min_x, min_y, max_x, min_y, max_x, max_y, min_x, max_y]
374
- else:
375
- min_x = min(bbox[0:-1:2])
376
- min_y = min(bbox[1::2])
377
- max_x = max(bbox[0:-1:2])
378
- max_y = max(bbox[1::2])
379
- box4 = [ [min_x, min_y], [max_x, min_y], [max_x, max_y], [min_x, max_y] ]
380
- out_mmocr_boxes_coordinates.append(box4)
381
- out_status = 'OK'
382
- except Exception as e:
383
- out_status = e
384
-
385
- return out_mmocr_boxes_coordinates, out_status
386
-
387
- ###
388
- def cropped_1box(in_box, in_img):
389
- """Construction of an cropped image corresponding to an area of the initial image
390
-
391
- Args:
392
- in_box (list) : box with coordinates
393
- in_img (matrix) : image
394
-
395
- Returns:
396
- matrix : cropped image
397
- """
398
- box_ar = np.array(in_box).astype(np.int64)
399
- x_min = box_ar[:, 0].min()
400
- x_max = box_ar[:, 0].max()
401
- y_min = box_ar[:, 1].min()
402
- y_max = box_ar[:, 1].max()
403
- out_cropped = in_img[y_min:y_max, x_min:x_max]
404
-
405
- return out_cropped
406
-
407
- ###
408
- @st.experimental_memo(show_spinner=False)
409
- def tesserocr_detect(in_image_path, _in_img, in_params):
410
- """Detection with Tesseract
411
-
412
- Args:
413
- in_image_path (string) : locally saved image path
414
- _in_img (PIL.Image) : image to consider
415
- in_params (list) : list with the parameters for detection
416
-
417
- Returns:
418
- list : list of the boxes coordinates
419
- exception on error, string 'OK' otherwise
420
- """
421
- try:
422
- dict_param = in_params[1]
423
- df_res = pytesseract.image_to_data(_in_img, **dict_param, output_type=Output.DATAFRAME)
424
-
425
- df_res['box'] = df_res.apply(lambda d: [[d['left'], d['top']], \
426
- [d['left'] + d['width'], d['top']], \
427
- [d['left'] + d['width'], d['top'] + d['height']], \
428
- [d['left'], d['top'] + d['height']], \
429
- ], axis=1)
430
- out_tesserocr_boxes_coordinates = df_res[df_res.word_num > 0]['box'].to_list()
431
- out_status = 'OK'
432
- except Exception as e:
433
- out_tesserocr_boxes_coordinates = []
434
- out_status = e
435
-
436
- return out_tesserocr_boxes_coordinates, out_status
437
-
438
- ###
439
- @st.experimental_memo(show_spinner=False)
440
- def process_detect(in_image_path, _in_list_images, _in_list_readers, in_list_params, in_color):
441
- """Detection process for each OCR solution
442
-
443
- Args:
444
- in_image_path (string) : locally saved image path
445
- _in_list_images (list) : list of original image
446
- _in_list_readers (list) : list with previously initialized reader's instances
447
- in_list_params (list) : list with dict parameters for each OCR solution
448
- in_color (tuple) : color for boxes around text
449
-
450
- Returns:
451
- list: list of detection results images
452
- list: list of boxes coordinates
453
- """
454
- ## ------- EasyOCR Text detection
455
- # with st.spinner('EasyOCR Text detection in progress ...'):
456
- # easyocr_boxes_coordinates,easyocr_status = easyocr_detect(_in_list_readers[0], \
457
- # in_image_path, in_list_params[0])
458
- # # Visualization
459
- # if easyocr_boxes_coordinates:
460
- # easyocr_image_detect = draw_detected(_in_list_images[0], easyocr_boxes_coordinates, \
461
- # in_color, 'None', 3)
462
- # else:
463
- # easyocr_boxes_coordinates = easyocr_status
464
- ##
465
-
466
- ## ------- PPOCR Text detection
467
- # with st.spinner('PPOCR Text detection in progress ...'):
468
- # ppocr_boxes_coordinates, ppocr_status = ppocr_detect(_in_list_readers[1], in_image_path)
469
- # # Visualization
470
- # if ppocr_boxes_coordinates:
471
- # ppocr_image_detect = draw_detected(_in_list_images[0], ppocr_boxes_coordinates, \
472
- # in_color, 'None', 3)
473
- # else:
474
- # ppocr_image_detect = ppocr_status
475
- ##
476
-
477
- ## ------- MMOCR Text detection
478
- with st.spinner('Text detection in progress ...'):
479
- mmocr_boxes_coordinates, mmocr_status = mmocr_detect(_in_list_readers[0], in_image_path)
480
- # Visualization
481
- if mmocr_boxes_coordinates:
482
- mmocr_image_detect = draw_detected(_in_list_images[0], mmocr_boxes_coordinates, \
483
- in_color, 'None', 3)
484
- else:
485
- mmocr_image_detect = mmocr_status
486
- ##
487
-
488
- ## ------- Tesseract Text detection
489
- # with st.spinner('Tesseract Text detection in progress ...'):
490
- # tesserocr_boxes_coordinates, tesserocr_status = tesserocr_detect(in_image_path, \
491
- # _in_list_images[0], \
492
- # in_list_params[3])
493
- # # Visualization
494
- # if tesserocr_status == 'OK':
495
- # tesserocr_image_detect = draw_detected(_in_list_images[0],tesserocr_boxes_coordinates,\
496
- # in_color, 'None', 3)
497
- # else:
498
- # tesserocr_image_detect = tesserocr_status
499
- ##
500
- #
501
- out_list_images = _in_list_images + [ mmocr_image_detect]
502
- out_list_coordinates = [mmocr_boxes_coordinates]
503
- # out_list_images = _in_list_images + [easyocr_image_detect, ppocr_image_detect, \
504
- # mmocr_image_detect, tesserocr_image_detect]
505
- # out_list_coordinates = [easyocr_boxes_coordinates, ppocr_boxes_coordinates, \
506
- # mmocr_boxes_coordinates, tesserocr_boxes_coordinates]
507
- #
508
-
509
- return out_list_images, out_list_coordinates
510
-
511
- ###
512
- def draw_detected(in_image, in_boxes_coordinates, in_color, posit='None', in_thickness=4):
513
- """Draw boxes around detected text
514
-
515
- Args:
516
- in_image (PIL.Image) : original image
517
- in_boxes_coordinates (list) : boxes coordinates, from top to bottom and from left to right
518
- [ [ [x_min, y_min], [x_max, y_min], [x_max, y_max], [x_min, y_max] ],
519
- [ ... ]
520
- ]
521
- in_color (tuple) : color for boxes around text
522
- posit (str, optional) : position for text. Defaults to 'None'.
523
- in_thickness (int, optional): thickness of the box. Defaults to 4.
524
-
525
- Returns:
526
- PIL.Image : original image with detected areas
527
- """
528
- work_img = in_image.copy()
529
- if in_boxes_coordinates:
530
- font = cv2.FONT_HERSHEY_SIMPLEX
531
- for ind_box, box in enumerate(in_boxes_coordinates):
532
- box = np.reshape(np.array(box), [-1, 1, 2]).astype(np.int64)
533
- work_img = cv2.polylines(np.array(work_img), [box], True, in_color, in_thickness)
534
- if posit != 'None':
535
- if posit == 'top_left':
536
- pos = tuple(box[0][0])
537
- elif posit == 'top_right':
538
- pos = tuple(box[1][0])
539
- work_img = cv2.putText(work_img, str(ind_box+1), pos, font, 5.5, color, \
540
- in_thickness,cv2.LINE_AA)
541
-
542
- out_image_drawn = Image.fromarray(work_img)
543
- else:
544
- out_image_drawn = work_img
545
-
546
- return out_image_drawn
547
-
548
- ###
549
- @st.experimental_memo(show_spinner=False)
550
- def get_cropped(in_boxes_coordinates, in_image_cv):
551
- """Construct list of cropped images corresponding of the input boxes coordinates list
552
-
553
- Args:
554
- in_boxes_coordinates (list) : list of boxes coordinates
555
- in_image_cv (matrix) : original image
556
-
557
- Returns:
558
- list : list with cropped images
559
- """
560
- out_list_images = []
561
- for box in in_boxes_coordinates:
562
- cropped = cropped_1box(box, in_image_cv)
563
- out_list_images.append(cropped)
564
- return out_list_images
565
-
566
- ###
567
- def process_recog(in_list_readers, in_image_cv, in_boxes_coordinates, in_list_dict_params):
568
- """Recognition process for each OCR solution
569
-
570
- Args:
571
- in_list_readers (list) : list with previously initialized reader's instances
572
- in_image_cv (matrix) : original image
573
- in_boxes_coordinates (list) : list of boxes coordinates
574
- in_list_dict_params (list) : list with dict parameters for each OCR solution
575
-
576
- Returns:
577
- data frame : results for each OCR solution, except Tesseract
578
- data frame : results for Tesseract
579
- list : status for each recognition (exception or 'OK')
580
- """
581
- out_df_results = pd.DataFrame([])
582
-
583
- list_text_easyocr = []
584
- list_confidence_easyocr = []
585
- list_text_ppocr = []
586
- list_confidence_ppocr = []
587
- list_text_mmocr = []
588
- list_confidence_mmocr = []
589
-
590
- # Create cropped images from detection
591
- list_cropped_images = get_cropped(in_boxes_coordinates, in_image_cv)
592
-
593
- # Recognize with EasyOCR
594
- # with st.spinner('EasyOCR Text recognition in progress ...'):
595
- # list_text_easyocr, list_confidence_easyocr, status_easyocr = \
596
- # easyocr_recog(list_cropped_images, in_list_readers[0], in_list_dict_params[0])
597
- ##
598
-
599
- # Recognize with PPOCR
600
- # with st.spinner('PPOCR Text recognition in progress ...'):
601
- # list_text_ppocr, list_confidence_ppocr, status_ppocr = \
602
- # ppocr_recog(list_cropped_images, in_list_dict_params[1])
603
- ##
604
-
605
- # Recognize with MMOCR
606
- with st.spinner('Text recognition in progress ...'):
607
- list_text_mmocr, list_confidence_mmocr, status_mmocr = \
608
- mmocr_recog(list_cropped_images, in_list_dict_params[0])
609
- ##
610
-
611
- # # Recognize with Tesseract
612
- # with st.spinner('Tesseract Text recognition in progress ...'):
613
- # out_df_results_tesseract, status_tesseract = \
614
- # tesserocr_recog(in_image_cv, in_list_dict_params[3], len(list_cropped_images))
615
- ##
616
-
617
- # Create results data frame
618
- out_df_results = pd.DataFrame({'cropped_image': list_cropped_images,
619
- 'text_mmocr': list_text_mmocr,
620
- 'confidence_mmocr': list_confidence_mmocr
621
- }
622
- )
623
-
624
- out_list_reco_status = [status_mmocr]
625
-
626
- return out_df_results, out_list_reco_status
627
-
628
- ###
629
- @st.experimental_memo(suppress_st_warning=True, show_spinner=False)
630
- def easyocr_recog(in_list_images, _in_reader_easyocr, in_params):
631
- """Recognition with EasyOCR
632
-
633
- Args:
634
- in_list_images (list) : list of cropped images
635
- _in_reader_easyocr (EasyOCR reader) : the previously initialized instance
636
- in_params (dict) : parameters for recognition
637
-
638
- Returns:
639
- list : list of recognized text
640
- list : list of recognition confidence
641
- string/Exception : recognition status
642
- """
643
- progress_bar = st.progress(0)
644
- out_list_text_easyocr = []
645
- out_list_confidence_easyocr = []
646
- ## ------- EasyOCR Text recognition
647
- try:
648
- step = 0*len(in_list_images) # first recognition process
649
- nb_steps = 4 * len(in_list_images)
650
- for ind_img, cropped in enumerate(in_list_images):
651
- result = _in_reader_easyocr.recognize(cropped, **in_params)
652
- try:
653
- out_list_text_easyocr.append(result[0][1])
654
- out_list_confidence_easyocr.append(np.round(100*result[0][2], 1))
655
- except:
656
- out_list_text_easyocr.append('Not recognize')
657
- out_list_confidence_easyocr.append(100.)
658
- progress_bar.progress((step+ind_img+1)/nb_steps)
659
- out_status = 'OK'
660
- except Exception as e:
661
- out_status = e
662
- progress_bar.empty()
663
-
664
- return out_list_text_easyocr, out_list_confidence_easyocr, out_status
665
-
666
- ###
667
- @st.experimental_memo(suppress_st_warning=True, show_spinner=False)
668
- def ppocr_recog(in_list_images, in_params):
669
- """Recognition with PPOCR
670
-
671
- Args:
672
- in_list_images (list) : list of cropped images
673
- in_params (dict) : parameters for recognition
674
-
675
- Returns:
676
- list : list of recognized text
677
- list : list of recognition confidence
678
- string/Exception : recognition status
679
- """
680
- ## ------- PPOCR Text recognition
681
- out_list_text_ppocr = []
682
- out_list_confidence_ppocr = []
683
- try:
684
- reader_ppocr = PaddleOCR(**in_params)
685
- step = 1*len(in_list_images) # second recognition process
686
- nb_steps = 4 * len(in_list_images)
687
- progress_bar = st.progress(step/nb_steps)
688
-
689
- for ind_img, cropped in enumerate(in_list_images):
690
- result = reader_ppocr.ocr(cropped, det=False, cls=False)
691
- try:
692
- out_list_text_ppocr.append(result[0][0])
693
- out_list_confidence_ppocr.append(np.round(100*result[0][1], 1))
694
- except:
695
- out_list_text_ppocr.append('Not recognize')
696
- out_list_confidence_ppocr.append(100.)
697
- progress_bar.progress((step+ind_img+1)/nb_steps)
698
- out_status = 'OK'
699
- except Exception as e:
700
- out_status = e
701
- progress_bar.empty()
702
-
703
- return out_list_text_ppocr, out_list_confidence_ppocr, out_status
704
-
705
- ###
706
- @st.experimental_memo(suppress_st_warning=True, show_spinner=False)
707
- def mmocr_recog(in_list_images, in_params):
708
- """Recognition with MMOCR
709
-
710
- Args:
711
- in_list_images (list) : list of cropped images
712
- in_params (dict) : parameters for recognition
713
-
714
- Returns:
715
- list : list of recognized text
716
- list : list of recognition confidence
717
- string/Exception : recognition status
718
- """
719
- ## ------- MMOCR Text recognition
720
- out_list_text_mmocr = []
721
- out_list_confidence_mmocr = []
722
- try:
723
- reader_mmocr = MMOCR(det=None, **in_params)
724
- step = 2*len(in_list_images) # third recognition process
725
- nb_steps = 4 * len(in_list_images)
726
- progress_bar = st.progress(step/nb_steps)
727
-
728
- for ind_img, cropped in enumerate(in_list_images):
729
- result = reader_mmocr.readtext(cropped, details=True)
730
- try:
731
- out_list_text_mmocr.append(result[0]['text'])
732
- out_list_confidence_mmocr.append(np.round(100* \
733
- (np.array(result[0]['score']).mean()), 1))
734
- except:
735
- out_list_text_mmocr.append('Not recognize')
736
- out_list_confidence_mmocr.append(100.)
737
- progress_bar.progress((step+ind_img+1)/nb_steps)
738
- out_status = 'OK'
739
- except Exception as e:
740
- out_status = e
741
- progress_bar.empty()
742
-
743
- return out_list_text_mmocr, out_list_confidence_mmocr, out_status
744
-
745
- ###
746
- @st.experimental_memo(suppress_st_warning=True, show_spinner=False)
747
- def tesserocr_recog(in_img, in_params, in_nb_images):
748
- """Recognition with Tesseract
749
-
750
- Args:
751
- in_image_cv (matrix) : original image
752
- in_params (dict) : parameters for recognition
753
- in_nb_images : nb cropped images (used for progress bar)
754
-
755
- Returns:
756
- Pandas data frame : recognition results
757
- string/Exception : recognition status
758
- """
759
- ## ------- Tesseract Text recognition
760
- step = 3*in_nb_images # fourth recognition process
761
- nb_steps = 4 * in_nb_images
762
- progress_bar = st.progress(step/nb_steps)
763
-
764
- try:
765
- out_df_result = pytesseract.image_to_data(in_img, **in_params,output_type=Output.DATAFRAME)
766
-
767
- out_df_result['box'] = out_df_result.apply(lambda d: [[d['left'], d['top']], \
768
- [d['left'] + d['width'], d['top']], \
769
- [d['left']+d['width'], d['top']+d['height']], \
770
- [d['left'], d['top'] + d['height']], \
771
- ], axis=1)
772
- out_df_result['cropped'] = out_df_result['box'].apply(lambda b: cropped_1box(b, in_img))
773
- out_df_result = out_df_result[(out_df_result.word_num > 0) & (out_df_result.text != ' ')] \
774
- .reset_index(drop=True)
775
- out_status = 'OK'
776
- except Exception as e:
777
- out_df_result = pd.DataFrame([])
778
- out_status = e
779
-
780
- progress_bar.progress(1.)
781
-
782
- return out_df_result, out_status
783
-
784
- ###
785
- def draw_reco_images(in_image, in_boxes_coordinates, in_list_texts, in_list_confid, \
786
- in_dict_back_colors, in_reader_type_list, \
787
- in_font_scale=1, in_conf_threshold=65):
788
- """Draw recognized text on original image, for each OCR solution used
789
-
790
- Args:
791
- in_image (matrix) : original image
792
- in_boxes_coordinates (list) : list of boxes coordinates
793
- in_list_texts (list): list of recognized text for each recognizer (except Tesseract)
794
- in_list_confid (list): list of recognition confidence for each recognizer (except Tesseract)
795
- in_df_results_tesseract (Pandas data frame): Tesseract recognition results
796
- in_font_scale (int, optional): text font scale. Defaults to 3.
797
-
798
- Returns:
799
- shows the results container
800
- """
801
- img = in_image.copy()
802
- nb_readers = 1
803
- # list_reco_images = img.copy()
804
-
805
- for num, box_ in enumerate(in_boxes_coordinates):
806
- box = np.array(box_).astype(np.int64)
807
-
808
- # For each box : draw the results of each recognizer
809
-
810
- confid = np.round(in_list_confid[0][num], 0)
811
- rgb_color = ImageColor.getcolor(in_dict_back_colors[confid], "RGB")
812
- if confid < in_conf_threshold:
813
- text_color = (0, 0, 0)
814
- else:
815
- text_color = (255, 255, 255)
816
-
817
- list_reco_images = cv2.rectangle(img, \
818
- (box[0][0], box[0][1]), \
819
- (box[2][0], box[2][1]), rgb_color, -1)
820
- list_reco_images = cv2.putText(img, \
821
- in_list_texts[0][num], \
822
- (box[0][0],int(np.round((box[0][1]+box[2][1])/2,0))), \
823
- cv2.FONT_HERSHEY_DUPLEX, in_font_scale, text_color, 2)
824
-
825
- # # Add Tesseract process
826
- # if not in_df_results_tesseract.empty:
827
- # ind_tessocr = nb_readers-1
828
- # for num, box_ in enumerate(in_df_results_tesseract['box'].to_list()):
829
- # box = np.array(box_).astype(np.int64)
830
- # confid = np.round(in_df_results_tesseract.iloc[num]['conf'], 0)
831
- # rgb_color = ImageColor.getcolor(in_dict_back_colors[confid], "RGB")
832
- # if confid < in_conf_threshold:
833
- # text_color = (0, 0, 0)
834
- # else:
835
- # text_color = (255, 255, 255)
836
-
837
- # list_reco_images[ind_tessocr] = \
838
- # cv2.rectangle(list_reco_images[ind_tessocr], (box[0][0], box[0][1]), \
839
- # (box[2][0], box[2][1]), rgb_color, -1)
840
- # try:
841
- # list_reco_images[ind_tessocr] = \
842
- # cv2.putText(list_reco_images[ind_tessocr], \
843
- # in_df_results_tesseract.iloc[num]['text'], \
844
- # (box[0][0],int(np.round((box[0][1]+box[2][1])/2,0))), \
845
- # cv2.FONT_HERSHEY_DUPLEX, in_font_scale, text_color, 2)
846
-
847
- # except:
848
-
849
- # pass
850
- with show_reco.container():
851
- # column_width = 400
852
-
853
- cols = st.columns((1,1))
854
- cols[0].image(list_reco_images,use_column_width=True)
855
- # with show_reco.container():
856
- # # Draw the results, 2 images per line
857
- # reco_lines = math.ceil(len(in_reader_type_list) / 2)
858
- # column_width = 400
859
- # for ind_lig in range(0, reco_lines+1, 2):
860
- # cols = st.columns(2)
861
- # for ind_col in range(2):
862
- # ind = ind_lig + ind_col
863
- # if ind <= len(in_reader_type_list):
864
- # if in_reader_type_list[ind] == 'Tesseract':
865
- # column_title = '<p style="font-size: 20px;color:rgb(0,0,0); \
866
- # ">Recognition with ' + in_reader_type_list[ind] + \
867
- # '<sp style="font-size: 17px"> (with its own detector) \
868
- # </sp></p>'
869
- # else:
870
- # column_title = '<p style="font-size: 20px;color:rgb(0,0,0); \
871
- # ">Recognition with ' + \
872
- # in_reader_type_list[ind]+ '</p>'
873
- # cols[ind_col].markdown(column_title, unsafe_allow_html=True)
874
- # if st.session_state.list_reco_status[ind] == 'OK':
875
- # cols[ind_col].image(list_reco_images[ind], \
876
- # width=column_width, use_column_width=True)
877
- # else:
878
- # cols[ind_col].write(list_reco_status[ind], \
879
- # use_column_width=True)
880
-
881
- # st.markdown(' 💡 Bad font size? you can adjust it below and refresh:')
882
-
883
- ###
884
- def highlight():
885
- """ Highlight MMOCR results """
886
- with show_detect.container():
887
- column_title = '<p style="font-size: 20px;color: rgb(228,26,28);">Detection with MMOCR</p>'
888
- show_detect.markdown(column_title, unsafe_allow_html=True)
889
- if isinstance(list_images[2], PIL.Image.Image):
890
- show_detect.image(list_images[2], width=400, use_column_width=True)
891
- else:
892
- show_detect.write(list_images[2], use_column_width=True)
893
-
894
-
895
- ###
896
- @st.cache(show_spinner=False)
897
- def get_demo():
898
- """Get the demo files
899
-
900
- Returns:
901
- PIL.Image : input file opened with Pillow
902
- PIL.Image : input file opened with Pillow
903
- """
904
-
905
- out_img_demo_1 = Image.open("img_demo_1.jpg")
906
- out_img_demo_2 = Image.open("img_demo_2.jpg")
907
-
908
- return out_img_demo_1, out_img_demo_2
909
-
910
- ###
911
- def raz():
912
- st.session_state.list_coordinates = []
913
- st.session_state.list_images = []
914
- st.session_state.detect_reader = reader_type_list[0]
915
-
916
- st.session_state.columns_size = [2] + [1 for x in reader_type_list[1:]]
917
- st.session_state.column_width = [400] + [300 for x in reader_type_list[1:]]
918
- st.session_state.columns_color = ["rgb(228,26,28)"] + \
919
- ["rgb(0,0,0)" for x in reader_type_list[1:]]
920
-
921
- # Clear caches
922
- easyocr_detect.clear()
923
- ppocr_detect.clear()
924
- mmocr_detect.clear()
925
- tesserocr_detect.clear()
926
- process_detect.clear()
927
- get_cropped.clear()
928
- easyocr_recog.clear()
929
- ppocr_recog.clear()
930
- mmocr_recog.clear()
931
- tesserocr_recog.clear()
932
-
933
-
934
- ##----------- Initializations ---------------------------------------------------------------------
935
- #print("PID : ", os.getpid())
936
-
937
- st.title("Scene text detection DEMO apps")
938
- #st.markdown("#### PID : " + str(os.getpid()))
939
-
940
- # Initializations
941
- with st.spinner("Initializations in progress ..."):
942
- reader_type_list, reader_type_dict, list_dict_lang, \
943
- cols_size, dict_back_colors, fig_colorscale = initializations()
944
- img_demo_1, img_demo_2 = get_demo()
945
-
946
- ##----------- Choose language & image -------------------------------------------------------------
947
- st.markdown("#### Choose languages:")
948
- lang_col = st.columns((1,3)) # 1/4 of the space for the dropdown, 3/4 for the rest of the content
949
- mmocr_key_lang = lang_col[0].selectbox("", list_dict_lang[0].keys(), 0)
950
- mmocr_lang = list_dict_lang[0][mmocr_key_lang]
951
-
952
-
953
- st.markdown("#### Choose picture:")
954
- cols_pict = st.columns([1, 2])
955
- img_typ = cols_pict[0].radio("", ['Upload file', 'Take a picture', 'Use a demo file'], \
956
- index=0, on_change=raz)
957
-
958
- if img_typ == 'Upload file':
959
- image_file = cols_pict[1].file_uploader("Upload a file:", type=["jpg","jpeg"], on_change=raz)
960
- if img_typ == 'Take a picture':
961
- image_file = cols_pict[1].camera_input("Take a picture:", on_change=raz)
962
- if img_typ == 'Use a demo file':
963
- with st.expander('Choose a demo file:', expanded=True):
964
- demo_used = st.radio('', ['File 1', 'File 2'], index=0, \
965
- horizontal=True, on_change=raz)
966
- cols_demo = st.columns([1, 2])
967
- cols_demo[0].markdown('###### File 1')
968
- cols_demo[0].image(img_demo_1, width=150)
969
- cols_demo[1].markdown('###### File 2')
970
- cols_demo[1].image(img_demo_2, width=300)
971
- if demo_used == 'File 1':
972
- image_file = 'img_demo_1.jpg'
973
- else:
974
- image_file = 'img_demo_2.jpg'
975
-
976
- ##----------- Process input image -----------------------------------------------------------------
977
- if image_file is not None:
978
- image_path, image_orig, image_cv2 = load_image(image_file)
979
- list_images = [image_orig, image_cv2]
980
-
981
- ##----------- Form with original image & hyperparameters for detectors ----------------------------
982
- with st.form("form1"):
983
- col1, col2 = st.columns(2, ) #gap="medium")
984
- col1.markdown("##### Original image")
985
- col1.image(list_images[0], width=400)
986
- col2.markdown("##### Hyperparameters values for detection")
987
-
988
- # with col2.expander("Choose detection hyperparameters for " + reader_type_list[0], \
989
- # expanded=False):
990
- # t0_min_size = st.slider("min_size", 1, 20, 10, step=1, \
991
- # help="min_size (int, default = 10) - Filter text box smaller than \
992
- # minimum value in pixel")
993
- # t0_text_threshold = st.slider("text_threshold", 0.1, 1., 0.7, step=0.1, \
994
- # help="text_threshold (float, default = 0.7) - Text confidence threshold")
995
- # t0_low_text = st.slider("low_text", 0.1, 1., 0.4, step=0.1, \
996
- # help="low_text (float, default = 0.4) - Text low-bound score")
997
- # t0_link_threshold = st.slider("link_threshold", 0.1, 1., 0.4, step=0.1, \
998
- # help="link_threshold (float, default = 0.4) - Link confidence threshold")
999
- # t0_canvas_size = st.slider("canvas_size", 2000, 5000, 2560, step=10, \
1000
- # help='''canvas_size (int, default = 2560) \n
1001
- # Maximum e size. Image bigger than this value will be resized down''')
1002
- # t0_mag_ratio = st.slider("mag_ratio", 0.1, 5., 1., step=0.1, \
1003
- # help="mag_ratio (float, default = 1) - Image magnification ratio")
1004
- # t0_slope_ths = st.slider("slope_ths", 0.01, 1., 0.1, step=0.01, \
1005
- # help='''slope_ths (float, default = 0.1) - Maximum slope \
1006
- # (delta y/delta x) to considered merging. \n
1007
- # Low valuans tiled boxes will not be merged.''')
1008
- # t0_ycenter_ths = st.slider("ycenter_ths", 0.1, 1., 0.5, step=0.1, \
1009
- # help='''ycenter_ths (float, default = 0.5) - Maximum shift in y direction. \n
1010
- # Boxes wiifferent level should not be merged.''')
1011
- # t0_height_ths = st.slider("height_ths", 0.1, 1., 0.5, step=0.1, \
1012
- # help='''height_ths (float, default = 0.5) - Maximum different in box height. \n
1013
- # Boxes wiery different text size should not be merged.''')
1014
- # t0_width_ths = st.slider("width_ths", 0.1, 1., 0.5, step=0.1, \
1015
- # help="width_ths (float, default = 0.5) - Maximum horizontal \
1016
- # distance to merge boxes.")
1017
- # t0_add_margin = st.slider("add_margin", 0.1, 1., 0.1, step=0.1, \
1018
- # help='''add_margin (float, default = 0.1) - \
1019
- # Extend bounding boxes in all direction by certain value. \n
1020
- # This is rtant for language with complex script (E.g. Thai).''')
1021
- # t0_optimal_num_chars = st.slider("optimal_num_chars", None, 100, None, step=10, \
1022
- # help="optimal_num_chars (int, default = None) - If specified, bounding boxes \
1023
- # with estimated number of characters near this value are returned first.")
1024
-
1025
- # with col2.expander("Choose detection hyperparameters for " + reader_type_list[1], \
1026
- # expanded=False):
1027
- # t1_det_algorithm = st.selectbox('det_algorithm', ['DB'], \
1028
- # help='Type of detection algorithm selected. (default = DB)')
1029
- # t1_det_max_side_len = st.slider('det_max_side_len', 500, 2000, 960, step=10, \
1030
- # help='''The maximum size of the long side of the image. (default = 960)\n
1031
- # Limit thximum image height and width.\n
1032
- # When theg side exceeds this value, the long side will be resized to this size, and the short side \
1033
- # will be ed proportionally.''')
1034
- # t1_det_db_thresh = st.slider('det_db_thresh', 0.1, 1., 0.3, step=0.1, \
1035
- # help='''Binarization threshold value of DB output map. (default = 0.3) \n
1036
- # Used to er the binarized image of DB prediction, setting 0.-0.3 has no obvious effect on the result.''')
1037
- # t1_det_db_box_thresh = st.slider('det_db_box_thresh', 0.1, 1., 0.6, step=0.1, \
1038
- # help='''The threshold value of the DB output box. (default = 0.6) \n
1039
- # DB post-essing filter box threshold, if there is a missing box detected, it can be reduced as appropriate. \n
1040
- # Boxes sclower than this value will be discard.''')
1041
- # t1_det_db_unclip_ratio = st.slider('det_db_unclip_ratio', 1., 3.0, 1.6, step=0.1, \
1042
- # help='''The expanded ratio of DB output box. (default = 1.6) \n
1043
- # Indicatee compactness of the text box, the smaller the value, the closer the text box to the text.''')
1044
- # t1_det_east_score_thresh = st.slider('det_east_cover_thresh', 0.1, 1., 0.8, step=0.1, \
1045
- # help="Binarization threshold value of EAST output map. (default = 0.8)")
1046
- # t1_det_east_cover_thresh = st.slider('det_east_cover_thresh', 0.1, 1., 0.1, step=0.1, \
1047
- # help='''The threshold value of the EAST output box. (default = 0.1) \n
1048
- # Boxes sclower than this value will be discarded.''')
1049
- # t1_det_east_nms_thresh = st.slider('det_east_nms_thresh', 0.1, 1., 0.2, step=0.1, \
1050
- # help="The NMS threshold value of EAST model output box. (default = 0.2)")
1051
- # t1_det_db_score_mode = st.selectbox('det_db_score_mode', ['fast', 'slow'], \
1052
- # help='''slow: use polygon box to calculate bbox score, fast: use rectangle box \
1053
- # to calculate. (default = fast) \n
1054
- # Use rectlar box to calculate faster, and polygonal box more accurate for curved text area.''')
1055
-
1056
- with col2.expander("Choose detection hyperparameters for detection model" ,expanded=False):
1057
- t2_det = 'DBPP_r50'
1058
- st.write("###### *More about text detection models* 👉 \
1059
- [here](https://mmocr.readthedocs.io/en/latest/textdet_models.html)")
1060
- t2_merge_xdist = st.slider('merge_xdist', 1, 50, 20, step=1, \
1061
- help='The maximum x-axis distance to merge boxes. (defaut=20)')
1062
-
1063
- # with col2.expander("Choose detection hyperparameters for " + reader_type_list[3], \
1064
- # expanded=False):
1065
- # t3_psm = st.selectbox('Page segmentation mode (psm)', \
1066
- # [' - Default', \
1067
- # ' 4 Assume a single column of text of variable sizes', \
1068
- # ' 5 Assume a single uniform block of vertically aligned text', \
1069
- # ' 6 Assume a single uniform block of text', \
1070
- # ' 7 Treat the image as a single text line', \
1071
- # ' 8 Treat the image as a single word', \
1072
- # ' 9 Treat the image as a single word in a circle', \
1073
- # '10 Treat the image as a single character', \
1074
- # '11 Sparse text. Find as much text as possible in no \
1075
- # particular order', \
1076
- # '13 Raw line. Treat the image as a single text line, \
1077
- # bypassing hacks that are Tesseract-specific'])
1078
- # t3_oem = st.selectbox('OCR engine mode', ['0 Legacy engine only', \
1079
- # '1 Neural nets LSTM engine only', \
1080
- # '2 Legacy + LSTM engines', \
1081
- # '3 Default, based on what is available'], 3)
1082
- # t3_whitelist = st.text_input('Limit tesseract to recognize only this characters :', \
1083
- # placeholder='Limit tesseract to recognize only this characters', \
1084
- # help='Example for numbers only : 0123456789')
1085
-
1086
- color_hex = col2.color_picker('Set a color for box outlines:', '#004C99')
1087
- color_part = color_hex.lstrip('#')
1088
- color = tuple(int(color_part[i:i+2], 16) for i in (0, 2, 4))
1089
-
1090
- submit_detect = st.form_submit_button("Launch detection")
1091
-
1092
- ##----------- Process text detection --------------------------------------------------------------
1093
- if submit_detect:
1094
- # Process text detection
1095
-
1096
- # if t0_optimal_num_chars == 0:
1097
- # t0_optimal_num_chars = None
1098
-
1099
- # Construct the config Tesseract parameter
1100
- # t3_config = ''
1101
- # psm = t3_psm[:2]
1102
- # if psm != ' -':
1103
- # t3_config += '--psm ' + psm.strip()
1104
- # oem = t3_oem[:1]
1105
- # if oem != '3':
1106
- # t3_config += ' --oem ' + oem
1107
- # if t3_whitelist != '':
1108
- # t3_config += ' -c tessedit_char_whitelist=' + t3_whitelist
1109
-
1110
- list_params_det = [[mmocr_lang, {'det': t2_det, 'merge_xdist': t2_merge_xdist}]]
1111
- # [[easyocr_lang, \
1112
- # {'min_size': t0_min_size, 'text_threshold': t0_text_threshold, \
1113
- # 'low_text': t0_low_text, 'link_threshold': t0_link_threshold, \
1114
- # 'canvas_size': t0_canvas_size, 'mag_ratio': t0_mag_ratio, \
1115
- # 'slope_ths': t0_slope_ths, 'ycenter_ths': t0_ycenter_ths, \
1116
- # 'height_ths': t0_height_ths, 'width_ths': t0_width_ths, \
1117
- # 'add_margin': t0_add_margin, 'optimal_num_chars': t0_optimal_num_chars \
1118
- # }], \
1119
- # [ppocr_lang, \
1120
- # {'det_algorithm': t1_det_algorithm, 'det_max_side_len': t1_det_max_side_len, \
1121
- # 'det_db_thresh': t1_det_db_thresh, 'det_db_box_thresh': t1_det_db_box_thresh, \
1122
- # 'det_db_unclip_ratio': t1_det_db_unclip_ratio, \
1123
- # 'det_east_score_thresh': t1_det_east_score_thresh, \
1124
- # 'det_east_cover_thresh': t1_det_east_cover_thresh, \
1125
- # 'det_east_nms_thresh': t1_det_east_nms_thresh, \
1126
- # 'det_db_score_mode': t1_det_db_score_mode}],
1127
- # [tesserocr_lang, {'lang': tesserocr_lang, 'config': t3_config}]
1128
- # ]
1129
-
1130
- show_info1 = st.empty()
1131
- show_info1.info("Readers initializations in progress (it may take a while) ...")
1132
- list_readers = init_readers(list_params_det)
1133
-
1134
- show_info1.info("Text detection in progress ...")
1135
- list_images, list_coordinates = process_detect(image_path, list_images, list_readers, \
1136
- list_params_det, color)
1137
- show_info1.empty()
1138
-
1139
- # Clear previous recognition results
1140
- st.session_state.df_results = pd.DataFrame([])
1141
-
1142
- st.session_state.list_readers = list_readers
1143
- st.session_state.list_coordinates = list_coordinates
1144
- st.session_state.list_images = list_images
1145
- st.session_state.list_params_det = list_params_det
1146
-
1147
- if 'columns_size' not in st.session_state:
1148
- st.session_state.columns_size = [2] + [1 for x in reader_type_list[1:]]
1149
- if 'column_width' not in st.session_state:
1150
- st.session_state.column_width = [400] + [300 for x in reader_type_list[1:]]
1151
- if 'columns_color' not in st.session_state:
1152
- st.session_state.columns_color = ["rgb(228,26,28)"] + \
1153
- ["rgb(0,0,0)" for x in reader_type_list[1:]]
1154
-
1155
- if st.session_state.list_coordinates:
1156
- list_coordinates = st.session_state.list_coordinates
1157
- list_images = st.session_state.list_images
1158
- list_readers = st.session_state.list_readers
1159
- list_params_det = st.session_state.list_params_det
1160
-
1161
- ##----------- Text detection results --------------------------------------------------------------
1162
- st.subheader("Text detection")
1163
- show_detect = st.empty()
1164
- list_ok_detect = []
1165
- with show_detect.container():
1166
- column_title = '<p style="font-size: 20px;color:' + \
1167
- st.session_state.columns_color[0] + \
1168
- ';">Detection with MMOCR</p>'
1169
- show_detect.markdown(column_title, unsafe_allow_html=True)
1170
- if isinstance(list_images[2], PIL.Image.Image):
1171
- show_detect.image(list_images[2], width=st.session_state.column_width[0], use_column_width=True)
1172
- list_ok_detect.append('MMOCR')
1173
- else:
1174
- show_detect.write(list_images[2], use_column_width=True)
1175
-
1176
-
1177
- st.subheader("Text recognition")
1178
-
1179
- # st.markdown("##### Using detection performed above by:")
1180
- # st.radio('Choose the detecter:', list_ok_detect, key='detect_reader', \
1181
- # horizontal=True, on_change=highlight)
1182
-
1183
- ##----------- Form with hyperparameters for recognition -----------------------
1184
- st.markdown("##### Hyperparameters values for recognition:")
1185
- with st.form("form2"):
1186
- # with st.expander("Choose recognition hyperparameters for " + reader_type_list[0], \
1187
- # expanded=False):
1188
- # t0_decoder = st.selectbox('decoder', ['greedy', 'beamsearch', 'wordbeamsearch'], \
1189
- # help="decoder (string, default = 'greedy') - options are 'greedy', \
1190
- # 'beamsearch' and 'wordbeamsearch.")
1191
- # t0_beamWidth = st.slider('beamWidth', 2, 20, 5, step=1, \
1192
- # help="beamWidth (int, default = 5) - How many beam to keep when decoder = \
1193
- # 'beamsearch' or 'wordbeamsearch'.")
1194
- # t0_batch_size = st.slider('batch_size', 1, 10, 1, step=1, \
1195
- # help="batch_size (int, default = 1) - batch_size>1 will make EasyOCR faster \
1196
- # but use more memory.")
1197
- # t0_workers = st.slider('workers', 0, 10, 0, step=1, \
1198
- # help="workers (int, default = 0) - Number thread used in of dataloader.")
1199
- # t0_allowlist = st.text_input('allowlist', value="", max_chars=None, \
1200
- # placeholder='Force EasyOCR to recognize only this subset of characters', \
1201
- # help='''allowlist (string) - Force EasyOCR to recognize only subset of characters.\n
1202
- # Usefor specific problem (E.g. license plate, etc.)''')
1203
- # t0_blocklist = st.text_input('blocklist', value="", max_chars=None, \
1204
- # placeholder='Block subset of character (will be ignored if allowlist is given)', \
1205
- # help='''blocklist (string) - Block subset of character. This argument will be \
1206
- # ignored if allowlist is given.''')
1207
- # t0_detail = st.radio('detail', [0, 1], 1, horizontal=True, \
1208
- # help="detail (int, default = 1) - Set this to 0 for simple output")
1209
- # t0_paragraph = st.radio('paragraph', [True, False], 1, horizontal=True, \
1210
- # help='paragraph (bool, default = False) - Combine result into paragraph')
1211
- # t0_contrast_ths = st.slider('contrast_ths', 0.05, 1., 0.1, step=0.01, \
1212
- # help='''contrast_ths (float, default = 0.1) - Text box with contrast lower than \
1213
- # this value will be passed into model 2 times.\n
1214
- # Firs with original image and second with contrast adjusted to 'adjust_contrast' value.\n
1215
- # The with more confident level will be returned as a result.''')
1216
- # t0_adjust_contrast = st.slider('adjust_contrast', 0.1, 1., 0.5, step=0.1, \
1217
- # help = 'adjust_contrast (float, default = 0.5) - target contrast level for low \
1218
- # contrast text box')
1219
-
1220
- # with st.expander("Choose recognition hyperparameters for " + reader_type_list[1], \
1221
- # expanded=False):
1222
- # t1_rec_algorithm = st.selectbox('rec_algorithm', ['CRNN', 'SVTR_LCNet'], 0, \
1223
- # help="Type of recognition algorithm selected. (default=CRNN)")
1224
- # t1_rec_batch_num = st.slider('rec_batch_num', 1, 50, step=1, \
1225
- # help="When performing recognition, the batchsize of forward images. \
1226
- # (default=30)")
1227
- # t1_max_text_length = st.slider('max_text_length', 3, 250, 25, step=1, \
1228
- # help="The maximum text length that the recognition algorithm can recognize. \
1229
- # (default=25)")
1230
- # t1_use_space_char = st.radio('use_space_char', [True, False], 0, horizontal=True, \
1231
- # help="Whether to recognize spaces. (default=TRUE)")
1232
- # t1_drop_score = st.slider('drop_score', 0., 1., 0.25, step=.05, \
1233
- # help="Filter the output by score (from the recognition model), and those \
1234
- # below this score will not be returned. (default=0.5)")
1235
-
1236
- with st.expander("Choose recognition hyperparameters for " + reader_type_list[2], \
1237
- expanded=False):
1238
- t2_recog = st.selectbox('recog', ['ABINet','CRNN','CRNN_TPS','MASTER', \
1239
- 'NRTR_1/16-1/8','NRTR_1/8-1/4','RobustScanner','SAR','SAR_CN', \
1240
- 'SATRN','SATRN_sm','SEG','Tesseract'], 7, \
1241
- help='Text recognition algorithm. (default = SAR)')
1242
- st.write("###### *More about text recognition models* 👉 \
1243
- [here](https://mmocr.readthedocs.io/en/latest/textrecog_models.html)")
1244
-
1245
- # with st.expander("Choose recognition hyperparameters for " + reader_type_list[3], \
1246
- # expanded=False):
1247
- # t3r_psm = st.selectbox('Page segmentation mode (psm)', \
1248
- # [' - Default', \
1249
- # ' 4 Assume a single column of text of variable sizes', \
1250
- # ' 5 Assume a single uniform block of vertically aligned \
1251
- # text', \
1252
- # ' 6 Assume a single uniform block of text', \
1253
- # ' 7 Treat the image as a single text line', \
1254
- # ' 8 Treat the image as a single word', \
1255
- # ' 9 Treat the image as a single word in a circle', \
1256
- # '10 Treat the image as a single character', \
1257
- # '11 Sparse text. Find as much text as possible in no \
1258
- # particular order', \
1259
- # '13 Raw line. Treat the image as a single text line, \
1260
- # bypassing hacks that are Tesseract-specific'])
1261
- # t3r_oem = st.selectbox('OCR engine mode', ['0 Legacy engine only', \
1262
- # '1 Neural nets LSTM engine only', \
1263
- # '2 Legacy + LSTM engines', \
1264
- # '3 Default, based on what is available'], 3)
1265
- # t3r_whitelist = st.text_input('Limit tesseract to recognize only this \
1266
- # characters :', \
1267
- # placeholder='Limit tesseract to recognize only this characters', \
1268
- # help='Example for numbers only : 0123456789')
1269
-
1270
- submit_reco = st.form_submit_button("Launch recognition")
1271
-
1272
- if submit_reco:
1273
- process_detect.clear()
1274
- ##----------- Process recognition ------------------------------------------
1275
- reader_ind = reader_type_dict[st.session_state.detect_reader]
1276
- list_boxes = list_coordinates[0]
1277
-
1278
- # # Construct the config Tesseract parameter
1279
- # t3r_config = ''
1280
- # psm = t3r_psm[:2]
1281
- # if psm != ' -':
1282
- # t3r_config += '--psm ' + psm.strip()
1283
- # oem = t3r_oem[:1]
1284
- # if oem != '3':
1285
- # t3r_config += ' --oem ' + oem
1286
- # if t3r_whitelist != '':
1287
- # t3r_config += ' -c tessedit_char_whitelist=' + t3r_whitelist
1288
-
1289
- list_params_rec = \
1290
- [
1291
- {'recog': t2_recog},
1292
- ]
1293
-
1294
- show_info2 = st.empty()
1295
-
1296
- with show_info2.container():
1297
- st.info("Text recognition in progress ...")
1298
- df_results, list_reco_status = \
1299
- process_recog(list_readers, list_images[1], list_boxes, list_params_rec)
1300
- show_info2.empty()
1301
-
1302
- st.session_state.df_results = df_results
1303
- st.session_state.list_boxes = list_boxes
1304
- # st.session_state.df_results_tesseract = df_results_tesseract
1305
- st.session_state.list_reco_status = list_reco_status
1306
-
1307
- if 'df_results' in st.session_state:
1308
- if not st.session_state.df_results.empty:
1309
- ##----------- Show recognition results ------------------------------------------------------------
1310
- results_cols = st.session_state.df_results.columns
1311
- list_col_text = np.arange(1, len(cols_size), 2)
1312
- list_col_confid = np.arange(2, len(cols_size), 2)
1313
-
1314
- dict_draw_reco = {'in_image': st.session_state.list_images[1], \
1315
- 'in_boxes_coordinates': st.session_state.list_boxes, \
1316
- 'in_list_texts': [st.session_state.df_results[results_cols[1]].to_list() ], \
1317
- 'in_list_confid': [st.session_state.df_results[results_cols[2]].to_list()], \
1318
- 'in_dict_back_colors': dict_back_colors, \
1319
- 'in_reader_type_list': reader_type_list
1320
- }
1321
- show_reco = st.empty()
1322
-
1323
- with st.form("form3"):
1324
- st.plotly_chart(fig_colorscale, use_container_width=True)
1325
-
1326
- col_font, col_threshold = st.columns(2)
1327
-
1328
- col_font.slider('Font scale', 1, 7, 1, step=1, key="font_scale_sld")
1329
- col_threshold.slider('% confidence threshold for text color change', 40, 100, 64, \
1330
- step=1, key="conf_threshold_sld")
1331
- col_threshold.write("(text color is black below this % confidence threshold, \
1332
- and white above)")
1333
-
1334
- draw_reco_images(**dict_draw_reco)
1335
-
1336
- submit_resize = st.form_submit_button("Refresh")
1337
-
1338
- if submit_resize:
1339
- draw_reco_images(**dict_draw_reco, \
1340
- in_font_scale=st.session_state.font_scale_sld, \
1341
- in_conf_threshold=st.session_state.conf_threshold_sld)
1342
-
1343
- st.subheader("Recognition details")
1344
- with st.expander("Detailed areas for EasyOCR, PPOCR, MMOCR", expanded=True):
1345
- cols = st.columns(3)
1346
- cols[0].markdown('#### Detected area')
1347
- cols[1].markdown('#### text ' + "OCR")
1348
- cols[2].markdown('#### confidence_score')
1349
- for row in st.session_state.df_results.itertuples():
1350
- #cols = st.columns(1 + len(reader_type_list)*2)
1351
- cols = st.columns(3)
1352
- cols[0].image(row.cropped_image, width=150)
1353
- cols[1].write(getattr(row, results_cols[1]))
1354
- cols[2].write("("+str( \
1355
- getattr(row, results_cols[2]))+"%)")
1356
-
1357
- st.download_button(
1358
- label="Download results as CSV file",
1359
- data=convert_df(st.session_state.df_results),
1360
- file_name='OCR_comparator_results.csv',
1361
- mime='text/csv',
1362
- )
1363
-
1364
- # if not st.session_state.df_results_tesseract.empty:
1365
- # with st.expander("Detailed areas for Tesseract", expanded=False):
1366
- # cols = st.columns([2,2,1])
1367
- # cols[0].markdown('#### Detected area')
1368
- # cols[1].markdown('#### with Tesseract')
1369
-
1370
- # for row in st.session_state.df_results_tesseract.itertuples():
1371
- # cols = st.columns([2,2,1])
1372
- # cols[0].image(row.cropped, width=150)
1373
- # cols[1].write(getattr(row, 'text'))
1374
- # cols[2].write("("+str(getattr(row, 'conf'))+"%)")
1375
-
1376
- # st.download_button(
1377
- # label="Download Tesseract results as CSV file",
1378
- # data=convert_df(st.session_state.df_results),
1379
- # file_name='OCR_comparator_Tesseract_results.csv',
1380
- # mime='text/csv',
1381
- # )
 
 
 
 
1
  import streamlit as st
2
+ from multipage import MultiPage
3
+ from app_pages import home, about, ocr_comparator
4
+
5
+ app = MultiPage()
6
+ st.set_page_config(
7
+ page_title='OCR Comparator', layout ="wide",
8
+ initial_sidebar_state="expanded",
9
+ )
10
+
11
+ # Add all your application here
12
+ app.add_page("App", "cast", ocr_comparator.app)
13
+ # app.add_page("Home", "house", home.app)
14
+ app.add_page("About", "info-circle", about.app)
15
+
16
+ # The main app
17
+ app.run()