mckabue commited on
Commit
50bee63
·
verified ·
1 Parent(s): b736379

RE_UPLOAD-REBUILD-RESTART

Browse files
Files changed (1) hide show
  1. main.py +243 -0
main.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import traceback
2
+ import gradio as gr
3
+ from utils.get_RGB_image import get_RGB_image, is_online_file, steam_online_file
4
+ import layoutparser as lp
5
+ from PIL import Image
6
+ from utils.get_features import get_features
7
+ from imagehash import average_hash
8
+ from sklearn.metrics.pairwise import cosine_similarity
9
+ from utils.visualize_bboxes_on_image import visualize_bboxes_on_image
10
+ import fitz
11
+
12
+ label_map = {0: 'Caption', 1: 'Footnote', 2: 'Formula', 3: 'List-item', 4: 'Page-footer',
13
+ 5: 'Page-header', 6: 'Picture', 7: 'Section-header', 8: 'Table', 9: 'Text', 10: 'Title'}
14
+ label_names = list(label_map.values())
15
+ color_map = {'Caption': '#FF0000', 'Footnote': '#00FF00', 'Formula': '#0000FF', 'List-item': '#FF00FF', 'Page-footer': '#FFFF00',
16
+ 'Page-header': '#000000', 'Picture': '#FFFFFF', 'Section-header': '#40E0D0', 'Table': '#F28030', 'Text': '#7F00FF', 'Title': '#C0C0C0'}
17
+ cache = {
18
+ 'output_document_image_1_hash': None,
19
+ 'output_document_image_2_hash': None,
20
+ 'document_image_1_features': None,
21
+ 'document_image_2_features': None,
22
+ 'original_document_image_1': None,
23
+ 'original_document_image_2': None
24
+ }
25
+ pre_message_style = 'border:2px solid pink;padding:4px;border-radius:4px;font-size: 16px;font-weight: 700;background-image: linear-gradient(to bottom right, #e0e619, #ffffff, #FF77CC, rgb(255, 122, 89));'
26
+ visualize_bboxes_on_image_kwargs = {
27
+ 'label_text_color': 'white',
28
+ 'label_fill_color': 'black',
29
+ 'label_text_size': 12,
30
+ 'label_text_padding': 3,
31
+ 'label_rectangle_left_margin': 0,
32
+ 'label_rectangle_top_margin': 0
33
+ }
34
+ vectors_types = ['vectors', 'weighted_vectors',
35
+ 'reduced_vectors', 'reduced_weighted_vectors']
36
+
37
+
38
+ def similarity_fn(model: lp.Detectron2LayoutModel, document_image_1: Image.Image, document_image_2: Image.Image, vectors_type: str):
39
+ message = None
40
+ annotations = {
41
+ 'predicted_bboxes': 'predicted_bboxes' if vectors_type in ['vectors', 'weighted_vectors'] else 'reduced_predicted_bboxes',
42
+ 'predicted_scores': 'predicted_scores' if vectors_type in ['vectors', 'weighted_vectors'] else 'reduced_predicted_scores',
43
+ 'predicted_labels': 'predicted_labels' if vectors_type in ['vectors', 'weighted_vectors'] else 'reduced_predicted_labels',
44
+ }
45
+ show_vectors_type = False
46
+ try:
47
+ if document_image_1 is None or document_image_2 is None:
48
+ message = 'Please load both the documents to compare.'
49
+ gr.Info(message)
50
+ else:
51
+ input_document_image_1_hash = str(average_hash(document_image_1))
52
+ input_document_image_2_hash = str(average_hash(document_image_2))
53
+
54
+ if input_document_image_1_hash == cache['output_document_image_1_hash']:
55
+ document_image_1_features = cache['document_image_1_features']
56
+ document_image_1 = cache['original_document_image_1']
57
+ else:
58
+ gr.Info('Generating features for document 1')
59
+ document_image_1_features = get_features(
60
+ document_image_1, model, label_names)
61
+ cache['document_image_1_features'] = document_image_1_features
62
+ cache['original_document_image_1'] = document_image_1
63
+
64
+ if input_document_image_2_hash == cache['output_document_image_2_hash']:
65
+ document_image_2_features = cache['document_image_2_features']
66
+ document_image_2 = cache['original_document_image_2']
67
+ else:
68
+ gr.Info('Generating features for document 2')
69
+ document_image_2_features = get_features(
70
+ document_image_2, model, label_names)
71
+ cache['document_image_2_features'] = document_image_2_features
72
+ cache['original_document_image_2'] = document_image_2
73
+
74
+ gr.Info('Calculating similarity')
75
+ [[similarity]] = cosine_similarity(
76
+ [
77
+ cache['document_image_1_features'][vectors_type]
78
+ ],
79
+ [
80
+ cache['document_image_2_features'][vectors_type]
81
+ ])
82
+ message = f'Similarity between the two documents is: {round(similarity, 4)}'
83
+ gr.Info(message)
84
+ gr.Info('Visualizing the bounding boxes for the predicted layout elements on the documents.')
85
+ document_image_1 = visualize_bboxes_on_image(
86
+ image=document_image_1,
87
+ bboxes=cache['document_image_1_features'][annotations['predicted_bboxes']],
88
+ labels=[f'{label}, score:{round(score, 2)}' for label, score in zip(
89
+ cache['document_image_1_features'][annotations['predicted_labels']],
90
+ cache['document_image_1_features'][annotations['predicted_scores']])],
91
+ bbox_outline_color=[
92
+ color_map[label] for label in cache['document_image_1_features'][annotations['predicted_labels']]],
93
+ bbox_fill_color=[
94
+ (color_map[label], 50) for label in cache['document_image_1_features'][annotations['predicted_labels']]],
95
+ **visualize_bboxes_on_image_kwargs)
96
+ document_image_2 = visualize_bboxes_on_image(
97
+ image=document_image_2,
98
+ bboxes=cache['document_image_2_features'][annotations['predicted_bboxes']],
99
+ labels=[f'{label}, score:{round(score, 2)}' for label, score in zip(
100
+ cache['document_image_2_features'][annotations['predicted_labels']],
101
+ cache['document_image_2_features'][annotations['predicted_scores']])],
102
+ bbox_outline_color=[
103
+ color_map[label] for label in cache['document_image_2_features'][annotations['predicted_labels']]],
104
+ bbox_fill_color=[
105
+ (color_map[label], 50) for label in cache['document_image_2_features'][annotations['predicted_labels']]],
106
+ **visualize_bboxes_on_image_kwargs)
107
+
108
+ cache['output_document_image_1_hash'] = str(
109
+ average_hash(document_image_1))
110
+ cache['output_document_image_2_hash'] = str(
111
+ average_hash(document_image_2))
112
+
113
+ show_vectors_type = True
114
+ except Exception as e:
115
+ message = f'<pre style="overflow:auto;">{traceback.format_exc()}</pre>'
116
+ gr.Info(message)
117
+ return [
118
+ gr.HTML(f'<div style="{pre_message_style}">{message}</div>', visible=True),
119
+ document_image_1,
120
+ document_image_2,
121
+ gr.Dropdown(visible=show_vectors_type)
122
+ ]
123
+
124
+
125
+ def load_image(filename, page=0):
126
+ try:
127
+ image = None
128
+ first_error = None
129
+ try:
130
+ if (is_online_file(filename)):
131
+ pixmap = fitz.open("pdf", steam_online_file(filename))[page].get_pixmap()
132
+ else:
133
+ pixmap = fitz.open(filename)[page].get_pixmap()
134
+ image = Image.frombytes("RGB", [pixmap.width, pixmap.height], pixmap.samples)
135
+ except Exception as e:
136
+ first_error = e
137
+ image = get_RGB_image(filename)
138
+ return [
139
+ image,
140
+ None
141
+ ]
142
+ except Exception as second_error:
143
+ error = f'{traceback.format_exc()}\n\nFirst Error:\n{first_error}\n\nSecond Error:\n{second_error}'
144
+ return [None, gr.HTML(value=error, visible=True)]
145
+
146
+
147
+ def preview_url(url, page=0):
148
+ [image, error] = load_image(url, page=page)
149
+ if image:
150
+ return [gr.Tabs(selected=0), image, error]
151
+ else:
152
+ return [gr.Tabs(selected=1), image, error]
153
+
154
+
155
+ def document_view(document_number: int, examples: list[str] = []):
156
+ gr.HTML(value=f'<h4>Load the {"first" if document_number == 1 else "second"} PDF or Document Image</h4>', elem_classes=[
157
+ 'center'])
158
+ gr.HTML(value=f'<p>Click the button below to upload Upload PDF or Document Image or cleck the URL tab to add using link.</p>', elem_classes=[
159
+ 'center'])
160
+ with gr.Tabs() as document_tabs:
161
+ with gr.Tab("From Image", id=0):
162
+ document = gr.Image(
163
+ type="pil", label=f"Document {document_number}", visible=False, interactive=False, show_download_button=True)
164
+ document_error_message = gr.HTML(
165
+ label="Error Message", visible=False)
166
+ document_preview = gr.UploadButton(
167
+ label="Upload PDF or Document Image",
168
+ file_types=["image", ".pdf"],
169
+ file_count="single")
170
+ with gr.Tab("From URL", id=1):
171
+ document_url = gr.Textbox(
172
+ label=f"Document {document_number} URL",
173
+ info="Paste a Link/URL to PDF or Document Image",
174
+ placeholder="https://datasets-server.huggingface.co/.../image.jpg")
175
+ document_url_error_message = gr.HTML(
176
+ label="Error Message", visible=False)
177
+ document_url_preview = gr.Button(
178
+ value="Preview Link Document", variant="secondary")
179
+ if len(examples) > 0:
180
+ gr.Examples(
181
+ examples=examples,
182
+ inputs=document,
183
+ label='Select any of these test document images')
184
+ document_preview.upload(
185
+ fn=lambda file: load_image(file.name),
186
+ inputs=[document_preview],
187
+ outputs=[document, document_error_message])
188
+ document_url_preview.click(
189
+ fn=preview_url,
190
+ inputs=[document_url],
191
+ outputs=[document_tabs, document, document_url_error_message])
192
+ document.change(
193
+ fn = lambda image: gr.Image(value=image, visible=True) if image else gr.Image(value=None, visible=False),
194
+ inputs = [document],
195
+ outputs = [document])
196
+ return document
197
+
198
+
199
+ def app(*, model_path:str, config_path:str, examples: list[str], debug=False):
200
+ model: lp.Detectron2LayoutModel = lp.Detectron2LayoutModel(
201
+ config_path=config_path,
202
+ model_path=model_path,
203
+ label_map=label_map)
204
+ title = 'Document Similarity Search Using Visual Layout Features'
205
+ description = f"<h2>{title}<h2>"
206
+ css = '''
207
+ image { max-height="86vh" !important; }
208
+ .center { display: flex; flex: 1 1 auto; align-items: center; align-content: center; justify-content: center; justify-items: center; }
209
+ .hr { width: 100%; display: block; padding: 0; margin: 0; background: gray; height: 4px; border: none; }
210
+ '''
211
+ with gr.Blocks(title=title, css=css) as interface:
212
+ with gr.Row():
213
+ gr.HTML(value=description, elem_classes=['center'])
214
+ with gr.Row(equal_height=False):
215
+ with gr.Column():
216
+ document_1_image = document_view(1, examples)
217
+ with gr.Column():
218
+ document_2_image = document_view(2, examples)
219
+ gr.HTML('<hr/>', elem_classes=['hr'])
220
+ with gr.Row(elem_classes=['center']):
221
+ with gr.Column():
222
+ submit = gr.Button(value="Get Similarity", variant="primary")
223
+ with gr.Column():
224
+ vectors_type = gr.Dropdown(
225
+ choices=vectors_types,
226
+ value=vectors_types[0],
227
+ visible=False,
228
+ label="Vectors Type",
229
+ info="Select the Vectors Type to use for Similarity Calculation")
230
+ similarity_output = gr.HTML(
231
+ label="Similarity Score", visible=False)
232
+ kwargs = {
233
+ 'fn': lambda document_1_image, document_2_image, vectors_type: similarity_fn(
234
+ model,
235
+ document_1_image,
236
+ document_2_image,
237
+ vectors_type),
238
+ 'inputs': [document_1_image, document_2_image, vectors_type],
239
+ 'outputs': [similarity_output, document_1_image, document_2_image, vectors_type]
240
+ }
241
+ submit.click(**kwargs)
242
+ vectors_type.change(**kwargs)
243
+ return interface.launch(debug=debug)