File size: 14,035 Bytes
bc12901
 
 
 
2359223
e62060d
 
2359223
253dc57
ab36703
bc12901
8bd074d
2359223
6c169ec
bc6a638
bc12901
 
 
 
 
 
 
bc6a638
225fcc2
2af0878
225fcc2
 
2359223
 
225fcc2
8bd074d
2359223
 
 
 
8171e8e
8bd074d
2359223
8171e8e
 
bc6a638
225fcc2
8bd074d
225fcc2
1af0b6d
 
 
 
87500f1
 
1af0b6d
 
fcfd908
1af0b6d
 
 
 
0b2b653
 
1af0b6d
 
 
fcfd908
 
 
 
 
 
 
 
bc12901
bc6a638
2af0878
2359223
87a4fef
 
2359223
 
47b5f74
87a4fef
2359223
 
47b5f74
87a4fef
2359223
 
bc6a638
47b5f74
3797c49
 
47b5f74
2af0878
3797c49
 
 
2af0878
 
 
d6edad9
 
3441721
 
 
 
 
2af0878
3441721
 
47b5f74
 
e38e364
 
d229b67
253dc57
 
d703b38
253dc57
 
d703b38
253dc57
d703b38
 
253dc57
d703b38
 
 
 
 
 
 
 
 
253dc57
d703b38
 
 
 
98e826c
d703b38
 
 
98e826c
b3797a3
d703b38
2359223
 
 
b3797a3
e62060d
b3797a3
bc6a638
253dc57
87ad231
d703b38
98e826c
 
225fcc2
bc6a638
0b2b653
bc6a638
 
2af0878
47b5f74
2af0878
 
 
 
 
 
 
 
 
 
 
253dc57
 
 
418105e
 
 
 
2f6c963
418105e
bc6a638
d1e1ea7
253dc57
 
 
 
98e826c
 
194858a
418105e
194858a
253dc57
 
 
15fad86
2359223
 
253dc57
2af0878
47c4130
2af0878
47c4130
2af0878
253dc57
47b5f74
 
 
 
 
 
2af0878
47b5f74
2af0878
 
47c4130
 
2af0878
 
 
8b77290
2af0878
 
 
98e826c
253dc57
d207d63
2af0878
 
e38e364
2af0878
d703b38
253dc57
2359223
 
27d0a44
d207d63
 
 
253dc57
d207d63
 
27d0a44
 
 
d207d63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a4d71f
d207d63
37a2f41
d207d63
 
 
 
 
 
 
 
 
 
27d0a44
37a2f41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3a4d71f
 
 
 
 
 
 
 
 
42081d7
 
 
 
 
 
 
 
 
 
 
b3797a3
 
 
 
3410d4d
 
 
 
 
 
27d0a44
 
 
883c3a9
d207d63
36034c6
 
2af0878
 
 
 
 
 
d207d63
 
2359223
253dc57
2359223
 
 
 
 
d207d63
3410d4d
d207d63
 
 
 
 
b3797a3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d207d63
4472e08
d207d63
2af0878
d207d63
27d0a44
2359223
d207d63
3410d4d
253dc57
 
 
418105e
 
3410d4d
253dc57
 
 
3410d4d
253dc57
d207d63
 
 
 
d703b38
d207d63
2359223
3410d4d
d207d63
253dc57
 
 
 
 
 
 
 
 
d207d63
253dc57
d207d63
3441721
 
 
 
253dc57
 
98e826c
3410d4d
47b5f74
 
3441721
 
 
 
 
 
 
 
 
 
98e826c
3441721
47b5f74
 
3441721
 
 
 
 
 
 
 
253dc57
 
 
 
 
 
 
 
 
 
3441721
 
98e826c
253dc57
3441721
d703b38
3441721
 
98e826c
253dc57
3441721
2359223
418105e
 
 
 
 
 
3441721
418105e
 
 
 
 
d229b67
2359223
 
98e826c
253dc57
177edb5
2359223
 
e62060d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
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
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
import os

os.environ["TOKENIZERS_PARALLELISM"] = "false"

from PIL import Image, ImageDraw
import traceback

import gradio as gr
from gradio import processing_utils

import torch
from docquery import pipeline
from docquery.document import load_bytes, load_document, ImageDocument
from docquery.ocr_reader import get_ocr_reader


