mizoru commited on
Commit
cbb4b5a
1 Parent(s): 29abe75

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +195 -0
app.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import argparse
3
+ import io
4
+ from typing import List
5
+
6
+ import pypdfium2
7
+ import streamlit as st
8
+ from surya.detection import batch_text_detection
9
+ from surya.layout import batch_layout_detection
10
+ from surya.model.detection.segformer import load_model, load_processor
11
+ from surya.model.recognition.model import load_model as load_rec_model
12
+ from surya.model.recognition.processor import load_processor as load_rec_processor
13
+ from surya.model.ordering.processor import load_processor as load_order_processor
14
+ from surya.model.ordering.model import load_model as load_order_model
15
+ from surya.ordering import batch_ordering
16
+ from surya.postprocessing.heatmap import draw_polys_on_image
17
+ from surya.ocr import run_ocr
18
+ from surya.postprocessing.text import draw_text_on_image
19
+ from PIL import Image
20
+ from surya.languages import CODE_TO_LANGUAGE
21
+ from surya.input.langs import replace_lang_with_code
22
+ from surya.schema import OCRResult, TextDetectionResult, LayoutResult, OrderResult
23
+ from surya.settings import settings
24
+
25
+ parser = argparse.ArgumentParser(description="Run OCR on an image or PDF.")
26
+ parser.add_argument("--math", action="store_true", help="Use math model for detection", default=False)
27
+
28
+ try:
29
+ args = parser.parse_args()
30
+ except SystemExit as e:
31
+ print(f"Error parsing arguments: {e}")
32
+ os._exit(e.code)
33
+
34
+ @st.cache_resource()
35
+ def load_det_cached():
36
+ checkpoint = settings.DETECTOR_MATH_MODEL_CHECKPOINT if args.math else settings.DETECTOR_MODEL_CHECKPOINT
37
+ return load_model(checkpoint=checkpoint), load_processor(checkpoint=checkpoint)
38
+
39
+
40
+ @st.cache_resource()
41
+ def load_rec_cached():
42
+ return load_rec_model(), load_rec_processor()
43
+
44
+
45
+ @st.cache_resource()
46
+ def load_layout_cached():
47
+ return load_model(checkpoint=settings.LAYOUT_MODEL_CHECKPOINT), load_processor(checkpoint=settings.LAYOUT_MODEL_CHECKPOINT)
48
+
49
+ @st.cache_resource()
50
+ def load_order_cached():
51
+ return load_order_model(), load_order_processor()
52
+
53
+
54
+ def text_detection(img) -> (Image.Image, TextDetectionResult):
55
+ pred = batch_text_detection([img], det_model, det_processor)[0]
56
+ polygons = [p.polygon for p in pred.bboxes]
57
+ det_img = draw_polys_on_image(polygons, img.copy())
58
+ return det_img, pred
59
+
60
+
61
+ def layout_detection(img) -> (Image.Image, LayoutResult):
62
+ _, det_pred = text_detection(img)
63
+ pred = batch_layout_detection([img], layout_model, layout_processor, [det_pred])[0]
64
+ polygons = [p.polygon for p in pred.bboxes]
65
+ labels = [p.label for p in pred.bboxes]
66
+ layout_img = draw_polys_on_image(polygons, img.copy(), labels=labels)
67
+ return layout_img, pred
68
+
69
+
70
+ def order_detection(img) -> (Image.Image, OrderResult):
71
+ _, layout_pred = layout_detection(img)
72
+ bboxes = [l.bbox for l in layout_pred.bboxes]
73
+ pred = batch_ordering([img], [bboxes], order_model, order_processor)[0]
74
+ polys = [l.polygon for l in pred.bboxes]
75
+ positions = [str(l.position) for l in pred.bboxes]
76
+ order_img = draw_polys_on_image(polys, img.copy(), labels=positions, label_font_size=20)
77
+ return order_img, pred
78
+
79
+
80
+ # Function for OCR
81
+ def ocr(img, langs: List[str]) -> (Image.Image, OCRResult):
82
+ replace_lang_with_code(langs)
83
+ img_pred = run_ocr([img], [langs], det_model, det_processor, rec_model, rec_processor)[0]
84
+
85
+ bboxes = [l.bbox for l in img_pred.text_lines]
86
+ text = [l.text for l in img_pred.text_lines]
87
+ rec_img = draw_text_on_image(bboxes, text, img.size, langs, has_math="_math" in langs)
88
+ return rec_img, img_pred
89
+
90
+
91
+ def open_pdf(pdf_file):
92
+ stream = io.BytesIO(pdf_file.getvalue())
93
+ return pypdfium2.PdfDocument(stream)
94
+
95
+
96
+ @st.cache_data()
97
+ def get_page_image(pdf_file, page_num, dpi=96):
98
+ doc = open_pdf(pdf_file)
99
+ renderer = doc.render(
100
+ pypdfium2.PdfBitmap.to_pil,
101
+ page_indices=[page_num - 1],
102
+ scale=dpi / 72,
103
+ )
104
+ png = list(renderer)[0]
105
+ png_image = png.convert("RGB")
106
+ return png_image
107
+
108
+
109
+ @st.cache_data()
110
+ def page_count(pdf_file):
111
+ doc = open_pdf(pdf_file)
112
+ return len(doc)
113
+
114
+
115
+ st.set_page_config(layout="wide")
116
+ col1, col2 = st.columns([.5, .5])
117
+
118
+ det_model, det_processor = load_det_cached()
119
+ rec_model, rec_processor = load_rec_cached()
120
+ layout_model, layout_processor = load_layout_cached()
121
+ order_model, order_processor = load_order_cached()
122
+
123
+
124
+ st.markdown("""
125
+ # Surya OCR Demo
126
+
127
+ This app will let you try surya, a multilingual OCR model. It supports text detection + layout analysis in any language, and text recognition in 90+ languages.
128
+
129
+ Notes:
130
+ - This works best on documents with printed text.
131
+ - Preprocessing the image (e.g. increasing contrast) can improve results.
132
+ - If OCR doesn't work, try changing the resolution of your image (increase if below 2048px width, otherwise decrease).
133
+ - This supports 90+ languages, see [here](https://github.com/VikParuchuri/surya/tree/master/surya/languages.py) for a full list.
134
+
135
+ Find the project [here](https://github.com/VikParuchuri/surya).
136
+ """)
137
+
138
+ in_file = st.sidebar.file_uploader("PDF file or image:", type=["pdf", "png", "jpg", "jpeg", "gif", "webp"])
139
+ languages = st.sidebar.multiselect("Languages", sorted(list(CODE_TO_LANGUAGE.values())), default=["English"], max_selections=4)
140
+
141
+ if in_file is None:
142
+ st.stop()
143
+
144
+ filetype = in_file.type
145
+ whole_image = False
146
+ if "pdf" in filetype:
147
+ page_count = page_count(in_file)
148
+ page_number = st.sidebar.number_input(f"Page number out of {page_count}:", min_value=1, value=1, max_value=page_count)
149
+
150
+ pil_image = get_page_image(in_file, page_number)
151
+ else:
152
+ pil_image = Image.open(in_file).convert("RGB")
153
+
154
+ text_det = st.sidebar.button("Run Text Detection")
155
+ text_rec = st.sidebar.button("Run OCR")
156
+ layout_det = st.sidebar.button("Run Layout Analysis")
157
+ order_det = st.sidebar.button("Run Reading Order")
158
+
159
+ if pil_image is None:
160
+ st.stop()
161
+
162
+ # Run Text Detection
163
+ if text_det:
164
+ det_img, pred = text_detection(pil_image)
165
+ with col1:
166
+ st.image(det_img, caption="Detected Text", use_column_width=True)
167
+ st.json(pred.model_dump(exclude=["heatmap", "affinity_map"]), expanded=True)
168
+
169
+
170
+ # Run layout
171
+ if layout_det:
172
+ layout_img, pred = layout_detection(pil_image)
173
+ with col1:
174
+ st.image(layout_img, caption="Detected Layout", use_column_width=True)
175
+ st.json(pred.model_dump(exclude=["segmentation_map"]), expanded=True)
176
+
177
+ # Run OCR
178
+ if text_rec:
179
+ rec_img, pred = ocr(pil_image, languages)
180
+ with col1:
181
+ st.image(rec_img, caption="OCR Result", use_column_width=True)
182
+ json_tab, text_tab = st.tabs(["JSON", "Text Lines (for debugging)"])
183
+ with json_tab:
184
+ st.json(pred.model_dump(), expanded=True)
185
+ with text_tab:
186
+ st.text("\n".join([p.text for p in pred.text_lines]))
187
+
188
+ if order_det:
189
+ order_img, pred = order_detection(pil_image)
190
+ with col1:
191
+ st.image(order_img, caption="Reading Order", use_column_width=True)
192
+ st.json(pred.model_dump(), expanded=True)
193
+
194
+ with col2:
195
+ st.image(pil_image, caption="Uploaded Image", use_column_width=True)