File size: 26,897 Bytes
1d3a103
e414859
1d3a103
 
435abb4
 
 
7e0dde7
73feb19
 
 
 
 
 
 
1d3a103
9c491e8
5f2c216
565eabb
87e5c9c
b8e1b99
c1cba4f
0f39362
665f924
435abb4
87e5c9c
 
 
b8e1b99
73feb19
b8e1b99
 
bd3ba15
 
80098ed
b8e1b99
 
87e5c9c
 
b8e1b99
87e5c9c
5f2c216
7e0dde7
 
b8e1b99
87e5c9c
c430753
9e8f29e
e414859
c430753
7e0dde7
c1cba4f
c430753
 
 
 
87e5c9c
 
 
9d26661
e9ed1f2
87e5c9c
435abb4
b8e1b99
 
 
21c203b
4b042ac
 
 
b8e1b99
1d3a103
435abb4
 
 
 
 
 
 
 
b8e1b99
e414859
7e0dde7
e414859
7e0dde7
73feb19
 
435abb4
73feb19
435abb4
 
 
e414859
 
 
 
 
9c491e8
e414859
 
 
7e0dde7
 
e414859
9c491e8
 
e414859
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7e0dde7
e414859
 
 
 
 
7e0dde7
e414859
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b8e1b99
 
 
 
 
 
 
1d3a103
 
 
 
 
 
 
 
 
 
b8e1b99
 
 
 
 
 
 
 
 
 
 
8312087
565eabb
 
 
8312087
b8e1b99
87e5c9c
 
 
 
b8e1b99
3927544
 
 
 
 
80098ed
0bd3372
87e5c9c
 
 
 
 
 
b8e1b99
87e5c9c
 
 
 
 
f84fce9
0bd3372
73feb19
 
0bd3372
73feb19
87e5c9c
 
f84fce9
87e5c9c
 
e414859
87e5c9c
 
 
 
 
 
 
 
 
 
 
73feb19
80098ed
 
 
73feb19
87e5c9c
 
0407083
 
9e8f29e
0407083
 
 
 
9e8f29e
87e5c9c
9e8f29e
 
665f924
0407083
665f924
c13ffb4
665f924
f84fce9
0407083
665f924
 
87e5c9c
 
 
9e8f29e
87e5c9c
 
3ddba7d
 
 
 
839eda3
 
 
 
3ddba7d
50d040d
3ddba7d
 
 
50d040d
3ddba7d
50d040d
d717178
50d040d
b8e1b99
9e8f29e
b8e1b99
 
87e5c9c
 
15c9486
87e5c9c
1d3a103
87e5c9c
 
 
c430753
87e5c9c
 
 
1d3a103
87e5c9c
1d3a103
87e5c9c
c13ffb4
87e5c9c
 
 
80098ed
03e9034
73feb19
c430753
87e5c9c
 
 
 
3927544
1d3a103
87e5c9c
1d3a103
 
 
 
 
87e5c9c
9c491e8
87e5c9c
 
716199b
5f2c216
 
87e5c9c
5f2c216
 
defd486
73feb19
5f2c216
 
 
 
 
 
 
 
 
 
87e5c9c
 
 
1d3a103
87e5c9c
1d3a103
87e5c9c
1d3a103
 
 
 
87e5c9c
9c491e8
bd3ba15
87e5c9c
 
 
 
 
bd3ba15
73feb19
5f2c216
 
1d3a103
5f2c216
7e0dde7
defd486
7e0dde7
5f2c216
 
 
 
 
 
 
73feb19
 
5f2c216
87e5c9c
 
bd3ba15
7e0dde7
87e5c9c
 
9c491e8
7e0dde7
9c491e8
435abb4
9c491e8
435abb4
9c491e8
435abb4
9c491e8
 
 
 
 
 
 
 
 
 
 
435abb4
 
 
 
 
 
 
9e8f29e
435abb4
 
 
 
 
 
9e8f29e
9c491e8
dcce2ac
 
 
 
 
 
 
 
9c491e8
 
435abb4
9c491e8
 
 
 
 
435abb4
9c491e8
 
 
87e5c9c
9c491e8
bd3ba15
9c491e8
 
435abb4
 
 
9c491e8
 
 
435abb4
 
 
 
 
 
 
dcce2ac
 
 
 
 
 
