File size: 12,136 Bytes
102cc89
 
 
 
 
 
 
d19b184
102cc89
 
 
 
de9b441
102cc89
 
 
 
 
09c590a
102cc89
 
09c590a
102cc89
 
2bd32ae
de9b441
102cc89
 
 
 
 
 
 
 
 
 
 
 
 
09c590a
102cc89
 
9aee3a2
09c590a
b92ee4f
 
 
 
9aee3a2
 
102cc89
09c590a
102cc89
9aee3a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102cc89
 
628df8b
9ee4991
102cc89
 
 
 
e519161
102cc89
 
 
 
 
09c590a
654244f
 
09c590a
 
654244f
5fc3cab
654244f
102cc89
e12f59b
 
 
 
102cc89
 
e12f59b
 
102cc89
 
 
09c590a
102cc89
 
 
 
 
f3924ac
102cc89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07a94cf
102cc89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373d0cc
102cc89
 
 
 
 
 
 
 
09c590a
 
102cc89
 
 
 
 
 
 
ac2835f
102cc89
9ee4991
102cc89
 
 
09c590a
102cc89
d4bf7d4
102cc89
 
09c590a
 
102cc89
 
691b011
e519161
102cc89
 
 
9ee4991
102cc89
 
 
 
 
 
 
 
 
 
de9b441
102cc89
de9b441
102cc89
 
 
 
 
 
 
 
 
 
 
 
9ee4991
102cc89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c54b15
102cc89
 
 
 
 
 
 
 
 
9ab6cfe
102cc89
 
c6727a8
102cc89
8f14423
 
102cc89
 
 
 
de9b441
102cc89
ac2835f
102cc89
 
ef238ef
102cc89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
09c590a
102cc89
 
09c590a
102cc89
e519161
102cc89
 
bc1a4e2
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
import logging
import time
from pathlib import Path

import gradio as gr
import nltk
from cleantext import clean
from summarize import load_model_and_tokenizer, summarize_via_tokenbatches
from utils import load_example_filenames, truncate_word_count

_here = Path(__file__).parent

nltk.download("stopwords")

logging.basicConfig(
    level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)


def proc_submission(
    input_text: str,
    model_size: str,
    num_beams,
    token_batch_length,
    length_penalty,
    max_input_length: int = 3060,
):
    """
    proc_submission - a helper function for the gradio module to process submissions
    Args:
        input_text (str): the input text to summarize
        model_size (str): the size of the model to use
        num_beams (int): the number of beams to use
        token_batch_length (int): the length of the token batches to use
        length_penalty (float): the length penalty to use
        repetition_penalty (float): the repetition penalty to use
        no_repeat_ngram_size (int): the no repeat ngram size to use
        max_input_length (int, optional): the maximum input length to use. Defaults to 768.
    Returns:
        str in HTML format, string of the summary, str of score
    """

    settings_det = {
        "length_penalty": float(length_penalty),
        "repetition_penalty": 3.5,
        "no_repeat_ngram_size": 3,
        "encoder_no_repeat_ngram_size": 4,
        "num_beams": int(num_beams),
        "min_length": 100,
        "max_length": 512,#int(token_batch_length // 4),
        "early_stopping": True,
        "do_sample": False,
    }
    settings_tldr = {
        "length_penalty": float(length_penalty),
        "repetition_penalty": 3.5,
        "no_repeat_ngram_size": 3,
        "encoder_no_repeat_ngram_size": 4,
        "num_beams": int(num_beams),
        "min_length": 11,
        "max_length": 62,
        "early_stopping": True,
        "do_sample": False,
    }
    
    if model_size == "tldr":
        settings = settings_tldr
    else:
        settings = settings_det
    
    st = time.perf_counter()
    history = {}
    clean_text = clean(input_text, extra_spaces=True, lowercase=True, reg="\b(?!(?:Although|Also)\b)(?:[A-Z][A-Za-z'`-]+)(?:,? (?:(?:and |& )?(?:[A-Z][A-Za-z'`-]+)|(?:et al.?)))*(?:, *(?:19|20)[0-9][0-9](?:, p\.? [0-9]+)?| *\((?:19|20)[0-9][0-9](?:, p\.? [0-9]+)?\))", reg_replace="")
    #max_input_length = 2048 if model_size == "tldr" else max_input_length
    processed = truncate_word_count(clean_text, max_input_length)

    if processed["was_truncated"]:
        tr_in = processed["truncated_text"]
        msg = f"Input text was truncated to {max_input_length} words to fit within the computational constraints of the inference API"
        logging.warning(msg)
        history["WARNING"] = msg
    else:
        tr_in = input_text
        msg = None

    _summaries = summarize_via_tokenbatches(
        tr_in,
        model_sm if model_size == "tldr" else model,
        tokenizer_sm if model_size == "tldr" else tokenizer,
        batch_length=token_batch_length,
        **settings,
    )
    sum_text = [f"Section {i}: " + s["summary"][0] for i, s in enumerate(_summaries)]
    rates = [
        f" - Section {i}: {round(s['compression_rate'],3)}"
        for i, s in enumerate(_summaries)
    ]

    sum_text_out = "\n".join(sum_text)
    history["Compression Rates"] = "<br><br>"
    rates_out = "\n".join(rates)
    rt = round((time.perf_counter() - st) / 60, 2)
    print(f"Runtime: {rt} minutes")
    html = ""
    html += f"<p>Runtime: {rt} minutes on CPU</p>"
    if msg is not None:
        html += f"<h2>WARNING:</h2><hr><b>{msg}</b><br><br>"

    html += ""

    return html, sum_text_out, rates_out


