import logging
import time
from pathlib import Path
import gradio as gr
import nltk
from cleantext import clean
import cleantext.clean as cl
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") # TODO=find where this requirement originates from
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 = 2048,
):
"""
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"] = "
"
rates_out = "\n".join(rates)
rt = round((time.perf_counter() - st) / 60, 2)
print(f"Runtime: {rt} minutes")
html = ""
html += f"
Runtime: {rt} minutes on CPU
" if msg is not None: html += f"Output will appear below:
") gr.Markdown("### Summary Output") summary_text = gr.Textbox( label="Summary 📝", placeholder="The generated 📝 will appear here" ) gr.Markdown( "The summary scores can be thought of as representing the quality of the summary. less-negative numbers (closer to 0) are better:" ) compression_rate = gr.Textbox( label="Compression rate 🗜", placeholder="The 🗜 will appear here" ) gr.Markdown("---") with gr.Column(): gr.Markdown("## About the Model") 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 or shorter 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)