XuNick commited on
Commit
e26071d
·
verified ·
1 Parent(s): 411fced

Update app.py

Browse files

new version demo start

Files changed (1) hide show
  1. app.py +65 -38
app.py CHANGED
@@ -9,37 +9,36 @@ import gradio as gr
9
 
10
 
11
  LANG_CONFIG = {
12
- "ch": {"num_workers": 2},
13
- "en": {"num_workers": 2},
14
  "fr": {"num_workers": 1},
15
  "german": {"num_workers": 1},
16
  "korean": {"num_workers": 1},
17
  "japan": {"num_workers": 1},
18
  }
19
- CONCURRENCY_LIMIT = 8
20
 
 
21
 
22
- class PaddleOCRModelManager(object):
23
- def __init__(self,
24
- num_workers,
25
- model_factory):
26
- super().__init__()
27
  self._model_factory = model_factory
28
  self._queue = Queue()
29
  self._workers = []
30
  self._model_initialized_event = Event()
 
31
  for _ in range(num_workers):
32
- worker = Thread(target=self._worker, daemon=False)
33
  worker.start()
34
  self._model_initialized_event.wait()
35
  self._model_initialized_event.clear()
36
  self._workers.append(worker)
37
 
38
  def infer(self, *args, **kwargs):
39
- # XXX: Should I use a more lightweight data structure, say, a future?
40
  result_queue = Queue(maxsize=1)
41
  self._queue.put((args, kwargs, result_queue))
42
  success, payload = result_queue.get()
 
43
  if success:
44
  return payload
45
  else:
@@ -48,24 +47,24 @@ class PaddleOCRModelManager(object):
48
  def close(self):
49
  for _ in self._workers:
50
  self._queue.put(None)
51
- for worker in self._workers:
52
- worker.join()
53
 
54
  def _worker(self):
55
  model = self._model_factory()
56
  self._model_initialized_event.set()
 
57
  while True:
58
  item = self._queue.get()
 
59
  if item is None:
60
  break
 
61
  args, kwargs, result_queue = item
 
62
  try:
63
  result = model.ocr(*args, **kwargs)
64
  result_queue.put((True, result))
65
  except Exception as e:
66
  result_queue.put((False, e))
67
- finally:
68
- self._queue.task_done()
69
 
70
 
71
  def create_model(lang):
@@ -73,9 +72,12 @@ def create_model(lang):
73
 
74
 
75
  model_managers = {}
 
76
  for lang, config in LANG_CONFIG.items():
77
- model_manager = PaddleOCRModelManager(config["num_workers"], functools.partial(create_model, lang=lang))
78
- model_managers[lang] = model_manager
 
 
79
 
80
 
81
  def close_model_managers():
@@ -83,48 +85,73 @@ def close_model_managers():
83
  manager.close()
84
 
85
 
86
- # XXX: Not sure if gradio allows adding custom teardown logic
87
  atexit.register(close_model_managers)
88
 
89
 
90
  def inference(img, lang):
91
  ocr = model_managers[lang]
92
- result = ocr.infer(img, cls=True)[0]
93
- img_path = img
94
- image = Image.open(img_path).convert("RGB")
 
 
 
 
 
 
 
95
  boxes = [line[0] for line in result]
96
  txts = [line[1][0] for line in result]
97
  scores = [line[1][1] for line in result]
98
- im_show = draw_ocr(image, boxes, txts, scores,
99
- font_path="./simfang.ttf")
 
 
 
 
 
 
 
100
  return im_show
101
 
102
 
103
- title = 'PaddleOCR'
104
- description = '''
105
- - Gradio demo for PaddleOCR. PaddleOCR demo supports Chinese, English, French, German, Korean and Japanese.
106
- - To use it, simply upload your image and choose a language from the dropdown menu, or click one of the examples to load them. Read more at the links below.
107
- - [Docs](https://paddlepaddle.github.io/PaddleOCR/), [Github Repository](https://github.com/PaddlePaddle/PaddleOCR).
108
- '''
 
 
 
 
109
 
110
  examples = [
111
- ['en_example.jpg','en'],
112
- ['cn_example.jpg','ch'],
113
- ['jp_example.jpg','japan'],
114
  ]
115
 
116
  css = ".output_image, .input_image {height: 40rem !important; width: 100% !important;}"