def load_single_example_text(
    example_path: str or Path,
):
    """
    load_single_example - a helper function for the gradio module to load examples
    Returns:
        list of str, the examples
    """
    global name_to_path
    full_ex_path = name_to_path[example_path]
    full_ex_path = Path(full_ex_path)
    # load the examples into a list
    with open(full_ex_path, "r", encoding="utf-8", errors="ignore") as f:
        raw_text = f.read()
        text = clean(raw_text, extra_spaces=True, lowercase=False) #see if it works
    return text


def load_uploaded_file(file_obj):
    """
    load_uploaded_file - process an uploaded file
    Args:
        file_obj (POTENTIALLY list): Gradio file object inside a list
    Returns:
        str, the uploaded file contents
    """

    # file_path = Path(file_obj[0].name)

    # check if mysterious file object is a list
    if isinstance(file_obj, list):
        file_obj = file_obj[0]
    file_path = Path(file_obj.name)
    try:
        with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
            raw_text = f.read()
        text = clean(raw_text, extra_spaces=True, lowercase=True, reg="\s(?=[\,.':;!?])",reg_replace="")
        return text
    except Exception as e:
        logging.info(f"Trying to load file with path {file_path}, error: {e}")
        return "Error: Could not read file. Ensure that it is a valid text file with encoding UTF-8."