def ensure_list(x):
    if isinstance(x, list):
        return x
    else:
        return [x]


CHECKPOINTS = {
    "LayoutLMv1 for Invoices 🧾": "impira/layoutlm-invoices",
}

PIPELINES = {}


def construct_pipeline(task, model):
    global PIPELINES
    if model in PIPELINES:
        return PIPELINES[model]

    device = "cuda" if torch.cuda.is_available() else "cpu"
    ret = pipeline(task=task, model=CHECKPOINTS[model], device=device)
    PIPELINES[model] = ret
    return ret


def run_pipeline(model, question, document, top_k):
    pipeline = construct_pipeline("document-question-answering", model)
    return pipeline(question=question, **document.context, top_k=top_k)


# TODO: Move into docquery
# TODO: Support words past the first page (or window?)
def lift_word_boxes(document, page):
    return document.context["image"][page][1]


def expand_bbox(word_boxes):
    if len(word_boxes) == 0:
        return None

    min_x, min_y, max_x, max_y = zip(*[x[1] for x in word_boxes])
    min_x, min_y, max_x, max_y = [min(min_x), min(min_y), max(max_x), max(max_y)]
    return [min_x, min_y, max_x, max_y]


# LayoutLM boxes are normalized to 0, 1000
def normalize_bbox(box, width, height, padding=0.005):
    min_x, min_y, max_x, max_y = [c / 1000 for c in box]
    if padding != 0:
        min_x = max(0, min_x - padding)
        min_y = max(0, min_y - padding)
        max_x = min(max_x + padding, 1)
        max_y = min(max_y + padding, 1)
    return [min_x * width, min_y * height, max_x * width, max_y * height]


EXAMPLES = [
    [
        "acze_tech.png",
        "Tech Invoice",
    ],
    [
        "acze.png",
        "Commercial Goods Invoice",
    ],
    [
        "north_sea.png",
        "Energy Invoice",
    ],
]

QUESTION_FILES = {
    "Tech Invoice": "acze_tech.pdf",
    "Energy Invoice": "north_sea.pdf",
}

for q in QUESTION_FILES.keys():
    assert any(x[1] == q for x in EXAMPLES)

FIELDS = {
    "Vendor Name": ["Vendor Name - Logo?", "Vendor Name - Address?"],
    "Vendor Address": ["Vendor Address?"],
    "Customer Name": ["Customer Name?"],
    "Customer Address": ["Customer Address?"],
    "Invoice Number": ["Invoice Number?"],
    "Invoice Date": ["Invoice Date?"],
    "Due Date": ["Due Date?"],
    "Subtotal": ["Subtotal?"],
    "Total Tax": ["Total Tax?"],
    "Invoice Total": ["Invoice Total?"],
    "Amount Due": ["Amount Due?"],
    "Payment Terms": ["Payment Terms?"],
    "Remit To Name": ["Remit To Name?"],
    "Remit To Address": ["Remit To Address?"],
}


def empty_table(fields):
    return {"value": [[name, None] for name in fields.keys()], "interactive": False}


def process_document(document, fields, model, error=None):
    if document is not None and error is None:
        preview, json_output, table = process_fields(document, fields, model)
        return (
            document,
            fields,
            preview,
            gr.update(visible=True),
            gr.update(visible=False, value=None),
            json_output,
            table,
        )
    else:
        return (
            None,
            fields,
            None,
            gr.update(visible=False),
            gr.update(visible=True, value=error) if error is not None else None,
            None,
            gr.update(**empty_table(fields)),
        )


def process_path(path, fields, model):
    error = None
    document = None
    if path:
        try:
            document = load_document(path)
        except Exception as e:
            traceback.print_exc()
            error = str(e)

    return process_document(document, fields, model, error)


def process_upload(file, fields, model):
    return process_path(file.name if file else None, fields, model)


colors = ["#64A087", "green", "black"]


def annotate_page(prediction, pages, document):
    if prediction is not None and "word_ids" in prediction:
        image = pages[prediction["page"]]
        draw = ImageDraw.Draw(image, "RGBA")
        word_boxes = lift_word_boxes(document, prediction["page"])
        x1, y1, x2, y2 = normalize_bbox(
            expand_bbox([word_boxes[i] for i in prediction["word_ids"]]),
            image.width,
            image.height,
        )
        draw.rectangle(((x1, y1), (x2, y2)), fill=(0, 255, 0, int(0.4 * 255)))


