rtr46 commited on
Commit
d6bd879
·
verified ·
1 Parent(s): 58969d7
Files changed (1) hide show
  1. app.py +45 -149
app.py CHANGED
@@ -1,181 +1,77 @@
1
  import gradio as gr
2
- import onnxruntime as ort
3
  import numpy as np
4
  import cv2
5
- from huggingface_hub import hf_hub_download
6
- import os
7
  import json
 
 
8
 
9
- # --- 1. configuration & model loading ---
10
- # this section runs once when the space starts up.
11
-
12
- print("loading models...")
13
-
14
- # configuration
15
- det_model_repo = "rtr46/meiki.text.detect.v0"
16
- det_model_name = "meiki.text.detect.v0.1.960x544.onnx"
17
- rec_model_repo = "rtr46/meiki.txt.recognition.v0"
18
- rec_model_name = "meiki.text.rec.v0.960x32.onnx"
19
-
20
- input_det_width = 960
21
- input_det_height = 544
22
- input_rec_height = 32
23
- input_rec_width = 960
24
- x_overlap_threshold = 0.3
25
- epsilon = 1e-6
26
-
27
- # load models from the hub
28
  try:
29
- det_model_path = hf_hub_download(repo_id=det_model_repo, filename=det_model_name)
30
- rec_model_path = hf_hub_download(repo_id=rec_model_repo, filename=rec_model_name)
31
-
32
- # use cpu execution provider for broad compatibility in spaces
33
- providers = ['CPUExecutionProvider']
34
- det_session = ort.InferenceSession(det_model_path, providers=providers)
35
- rec_session = ort.InferenceSession(rec_model_path, providers=providers)
36
-
37
- print("models loaded successfully.")
38
  except Exception as e:
