Charles Kabui
commited on
Commit
·
4ce1f5f
1
Parent(s):
a7b5719
print('document_image_1.info.get(annotation_key) == True, end:', document_image_1.info.get(annotation_key) == True)
Browse files- analysis.ipynb +12 -17
- data/preview.ipynb +0 -0
- main.py +105 -37
- utils/get_features.py +0 -4
analysis.ipynb
CHANGED
@@ -11,18 +11,9 @@
|
|
11 |
},
|
12 |
{
|
13 |
"cell_type": "code",
|
14 |
-
"execution_count":
|
15 |
"metadata": {},
|
16 |
-
"outputs": [
|
17 |
-
{
|
18 |
-
"name": "stdout",
|
19 |
-
"output_type": "stream",
|
20 |
-
"text": [
|
21 |
-
"The autoreload extension is already loaded. To reload it, use:\n",
|
22 |
-
" %reload_ext autoreload\n"
|
23 |
-
]
|
24 |
-
}
|
25 |
-
],
|
26 |
"source": [
|
27 |
"%load_ext autoreload\n",
|
28 |
"%autoreload 2\n",
|
@@ -310,7 +301,7 @@
|
|
310 |
},
|
311 |
{
|
312 |
"cell_type": "code",
|
313 |
-
"execution_count":
|
314 |
"metadata": {},
|
315 |
"outputs": [
|
316 |
{
|
@@ -338,10 +329,14 @@
|
|
338 |
"name": "stdout",
|
339 |
"output_type": "stream",
|
340 |
"text": [
|
341 |
-
"
|
342 |
-
"
|
343 |
-
"
|
344 |
-
"
|
|
|
|
|
|
|
|
|
345 |
"Keyboard interruption in main thread... closing server.\n"
|
346 |
]
|
347 |
},
|
@@ -349,7 +344,7 @@
|
|
349 |
"data": {
|
350 |
"text/plain": []
|
351 |
},
|
352 |
-
"execution_count":
|
353 |
"metadata": {},
|
354 |
"output_type": "execute_result"
|
355 |
}
|
|
|
11 |
},
|
12 |
{
|
13 |
"cell_type": "code",
|
14 |
+
"execution_count": 1,
|
15 |
"metadata": {},
|
16 |
+
"outputs": [],
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
"source": [
|
18 |
"%load_ext autoreload\n",
|
19 |
"%autoreload 2\n",
|
|
|
301 |
},
|
302 |
{
|
303 |
"cell_type": "code",
|
304 |
+
"execution_count": 33,
|
305 |
"metadata": {},
|
306 |
"outputs": [
|
307 |
{
|
|
|
329 |
"name": "stdout",
|
330 |
"output_type": "stream",
|
331 |
"text": [
|
332 |
+
"{'predicted_bboxes': 'predicted_bboxes', 'predicted_scores': 'predicted_scores', 'predicted_labels': 'predicted_labels'}\n",
|
333 |
+
"document_image_1.info.get(annotation_key) == True, start: False\n",
|
334 |
+
"document_image_1.info.get(annotation_key) == True, middle: False\n",
|
335 |
+
"document_image_1.info.get(annotation_key) == True, end: True\n",
|
336 |
+
"{'predicted_bboxes': 'reduced_predicted_bboxes', 'predicted_scores': 'reduced_predicted_scores', 'predicted_labels': 'reduced_predicted_labels'}\n",
|
337 |
+
"document_image_1.info.get(annotation_key) == True, start: False\n",
|
338 |
+
"document_image_1.info.get(annotation_key) == True, middle: False\n",
|
339 |
+
"document_image_1.info.get(annotation_key) == True, end: True\n",
|
340 |
"Keyboard interruption in main thread... closing server.\n"
|
341 |
]
|
342 |
},
|
|
|
344 |
"data": {
|
345 |
"text/plain": []
|
346 |
},
|
347 |
+
"execution_count": 33,
|
348 |
"metadata": {},
|
349 |
"output_type": "execute_result"
|
350 |
}
|
data/preview.ipynb
CHANGED
The diff for this file is too large to render.
See raw diff
|
|
main.py
CHANGED
@@ -7,6 +7,7 @@ from PIL import Image
|
|
7 |
from utils.get_features import get_features
|
8 |
from imagehash import average_hash
|
9 |
from sklearn.metrics.pairwise import cosine_similarity
|
|
|
10 |
|
11 |
label_map = {0: 'Caption', 1: 'Footnote', 2: 'Formula', 3: 'List-item', 4: 'Page-footer', 5: 'Page-header', 6: 'Picture', 7: 'Section-header', 8: 'Table', 9: 'Text', 10: 'Title'}
|
12 |
label_names = list(label_map.values())
|
@@ -17,39 +18,96 @@ cache = {
|
|
17 |
'document_image_1_features': None,
|
18 |
'document_image_2_features': None,
|
19 |
}
|
20 |
-
pre_message_style = 'overflow:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
-
def similarity_fn(document_image_1: Image.Image, document_image_2: Image.Image,
|
23 |
message = None
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
try:
|
25 |
-
|
26 |
-
|
27 |
-
|
28 |
-
if document_image_1_hash == cache['document_image_1_hash']:
|
29 |
-
document_image_1_features = cache['document_image_1_features']
|
30 |
else:
|
31 |
-
|
32 |
-
|
33 |
-
cache['document_image_1_features'] = document_image_1_features
|
34 |
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
except Exception as e:
|
51 |
message = f'<pre style="{pre_message_style}">{traceback.format_exc()}<pre>'
|
52 |
-
return
|
|
|
|
|
|
|
|
|
|
|
53 |
|
54 |
def load_image(filename, page = 0):
|
55 |
try:
|
@@ -83,7 +141,7 @@ def document_view(document_number: int):
|
|
83 |
document = gr.Image(type="pil", label=f"Document {document_number}", visible=False)
|
84 |
document_error_message = gr.HTML(label="Error Message", visible=False)
|
85 |
document_preview = gr.UploadButton(
|
86 |
-
"
|
87 |
file_types=["image", ".pdf"],
|
88 |
file_count="single")
|
89 |
with gr.Tab("From URL", id=1):
|
@@ -114,7 +172,7 @@ def app(*, model_path, config_path, debug = False):
|
|
114 |
image { max-height="86vh" !important; }
|
115 |
.center { display: flex; flex: 1 1 auto; align-items: center; align-content: center; justify-content: center; justify-items: center; }
|
116 |
.hr { width: 100%; display: block; padding: 0; margin: 0; background: gray; height: 4px; border: none; }
|
117 |
-
|
118 |
with gr.Blocks(title=title, css=css) as app:
|
119 |
with gr.Row():
|
120 |
gr.HTML(value=description, elem_classes=['center'])
|
@@ -126,15 +184,25 @@ def app(*, model_path, config_path, debug = False):
|
|
126 |
gr.HTML('<hr/>', elem_classes=['hr'])
|
127 |
with gr.Row(elem_classes=['center']):
|
128 |
with gr.Column():
|
129 |
-
submit = gr.Button(value="Similarity", variant="primary")
|
130 |
-
reset = gr.Button(value="Reset", variant="secondary")
|
131 |
with gr.Column():
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
return app.launch(debug=debug)
|
|
|
7 |
from utils.get_features import get_features
|
8 |
from imagehash import average_hash
|
9 |
from sklearn.metrics.pairwise import cosine_similarity
|
10 |
+
from utils.visualize_bboxes_on_image import visualize_bboxes_on_image
|
11 |
|
12 |
label_map = {0: 'Caption', 1: 'Footnote', 2: 'Formula', 3: 'List-item', 4: 'Page-footer', 5: 'Page-header', 6: 'Picture', 7: 'Section-header', 8: 'Table', 9: 'Text', 10: 'Title'}
|
13 |
label_names = list(label_map.values())
|
|
|
18 |
'document_image_1_features': None,
|
19 |
'document_image_2_features': None,
|
20 |
}
|
21 |
+
pre_message_style = 'overflow:auto;border:2px solid pink;padding:4px;border-radius:4px;'
|
22 |
+
visualize_bboxes_on_image_kwargs = {
|
23 |
+
'label_text_color': 'white',
|
24 |
+
'label_rectangle_color': 'black',
|
25 |
+
'label_text_size': 12,
|
26 |
+
'label_text_padding': 3,
|
27 |
+
'label_rectangle_left_margin': 0,
|
28 |
+
'label_rectangle_top_margin': 0
|
29 |
+
}
|
30 |
+
vectors_types = ['vectors', 'weighted_vectors', 'reduced_vectors', 'reduced_weighted_vectors']
|
31 |
+
|
32 |
+
annotation_key = 'is_annotated_document_image'
|
33 |
+
annotation_original_image_key = 'original_image'
|
34 |
+
def annotate_document_image(document_image: Image.Image, original_document_image: Image.Image):
|
35 |
+
document_image.info.update({
|
36 |
+
annotation_key: True,
|
37 |
+
annotation_original_image_key: original_document_image
|
38 |
+
})
|
39 |
+
return document_image
|
40 |
+
|
41 |
+
def get_original_document_image(document_image: Image.Image):
|
42 |
+
if document_image.info.get(annotation_key) == True:
|
43 |
+
return document_image.info.get(annotation_original_image_key)
|
44 |
+
return document_image
|
45 |
|
46 |
+
def similarity_fn(model: lp.Detectron2LayoutModel, document_image_1: Image.Image, document_image_2: Image.Image, vectors_type: str):
|
47 |
message = None
|
48 |
+
annotations = {
|
49 |
+
'predicted_bboxes': 'predicted_bboxes' if vectors_type in ['vectors', 'weighted_vectors'] else 'reduced_predicted_bboxes',
|
50 |
+
'predicted_scores': 'predicted_scores' if vectors_type in ['vectors', 'weighted_vectors'] else 'reduced_predicted_scores',
|
51 |
+
'predicted_labels': 'predicted_labels' if vectors_type in ['vectors', 'weighted_vectors'] else 'reduced_predicted_labels',
|
52 |
+
}
|
53 |
+
show_vectors_type = False
|
54 |
try:
|
55 |
+
if document_image_1 is None or document_image_2 is None:
|
56 |
+
message = f'<pre style="{pre_message_style}">Please load both the documents to compare.<pre>'
|
|
|
|
|
|
|
57 |
else:
|
58 |
+
document_image_1 = get_original_document_image(document_image_1)
|
59 |
+
document_image_2 = get_original_document_image(document_image_2)
|
|
|
60 |
|
61 |
+
document_image_1_hash = str(average_hash(document_image_1))
|
62 |
+
document_image_2_hash = str(average_hash(document_image_2))
|
63 |
+
|
64 |
+
if document_image_1_hash == cache['document_image_1_hash']:
|
65 |
+
document_image_1_features = cache['document_image_1_features']
|
66 |
+
else:
|
67 |
+
document_image_1_features = get_features(document_image_1, model, label_names)
|
68 |
+
cache['document_image_1_hash'] = document_image_1_hash
|
69 |
+
cache['document_image_1_features'] = document_image_1_features
|
70 |
+
|
71 |
+
if document_image_2_hash == cache['document_image_2_hash']:
|
72 |
+
document_image_2_features = cache['document_image_2_features']
|
73 |
+
else:
|
74 |
+
document_image_2_features = get_features(document_image_2, model, label_names)
|
75 |
+
cache['document_image_2_hash'] = document_image_2_hash
|
76 |
+
cache['document_image_2_features'] = document_image_2_features
|
77 |
|
78 |
+
[[similarity]] = cosine_similarity(
|
79 |
+
[
|
80 |
+
cache['document_image_1_features'][vectors_type]
|
81 |
+
],
|
82 |
+
[
|
83 |
+
cache['document_image_2_features'][vectors_type]
|
84 |
+
])
|
85 |
+
message = f'<pre style="{pre_message_style}">Similarity between the two documents is: {round(similarity, 4)}<pre>'
|
86 |
+
annotated_document_image_1 = visualize_bboxes_on_image(
|
87 |
+
image = document_image_1,
|
88 |
+
bboxes = cache['document_image_1_features'][annotations['predicted_bboxes']],
|
89 |
+
titles = [f'{label}, score:{round(score, 2)}' for label, score in zip(
|
90 |
+
cache['document_image_1_features'][annotations['predicted_labels']],
|
91 |
+
cache['document_image_1_features'][annotations['predicted_scores']])],
|
92 |
+
**visualize_bboxes_on_image_kwargs)
|
93 |
+
annotated_document_image_2 = visualize_bboxes_on_image(
|
94 |
+
image = document_image_2,
|
95 |
+
bboxes = cache['document_image_2_features'][annotations['predicted_bboxes']],
|
96 |
+
titles = [f'{label}, score:{score}' for label, score in zip(
|
97 |
+
cache['document_image_2_features'][annotations['predicted_labels']],
|
98 |
+
cache['document_image_2_features'][annotations['predicted_scores']])],
|
99 |
+
**visualize_bboxes_on_image_kwargs)
|
100 |
+
show_vectors_type = True
|
101 |
+
document_image_1 = annotate_document_image(annotated_document_image_1, document_image_1)
|
102 |
+
document_image_2 = annotate_document_image(annotated_document_image_2, document_image_2)
|
103 |
except Exception as e:
|
104 |
message = f'<pre style="{pre_message_style}">{traceback.format_exc()}<pre>'
|
105 |
+
return [
|
106 |
+
gr.HTML(message, visible=True),
|
107 |
+
document_image_1,
|
108 |
+
document_image_2,
|
109 |
+
gr.Dropdown(visible=show_vectors_type)
|
110 |
+
]
|
111 |
|
112 |
def load_image(filename, page = 0):
|
113 |
try:
|
|
|
141 |
document = gr.Image(type="pil", label=f"Document {document_number}", visible=False)
|
142 |
document_error_message = gr.HTML(label="Error Message", visible=False)
|
143 |
document_preview = gr.UploadButton(
|
144 |
+
"Upload PDF or Document Image",
|
145 |
file_types=["image", ".pdf"],
|
146 |
file_count="single")
|
147 |
with gr.Tab("From URL", id=1):
|
|
|
172 |
image { max-height="86vh" !important; }
|
173 |
.center { display: flex; flex: 1 1 auto; align-items: center; align-content: center; justify-content: center; justify-items: center; }
|
174 |
.hr { width: 100%; display: block; padding: 0; margin: 0; background: gray; height: 4px; border: none; }
|
175 |
+
'''
|
176 |
with gr.Blocks(title=title, css=css) as app:
|
177 |
with gr.Row():
|
178 |
gr.HTML(value=description, elem_classes=['center'])
|
|
|
184 |
gr.HTML('<hr/>', elem_classes=['hr'])
|
185 |
with gr.Row(elem_classes=['center']):
|
186 |
with gr.Column():
|
187 |
+
submit = gr.Button(value="Get Similarity", variant="primary")
|
|
|
188 |
with gr.Column():
|
189 |
+
vectors_type = gr.Dropdown(
|
190 |
+
choices = vectors_types,
|
191 |
+
value = vectors_types[0],
|
192 |
+
visible = False,
|
193 |
+
label = "Vectors Type",
|
194 |
+
info = "Select the Vectors Type to use for Similarity Calculation")
|
195 |
+
similarity_output = gr.HTML(label="Similarity Score", visible=False)
|
196 |
+
reset = gr.Button(value="Reset", variant="secondary")
|
197 |
+
kwargs = {
|
198 |
+
'fn': lambda document_1_image, document_2_image, vectors_type: similarity_fn(
|
199 |
+
model,
|
200 |
+
document_1_image,
|
201 |
+
document_2_image,
|
202 |
+
vectors_type),
|
203 |
+
'inputs': [document_1_image, document_2_image, vectors_type],
|
204 |
+
'outputs': [similarity_output, document_1_image, document_2_image, vectors_type]
|
205 |
+
}
|
206 |
+
submit.click(**kwargs)
|
207 |
+
vectors_type.change(**kwargs)
|
208 |
return app.launch(debug=debug)
|
utils/get_features.py
CHANGED
@@ -31,10 +31,6 @@ def get_vectors(*,
|
|
31 |
'''
|
32 |
index_of_jaccard_index = jaccard_indexes.argmax() if not weighted_jaccard_index else np.multiply(jaccard_indexes, predicted_scores).argmax()
|
33 |
jaccard_index = jaccard_indexes[index_of_jaccard_index]
|
34 |
-
print(index_of_jaccard_index)
|
35 |
-
print(jaccard_index)
|
36 |
-
print(predicted_labels)
|
37 |
-
print(labels_nonce)
|
38 |
jaccard_index_bbox_label__nonce = labels_nonce[predicted_labels[index_of_jaccard_index]]
|
39 |
jaccard_index_bbox_score = predicted_scores[index_of_jaccard_index]
|
40 |
vector = region_nonce * jaccard_index * jaccard_index_bbox_label__nonce * jaccard_index_bbox_score
|
|
|
31 |
'''
|
32 |
index_of_jaccard_index = jaccard_indexes.argmax() if not weighted_jaccard_index else np.multiply(jaccard_indexes, predicted_scores).argmax()
|
33 |
jaccard_index = jaccard_indexes[index_of_jaccard_index]
|
|
|
|
|
|
|
|
|
34 |
jaccard_index_bbox_label__nonce = labels_nonce[predicted_labels[index_of_jaccard_index]]
|
35 |
jaccard_index_bbox_score = predicted_scores[index_of_jaccard_index]
|
36 |
vector = region_nonce * jaccard_index * jaccard_index_bbox_label__nonce * jaccard_index_bbox_score
|