Spaces:
Running on Zero
Running on Zero
Upload 2 files
Browse files
README.md
CHANGED
|
@@ -1,56 +1,56 @@
|
|
| 1 |
-
---
|
| 2 |
-
title: OpenOCR-MLT
|
| 3 |
-
emoji: 🌐
|
| 4 |
-
colorFrom: indigo
|
| 5 |
-
colorTo: purple
|
| 6 |
-
sdk: gradio
|
| 7 |
-
sdk_version: 6.31.0
|
| 8 |
-
python_version: "3.10"
|
| 9 |
-
app_file: app.py
|
| 10 |
-
pinned: false
|
| 11 |
-
preload_from_hub:
|
| 12 |
-
- ericleyu/openocr-mlt-models scriptmoe-medium-fp32-20261101-v1.tar.gz 7ef39160a893fc7e605e146c1544ba64c1a57f43
|
| 13 |
-
short_description: A visual demo for the openocr-mlt repository
|
| 14 |
-
---
|
| 15 |
-
|
| 16 |
-
# OpenOCR-MLT
|
| 17 |
-
|
| 18 |
-
A visual demo for the [openocr-mlt](https://pypi.org/project/openocr-mlt/)
|
| 19 |
-
|
| 20 |
-
## Usage
|
| 21 |
-
|
| 22 |
-
Choose a task, upload an image or select an example, and run the task. **Whole-image OCR** returns text regions and recognized text. **Text detection** returns text regions. **Cropped recognition** reads a single word or line from a crop. The right column shows the visualization, latency, and JSON. Expand the results panel for plain text and confidence scores.
|
| 23 |
-
|
| 24 |
-
The recognition confidence slider defaults to 0.5 and applies to whole-image OCR and cropped recognition. Filtered rows keep their original scores and raw text in JSON. Whole-image OCR and cropped recognition resize inputs with a longest side above 2000 pixels proportionally for inference. Visualization coordinates refer to the original image. Processing is serial. The first request includes ONNX session initialization.
|
| 25 |
-
|
| 26 |
-
## Examples
|
| 27 |
-
|
| 28 |
-
The six images under `examples/page/` come from the [MultilingualOCR-Demo Space](https://huggingface.co/spaces/Yesianrohn/MultilingualOCR-Demo/tree/3420e727c1ec75410c842ee66ad9545327067495/examples) and are available in whole-image OCR and text detection. The source Space declares Apache 2.0. See [examples/LICENSE](examples/LICENSE).
|
| 29 |
-
|
| 30 |
-
The six images under `examples/recognition/` each contain one text line cropped from the corresponding full image. They cover French, Korean, Russian, Thai, Hindi, and Arabic and are available in cropped recognition mode. To add more examples, place PNG, JPEG, BMP, TIFF, or WebP word or line images in this directory and restart the app.
|
| 31 |
-
|
| 32 |
-
## Hosting
|
| 33 |
-
|
| 34 |
-
Upload this repository to a Gradio Space and select **ZeroGPU** under **Settings → Space hardware**. The build installs PyTorch 2.8 with its CUDA dependencies and preloads the pinned model archive from Hugging Face. Startup verifies and unpacks the local archive.
|
| 35 |
-
|
| 36 |
-
On ZeroGPU, all three tasks share a callback wrapped with `spaces.GPU(duration=60)`. The wrapper requests a GPU slot for each call. Inside the worker, `openocr-mlt` opens its ONNX Runtime CUDA sessions on the first inference and reads the preloaded models in offline mode. A successful GPU run shows `CUDA:0` in **Latency** and `"device": "cuda:0"` in **Result (JSON)**. See the [Hugging Face ZeroGPU guide](https://huggingface.co/docs/hub/spaces-zerogpu).
|
| 37 |
-
|
| 38 |
-
## Run locally
|
| 39 |
-
|
| 40 |
-
Use Linux x86_64 with Python 3.10.
|
| 41 |
-
|
| 42 |
-
```bash
|
| 43 |
-
python -m venv .venv
|
| 44 |
-
source .venv/bin/activate
|
| 45 |
-
python -m pip install openocr-mlt==0.5.3 gradio==6.31.0
|
| 46 |
-
python app.py
|
| 47 |
-
```
|
| 48 |
-
|
| 49 |
-
For local runs, `openocr-mlt` selects the device and manages model downloads and verification. Set `OPENOCR_MLT_DEVICE` to choose a device explicitly or `OPENOCR_MLT_CACHE_DIR` to select a model cache.
|
| 50 |
-
|
| 51 |
-
## Sources
|
| 52 |
-
|
| 53 |
-
- [ScriptMoE](https://github.com/YesianRohn/ScriptMoE), multilingual recognition.
|
| 54 |
-
- PP-OCRv6 medium, the detector distributed by Paddle.
|
| 55 |
-
- [MultilingualOCR-Demo](https://huggingface.co/spaces/Yesianrohn/MultilingualOCR-Demo), interface reference and example images.
|
| 56 |
-
- [Model sources and licensing](https://huggingface.co/ericleyu/openocr-mlt-models/blob/main/THIRD_PARTY_NOTICES.md).
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: OpenOCR-MLT
|
| 3 |
+
emoji: 🌐
|
| 4 |
+
colorFrom: indigo
|
| 5 |
+
colorTo: purple
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 6.31.0
|
| 8 |
+
python_version: "3.10"
|
| 9 |
+
app_file: app.py
|
| 10 |
+
pinned: false
|
| 11 |
+
preload_from_hub:
|
| 12 |
+
- ericleyu/openocr-mlt-models scriptmoe-medium-fp32-20261101-v1.tar.gz 7ef39160a893fc7e605e146c1544ba64c1a57f43
|
| 13 |
+
short_description: A visual demo for the openocr-mlt repository
|
| 14 |
+
---
|
| 15 |
+
|
| 16 |
+
# OpenOCR-MLT
|
| 17 |
+
|
| 18 |
+
A visual demo for the [openocr-mlt](https://pypi.org/project/openocr-mlt/) repository, developed by the **FVL OpenOCR team**. All three tasks run through the package's `OpenOCRMLT` Python API. Recognition uses ScriptMoE FP32 ONNX models. Detection uses PP-OCRv6 medium ONNX.
|
| 19 |
+
|
| 20 |
+
## Usage
|
| 21 |
+
|
| 22 |
+
Choose a task, upload an image or select an example, and run the task. **Whole-image OCR** returns text regions and recognized text. **Text detection** returns text regions. **Cropped recognition** reads a single word or line from a crop. The right column shows the visualization, latency, and JSON. Expand the results panel for plain text and confidence scores.
|
| 23 |
+
|
| 24 |
+
The recognition confidence slider defaults to 0.5 and applies to whole-image OCR and cropped recognition. Filtered rows keep their original scores and raw text in JSON. Whole-image OCR and cropped recognition resize inputs with a longest side above 2000 pixels proportionally for inference. Visualization coordinates refer to the original image. Processing is serial. The first request includes ONNX session initialization.
|
| 25 |
+
|
| 26 |
+
## Examples
|
| 27 |
+
|
| 28 |
+
The six images under `examples/page/` come from the [MultilingualOCR-Demo Space](https://huggingface.co/spaces/Yesianrohn/MultilingualOCR-Demo/tree/3420e727c1ec75410c842ee66ad9545327067495/examples) and are available in whole-image OCR and text detection. The source Space declares Apache 2.0. See [examples/LICENSE](examples/LICENSE).
|
| 29 |
+
|
| 30 |
+
The six images under `examples/recognition/` each contain one text line cropped from the corresponding full image. They cover French, Korean, Russian, Thai, Hindi, and Arabic and are available in cropped recognition mode. To add more examples, place PNG, JPEG, BMP, TIFF, or WebP word or line images in this directory and restart the app.
|
| 31 |
+
|
| 32 |
+
## Hosting
|
| 33 |
+
|
| 34 |
+
Upload this repository to a Gradio Space and select **ZeroGPU** under **Settings → Space hardware**. The build installs PyTorch 2.8 with its CUDA dependencies and preloads the pinned model archive from Hugging Face. Startup verifies and unpacks the local archive.
|
| 35 |
+
|
| 36 |
+
On ZeroGPU, all three tasks share a callback wrapped with `spaces.GPU(duration=60)`. The wrapper requests a GPU slot for each call. Inside the worker, `openocr-mlt` opens its ONNX Runtime CUDA sessions on the first inference and reads the preloaded models in offline mode. A successful GPU run shows `CUDA:0` in **Latency** and `"device": "cuda:0"` in **Result (JSON)**. See the [Hugging Face ZeroGPU guide](https://huggingface.co/docs/hub/spaces-zerogpu).
|
| 37 |
+
|
| 38 |
+
## Run locally
|
| 39 |
+
|
| 40 |
+
Use Linux x86_64 with Python 3.10.
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
python -m venv .venv
|
| 44 |
+
source .venv/bin/activate
|
| 45 |
+
python -m pip install openocr-mlt==0.5.3 gradio==6.31.0
|
| 46 |
+
python app.py
|
| 47 |
+
```
|
| 48 |
+
|
| 49 |
+
For local runs, `openocr-mlt` selects the device and manages model downloads and verification. Set `OPENOCR_MLT_DEVICE` to choose a device explicitly or `OPENOCR_MLT_CACHE_DIR` to select a model cache.
|
| 50 |
+
|
| 51 |
+
## Sources
|
| 52 |
+
|
| 53 |
+
- [ScriptMoE](https://github.com/YesianRohn/ScriptMoE), multilingual recognition.
|
| 54 |
+
- PP-OCRv6 medium, the detector distributed by Paddle.
|
| 55 |
+
- [MultilingualOCR-Demo](https://huggingface.co/spaces/Yesianrohn/MultilingualOCR-Demo), interface reference and example images.
|
| 56 |
+
- [Model sources and licensing](https://huggingface.co/ericleyu/openocr-mlt-models/blob/main/THIRD_PARTY_NOTICES.md).
|
app.py
CHANGED
|
@@ -1,281 +1,281 @@
|
|
| 1 |
-
"""OpenOCR-MLT interactive demo using the published Python package."""
|
| 2 |
-
import logging
|
| 3 |
-
import os
|
| 4 |
-
from functools import cache
|
| 5 |
-
from pathlib import Path
|
| 6 |
-
from threading import RLock
|
| 7 |
-
from time import perf_counter
|
| 8 |
-
|
| 9 |
-
# Match the spaces SDK's accepted values and keep it optional for local CPU use.
|
| 10 |
-
ZERO_GPU = os.environ.get("SPACES_ZERO_GPU", "").lower() in {"1", "t", "true"}
|
| 11 |
-
if ZERO_GPU:
|
| 12 |
-
import spaces
|
| 13 |
-
|
| 14 |
-
import gradio as gr
|
| 15 |
-
from PIL import ImageDraw, ImageFont
|
| 16 |
-
from openocr_mlt import OpenOCRMLT
|
| 17 |
-
|
| 18 |
-
ROOT = Path(__file__).resolve().parent
|
| 19 |
-
DEVICE = os.environ.get("OPENOCR_MLT_DEVICE", "cuda:0" if ZERO_GPU else None)
|
| 20 |
-
CACHE_DIR = os.environ.get("OPENOCR_MLT_CACHE_DIR")
|
| 21 |
-
MODEL_REPOSITORY = "ericleyu/openocr-mlt-models"
|
| 22 |
-
MODEL_REVISION = "7ef39160a893fc7e605e146c1544ba64c1a57f43"
|
| 23 |
-
MODEL_ARCHIVE = "scriptmoe-medium-fp32-20261101-v1.tar.gz"
|
| 24 |
-
# Display English labels while keeping the existing /predict task values.
|
| 25 |
-
TASK_CHOICES = [
|
| 26 |
-
("Whole-image OCR", "Whole-image OCR / 整图识别"),
|
| 27 |
-
("Text detection", "Text detection / 文字检测"),
|
| 28 |
-
("Cropped recognition", "Cropped text / 裁剪识别"),
|
| 29 |
-
]
|
| 30 |
-
TASKS = {value: mode for (_, value), mode in zip(TASK_CHOICES, ("ocr", "det", "rec"))}
|
| 31 |
-
LOCK = RLock()
|
| 32 |
-
LOGGER = logging.getLogger("openocr-mlt-space")
|
| 33 |
-
|
| 34 |
-
HEADER = """
|
| 35 |
-
<header class="app-header">
|
| 36 |
-
<h1>OpenOCR-MLT</h1>
|
| 37 |
-
<p class="tagline">A visual demo for the <a href="https://pypi.org/project/openocr-mlt/">openocr-mlt</a>
|
| 38 |
-
|
| 39 |
-
<p class="script-line">
|
| 40 |
-
<strong>Multilingual text recognition</strong>
|
| 41 |
-
<span>Latin</span><span>Chinese</span><span>Japanese</span><span>Korean</span><span>Arabic</span>
|
| 42 |
-
<span>Bangla</span><span>Devanagari</span><span>Cyrillic</span><span>Thai</span><span>Tibetan</span>
|
| 43 |
-
</p>
|
| 44 |
-
</header>
|
| 45 |
-
"""
|
| 46 |
-
|
| 47 |
-
# Gradio 6.31 loads built-in controls in the browser locale before running head scripts.
|
| 48 |
-
# Switch that locale through the same frontend function used by Gradio's settings.
|
| 49 |
-
ENGLISH_LOCALE = r"""
|
| 50 |
-
<script type="module">
|
| 51 |
-
const core = performance.getEntriesByType("resource").find(({ name }) => {
|
| 52 |
-
const url = new URL(name);
|
| 53 |
-
return url.origin === location.origin && /\/assets\/core-[\w-]+\.js$/.test(url.pathname);
|
| 54 |
-
});
|
| 55 |
-
if (core) {
|
| 56 |
-
const { changeLocale } = await import(core.name);
|
| 57 |
-
changeLocale("en");
|
| 58 |
-
}
|
| 59 |
-
</script>
|
| 60 |
-
"""
|
| 61 |
-
|
| 62 |
-
CSS = """
|
| 63 |
-
.app-header {
|
| 64 |
-
text-align: center;
|
| 65 |
-
max-width: 1200px;
|
| 66 |
-
margin: 20px auto;
|
| 67 |
-
padding: 24px 20px;
|
| 68 |
-
}
|
| 69 |
-
.app-header h1 {
|
| 70 |
-
font-size: clamp(2rem, 5vw, 2.4rem);
|
| 71 |
-
font-weight: 700;
|
| 72 |
-
letter-spacing: -.01em;
|
| 73 |
-
margin: 0 0 10px;
|
| 74 |
-
}
|
| 75 |
-
.app-header .tagline {
|
| 76 |
-
font-size: 1.1em;
|
| 77 |
-
line-height: 1.6;
|
| 78 |
-
margin: 0 0 14px;
|
| 79 |
-
}
|
| 80 |
-
.app-header .script-line {
|
| 81 |
-
font-size: .95em;
|
| 82 |
-
line-height: 1.7;
|
| 83 |
-
margin: 0;
|
| 84 |
-
}
|
| 85 |
-
.script-line strong { margin-right: 5px; }
|
| 86 |
-
.script-line span {
|
| 87 |
-
display: inline-block;
|
| 88 |
-
background: color-mix(in srgb, currentColor 8%, transparent);
|
| 89 |
-
border-radius: 999px;
|
| 90 |
-
margin: 2px 3px;
|
| 91 |
-
padding: 2px 10px;
|
| 92 |
-
font-size: .88em;
|
| 93 |
-
}
|
| 94 |
-
.image-container img { object-fit: contain; }
|
| 95 |
-
"""
|
| 96 |
-
|
| 97 |
-
EXAMPLE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp"}
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
def example_images(group):
|
| 101 |
-
folder = ROOT / "examples" / group
|
| 102 |
-
return [
|
| 103 |
-
str(path) for path in sorted(folder.glob("*"))
|
| 104 |
-
if path.is_file() and path.suffix.lower() in EXAMPLE_EXTENSIONS
|
| 105 |
-
]
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
@cache
|
| 109 |
-
def get_engine(task):
|
| 110 |
-
options = {}
|
| 111 |
-
if task == "ocr":
|
| 112 |
-
options = {"page_max_side": 2000, "rec_threshold": 0}
|
| 113 |
-
elif task == "rec":
|
| 114 |
-
options = {"max_side": 2000, "rec_threshold": 0}
|
| 115 |
-
return OpenOCRMLT(task=task, device=DEVICE, cache_dir=CACHE_DIR, offline=ZERO_GPU, **options)
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
def draw_boxes(image, boxes):
|
| 119 |
-
canvas = image.copy()
|
| 120 |
-
draw = ImageDraw.Draw(canvas)
|
| 121 |
-
font = ImageFont.load_default(size=16)
|
| 122 |
-
width = max(2, round(max(canvas.size) / 600))
|
| 123 |
-
for index, points in enumerate(boxes, 1):
|
| 124 |
-
polygon = [tuple(point) for point in points]
|
| 125 |
-
draw.line(polygon + [polygon[0]], fill="#059669", width=width)
|
| 126 |
-
x = min(max(int(p[0]) for p in polygon), canvas.width - 1)
|
| 127 |
-
y = min(max(0, min(int(p[1]) for p in polygon) - 22), canvas.height - 1)
|
| 128 |
-
label = str(index)
|
| 129 |
-
left, top, right, bottom = draw.textbbox((x, y), label, font=font)
|
| 130 |
-
draw.rectangle((left - 2, top - 2, right + 3, bottom + 2), fill="#059669")
|
| 131 |
-
draw.text((x, y), label, font=font, fill="white")
|
| 132 |
-
return canvas
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
def run_ocr(image, task_label, rec_threshold=0.5):
|
| 136 |
-
if image is None:
|
| 137 |
-
raise gr.Error("Upload an image or select an example.")
|
| 138 |
-
task = TASKS.get(task_label)
|
| 139 |
-
if task is None:
|
| 140 |
-
raise gr.Error("Select an OCR task.")
|
| 141 |
-
if image.width * image.height > 16_000_000:
|
| 142 |
-
raise gr.Error("Please use an image with at most 16 megapixels.")
|
| 143 |
-
if isinstance(rec_threshold, bool) or not isinstance(rec_threshold, (int, float)) or not 0 <= rec_threshold <= 1:
|
| 144 |
-
raise gr.Error("Recognition confidence must be between 0 and 1.")
|
| 145 |
-
threshold = float(rec_threshold)
|
| 146 |
-
started = perf_counter()
|
| 147 |
-
try:
|
| 148 |
-
with LOCK:
|
| 149 |
-
engine = get_engine(task)
|
| 150 |
-
prediction = engine(image=image)
|
| 151 |
-
device = engine.info["device"]
|
| 152 |
-
except (OSError, RuntimeError, ValueError) as error:
|
| 153 |
-
LOGGER.exception("OCR request failed for task=%s", task)
|
| 154 |
-
raise gr.Error("Processing failed. Please retry or try another image.") from error
|
| 155 |
-
elapsed = perf_counter() - started
|
| 156 |
-
|
| 157 |
-
records = [item.to_dict() for item in (prediction.items if task == "ocr" else prediction)]
|
| 158 |
-
score_key = "rec_score" if task == "ocr" else "score"
|
| 159 |
-
table = []
|
| 160 |
-
for index, row in enumerate(records, 1):
|
| 161 |
-
score = row[score_key]
|
| 162 |
-
# Apply the slider to the display without recreating the model session.
|
| 163 |
-
if row.get("text") and score < threshold:
|
| 164 |
-
row.update(text="", status="filtered")
|
| 165 |
-
table.append([index, row.get("text", ""), score, row.get("status", "detected")])
|
| 166 |
-
|
| 167 |
-
text = "\n".join(row["text"] for row in records if row.get("text"))
|
| 168 |
-
boxes = [row["points"] for row in records if "points" in row]
|
| 169 |
-
payload = {
|
| 170 |
-
"task": task, "image_size": list(image.size), "device": device, "results": records,
|
| 171 |
-
"recognition_threshold": None if task == "det" else threshold,
|
| 172 |
-
}
|
| 173 |
-
count = len(records)
|
| 174 |
-
unit = "prediction" if task == "rec" else "region"
|
| 175 |
-
status = f"{elapsed:.2f} s · {device.upper()} · {count} {unit}{'s' if count != 1 else ''}"
|
| 176 |
-
if not records:
|
| 177 |
-
status += " · No text found"
|
| 178 |
-
elif task != "det" and not text:
|
| 179 |
-
status += f" · No text passed confidence {threshold:g}"
|
| 180 |
-
return draw_boxes(image, boxes), text, table, status, payload
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
# ONNX Runtime opens its CUDA sessions on the first inference in the GPU worker.
|
| 184 |
-
predict = spaces.GPU(duration=60)(run_ocr) if ZERO_GPU else run_ocr
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
def create_demo():
|
| 188 |
-
cropped_examples = example_images("recognition")
|
| 189 |
-
with gr.Blocks(title="OpenOCR-MLT") as demo:
|
| 190 |
-
gr.HTML(HEADER)
|
| 191 |
-
with gr.Row():
|
| 192 |
-
with gr.Column():
|
| 193 |
-
image = gr.Image(
|
| 194 |
-
label="Input image", type="pil", sources=["upload"],
|
| 195 |
-
elem_classes=["image-container"], height=380,
|
| 196 |
-
)
|
| 197 |
-
task = gr.Radio(
|
| 198 |
-
choices=TASK_CHOICES, value=TASK_CHOICES[0][1], label="Task",
|
| 199 |
-
)
|
| 200 |
-
with gr.Column() as page_gallery:
|
| 201 |
-
gr.Examples(
|
| 202 |
-
examples=example_images("page"), inputs=image,
|
| 203 |
-
label="Examples for whole-image OCR and text detection", cache_examples=False,
|
| 204 |
-
)
|
| 205 |
-
with gr.Column(visible=False) as crop_gallery:
|
| 206 |
-
if cropped_examples:
|
| 207 |
-
gr.Examples(
|
| 208 |
-
examples=cropped_examples, inputs=image,
|
| 209 |
-
label="Cropped recognition examples", cache_examples=False,
|
| 210 |
-
)
|
| 211 |
-
else:
|
| 212 |
-
gr.Markdown("Upload an image cropped to a single word or line of text.")
|
| 213 |
-
run = gr.Button("Run OCR", variant="primary")
|
| 214 |
-
rec_threshold = gr.Slider(
|
| 215 |
-
maximum=1, value=0.5, step=0.01,
|
| 216 |
-
label="Recognition confidence",
|
| 217 |
-
info="Minimum confidence for recognized text.",
|
| 218 |
-
)
|
| 219 |
-
with gr.Column():
|
| 220 |
-
visualization = gr.Image(
|
| 221 |
-
label="Visualization",
|
| 222 |
-
elem_classes=["image-container"], height=380,
|
| 223 |
-
)
|
| 224 |
-
status = gr.Textbox(label="Latency")
|
| 225 |
-
structured = gr.JSON(label="Result (JSON)", height=310)
|
| 226 |
-
with gr.Accordion("Recognized text and confidence scores", open=False):
|
| 227 |
-
text = gr.Textbox(label="Recognized text", lines=6, buttons=["copy"])
|
| 228 |
-
table = gr.Dataframe(
|
| 229 |
-
headers=["ID", "Text", "Confidence", "Status"],
|
| 230 |
-
datatype=["number", "str", "number", "str"],
|
| 231 |
-
wrap=True, label="Results",
|
| 232 |
-
)
|
| 233 |
-
|
| 234 |
-
def update_task(label):
|
| 235 |
-
mode = TASKS.get(label)
|
| 236 |
-
return (
|
| 237 |
-
gr.update(visible=mode != "rec"),
|
| 238 |
-
gr.update(visible=mode == "rec"),
|
| 239 |
-
gr.update(visible=mode != "det"),
|
| 240 |
-
gr.update(value={"det": "Run Detection", "rec": "Run Recognition"}.get(mode, "Run OCR")),
|
| 241 |
-
)
|
| 242 |
-
|
| 243 |
-
task.change(
|
| 244 |
-
update_task, inputs=task, outputs=[page_gallery, crop_gallery, rec_threshold, run],
|
| 245 |
-
queue=False, api_visibility="private",
|
| 246 |
-
)
|
| 247 |
-
run.click(
|
| 248 |
-
predict, inputs=[image, task, rec_threshold],
|
| 249 |
-
outputs=[visualization, text, table, status, structured],
|
| 250 |
-
api_name="predict", concurrency_limit=1,
|
| 251 |
-
)
|
| 252 |
-
gr.Markdown(
|
| 253 |
-
"[PyPI](https://pypi.org/project/openocr-mlt/) · "
|
| 254 |
-
"[Models](https://huggingface.co/ericleyu/openocr-mlt-models) · "
|
| 255 |
-
"[ScriptMoE](https://github.com/YesianRohn/ScriptMoE) · "
|
| 256 |
-
"[Reference demo and example images](https://huggingface.co/spaces/Yesianrohn/MultilingualOCR-Demo)"
|
| 257 |
-
)
|
| 258 |
-
return demo.queue(max_size=12)
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
def prepare_space_assets():
|
| 262 |
-
"""Verify and unpack the build-preloaded model archive without opening CUDA sessions."""
|
| 263 |
-
from huggingface_hub import hf_hub_download
|
| 264 |
-
from openocr_mlt import fetch_models
|
| 265 |
-
|
| 266 |
-
archive = hf_hub_download(
|
| 267 |
-
repo_id=MODEL_REPOSITORY,
|
| 268 |
-
filename=MODEL_ARCHIVE,
|
| 269 |
-
revision=MODEL_REVISION,
|
| 270 |
-
local_files_only=True,
|
| 271 |
-
)
|
| 272 |
-
fetch_models(source=archive, cache_dir=CACHE_DIR, offline=True)
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
if __name__ == "__main__":
|
| 276 |
-
if ZERO_GPU:
|
| 277 |
-
prepare_space_assets()
|
| 278 |
-
create_demo().launch(
|
| 279 |
-
server_name="0.0.0.0", max_file_size="20mb",
|
| 280 |
-
theme=gr.themes.Soft(), css=CSS, head=ENGLISH_LOCALE,
|
| 281 |
-
)
|
|
|
|
| 1 |
+
"""OpenOCR-MLT interactive demo using the published Python package."""
|
| 2 |
+
import logging
|
| 3 |
+
import os
|
| 4 |
+
from functools import cache
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from threading import RLock
|
| 7 |
+
from time import perf_counter
|
| 8 |
+
|
| 9 |
+
# Match the spaces SDK's accepted values and keep it optional for local CPU use.
|
| 10 |
+
ZERO_GPU = os.environ.get("SPACES_ZERO_GPU", "").lower() in {"1", "t", "true"}
|
| 11 |
+
if ZERO_GPU:
|
| 12 |
+
import spaces
|
| 13 |
+
|
| 14 |
+
import gradio as gr
|
| 15 |
+
from PIL import ImageDraw, ImageFont
|
| 16 |
+
from openocr_mlt import OpenOCRMLT
|
| 17 |
+
|
| 18 |
+
ROOT = Path(__file__).resolve().parent
|
| 19 |
+
DEVICE = os.environ.get("OPENOCR_MLT_DEVICE", "cuda:0" if ZERO_GPU else None)
|
| 20 |
+
CACHE_DIR = os.environ.get("OPENOCR_MLT_CACHE_DIR")
|
| 21 |
+
MODEL_REPOSITORY = "ericleyu/openocr-mlt-models"
|
| 22 |
+
MODEL_REVISION = "7ef39160a893fc7e605e146c1544ba64c1a57f43"
|
| 23 |
+
MODEL_ARCHIVE = "scriptmoe-medium-fp32-20261101-v1.tar.gz"
|
| 24 |
+
# Display English labels while keeping the existing /predict task values.
|
| 25 |
+
TASK_CHOICES = [
|
| 26 |
+
("Whole-image OCR", "Whole-image OCR / 整图识别"),
|
| 27 |
+
("Text detection", "Text detection / 文字检测"),
|
| 28 |
+
("Cropped recognition", "Cropped text / 裁剪识别"),
|
| 29 |
+
]
|
| 30 |
+
TASKS = {value: mode for (_, value), mode in zip(TASK_CHOICES, ("ocr", "det", "rec"))}
|
| 31 |
+
LOCK = RLock()
|
| 32 |
+
LOGGER = logging.getLogger("openocr-mlt-space")
|
| 33 |
+
|
| 34 |
+
HEADER = """
|
| 35 |
+
<header class="app-header">
|
| 36 |
+
<h1>OpenOCR-MLT</h1>
|
| 37 |
+
<p class="tagline">A visual demo for the <a href="https://pypi.org/project/openocr-mlt/">openocr-mlt</a>
|
| 38 |
+
repository, developed by the <strong>FVL OpenOCR team</strong>.</p>
|
| 39 |
+
<p class="script-line">
|
| 40 |
+
<strong>Multilingual text recognition</strong>
|
| 41 |
+
<span>Latin</span><span>Chinese</span><span>Japanese</span><span>Korean</span><span>Arabic</span>
|
| 42 |
+
<span>Bangla</span><span>Devanagari</span><span>Cyrillic</span><span>Thai</span><span>Tibetan</span>
|
| 43 |
+
</p>
|
| 44 |
+
</header>
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
# Gradio 6.31 loads built-in controls in the browser locale before running head scripts.
|
| 48 |
+
# Switch that locale through the same frontend function used by Gradio's settings.
|
| 49 |
+
ENGLISH_LOCALE = r"""
|
| 50 |
+
<script type="module">
|
| 51 |
+
const core = performance.getEntriesByType("resource").find(({ name }) => {
|
| 52 |
+
const url = new URL(name);
|
| 53 |
+
return url.origin === location.origin && /\/assets\/core-[\w-]+\.js$/.test(url.pathname);
|
| 54 |
+
});
|
| 55 |
+
if (core) {
|
| 56 |
+
const { changeLocale } = await import(core.name);
|
| 57 |
+
changeLocale("en");
|
| 58 |
+
}
|
| 59 |
+
</script>
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
CSS = """
|
| 63 |
+
.app-header {
|
| 64 |
+
text-align: center;
|
| 65 |
+
max-width: 1200px;
|
| 66 |
+
margin: 20px auto;
|
| 67 |
+
padding: 24px 20px;
|
| 68 |
+
}
|
| 69 |
+
.app-header h1 {
|
| 70 |
+
font-size: clamp(2rem, 5vw, 2.4rem);
|
| 71 |
+
font-weight: 700;
|
| 72 |
+
letter-spacing: -.01em;
|
| 73 |
+
margin: 0 0 10px;
|
| 74 |
+
}
|
| 75 |
+
.app-header .tagline {
|
| 76 |
+
font-size: 1.1em;
|
| 77 |
+
line-height: 1.6;
|
| 78 |
+
margin: 0 0 14px;
|
| 79 |
+
}
|
| 80 |
+
.app-header .script-line {
|
| 81 |
+
font-size: .95em;
|
| 82 |
+
line-height: 1.7;
|
| 83 |
+
margin: 0;
|
| 84 |
+
}
|
| 85 |
+
.script-line strong { margin-right: 5px; }
|
| 86 |
+
.script-line span {
|
| 87 |
+
display: inline-block;
|
| 88 |
+
background: color-mix(in srgb, currentColor 8%, transparent);
|
| 89 |
+
border-radius: 999px;
|
| 90 |
+
margin: 2px 3px;
|
| 91 |
+
padding: 2px 10px;
|
| 92 |
+
font-size: .88em;
|
| 93 |
+
}
|
| 94 |
+
.image-container img { object-fit: contain; }
|
| 95 |
+
"""
|
| 96 |
+
|
| 97 |
+
EXAMPLE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".bmp", ".tif", ".tiff", ".webp"}
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def example_images(group):
|
| 101 |
+
folder = ROOT / "examples" / group
|
| 102 |
+
return [
|
| 103 |
+
str(path) for path in sorted(folder.glob("*"))
|
| 104 |
+
if path.is_file() and path.suffix.lower() in EXAMPLE_EXTENSIONS
|
| 105 |
+
]
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@cache
|
| 109 |
+
def get_engine(task):
|
| 110 |
+
options = {}
|
| 111 |
+
if task == "ocr":
|
| 112 |
+
options = {"page_max_side": 2000, "rec_threshold": 0}
|
| 113 |
+
elif task == "rec":
|
| 114 |
+
options = {"max_side": 2000, "rec_threshold": 0}
|
| 115 |
+
return OpenOCRMLT(task=task, device=DEVICE, cache_dir=CACHE_DIR, offline=ZERO_GPU, **options)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def draw_boxes(image, boxes):
|
| 119 |
+
canvas = image.copy()
|
| 120 |
+
draw = ImageDraw.Draw(canvas)
|
| 121 |
+
font = ImageFont.load_default(size=16)
|
| 122 |
+
width = max(2, round(max(canvas.size) / 600))
|
| 123 |
+
for index, points in enumerate(boxes, 1):
|
| 124 |
+
polygon = [tuple(point) for point in points]
|
| 125 |
+
draw.line(polygon + [polygon[0]], fill="#059669", width=width)
|
| 126 |
+
x = min(max(int(p[0]) for p in polygon), canvas.width - 1)
|
| 127 |
+
y = min(max(0, min(int(p[1]) for p in polygon) - 22), canvas.height - 1)
|
| 128 |
+
label = str(index)
|
| 129 |
+
left, top, right, bottom = draw.textbbox((x, y), label, font=font)
|
| 130 |
+
draw.rectangle((left - 2, top - 2, right + 3, bottom + 2), fill="#059669")
|
| 131 |
+
draw.text((x, y), label, font=font, fill="white")
|
| 132 |
+
return canvas
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def run_ocr(image, task_label, rec_threshold=0.5):
|
| 136 |
+
if image is None:
|
| 137 |
+
raise gr.Error("Upload an image or select an example.")
|
| 138 |
+
task = TASKS.get(task_label)
|
| 139 |
+
if task is None:
|
| 140 |
+
raise gr.Error("Select an OCR task.")
|
| 141 |
+
if image.width * image.height > 16_000_000:
|
| 142 |
+
raise gr.Error("Please use an image with at most 16 megapixels.")
|
| 143 |
+
if isinstance(rec_threshold, bool) or not isinstance(rec_threshold, (int, float)) or not 0 <= rec_threshold <= 1:
|
| 144 |
+
raise gr.Error("Recognition confidence must be between 0 and 1.")
|
| 145 |
+
threshold = float(rec_threshold)
|
| 146 |
+
started = perf_counter()
|
| 147 |
+
try:
|
| 148 |
+
with LOCK:
|
| 149 |
+
engine = get_engine(task)
|
| 150 |
+
prediction = engine(image=image)
|
| 151 |
+
device = engine.info["device"]
|
| 152 |
+
except (OSError, RuntimeError, ValueError) as error:
|
| 153 |
+
LOGGER.exception("OCR request failed for task=%s", task)
|
| 154 |
+
raise gr.Error("Processing failed. Please retry or try another image.") from error
|
| 155 |
+
elapsed = perf_counter() - started
|
| 156 |
+
|
| 157 |
+
records = [item.to_dict() for item in (prediction.items if task == "ocr" else prediction)]
|
| 158 |
+
score_key = "rec_score" if task == "ocr" else "score"
|
| 159 |
+
table = []
|
| 160 |
+
for index, row in enumerate(records, 1):
|
| 161 |
+
score = row[score_key]
|
| 162 |
+
# Apply the slider to the display without recreating the model session.
|
| 163 |
+
if row.get("text") and score < threshold:
|
| 164 |
+
row.update(text="", status="filtered")
|
| 165 |
+
table.append([index, row.get("text", ""), score, row.get("status", "detected")])
|
| 166 |
+
|
| 167 |
+
text = "\n".join(row["text"] for row in records if row.get("text"))
|
| 168 |
+
boxes = [row["points"] for row in records if "points" in row]
|
| 169 |
+
payload = {
|
| 170 |
+
"task": task, "image_size": list(image.size), "device": device, "results": records,
|
| 171 |
+
"recognition_threshold": None if task == "det" else threshold,
|
| 172 |
+
}
|
| 173 |
+
count = len(records)
|
| 174 |
+
unit = "prediction" if task == "rec" else "region"
|
| 175 |
+
status = f"{elapsed:.2f} s · {device.upper()} · {count} {unit}{'s' if count != 1 else ''}"
|
| 176 |
+
if not records:
|
| 177 |
+
status += " · No text found"
|
| 178 |
+
elif task != "det" and not text:
|
| 179 |
+
status += f" · No text passed confidence {threshold:g}"
|
| 180 |
+
return draw_boxes(image, boxes), text, table, status, payload
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# ONNX Runtime opens its CUDA sessions on the first inference in the GPU worker.
|
| 184 |
+
predict = spaces.GPU(duration=60)(run_ocr) if ZERO_GPU else run_ocr
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def create_demo():
|
| 188 |
+
cropped_examples = example_images("recognition")
|
| 189 |
+
with gr.Blocks(title="OpenOCR-MLT") as demo:
|
| 190 |
+
gr.HTML(HEADER)
|
| 191 |
+
with gr.Row():
|
| 192 |
+
with gr.Column():
|
| 193 |
+
image = gr.Image(
|
| 194 |
+
label="Input image", type="pil", sources=["upload"],
|
| 195 |
+
elem_classes=["image-container"], height=380,
|
| 196 |
+
)
|
| 197 |
+
task = gr.Radio(
|
| 198 |
+
choices=TASK_CHOICES, value=TASK_CHOICES[0][1], label="Task",
|
| 199 |
+
)
|
| 200 |
+
with gr.Column() as page_gallery:
|
| 201 |
+
gr.Examples(
|
| 202 |
+
examples=example_images("page"), inputs=image,
|
| 203 |
+
label="Examples for whole-image OCR and text detection", cache_examples=False,
|
| 204 |
+
)
|
| 205 |
+
with gr.Column(visible=False) as crop_gallery:
|
| 206 |
+
if cropped_examples:
|
| 207 |
+
gr.Examples(
|
| 208 |
+
examples=cropped_examples, inputs=image,
|
| 209 |
+
label="Cropped recognition examples", cache_examples=False,
|
| 210 |
+
)
|
| 211 |
+
else:
|
| 212 |
+
gr.Markdown("Upload an image cropped to a single word or line of text.")
|
| 213 |
+
run = gr.Button("Run OCR", variant="primary")
|
| 214 |
+
rec_threshold = gr.Slider(
|
| 215 |
+
maximum=1, value=0.5, step=0.01,
|
| 216 |
+
label="Recognition confidence",
|
| 217 |
+
info="Minimum confidence for recognized text.",
|
| 218 |
+
)
|
| 219 |
+
with gr.Column():
|
| 220 |
+
visualization = gr.Image(
|
| 221 |
+
label="Visualization",
|
| 222 |
+
elem_classes=["image-container"], height=380,
|
| 223 |
+
)
|
| 224 |
+
status = gr.Textbox(label="Latency")
|
| 225 |
+
structured = gr.JSON(label="Result (JSON)", height=310)
|
| 226 |
+
with gr.Accordion("Recognized text and confidence scores", open=False):
|
| 227 |
+
text = gr.Textbox(label="Recognized text", lines=6, buttons=["copy"])
|
| 228 |
+
table = gr.Dataframe(
|
| 229 |
+
headers=["ID", "Text", "Confidence", "Status"],
|
| 230 |
+
datatype=["number", "str", "number", "str"],
|
| 231 |
+
wrap=True, label="Results",
|
| 232 |
+
)
|
| 233 |
+
|
| 234 |
+
def update_task(label):
|
| 235 |
+
mode = TASKS.get(label)
|
| 236 |
+
return (
|
| 237 |
+
gr.update(visible=mode != "rec"),
|
| 238 |
+
gr.update(visible=mode == "rec"),
|
| 239 |
+
gr.update(visible=mode != "det"),
|
| 240 |
+
gr.update(value={"det": "Run Detection", "rec": "Run Recognition"}.get(mode, "Run OCR")),
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
task.change(
|
| 244 |
+
update_task, inputs=task, outputs=[page_gallery, crop_gallery, rec_threshold, run],
|
| 245 |
+
queue=False, api_visibility="private",
|
| 246 |
+
)
|
| 247 |
+
run.click(
|
| 248 |
+
predict, inputs=[image, task, rec_threshold],
|
| 249 |
+
outputs=[visualization, text, table, status, structured],
|
| 250 |
+
api_name="predict", concurrency_limit=1,
|
| 251 |
+
)
|
| 252 |
+
gr.Markdown(
|
| 253 |
+
"[PyPI](https://pypi.org/project/openocr-mlt/) · "
|
| 254 |
+
"[Models](https://huggingface.co/ericleyu/openocr-mlt-models) · "
|
| 255 |
+
"[ScriptMoE](https://github.com/YesianRohn/ScriptMoE) · "
|
| 256 |
+
"[Reference demo and example images](https://huggingface.co/spaces/Yesianrohn/MultilingualOCR-Demo)"
|
| 257 |
+
)
|
| 258 |
+
return demo.queue(max_size=12)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def prepare_space_assets():
|
| 262 |
+
"""Verify and unpack the build-preloaded model archive without opening CUDA sessions."""
|
| 263 |
+
from huggingface_hub import hf_hub_download
|
| 264 |
+
from openocr_mlt import fetch_models
|
| 265 |
+
|
| 266 |
+
archive = hf_hub_download(
|
| 267 |
+
repo_id=MODEL_REPOSITORY,
|
| 268 |
+
filename=MODEL_ARCHIVE,
|
| 269 |
+
revision=MODEL_REVISION,
|
| 270 |
+
local_files_only=True,
|
| 271 |
+
)
|
| 272 |
+
fetch_models(source=archive, cache_dir=CACHE_DIR, offline=True)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
if __name__ == "__main__":
|
| 276 |
+
if ZERO_GPU:
|
| 277 |
+
prepare_space_assets()
|
| 278 |
+
create_demo().launch(
|
| 279 |
+
server_name="0.0.0.0", max_file_size="20mb",
|
| 280 |
+
theme=gr.themes.Soft(), css=CSS, head=ENGLISH_LOCALE,
|
| 281 |
+
)
|