39
- det_session, rec_session = None, None
40
- print(f"error loading models: {e}")
41
- raise gr.Error(f"failed to load models. please check space logs. error: {e}")
42
-
43
- # --- 2. ocr pipeline helper functions ---
44
- # (these functions remain unchanged)
45
-
46
- def preprocess_for_detection(image):
47
- h_orig, w_orig, _ = image.shape
48
- resized = cv2.resize(image, (input_det_width, input_det_height), interpolation=cv2.INTER_LINEAR)
49
- input_tensor = resized.astype(np.float32) / 255.0
50
- input_tensor = np.transpose(input_tensor, (2, 0, 1))
51
- input_tensor = np.expand_dims(input_tensor, axis=0)
52
- scale_x = w_orig / input_det_width
53
- scale_y = h_orig / input_det_height
54
- return input_tensor, scale_x, scale_y
55
-
56
- def postprocess_detection_results(raw_outputs, scale_x, scale_y, conf_threshold):
57
- _, boxes, scores = raw_outputs
58
- boxes, scores = boxes[0], scores[0]
59
- text_boxes = []
60
- for box, score in zip(boxes, scores):
61
- if score < conf_threshold: continue
62
- x1, y1, x2, y2 = box
63
- x1_orig, y1_orig = int(x1 * scale_x), int(y1 * scale_y)
64
- x2_orig, y2_orig = int(x2 * scale_x), int(y2 * scale_y)
65
- text_boxes.append({'bbox': [x1_orig, y1_orig, x2_orig, y2_orig]})
66
- text_boxes.sort(key=lambda tb: tb['bbox'][1])
67
- return text_boxes
68
-
69
- def preprocess_for_recognition(image, text_boxes):
70
- tensors, valid_indices, crop_metadata = [], [], []
71
- for i, tb in enumerate(text_boxes):
72
- x1, y1, x2, y2 = tb['bbox']
73
- width, height = x2 - x1, y2 - y1
74
- if width < height or width == 0 or height == 0: continue
75
- crop = image[y1:y2, x1:x2]
76
- h, w, _ = crop.shape
77
- new_h, new_w = input_rec_height, int(round(w * (input_rec_height / h)))
78
- if new_w > input_rec_width:
79
- scale = input_rec_width / new_w
80
- new_w, new_h = input_rec_width, int(round(new_h * scale))
81
- resized = cv2.resize(crop, (new_w, new_h), interpolation=cv2.INTER_LINEAR)
82
- pad_w, pad_h = input_rec_width - new_w, input_rec_height - new_h
83
- padded = np.pad(resized, ((0, pad_h), (0, pad_w), (0, 0)), constant_values=0)
84
- tensor = (padded.astype(np.float32) / 255.0)
85
- tensor = np.transpose(tensor, (2, 0, 1))
86
- tensors.append(tensor)
87
- valid_indices.append(i)
88
- crop_metadata.append({'orig_bbox': [x1, y1, x2, y2], 'effective_w': new_w})
89
- if not tensors: return None, [], []
90
- return np.stack(tensors, axis=0), valid_indices, crop_metadata
91
-
92
- def postprocess_recognition_results(raw_rec_outputs, valid_indices, crop_metadata, rec_conf_threshold, num_total_boxes):
93
- labels_batch, boxes_batch, scores_batch = raw_rec_outputs
94
- full_results = [{'text': '', 'chars': []} for _ in range(num_total_boxes)]
95
- for i, (labels, boxes, scores) in enumerate(zip(labels_batch, boxes_batch, scores_batch)):
96
- meta = crop_metadata[i]
97
- gx1, gy1, gx2, gy2 = meta['orig_bbox']
98
- crop_w, crop_h = gx2 - gx1, gy2 - gy1
99
- effective_w = meta['effective_w']
100
- candidates = []
101
- for lbl, box, scr in zip(labels, boxes, scores):
102
- if scr < rec_conf_threshold: continue
103
- char = chr(lbl)
104
- rx1, ry1, rx2, ry2 = box
105
- rx1, rx2 = min(rx1, effective_w), min(rx2, effective_w)
106
- cx1, cx2 = (rx1 / effective_w) * crop_w, (rx2 / effective_w) * crop_w
107
- cy1, cy2 = (ry1 / input_rec_height) * crop_h, (ry2 / input_rec_height) * crop_h
108
- gx1_char, gy1_char = gx1 + int(cx1), gy1 + int(cy1)
109
- gx2_char, gy2_char = gx1 + int(cx2), gy1 + int(cy2)
110
- candidates.append({'char': char, 'bbox': [gx1_char, gy1_char, gx2_char, gy2_char], 'x_interval': (gx1_char, gx2_char), 'conf': float(scr)})
111
- candidates.sort(key=lambda c: c['conf'], reverse=True)
112
- accepted = []
113
- for cand in candidates:
114
- x1_c, x2_c = cand['x_interval']
115
- width_c = x2_c - x1_c + epsilon
116
- is_overlap = any((max(0, min(x2_c, x2_a) - max(x1_c, x1_a)) / width_c) > x_overlap_threshold for x1_a, x2_a in (acc['x_interval'] for acc in accepted))
117
- if not is_overlap: accepted.append(cand)
118
- accepted.sort(key=lambda c: c['x_interval'][0])
119
- text = ''.join(c['char'] for c in accepted)
120
- final_chars = [{'char': c['char'], 'bbox': c['bbox'], 'conf': c['conf']} for c in accepted]
121
- full_results[valid_indices[i]] = {'text': text, 'chars': final_chars}
122
- return full_results
123
-
124
- # --- 3. main gradio processing function ---
125
 
126
  def run_ocr_pipeline(input_image, det_threshold, rec_threshold):
 
 
 
 
127
  if input_image is None:
128
- raise gr.Error("please upload an image to process.")
129
-
130
- det_input, sx, sy = preprocess_for_detection(input_image)
131
- det_raw = det_session.run(None, {det_session.get_inputs()[0].name: det_input, det_session.get_inputs()[1].name: np.array([[input_det_width, input_det_height]], dtype=np.int64)})
132
- text_boxes = postprocess_detection_results(det_raw, sx, sy, det_threshold)
133
 