def process_question(
    question, document, img_gallery, model, fields, output, output_table
):
    field_name = question
    if field_name is not None:
        fields = {field_name: [question], **fields}

    if not question or document is None:
        return None, document, fields, output, gr.update(value=output_table)

    text_value = None
    pages = [processing_utils.decode_base64_to_image(p) for p in img_gallery]
    prediction = run_pipeline(model, question, document, 1)
    annotate_page(prediction, pages, document)

    output = {field_name: prediction, **output}
    table = [[field_name, prediction.get("answer")]] + output_table.values.tolist()
    return (
        None,
        gr.update(visible=True, value=pages),
        fields,
        output,
        gr.update(value=table, interactive=False),
    )


def process_fields(document, fields, model=list(CHECKPOINTS.keys())[0]):
    pages = [x.copy().convert("RGB") for x in document.preview]

    ret = {}
    table = []

    for (field_name, questions) in fields.items():
        answers = [
            a
            for q in questions
            for a in ensure_list(run_pipeline(model, q, document, top_k=1))
            if a.get("score", 1) > 0.5
        ]
        answers.sort(key=lambda x: -x.get("score", 0) if x else 0)
        top = answers[0] if len(answers) > 0 else None
        annotate_page(top, pages, document)
        ret[field_name] = top
        table.append([field_name, top.get("answer") if top is not None else None])

    return (
        gr.update(visible=True, value=pages),
        gr.update(visible=True, value=ret),
        table
    )


def load_example_document(img, title, fields, model):
    document = None
    if img is not None:
        if title in QUESTION_FILES:
            document = load_document(QUESTION_FILES[title])
        else:
            document = ImageDocument(Image.fromarray(img), ocr_reader=get_ocr_reader())

    return process_document(document, fields, model)


CSS = """
#question input {
    font-size: 16px;
}
#url-textbox, #question-textbox {
    padding: 0 !important;
}
#short-upload-box .w-full {
    min-height: 10rem !important;
}
/* I think something like this can be used to re-shape
 * the table
 */
/*
.gr-samples-table tr {
    display: inline;
}
.gr-samples-table .p-2 {
    width: 100px;
}
*/
#select-a-file {
    width: 100%;
}
#file-clear {
    padding-top: 2px !important;
    padding-bottom: 2px !important;
    padding-left: 8px !important;
    padding-right: 8px !important;
	margin-top: 10px;
}
.gradio-container .gr-button-primary {
    background: linear-gradient(180deg, #CDF9BE 0%, #AFF497 100%);
    border: 1px solid #B0DCCC;
    border-radius: 8px;
    color: #1B8700;
}
.gradio-container.dark button#submit-button {
    background: linear-gradient(180deg, #CDF9BE 0%, #AFF497 100%);
    border: 1px solid #B0DCCC;
    border-radius: 8px;
    color: #1B8700
}

table.gr-samples-table tr td {
    border: none;
    outline: none;
}

table.gr-samples-table tr td:first-of-type {
    width: 0%;
}

div#short-upload-box div.absolute {
    display: none !important;
}

gradio-app > div > div > div > div.w-full > div, .gradio-app > div > div > div > div.w-full > div {
    gap: 0px 2%;
}

gradio-app div div div div.w-full, .gradio-app div div div div.w-full {
    gap: 0px;
}

gradio-app h2, .gradio-app h2 {
    padding-top: 10px;
}

#answer {
    overflow-y: scroll;
    color: white;
    background: #666;
    border-color: #666;
    font-size: 20px;
    font-weight: bold;
}

#answer span {
    color: white;
}

#answer textarea {
    color:white;
    background: #777;
    border-color: #777;
    font-size: 18px;
}

#url-error input {
    color: red;
}

#results-table {
    max-height: 600px;
    overflow-y: scroll;
}

"""

