Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files
app.py
CHANGED
@@ -1,170 +1,169 @@
|
|
1 |
-
import streamlit as st
|
2 |
-
import warnings
|
3 |
-
warnings.simplefilter("ignore", UserWarning)
|
4 |
-
|
5 |
-
from uuid import uuid4
|
6 |
-
from laia.scripts.htr.decode_ctc import run as decode
|
7 |
-
from laia.common.arguments import CommonArgs, DataArgs, TrainerArgs, DecodeArgs
|
8 |
-
import sys
|
9 |
-
from tempfile import NamedTemporaryFile, mkdtemp
|
10 |
-
from pathlib import Path
|
11 |
-
from contextlib import redirect_stdout
|
12 |
-
import re
|
13 |
-
from PIL import Image
|
14 |
-
from bidi.algorithm import get_display
|
15 |
-
import multiprocessing
|
16 |
-
from ultralytics import YOLO
|
17 |
-
import cv2
|
18 |
-
import numpy as np
|
19 |
-
import pandas as pd
|
20 |
-
import logging
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
use_language_model
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
"
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
70 |
-
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
input_img
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
)
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
boxes
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
predicted
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
segmented_image, table_data
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
# Display the table with polygons and recognized text
|
170 |
st.table(table_data)
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import warnings
|
3 |
+
warnings.simplefilter("ignore", UserWarning)
|
4 |
+
|
5 |
+
from uuid import uuid4
|
6 |
+
from laia.scripts.htr.decode_ctc import run as decode
|
7 |
+
from laia.common.arguments import CommonArgs, DataArgs, TrainerArgs, DecodeArgs
|
8 |
+
import sys
|
9 |
+
from tempfile import NamedTemporaryFile, mkdtemp
|
10 |
+
from pathlib import Path
|
11 |
+
from contextlib import redirect_stdout
|
12 |
+
import re
|
13 |
+
from PIL import Image
|
14 |
+
from bidi.algorithm import get_display
|
15 |
+
import multiprocessing
|
16 |
+
from ultralytics import YOLO
|
17 |
+
import cv2
|
18 |
+
import numpy as np
|
19 |
+
import pandas as pd
|
20 |
+
import logging
|
21 |
+
|
22 |
+
# Configure logging
|
23 |
+
logging.getLogger("lightning.pytorch").setLevel(logging.ERROR)
|
24 |
+
|
25 |
+
# Load YOLOv8 model
|
26 |
+
model = YOLO('model.pt')
|
27 |
+
images = Path(mkdtemp())
|
28 |
+
DEFAULT_HEIGHT = 128
|
29 |
+
TEXT_DIRECTION = "RTL"
|
30 |
+
NUM_WORKERS = multiprocessing.cpu_count()
|
31 |
+
|
32 |
+
# Regex pattern for extracting results
|
33 |
+
IMAGE_ID_PATTERN = r"(?P<image_id>[-a-z0-9]{36})"
|
34 |
+
CONFIDENCE_PATTERN = r"(?P<confidence>[0-9.]+)" # For line
|
35 |
+
TEXT_PATTERN = r"\s*(?P<text>.*)\s*"
|
36 |
+
LINE_PREDICTION = re.compile(rf"{IMAGE_ID_PATTERN} {CONFIDENCE_PATTERN} {TEXT_PATTERN}")
|
37 |
+
models_name = ["johnlockejrr/pylaia-heb_sam_v1"]
|
38 |
+
MODELS = {}
|
39 |
+
|
40 |
+
def get_width(image, height=DEFAULT_HEIGHT):
|
41 |
+
aspect_ratio = image.width / image.height
|
42 |
+
return height * aspect_ratio
|
43 |
+
|
44 |
+
def load_model(model_name):
|
45 |
+
if model_name not in MODELS:
|
46 |
+
MODELS[model_name] = Path(snapshot_download(model_name))
|
47 |
+
return MODELS[model_name]
|
48 |
+
|
49 |
+
def predict(model_name, input_img):
|
50 |
+
model_dir = load_model(model_name)
|
51 |
+
|
52 |
+
temperature = 2.0
|
53 |
+
batch_size = 1
|
54 |
+
|
55 |
+
weights_path = model_dir / "weights.ckpt"
|
56 |
+
syms_path = model_dir / "syms.txt"
|
57 |
+
language_model_params = {"language_model_weight": 1.0}
|
58 |
+
use_language_model = (model_dir / "tokens.txt").exists()
|
59 |
+
if use_language_model:
|
60 |
+
language_model_params.update(
|
61 |
+
{
|
62 |
+
"language_model_path": str(model_dir / "language_model.binary"),
|
63 |
+
"lexicon_path": str(model_dir / "lexicon.txt"),
|
64 |
+
"tokens_path": str(model_dir / "tokens.txt"),
|
65 |
+
}
|
66 |
+
)
|
67 |
+
|
68 |
+
common_args = CommonArgs(
|
69 |
+
checkpoint=str(weights_path.relative_to(model_dir)),
|
70 |
+
train_path=str(model_dir),
|
71 |
+
experiment_dirname="",
|
72 |
+
)
|
73 |
+
|
74 |
+
data_args = DataArgs(batch_size=batch_size, color_mode="L", num_workers=NUM_WORKERS)
|
75 |
+
trainer_args = TrainerArgs(progress_bar_refresh_rate=0)
|
76 |
+
decode_args = DecodeArgs(
|
77 |
+
include_img_ids=True,
|
78 |
+
join_string="",
|
79 |
+
convert_spaces=True,
|
80 |
+
print_line_confidence_scores=True,
|
81 |
+
print_word_confidence_scores=False,
|
82 |
+
temperature=temperature,
|
83 |
+
use_language_model=use_language_model,
|
84 |
+
**language_model_params,
|
85 |
+
)
|
86 |
+
|
87 |
+
with NamedTemporaryFile() as pred_stdout, NamedTemporaryFile() as img_list:
|
88 |
+
image_id = uuid4()
|
89 |
+
input_img = input_img.resize((int(get_width(input_img)), DEFAULT_HEIGHT))
|
90 |
+
input_img.save(f"{images}/{image_id}.jpg")
|
91 |
+
Path(img_list.name).write_text("\n".join([str(image_id)]))
|
92 |
+
|
93 |
+
with redirect_stdout(open(pred_stdout.name, mode="w")):
|
94 |
+
decode(
|
95 |
+
syms=str(syms_path),
|
96 |
+
img_list=img_list.name,
|
97 |
+
img_dirs=[str(images)],
|
98 |
+
common=common_args,
|
99 |
+
data=data_args,
|
100 |
+
trainer=trainer_args,
|
101 |
+
decode=decode_args,
|
102 |
+
num_workers=1,
|
103 |
+
)
|
104 |
+
sys.stdout.flush()
|
105 |
+
predictions = Path(pred_stdout.name).read_text().strip().splitlines()
|
106 |
+
|
107 |
+
_, score, text = LINE_PREDICTION.match(predictions[0]).groups()
|
108 |
+
if TEXT_DIRECTION == "RTL":
|
109 |
+
return input_img, {"text": get_display(text), "score": score}
|
110 |
+
else:
|
111 |
+
return input_img, {"text": text, "score": score}
|
112 |
+
|
113 |
+
def process_image(image):
|
114 |
+
# Perform inference on an image, select textline only
|
115 |
+
results = model(image, classes=1)
|
116 |
+
|
117 |
+
img_cv2 = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
|
118 |
+
boxes = results[0].boxes.xyxy.tolist()
|
119 |
+
boxes.sort(key=lambda x: x[1])
|
120 |
+
|
121 |
+
bboxes = []
|
122 |
+
polygons = []
|
123 |
+
texts = []
|
124 |
+
|
125 |
+
for i, box in enumerate(boxes):
|
126 |
+
x1, y1, x2, y2 = map(int, box)
|
127 |
+
crop_img = img_cv2[y1:y2, x1:x2]
|
128 |
+
crop_pil = Image.fromarray(cv2.cvtColor(crop_img, cv2.COLOR_BGR2RGB))
|
129 |
+
|
130 |
+
# Recognize text using PyLaia model
|
131 |
+
predicted = predict(models_name, crop_pil)
|
132 |
+
texts.append(predicted[1]["text"])
|
133 |
+
|
134 |
+
bboxes.append((x1, y1, x2, y2))
|
135 |
+
polygons.append(f"Line {i+1}: {[(x1, y1), (x2, y1), (x2, y2), (x1, y2)]}")
|
136 |
+
|
137 |
+
# Draw bounding box
|
138 |
+
cv2.rectangle(img_cv2, (x1, y1), (x2, y2), (0, 255, 0), 2)
|
139 |
+
|
140 |
+
# Convert image back to RGB for display in Streamlit
|
141 |
+
img_result = cv2.cvtColor(img_cv2, cv2.COLOR_BGR2RGB)
|
142 |
+
|
143 |
+
# Combine polygons and texts into a DataFrame for table display
|
144 |
+
table_data = pd.DataFrame({"Polygons": polygons, "Recognized Text": texts})
|
145 |
+
return Image.fromarray(img_result), table_data
|
146 |
+
|
147 |
+
def segment_and_recognize(image):
|
148 |
+
segmented_image, table_data = process_image(image)
|
149 |
+
return segmented_image, table_data
|
150 |
+
|
151 |
+
# Streamlit app layout
|
152 |
+
st.title("YOLOv8 Text Line Segmentation & PyLaia Text Recognition")
|
153 |
+
|
154 |
+
# File uploader
|
155 |
+
uploaded_image = st.file_uploader("Upload an image", type=["png", "jpg", "jpeg"])
|
156 |
+
|
157 |
+
# Process the image if uploaded
|
158 |
+
if uploaded_image is not None:
|
159 |
+
image = Image.open(uploaded_image)
|
160 |
+
|
161 |
+
if st.button("Segment and Recognize"):
|
162 |
+
# Perform segmentation and recognition
|
163 |
+
segmented_image, table_data = segment_and_recognize(image)
|
164 |
+
|
165 |
+
# Display the segmented image
|
166 |
+
st.image(segmented_image, caption="Segmented Image with Bounding Boxes", use_column_width=True)
|
167 |
+
|
168 |
+
# Display the table with polygons and recognized text
|
|
|
169 |
st.table(table_data)
|
model.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:02a10695831265b2821a267e5a239e78eeaae8e2865c57bf0c2c06cabe2e68be
|
3 |
+
size 54827221
|