134
- if not text_boxes:
135
- return input_image, "no text detected. try lowering the 'detection confidence' slider.", ""
136
 
137
- rec_batch, valid_indices, crop_metadata = preprocess_for_recognition(input_image, text_boxes)
138
- rec_raw = rec_session.run(None, {"images": rec_batch, "orig_target_sizes": np.array([[input_rec_width, input_rec_height]], dtype=np.int64)})
139
- results = postprocess_recognition_results(rec_raw, valid_indices, crop_metadata, rec_threshold, len(text_boxes))
140
 
 
141
  output_image = input_image.copy()
142
- full_text = []
143
- for res in results:
144
- if res['text']: full_text.append(res['text'])
145
- for char_info in res['chars']:
 
 
 
 
146
  x1, y1, x2, y2 = char_info['bbox']
147
  cv2.rectangle(output_image, (x1, y1), (x2, y2), (0, 255, 0), 2)
148
 
 
 
149
  json_output = json.dumps(results, indent=2, ensure_ascii=False)
150
 
151
- return output_image, "\n".join(full_text), json_output
152
-
153
- # --- 4. gradio interface definition ---
154
 
155
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
156
- gr.Markdown("# meikiocr: japanese video game ocr")
157
  gr.Markdown(
158
- "upload a screenshot from a japanese video game to see the high-accuracy ocr in action. "
159
- "the pipeline first detects text lines, then recognizes the characters in each line. "
160
- "adjust the confidence sliders if text is missed or incorrectly detected."
161
  )
162
 
163
  with gr.Row():
164
  with gr.Column(scale=1):
165
- input_image = gr.Image(type="numpy", label="upload image")
166
- det_threshold = gr.Slider(minimum=0.1, maximum=1.0, value=0.5, step=0.05, label="detection confidence")
167
- rec_threshold = gr.Slider(minimum=0.0, maximum=1.0, value=0.1, step=0.05, label="recognition confidence")
168
- run_button = gr.Button("run ocr", variant="primary")
169
 
170
  with gr.Column(scale=2):
171
- output_image = gr.Image(type="numpy", label="ocr result")
172
- output_text = gr.Textbox(label="recognized text", lines=5)
173
- output_json = gr.Code(label="json output", language="json", lines=5)
174
 
 
175
  def process_example(img):
176
- # examples are pre-loaded as numpy by gradio, so we can pass them directly
177
  return run_ocr_pipeline(img, 0.5, 0.1)
178
 
 
179
  example_image_path = os.path.join(os.path.dirname(__file__), "example.jpg")
180
  if os.path.exists(example_image_path):
181
  gr.Examples(
@@ -186,6 +82,7 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
186
  cache_examples=True
187
  )
