File size: 4,275 Bytes
39d4462
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import sys
import subprocess
from pathlib import Path
from os import getenv

from importlib.metadata import version
from PIL import Image
from minijinja import Environment

import gradio as gr

# Config
document_name = "document-template.typ"

do_share = getenv("DO_SHARE")

concurrency_limit = getenv("CONCURRENCY_LIMIT", 1)

typst_bin_path = getenv("TYPST_BIN", "/home/user/app/typst")

# App description
title = "Typst-based PDF generation"

examples = [
    """
I begin this story with a neutral statement.
Basically this is a very silly test.
""",
]

description_head = f"""
# {title}

## Overview

We use https://typst.app to generate a PDF file with some parameters from this Gradio app.
""".strip()

tech_env = f"""
#### Environment

- Python: {sys.version}
""".strip()


def app_version(bin_path):
    return subprocess.run([bin_path, "--version"], capture_output=True, text=True)


def typst_compile(typst_bin_path, filename, export_template):
    args = [typst_bin_path, "compile", filename, export_template]
    print("Running:", args)

    return subprocess.run(
        args,
        capture_output=False,
    )


def convert_document(bin_paths, text):
    print("Converting...")

    env = Environment(
        templates={
            "document": Path("document-template.typ").read_text(),
        }
    )
    formatted_document = env.render_template("document", text=text)

    # Write the rendered document to a temporary file
    document_file = Path("document.typ")
    document_file.write_text(formatted_document)

    # Compile the .typ file to a .pdf file
    c = typst_compile(bin_paths["typst"], "document.typ", "document.pdf")
    if c.returncode != 0:
        raise gr.Error("Typst compilation failed.")

    print("Result:", c)

    # Extract the first page of the PDF file
    c = typst_compile(bin_paths["typst"], "document.typ", "file-{n}.png")
    if c.returncode != 0:
        raise gr.Error("Typst exporting to PNGs failed.")

    print("Result:", c)

    first_page = Path("file-1.png")
    if not first_page.exists():
        raise gr.Error("The first page has not been exported.")

    # Move the image to an object
    image = Image.open(first_page.absolute())

    # Remove the temporary files
    first_page.unlink(missing_ok=True)
    document_file.unlink(missing_ok=True)

    return image


typst_version_info = app_version(typst_bin_path)
if typst_version_info.returncode != 0:
    print("Error: Typst version command failed.")
    exit(1)

r_tech_env = f"""
#### Typst Environment

```
{typst_version_info.stdout.strip()}
```
""".strip()

tech_libraries = f"""
#### Libraries

- gradio: {version("gradio")}
""".strip()


def generate_pdf(text, progress=gr.Progress()):
    if not text:
        raise gr.Error("Please paste your text.")

    # Remove the previous PDF file and Typst file
    Path("document.pdf").unlink(missing_ok=True)
    Path("document.typ").unlink(missing_ok=True)

    gr.Info("Generating the PDF document", duration=1)

    bin_paths = {
        "typst": typst_bin_path,
    }
    image = convert_document(bin_paths, text)

    gr.Success("Finished!", duration=2)

    pdf_file = gr.DownloadButton(
        label="Download document.pdf",
        value="./document.pdf",
        visible=True,
    )

    return [image, pdf_file]


demo = gr.Blocks(
    title=title,
    analytics_enabled=False,
    theme=gr.themes.Base(),
)

with demo:
    gr.Markdown(description_head)

    gr.Markdown("## Usage")

    with gr.Row():
        text = gr.Textbox(label="Text", autofocus=True, max_lines=50)

        with gr.Column():
            pdf_file = gr.DownloadButton(label="Download PDF", visible=False)
            preview_image = gr.Image(
                label="Preview image",
            )

    gr.Button("Generate").click(
        generate_pdf,
        concurrency_limit=concurrency_limit,
        inputs=text,
        outputs=[preview_image, pdf_file],
    )

    with gr.Row():
        gr.Examples(label="Choose an example", inputs=text, examples=examples)

    gr.Markdown("### Gradio app uses:")
    gr.Markdown(tech_env)
    gr.Markdown(r_tech_env)
    gr.Markdown(tech_libraries)

if __name__ == "__main__":
    demo.queue()

    if do_share:
        demo.launch(share=True)
    else:
        demo.launch()