bd3ba15
5f2c216
 
 
 
 
 
 
435abb4
 
87e5c9c
bd3ba15
73feb19
 
0f39362
435abb4
87e5c9c
5f2c216
87e5c9c
7c0cbdc
 
 
 
 
 
 
 
 
87e5c9c
 
 
 
4874c8d
 
 
 
87e5c9c
ba90de1
 
b8e1b99
3927544
 
 
72c7da5
 
435abb4
86215a1
72c7da5
 
3927544
 
 
86215a1
ba90de1
1413bdf
 
 
 
 
 
 
 
55b49e6
1413bdf
 
0f39362
 
7452863
73feb19
7e0dde7
7452863
0f39362
6a1173d
87e5c9c
 
7e0dde7
 
 
 
 
 
 
 
87e5c9c
c430753
7e0dde7
895976b
15c9486
4874c8d
 
 
15c9486
 
 
 
 
 
 
 
7e0dde7
15c9486
 
 
 
 
7e0dde7
 
e414859
7e0dde7
 
e414859
 
7e0dde7
 
 
 
 
 
 
 
 
 
 
f84fce9
 
7e0dde7
 
 
 
 
 
 
 
9e8f29e
7e0dde7
34de38e
22fd690
c13ffb4
 
4874c8d
 
 
ba90de1
3927544
1d116fb
 
c13ffb4
bd3ba15
c13ffb4
 
 
435abb4
c13ffb4
435abb4
 
c13ffb4
87e5c9c
ba90de1
3927544
c13ffb4
 
 
bd3ba15
c13ffb4
 
 
1d116fb
c13ffb4
 
 
80098ed
 
 
 
87e5c9c
7e0dde7
87e5c9c
7e0dde7
3927544
 
7e0dde7
87e5c9c
73feb19
7e0dde7
73feb19
87e5c9c
 
 
 
 
 
 
 
 
 
 
 
 
 
b8e1b99
87e5c9c
 
 
 
 
80098ed
87e5c9c
34de38e
87e5c9c
e414859
 
 
 
 
9c491e8
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
"""
app.py - the main module for the gradio app for summarization

Usage:
    app.py [-h] [--share] [-m MODEL] [-nb ADD_BEAM_OPTION] [-batch TOKEN_BATCH_OPTION]
              [-level {DEBUG,INFO,WARNING,ERROR}]
Details:
    python app.py --help

Environment Variables:
    USE_TORCH (str): whether to use torch (1) or not (0)
    TOKENIZERS_PARALLELISM (str): whether to use parallelism (true) or not (false)
Optional Environment Variables:
    APP_MAX_WORDS (int): the maximum number of words to use for summarization
    APP_OCR_MAX_PAGES (int): the maximum number of pages to use for OCR
"""
import argparse
import contextlib
import gc
import logging
import os
import pprint as pp
import random
import re
import sys
import time
from pathlib import Path

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

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s - %(message)s",
    datefmt="%Y-%b-%d %H:%M:%S",
)

import gradio as gr
import nltk
import torch
from cleantext import clean
from doctr.models import ocr_predictor

from aggregate import BatchAggregator
from pdf2text import convert_PDF_to_Text
from summarize import load_model_and_tokenizer, summarize_via_tokenbatches
from utils import (
    contraction_aware_tokenize,
    extract_batches,
    load_example_filenames,
    remove_stagnant_files,
    remove_stopwords,
    saves_summary,
    textlist2html,
    truncate_word_count,
)

_here = Path(__file__).parent

nltk.download("punkt", force=True, quiet=True)
nltk.download("popular", force=True, quiet=True)

# Constants & Globals
MODEL_OPTIONS = [
    "pszemraj/long-t5-tglobal-base-16384-book-summary",
    "pszemraj/long-t5-tglobal-base-sci-simplify",
    "pszemraj/long-t5-tglobal-base-summary-souffle-16384-loD",
    "pszemraj/long-t5-tglobal-base-synthsumm_direct",
    "pszemraj/long-t5-tglobal-base-book_synthsumm-v2",
    "pszemraj/pegasus-x-large-book_synthsumm",
    "pszemraj/pegasus-x-large-book-summary",
]  # models users can choose from
BEAM_OPTIONS = [2, 3, 4]  # beam sizes users can choose from
TOKEN_BATCH_OPTIONS = [
    1024,
    1536,
    2048,
    2560,
    3072,
]  # token batch sizes users can choose from