188
 
 
189
  run_button.click(
190
  fn=run_ocr_pipeline,
191
  inputs=[input_image, det_threshold, rec_threshold],
@@ -195,11 +92,10 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
195
  gr.Markdown(
196
  """
197
  ---
198
- ### official github repository
199
- the full source code, documentation, and local command-line script for `meikiocr` are available on github.
200
  **[github.com/rtr46/meikiocr](https://github.com/rtr46/meikiocr)**
201
  """
202
  )
203
 
204
- # --- 5. launch the app ---
205
  demo.launch()
 
1
  import gradio as gr
 
2
  import numpy as np
3
  import cv2
 
 
4
  import json
5
+ import os
6
+ from meikiocr import MeikiOCR
7
 
8
+ print("Initializing meikiocr...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  try:
10
+ ocr = MeikiOCR(provider='CPUExecutionProvider')
11
+ print("meikiocr initialized successfully.")
 
 
 
 
 
 
 
12
  except Exception as e:
13
+ ocr = None
14
+ print(f"Error initializing meikiocr: {e}")
15
+ # Display a persistent error in the Gradio interface if model loading fails.
16
+ raise gr.Error(f"Failed to load OCR models. Please check the space logs for details. Error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  def run_ocr_pipeline(input_image, det_threshold, rec_threshold):
19
+ """
20
+ Takes a user-uploaded image and confidence thresholds, runs the OCR pipeline,
21
+ and returns the results formatted for the Gradio interface.
22
+ """
23
  if input_image is None:
24
+ raise gr.Error("Please upload an image to process.")
 
 
 
 
25
 
26
+ results = ocr.run_ocr(input_image, det_threshold=det_threshold, rec_threshold=rec_threshold)
 
27
 
28
+ if not results:
29
+ return input_image, "No text detected. Try lowering the 'Detection Confidence' slider.", ""
 
30
 
31
+ # Prepare the outputs for Gradio
32
  output_image = input_image.copy()
33
+ full_text_lines = []
34
+
35
+ # Draw bounding boxes and collect text
36
+ for line_result in results:
37
+ if line_result['text']:
38
+ full_text_lines.append(line_result['text'])
39
+ # Draw a green rectangle for each recognized character
40
+ for char_info in line_result['chars']:
41
  x1, y1, x2, y2 = char_info['bbox']
42
  cv2.rectangle(output_image, (x1, y1), (x2, y2), (0, 255, 0), 2)
43
 
44
+ # Format the full text and JSON output
45
+ recognized_text = "\n".join(full_text_lines)
46
  json_output = json.dumps(results, indent=2, ensure_ascii=False)
47
 
48
+ return output_image, recognized_text, json_output
 
 
49
 
50
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
51
+ gr.Markdown("# meikiocr: Japanese Video Game OCR")
52
  gr.Markdown(
53
+ "Upload a screenshot from a Japanese video game to see the high-accuracy OCR in action. "
54
+ "The pipeline first detects text lines, then recognizes the characters in each line. "
55
+ "Adjust the confidence sliders if text is missed or incorrectly detected."
56
  )
57
 
58
  with gr.Row():
59
  with gr.Column(scale=1):
60
+ input_image = gr.Image(type="numpy", label="Upload Image")
61
+ det_threshold = gr.Slider(minimum=0.1, maximum=1.0, value=0.5, step=0.05, label="Detection Confidence")
62
+ rec_threshold = gr.Slider(minimum=0.0, maximum=1.0, value=0.1, step=0.05, label="Recognition Confidence")
63
+ run_button = gr.Button("Run OCR", variant="primary")
64
 
65
  with gr.Column(scale=2):
66
+ output_image = gr.Image(type="numpy", label="OCR Result")
67
+ output_text = gr.Textbox(label="Recognized Text", lines=5)
68
+ output_json = gr.Code(label="JSON Output", language="json", lines=5)
69
 
70
+ # The function for handling examples is also simplified.
71
  def process_example(img):
 
72
  return run_ocr_pipeline(img, 0.5, 0.1)
73
 
74
+ # Load the example image if it exists
75
  example_image_path = os.path.join(os.path.dirname(__file__), "example.jpg")
76
  if os.path.exists(example_image_path):
77
  gr.Examples(
 
82
  cache_examples=True
83
  )
84
 
85
+ # Connect the button click to the main processing function
86
  run_button.click(
87
  fn=run_ocr_pipeline,
88
  inputs=[input_image, det_threshold, rec_threshold],
 
92
  gr.Markdown(
93
  """
94
  ---
95
+ ### Official GitHub Repository
96
+ The full source code, documentation, and local command-line script for `meikiocr` are available on GitHub.
97
  **[github.com/rtr46/meikiocr](https://github.com/rtr46/meikiocr)**
98
  """
99
  )
100
 
 
101
  demo.launch()