File size: 2,150 Bytes
145d936
 
9bdea1a
4d1d4d1
c1d7645
 
145d936
 
9bdea1a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4d1d4d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34c42f9
 
 
c1d7645
34c42f9
4d1d4d1
145d936
c1d7645
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
145d936
c1d7645
145d936
 
 
 
c1d7645
 
 
 
 
 
 
 
 
145d936
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
import spaces
import gradio as gr
import surya.detection as detection
import surya.layout as layout
import os
import base64


# Monkey patch to prevent spawning processes
def batch_text_detection(images, model, processor, batch_size=None):
    preds, orig_sizes = detection.batch_detection(
        images, model, processor, batch_size=batch_size
    )
    results = []
    for i in range(len(images)):
        result = detection.parallel_get_lines(preds[i], orig_sizes[i])
        results.append(result)

    return results


detection.batch_text_detection = batch_text_detection


def batch_layout_detection(
    images, model, processor, detection_results=None, batch_size=None
):
    preds, orig_sizes = layout.batch_detection(
        images, model, processor, batch_size=batch_size
    )
    id2label = model.config.id2label

    results = []
    for i in range(len(images)):
        result = layout.parallel_get_regions(
            preds[i],
            orig_sizes[i],
            id2label,
            detection_results[i] if detection_results else None,
        )
        results.append(result)

    return results


layout.batch_layout_detection = batch_layout_detection

from marker.convert import convert_single_pdf
from marker.models import load_all_models

model_list = load_all_models()


@spaces.GPU
def convert(pdf_file, extract_images):
    global model_list

    full_text, images, out_meta = convert_single_pdf(pdf_file, model_list)
    image_data = {}
    if extract_images:
        for filename, image in images.items():
            image.save(filename, "PNG")

            with open(filename, "rb") as f:
                image_bytes = f.read()

            image_base64 = base64.b64encode(image_bytes).decode("utf-8")
            image_data[filename] = image_base64

            os.remove(filename)

    return full_text, out_meta, image_data


gr.Interface(
    convert,
    inputs=[
        gr.File(label="Upload PDF", type="filepath"),
        gr.Checkbox(label="Extract Images"),
    ],
    outputs=[
        gr.Text(label="Markdown"),
        gr.JSON(label="Metadata"),
        gr.JSON(label="Images"),
    ],
).launch()