with gr.Blocks(css=CSS) as demo:
    gr.Markdown("# DocQuery for Invoices")
    gr.Markdown(
        "DocQuery (created by [Impira](https://impira.com?utm_source=huggingface&utm_medium=referral&utm_campaign=invoices_space))"
        " uses LayoutLMv1 fine-tuned on an invoice dataset"
        " as well as DocVQA and SQuAD, which boot its general comprehension skills. The model is an enhanced"
        " QA architecture that supports selecting blocks of text which may be non-consecutive, which is a major"
        " issue when dealing with invoice documents (e.g. addresses)."
        " To use it, simply upload an image or PDF invoice and the model will predict values for several fields."
        " You can also create additional fields by simply typing in a question."
        " DocQuery is available on [Github](https://github.com/impira/docquery)."
    )

    document = gr.Variable()
    fields = gr.Variable(value={**FIELDS})
    example_question = gr.Textbox(visible=False)
    example_image = gr.Image(visible=False)

    with gr.Row(equal_height=True):
        with gr.Column():
            with gr.Row():
                gr.Markdown("## Select an invoice", elem_id="select-a-file")
                img_clear_button = gr.Button(
                    "Clear", variant="secondary", elem_id="file-clear", visible=False
                )
            image = gr.Gallery(visible=False)
            with gr.Row(equal_height=True):
                with gr.Column():
                    with gr.Row():
                        url = gr.Textbox(
                            show_label=False,
                            placeholder="URL",
                            lines=1,
                            max_lines=1,
                            elem_id="url-textbox",
                        )
                        submit = gr.Button("Get")
                    url_error = gr.Textbox(
                        visible=False,
                        elem_id="url-error",
                        max_lines=1,
                        interactive=False,
                        label="Error",
                    )
            gr.Markdown("— or —")
            upload = gr.File(label=None, interactive=True, elem_id="short-upload-box")
            gr.Examples(
                examples=EXAMPLES,
                inputs=[example_image, example_question],
            )

        with gr.Column() as col:
            gr.Markdown("## Results")
            with gr.Tabs():
                with gr.TabItem("Table"):
                    output_table = gr.Dataframe(
                        headers=["Field", "Value"],
                        **empty_table(fields.value),
                        elem_id="results-table"
                    )

                with gr.TabItem("JSON"):
                    output = gr.JSON(label="Output", visible=True)

            model = gr.Radio(
                choices=list(CHECKPOINTS.keys()),
                value=list(CHECKPOINTS.keys())[0],
                label="Model",
                visible=False,
            )

            gr.Markdown("### Ask a question")
            with gr.Row():
                question = gr.Textbox(
                    label="Question",
                    show_label=False,
                    placeholder="e.g. What is the invoice number?",
                    lines=1,
                    max_lines=1,
                    elem_id="question-textbox",
                )
                clear_button = gr.Button("Clear", variant="secondary", visible=False)
                submit_button = gr.Button(
                    "Add", variant="primary", elem_id="submit-button"
                )

    for cb in [img_clear_button, clear_button]:
        cb.click(
            lambda _: (
                gr.update(visible=False, value=None),  # image
                None,  # document
                # {**FIELDS},  # fields
                gr.update(value=None),  # output
                gr.update(**empty_table(fields.value)),  # output_table
                gr.update(visible=False),
                None,
                None,
                None,
                gr.update(visible=False, value=None),
                None,
            ),
            inputs=clear_button,
            outputs=[
                image,
                document,
                # fields,
                output,
                output_table,
                img_clear_button,
                example_image,
                upload,
                url,
                url_error,
                question,
            ],
        )

    submit_outputs = [
        document,
        fields,
        image,
        img_clear_button,
        url_error,
        output,
        output_table,
    ]

    upload.change(
        fn=process_upload,
        inputs=[upload, fields, model],
        outputs=submit_outputs,
    )

    submit.click(
        fn=process_path,
        inputs=[url, fields, model],
        outputs=submit_outputs,
    )

    for action in [question.submit, submit_button.click]:
        action(
            fn=process_question,
            inputs=[question, document, image, model, fields, output, output_table],
            outputs=[question, image, fields, output, output_table],
        )

#    model.change(
#        process_question,
#        inputs=[question, document, model],
#        outputs=[image, output, output_table],
#    )

    example_image.change(
        fn=load_example_document,
        inputs=[example_image, example_question, fields, model],
        outputs=submit_outputs,
    )

if __name__ == "__main__":
    demo.launch(enable_queue=False)