SUMMARY_PLACEHOLDER = "<p><em>Output will appear below:</em></p>"
AGGREGATE_MODEL = "MBZUAI/LaMini-Flan-T5-783M"  # model to use for aggregation

# if duplicating space: uncomment this line to adjust the max words
# os.environ["APP_MAX_WORDS"] = str(2048)  # set the max words to 2048
# os.environ["APP_OCR_MAX_PAGES"] = str(40)  # set the max pages to 40
# os.environ["APP_AGG_FORCE_CPU"] = str(1)  # force cpu for aggregation

aggregator = BatchAggregator(
    AGGREGATE_MODEL, force_cpu=os.environ.get("APP_AGG_FORCE_CPU", False)
)


def aggregate_text(
    summary_text: str,
    text_file: gr.inputs.File = None,
) -> str:
    """
    Aggregate the text from the batches.

        NOTE: you should probably include the BatchAggregator object as a fn arg if using this code

    :param batches_html: The batches to aggregate, in html format
    :param text_file: The text file to append the aggregate summary to
    :return: The aggregate summary in html format
    """
    if summary_text is None or summary_text == SUMMARY_PLACEHOLDER:
        logging.error("No text provided. Make sure a summary has been generated first.")
        return "Error: No text provided. Make sure a summary has been generated first."

    try:
        extracted_batches = extract_batches(summary_text)
    except Exception as e:
        logging.info(summary_text)
        logging.info(f"the batches html is: {type(summary_text)}")
        return f"Error: unable to extract batches - check input: {e}"
    if not extracted_batches:
        logging.error("unable to extract batches - check input")
        return "Error: unable to extract batches - check input"

    out_path = None
    if text_file is not None:
        out_path = text_file.name  # assuming name attribute stores the file path

    content_batches = [batch["content"] for batch in extracted_batches]
    full_summary = aggregator.infer_aggregate(content_batches)

    # if a path that exists is provided, append the summary with markdown formatting
    if out_path:
        out_path = Path(out_path)

        try:
            with open(out_path, "a", encoding="utf-8") as f:
                f.write("\n\n## Aggregate Summary\n\n")
                f.write(
                    "- This is an instruction-based LLM aggregation of the previous 'summary batches'.\n"
                )
                f.write(f"- Aggregation model: {aggregator.model_name}\n\n")
                f.write(f"{full_summary}\n\n")
            logging.info(f"Updated {out_path} with aggregate summary")
        except Exception as e:
            logging.error(f"unable to update {out_path} with aggregate summary: {e}")

    full_summary_html = f"""
        <div style="
            margin-bottom: 20px;
            font-size: 18px;
            line-height: 1.5em;
            color: #333;
        ">
            <h2 style="font-size: 22px; color: #555;">Aggregate Summary:</h2>
            <p style="white-space: pre-line;">{full_summary}</p>
        </div>
        """
    return full_summary_html


def predict(
    input_text: str,
    model_name: str,
    token_batch_length: int = 1024,
    empty_cache: bool = True,
    **settings,
) -> list:
    """
    predict - helper fn to support multiple models for summarization at once

    :param str input_text: the input text to summarize
    :param str model_name: model name to use
    :param int token_batch_length: the length of the token batches to use
    :param bool empty_cache: whether to empty the cache before loading a new= model
    :return: list of dicts with keys "summary" and "score"
    """
    if torch.cuda.is_available() and empty_cache:
        torch.cuda.empty_cache()

    model, tokenizer = load_model_and_tokenizer(model_name)
    summaries = summarize_via_tokenbatches(
        input_text,
        model,
        tokenizer,
        batch_length=token_batch_length,
        **settings,
    )

    del model
    del tokenizer
    gc.collect()

    return summaries