117
- gr.Interface(
118
- inference,
119
- [
120
- gr.Image(type='filepath', label='Input'),
121
- gr.Dropdown(choices=list(LANG_CONFIG.keys()), value='en', label='language')
 
 
 
 
 
 
122
  ],
123
- gr.Image(type='pil', label='Output'),
124
  title=title,
125
  description=description,
126
  examples=examples,
127
  cache_examples=False,
128
  css=css,
129
  concurrency_limit=CONCURRENCY_LIMIT,
130
- ).launch(debug=False, share=True, ssr_mode=False)
 
 
 
9
 
10
 
11
  LANG_CONFIG = {
12
+ "ch": {"num_workers": 1},
13
+ "en": {"num_workers": 1},
14
  "fr": {"num_workers": 1},
15
  "german": {"num_workers": 1},
16
  "korean": {"num_workers": 1},
17
  "japan": {"num_workers": 1},
18
  }
 
19
 
20
+ CONCURRENCY_LIMIT = 2
21
 
22
+
23
+ class PaddleOCRModelManager:
24
+ def __init__(self, num_workers, model_factory):
 
 
25
  self._model_factory = model_factory
26
  self._queue = Queue()
27
  self._workers = []
28
  self._model_initialized_event = Event()
29
+
30
  for _ in range(num_workers):
31
+ worker = Thread(target=self._worker, daemon=True)
32
  worker.start()
33
  self._model_initialized_event.wait()
34
  self._model_initialized_event.clear()
35
  self._workers.append(worker)
36
 
37
  def infer(self, *args, **kwargs):
 
38
  result_queue = Queue(maxsize=1)
39
  self._queue.put((args, kwargs, result_queue))
40
  success, payload = result_queue.get()
41
+
42
  if success:
43
  return payload
44
  else:
 
47
  def close(self):
48
  for _ in self._workers:
49
  self._queue.put(None)
 
 
50
 
51
  def _worker(self):
52
  model = self._model_factory()
53
  self._model_initialized_event.set()
54
+
55
  while True:
56
  item = self._queue.get()
57
+
58
  if item is None:
59
  break
60
+
61
  args, kwargs, result_queue = item
62
+
63
  try:
64
  result = model.ocr(*args, **kwargs)
65
  result_queue.put((True, result))
66
  except Exception as e:
67
  result_queue.put((False, e))
 
 
68
 
69
 
70
  def create_model(lang):
 
72
 
73
 
74
  model_managers = {}
75
+
76
  for lang, config in LANG_CONFIG.items():
77
+ model_managers[lang] = PaddleOCRModelManager(
78
+ config["num_workers"],
79
+ functools.partial(create_model, lang=lang)
80
+ )
81
 
82
 
83
  def close_model_managers():
 
85
  manager.close()
86
 
87
 
 
88
  atexit.register(close_model_managers)
89
 
90
 
91
  def inference(img, lang):
92
  ocr = model_managers[lang]
93
+
94
+ result = ocr.infer(img, cls=True)
95
+
96
+ if not result or not result[0]:
97
+ return Image.open(img)
98
+
99
+ result = result[0]
100
+
101
+ image = Image.open(img).convert("RGB")
102
+
103
  boxes = [line[0] for line in result]
104
  txts = [line[1][0] for line in result]
105
  scores = [line[1][1] for line in result]
106
+
107
+ im_show = draw_ocr(
108
+ image,
109
+ boxes,
110
+ txts,
111
+ scores,
112
+ font_path="./simfang.ttf"
113
+ )
114
+
115
  return im_show
116
 
117
 
118
+ title = "PaddleOCR"
119
+
120
+ description = """
121
+ Gradio demo for PaddleOCR.
122
+
123
+ Supported languages:
124
+ Chinese, English, French, German, Korean, Japanese.
125
+
126
+ Upload an image and select the language.
127
+ """
128
 
129
  examples = [
130
+ ["en_example.jpg", "en"],
131
+ ["cn_example.jpg", "ch"],
132
+ ["jp_example.jpg", "japan"],
133
  ]
134
 
135
  css = ".output_image, .input_image {height: 40rem !important; width: 100% !important;}"
136
+
137
+
138
+ demo = gr.Interface(
139
+ fn=inference,
140
+ inputs=[
141
+ gr.Image(type="filepath", label="Input"),
142
+ gr.Dropdown(
143
+ choices=list(LANG_CONFIG.keys()),
144
+ value="en",
145
+ label="Language"
146
+ ),
147
  ],
148
+ outputs=gr.Image(type="pil", label="Output"),
149
  title=title,
150
  description=description,
151
  examples=examples,
152
  cache_examples=False,
153
  css=css,
154
  concurrency_limit=CONCURRENCY_LIMIT,
155
+ )
156
+
157
+ demo.launch()