if __name__ == "__main__":

    model, tokenizer = load_model_and_tokenizer("Blaise-g/longt5_tglobal_large_sumpubmed")
    model_sm, tokenizer_sm = load_model_and_tokenizer("Blaise-g/longt5_tglobal_large_scitldr")

    name_to_path = load_example_filenames(_here / "examples")
    logging.info(f"Loaded {len(name_to_path)} examples")
    demo = gr.Blocks()

    with demo:

        gr.Markdown("# Automatic summarization of biomedical research papers with neural abstractive methods into a long and comprehensive synopsis or extreme TLDR summary version")
        gr.Markdown(
            "A demo developed for my Master Thesis project using ad-hoc fine-tuned abstractive summarization models to summarize long biomedical articles into a detailed, explanatory synopsis or extreme TLDR summary."
        )
        with gr.Column():

            gr.Markdown("### Select Summary type and text generation parameters then load input text")
            gr.Markdown(
                "Enter text below in the text area or alternatively load an example below or upload a file."
            )
            with gr.Row():
                model_size = gr.Radio(
                    choices=["tldr", "detailed"], label="Summary type", value="detailed"
                )
                num_beams = gr.Radio(
                    choices=[2, 3, 4],
                    label="Beam Search: Number of Beams",
                    value=2,
                )
            gr.Markdown(
                "_For optimal results use a GPU as the hosted CPU inference is lacking at times and hinders the output summary quality as well as forcing to divide the input text into batches._"
            )
            with gr.Row():
                length_penalty = gr.inputs.Slider(
                    minimum=0.5,
                    maximum=1.0,
                    label="length penalty",
                    default=0.7,
                    step=0.05,
                )
                token_batch_length = gr.Radio(
                    choices=[1024, 2048, 3060],
                    label="token batch length",
                    value=2048,
                )
            with gr.Row():
                example_name = gr.Dropdown(
                    list(name_to_path.keys()),
                    label="Choose an Example",
                )
                load_examples_button = gr.Button(
                    "Load Example",
                )
            input_text = gr.Textbox(
                lines=6,
                label="Input Text (for summarization)",
                placeholder="Enter any scientific text to be condensed into a detailed, explanatory synopsis or TLDR summary version. The input text is divided into batches of the selected token lengths to fit within the memory constraints, pre-processed and fed into the model of choice. The models were trained to handle long scientific papers but generalize reasonably well also to shorter text documents like scientific abstracts. Might take a while to produce long summaries :)",
            )
            gr.Markdown("Upload your own file:")
            with gr.Row():
                uploaded_file = gr.File(
                    label="Upload a text file",
                    file_count="single",
                    type="file",
                )
                load_file_button = gr.Button("Load Uploaded File")

            gr.Markdown("---")

        with gr.Column():
            gr.Markdown("## Generate Summary")
            gr.Markdown(
                "Summary generation should take approximately 2-3 minutes for most generation settings but can take significantly more time for very long documents with a high beam number."
            )
            summarize_button = gr.Button(
                "Summarize!",
                variant="primary",
            )

            output_text = gr.HTML("<p><em>Output will appear below:</em></p>")
            gr.Markdown("### Summary Output")
            summary_text = gr.Textbox(
                label="Summary πŸ“", placeholder="The generated πŸ“ will appear here"
            )
            gr.Markdown(
                "The compression rate πŸ—œ indicates the ratio between the machine-generated summary length and the input text (from 0% to 100%). The higher the πŸ—œ the more extreme the summary is."
            )
            compression_rate = gr.Textbox(
                label="Compression rate πŸ—œ", placeholder="The πŸ—œ will appear here"
            )
            gr.Markdown("---")

        with gr.Column():
            gr.Markdown("## About the Models")
            gr.Markdown(
                "- [Blaise-g/longt5_tglobal_large_sumpubmed](https://huggingface.co/Blaise-g/longt5_tglobal_large_sumpubmed) is a fine-tuned checkpoint of [Stancld/longt5-tglobal-large-16384-pubmed-3k_steps](https://huggingface.co/Stancld/longt5-tglobal-large-16384-pubmed-3k_steps) on the [SumPubMed dataset](https://aclanthology.org/2021.acl-srw.30/). [Blaise-g/longt5_tglobal_large_scitldr](https://huggingface.co/Blaise-g/longt5_tglobal_large_scitldr) is a fine-tuned checkpoint of [Blaise-g/longt5_tglobal_large_sumpubmed](https://huggingface.co/Blaise-g/longt5_tglobal_large_sumpubmed) on the [Scitldr dataset](https://arxiv.org/abs/2004.15011). The goal was to create two models capable of handling the complex information contained in long biomedical documents and subsequently producing scientific summaries according to one of the two possible levels of conciseness: 1) A long explanatory synopsis that retains the majority of domain-specific language used in the original source text. 2)A one sentence long, TLDR style summary."
            )
            gr.Markdown(
                "- The two most important text generation parameters are the number of beams and length penalty : 1) Choosing a higher number of beams for the beam search algorithm results in generating a summary with higher probability (hence theoretically higher quality) at the cost of increasing computation times and memory usage. 2) The length penalty encourages the model to generate longer (with values closer to 1.0) or shorter (with values closer to 0.0) summary sequences by placing an exponential penalty on the beam score according to the current sequence length."
            )
            gr.Markdown("---")

        load_examples_button.click(
            fn=load_single_example_text, inputs=[example_name], outputs=[input_text]
        )

        load_file_button.click(
            fn=load_uploaded_file, inputs=uploaded_file, outputs=[input_text]
        )

        summarize_button.click(
            fn=proc_submission,
            inputs=[
                input_text,
                model_size,
                num_beams,
                token_batch_length,
                length_penalty,
            ],
            outputs=[output_text, summary_text, compression_rate],
        )

    demo.launch(enable_queue=True, share=False)