def proc_submission(
    input_text: str,
    model_name: str,
    num_beams: int,
    token_batch_length: int,
    length_penalty: float,
    repetition_penalty: float,
    no_repeat_ngram_size: int,
    predrop_stopwords: bool,
    max_input_length: int = 6144,
):
    """
    proc_submission - a helper function for the gradio module to process submissions

    Args:
        input_text (str): the input text to summarize
        model_name (str): the hf model tag 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
        predrop_stopwords (bool): whether to pre-drop stopwords before truncating/summarizing
        max_input_length (int, optional): the maximum input length to use. Defaults to 6144.

    Note:
        the max_input_length is set to 6144 by default, but can be changed by setting the
        environment variable APP_MAX_WORDS to a different value.

    Returns:
        tuple (4): a tuple containing the following:
    """

    remove_stagnant_files()  # clean up old files
    settings = {
        "length_penalty": float(length_penalty),
        "repetition_penalty": float(repetition_penalty),
        "no_repeat_ngram_size": int(no_repeat_ngram_size),
        "encoder_no_repeat_ngram_size": 4,
        "num_beams": int(num_beams),
        "min_length": 4,
        "max_length": int(token_batch_length // 4),
        "early_stopping": True,
        "do_sample": False,
    }
    max_input_length = int(os.environ.get("APP_MAX_WORDS", max_input_length))
    logging.info(
        f"max_input_length set to: {max_input_length}. pre-drop stopwords: {predrop_stopwords}"
    )

    st = time.perf_counter()
    history = {}
    cln_text = clean(input_text, lower=False)
    parsed_cln_text = remove_stopwords(cln_text) if predrop_stopwords else cln_text
    logging.info(
        f"pre-truncation word count: {len(contraction_aware_tokenize(parsed_cln_text))}"
    )
    truncation_validated = truncate_word_count(
        parsed_cln_text, max_words=max_input_length
    )

    if truncation_validated["was_truncated"]:
        model_input_text = truncation_validated["processed_text"]
        # create elaborate HTML warning
        input_wc = len(contraction_aware_tokenize(parsed_cln_text))
        msg = f"""
        <div style="background-color: #FFA500; color: white; padding: 20px;">
        <h3>Warning</h3>
        <p>Input text was truncated to {max_input_length} words. That's about {100*max_input_length/input_wc:.2f}% of the original text.</p>
        <p>Dropping stopwords is set to {predrop_stopwords}. If this is not what you intended, please validate the advanced settings.</p>
        </div>
        """
        logging.warning(msg)
        history["WARNING"] = msg
    else:
        model_input_text = truncation_validated["processed_text"]
        msg = None

    if len(input_text) < 50:
        # this is essentially a different case from the above
        msg = f"""
        <div style="background-color: #880808; color: white; padding: 20px;">
        <br>
        <img src="https://i.imgflip.com/7kadd9.jpg" alt="no text">
        <br>
        <h3>Error</h3>
        <p>Input text is too short to summarize. Detected {len(input_text)} characters.
        Please load text by selecting an example from the dropdown menu or by pasting text into the text box.</p>
        </div>
        """
        logging.warning(msg)
        logging.warning("RETURNING EMPTY STRING")
        history["WARNING"] = msg

        return msg, "<strong>No summary generated.</strong>", "", []

    _summaries = predict(
        input_text=model_input_text,
        model_name=model_name,
        token_batch_length=token_batch_length,
        **settings,
    )
    sum_text = [s["summary"][0].strip() + "\n" for s in _summaries]
    sum_scores = [
        f" - Batch Summary {i}: {round(s['summary_score'],4)}"
        for i, s in enumerate(_summaries)
    ]

    full_summary = textlist2html(sum_text)
    history["Summary Scores"] = "<br><br>"
    scores_out = "\n".join(sum_scores)
    rt = round((time.perf_counter() - st) / 60, 2)
    logging.info(f"Runtime: {rt} minutes")
    html = ""
    html += f"<p>Runtime: {rt} minutes with model: {model_name}</p>"
    if msg is not None:
        html += msg

    html += ""

    settings["remove_stopwords"] = predrop_stopwords
    settings["model_name"] = model_name
    saved_file = saves_summary(summarize_output=_summaries, outpath=None, **settings)
    return html, full_summary, scores_out, saved_file


def load_single_example_text(
    example_path: str or Path,
    max_pages: int = 20,
) -> str:
    """
    load_single_example_text - loads a single example text file

    :param strorPath example_path: name of the example to load
    :param int max_pages: the maximum number of pages to load from a PDF
    :return str: the text of the example
    """
    global name_to_path, ocr_model
    full_ex_path = name_to_path[example_path]
    full_ex_path = Path(full_ex_path)
    if full_ex_path.suffix in [".txt", ".md"]:
        with open(full_ex_path, "r", encoding="utf-8", errors="ignore") as f:
            raw_text = f.read()
        text = clean(raw_text, lower=False)
    elif full_ex_path.suffix == ".pdf":
        logging.info(f"Loading PDF file {full_ex_path}")
        max_pages = int(os.environ.get("APP_OCR_MAX_PAGES", max_pages))
        logging.info(f"max_pages set to: {max_pages}")
        conversion_stats = convert_PDF_to_Text(
            full_ex_path,
            ocr_model=ocr_model,
            max_pages=max_pages,
        )
        text = conversion_stats["converted_text"]
    else:
        logging.error(f"Unknown file type {full_ex_path.suffix}")
        text = "ERROR - check example path"

    return text


def load_uploaded_file(file_obj, max_pages: int = 20, lower: bool = False) -> str:
    """
    load_uploaded_file - loads a file uploaded by the user

    :param file_obj (POTENTIALLY list): Gradio file object inside a list
    :param int max_pages: the maximum number of pages to load from a PDF
    :param bool lower: whether to lowercase the text
    :return str: the text of the file
    """
    global ocr_model
    logger = logging.getLogger(__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:
        logger.info(f"Loading file:\t{file_path}")
        if file_path.suffix in [".txt", ".md"]:
            with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
                raw_text = f.read()
            text = clean(raw_text, lower=lower)
        elif file_path.suffix == ".pdf":
            logger.info(f"loading a PDF file: {file_path.name}")
            max_pages = int(os.environ.get("APP_OCR_MAX_PAGES", max_pages))
            logger.info(f"max_pages is: {max_pages}. Starting conversion...")
            conversion_stats = convert_PDF_to_Text(
                file_path,
                ocr_model=ocr_model,
                max_pages=max_pages,
            )
            text = conversion_stats["converted_text"]
        else:
            logger.error(f"Unknown file type:\t{file_path.suffix}")
            text = "ERROR - check file - unknown file type. PDF, TXT, and MD are supported."

        return text
    except Exception as e:
        logger.error(f"Trying to load file:\t{file_path},\nerror:\t{e}")
        return f"Error: Could not read file {file_path.name}. Make sure it is a PDF, TXT, or MD file."


def parse_args():
    """arguments for the command line interface"""
    parser = argparse.ArgumentParser(
        description="Document Summarization with Long-Document Transformers - Demo",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        epilog="Runs a local-only web UI to summarize documents. pass --share for a public link to share.",
    )

    parser.add_argument(
        "--share",
        dest="share",
        action="store_true",
        help="Create a public link to share",
    )
    parser.add_argument(
        "-m",
        "--model",
        type=str,
        default=None,
        help=f"Add a custom model to the list of models: {pp.pformat(MODEL_OPTIONS, compact=True)}",
    )
    parser.add_argument(
        "-nb",
        "--add_beam_option",
        type=int,
        default=None,
        help=f"Add a beam search option to the demo UI options, default: {pp.pformat(BEAM_OPTIONS, compact=True)}",
    )
    parser.add_argument(
        "-batch",
        "--token_batch_option",
        type=int,
        default=None,
        help=f"Add a token batch size to the demo UI options, default: {pp.pformat(TOKEN_BATCH_OPTIONS, compact=True)}",
    )
    parser.add_argument(
        "-max_agg",
        "-2x",
        "--aggregator_beam_boost",
        dest="aggregator_beam_boost",
        action="store_true",
        help="Double the number of beams for the aggregator during beam search",
    )
    parser.add_argument(
        "-level",
        "--log_level",
        type=str,
        default="INFO",
        choices=["DEBUG", "INFO", "WARNING", "ERROR"],
        help="Set the logging level",
    )

    return parser.parse_args()


if __name__ == "__main__":
    """main - the main function of the app"""
    logger = logging.getLogger(__name__)
    args = parse_args()
    logger.setLevel(args.log_level)
    logger.info(f"args: {pp.pformat(args.__dict__, compact=True)}")

    # add any custom options
    if args.model is not None:
        logger.info(f"Adding model {args.model} to the list of models")
        MODEL_OPTIONS.append(args.model)
    if args.add_beam_option is not None:
        logger.info(f"Adding beam search option {args.add_beam_option} to the list")
        BEAM_OPTIONS.append(args.add_beam_option)
    if args.token_batch_option is not None:
        logger.info(f"Adding token batch option {args.token_batch_option} to the list")
        TOKEN_BATCH_OPTIONS.append(args.token_batch_option)

    if args.aggregator_beam_boost:
        logger.info("Doubling aggregator num_beams")
        _agg_cfg = aggregator.get_generation_config()
        _agg_cfg["num_beams"] = _agg_cfg["num_beams"] * 2
        aggregator.update_generation_config(**_agg_cfg)

    logger.info("Loading OCR model")
    with contextlib.redirect_stdout(None):
        ocr_model = ocr_predictor(
            "db_resnet50",
            "crnn_mobilenet_v3_large",
            pretrained=True,
            assume_straight_pages=True,
        )

    # load the examples
    name_to_path = load_example_filenames(_here / "examples")
    logger.info(f"Loaded {len(name_to_path)} examples")

    demo = gr.Blocks(title="Document Summarization with Long-Document Transformers")
    _examples = list(name_to_path.keys())
    logger.info("Starting app instance")
    with demo:
        gr.Markdown("# Document Summarization with Long-Document Transformers")
        gr.Markdown(
            """An example use case for fine-tuned long document transformers. Model(s) are trained on [book summaries](https://hf.co/datasets/kmfoda/booksum). Architectures [in this demo](https://hf.co/spaces/pszemraj/document-summarization) are [LongT5-base](https://hf.co/pszemraj/long-t5-tglobal-base-16384-book-summary) and [Pegasus-X-Large](https://hf.co/pszemraj/pegasus-x-large-book-summary).

            **Want more performance? Run this demo from a free Google Colab GPU:**.
            <br>
            <a href="https://colab.research.google.com/gist/pszemraj/52f67cf7326e780155812a6a1f9bb724/document-summarization-on-gpu.ipynb">
            <img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/>
            </a>
            <br>
            """
        )
        with gr.Column():
            gr.Markdown("## Load Inputs & Select Parameters")
            gr.Markdown(
                """Enter/paste text below, or upload a file. Pick a model & adjust params (_optional_), and press **Summarize!**

                See [the guide doc](https://gist.github.com/pszemraj/722a7ba443aa3a671b02d87038375519) for details.
                """
            )
            with gr.Row(variant="compact"):
                with gr.Column(scale=0.5, variant="compact"):
                    model_name = gr.Dropdown(
                        choices=MODEL_OPTIONS,
                        value=MODEL_OPTIONS[0],
                        label="Model Name",
                    )
                    num_beams = gr.Radio(
                        choices=BEAM_OPTIONS,
                        value=BEAM_OPTIONS[len(BEAM_OPTIONS) // 2],
                        label="Beam Search: # of Beams",
                    )
                    load_examples_button = gr.Button(
                        "Load Example in Dropdown",
                    )
                    load_file_button = gr.Button("Upload & Process File")
                with gr.Column(variant="compact"):
                    example_name = gr.Dropdown(
                        _examples,
                        label="Examples",
                        value=random.choice(_examples),
                    )
                    uploaded_file = gr.File(
                        label="File Upload",
                        file_count="single",
                        file_types=[".txt", ".md", ".pdf"],
                        type="file",
                    )
            with gr.Row():
                input_text = gr.Textbox(
                    lines=4,
                    max_lines=12,
                    label="Text to Summarize",
                    placeholder="Enter text to summarize, the text will be cleaned and truncated on Spaces. Narrative, academic (both papers and lecture transcription), and article text work well. May take a bit to generate depending on the input text :)",
                )
        gr.Markdown("---")
        with gr.Column():
            gr.Markdown("## Generate Summary")
            with gr.Row():
                summarize_button = gr.Button(
                    "Summarize!",
                    variant="primary",
                )
                gr.Markdown(
                    "_Summarization should take ~1-2 minutes for most settings, but may extend up to 5-10 minutes in some scenarios._"
                )
            output_text = gr.HTML("<p><em>Output will appear below:</em></p>")
            with gr.Column():
                gr.Markdown("### Results & Scores")
                with gr.Row():
                    with gr.Column(variant="compact"):
                        gr.Markdown(
                            "Download the summary as a text file, with parameters and scores."
                        )
                        text_file = gr.File(
                            label="Download as Text File",
                            file_count="single",
                            type="file",
                            interactive=False,
                        )
                    with gr.Column(variant="compact"):
                        gr.Markdown(
                            "Scores **roughly** represent the summary quality as a measure of the model's 'confidence'. less-negative numbers (closer to 0) are better."
                        )
                        summary_scores = gr.Textbox(
                            label="Summary Scores",
                            placeholder="Summary scores will appear here",
                        )
            with gr.Column(variant="panel"):
                gr.Markdown("### **Summary Output**")
                summary_text = gr.HTML(
                    label="Summary",
                    value="<center><i>Summary will appear here!</i></center>",
                )
            with gr.Column():
                gr.Markdown("### **Aggregate Summary Batches**")
                gr.Markdown(
                    "_Note: this is an experimental feature. Feedback welcome in the [discussions](https://hf.co/spaces/pszemraj/document-summarization/discussions)!_"
                )
                with gr.Row():
                    aggregate_button = gr.Button(
                        "Aggregate!",
                        variant="primary",
                    )
                    gr.Markdown(
                        f"""Aggregate the above batches into a cohesive summary.
                    - A secondary instruct-tuned LM consolidates info
                    - Current model: [{AGGREGATE_MODEL}](https://hf.co/{AGGREGATE_MODEL})
                                """
                    )
                with gr.Column(variant="panel"):
                    aggregated_summary = gr.HTML(
                        label="Aggregate Summary",
                        value="<center><i>Aggregate summary will appear here!</i></center>",
                    )
                    gr.Markdown(
                        "\n\n_Aggregate summary is also appended to the bottom of the `.txt` file._"
                    )

        gr.Markdown("---")
        with gr.Column():
            gr.Markdown("### Advanced Settings")
            gr.Markdown(
                "Refer to [the guide doc](https://gist.github.com/pszemraj/722a7ba443aa3a671b02d87038375519) for what these are, and how they impact _quality_ and _speed_."
            )
            with gr.Row(variant="compact"):
                length_penalty = gr.Slider(
                    minimum=0.3,
                    maximum=1.1,
                    label="length penalty",
                    value=0.7,
                    step=0.05,
                )
                token_batch_length = gr.Radio(
                    choices=TOKEN_BATCH_OPTIONS,
                    label="token batch length",
                    # select median option
                    value=TOKEN_BATCH_OPTIONS[len(TOKEN_BATCH_OPTIONS) // 2],
                )

            with gr.Row(variant="compact"):
                repetition_penalty = gr.Slider(
                    minimum=1.0,
                    maximum=5.0,
                    label="repetition penalty",
                    value=1.5,
                    step=0.1,
                )
                no_repeat_ngram_size = gr.Radio(
                    choices=[2, 3, 4, 5],
                    label="no repeat ngram size",
                    value=3,
                )
                predrop_stopwords = gr.Checkbox(
                    label="Drop Stopwords (Pre-Truncation)",
                    value=False,
                )
        with gr.Column():
            gr.Markdown("## About")
            gr.Markdown(
                "- Models are fine-tuned on the [🅱️ookSum dataset](https://arxiv.org/abs/2105.08209). The goal was to create a model that generalizes well and is useful for summarizing text in academic and everyday use."
            )
            gr.Markdown(
                "- _Update April 2023:_ Additional models fine-tuned on the [PLOS](https://hf.co/datasets/pszemraj/scientific_lay_summarisation-plos-norm) and [ELIFE](https://hf.co/datasets/pszemraj/scientific_lay_summarisation-elife-norm) subsets of the [scientific lay summaries](https://arxiv.org/abs/2210.09932) dataset are available (see dropdown at the top)."
            )
            gr.Markdown(
                "Adjust the max input words & max PDF pages for OCR by duplicating this space and [setting the environment variables](https://hf.co/docs/hub/spaces-overview#managing-secrets) `APP_MAX_WORDS` and `APP_OCR_MAX_PAGES` to the desired integer values."
            )
            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_name,
                num_beams,
                token_batch_length,
                length_penalty,
                repetition_penalty,
                no_repeat_ngram_size,
                predrop_stopwords,
            ],
            outputs=[output_text, summary_text, summary_scores, text_file],
        )
        aggregate_button.click(
            fn=aggregate_text,
            inputs=[summary_text, text_file],
            outputs=[aggregated_summary],
        )
    demo.launch(enable_queue=True, share=args.share)