Implementing Text Summarization in Google Sheets with BART

Implementing Text Summarization in Google Sheets with BART

Google Sheets has a built-in capability, the Apps Script editor, that allows users to create custom functions and automate otherwise complex tasks directly within their spreadsheets. One interesting example of what can be done here is integrating pre-trained language models hosted on the Hugging Face Hub to leverage advanced natural language processing (NLP) capabilities. This enables users to address a range of language use cases, from text summarization to sentiment analysis, and even translation: all within Google Sheets and by just using formulae.

Interested? Let’s see how!

Preparatory Steps: Integrating BART Model

BART (Bidirectional and Auto-Regressive Transformer) is a sequence-to-sequence model that combines the encoding for language understanding capabilities of BERT models (specialized in tasks like text classification), and the autoregressive decoding for text generation that characterizes models like GPT (specialized in prompt-to-text generation). Its unique architecture is especially suited for generating coherent and concise text summaries, hence it is suitable for this particular kind of text-to-text language task.

Some examples of readily available BART models for summarization in Hugging Face, include:

  • facebook/bart-large-cnn
  • facebook/bart-large-xsum
  • facebook/bart-base
  • sshleifer/distilbart-cnn-12-6

To create a custom function that calls any of these models for summarizing text in a cell, open in a new tab the Apps Script editor found in the Extensions menu on the top of Sheets. Create a new script file with the extension .gs on the left-hand pane, and add this code, which encapsulates the function we will use for summarizing any input text in a cell by using our choice of Hugging Face model.

function summarizeText(text) {
  const apiKey = 'YOUR_HUGGING_FACE_API_TOKEN';
  const model = 'facebook/bart-large-cnn';

  const url = `https://api-inference.huggingface.co/models/${model}`;
  const options = {
    method: 'post',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    },
    payload: JSON.stringify({inputs: text})
  };

  try {
    const response = UrlFetchApp.fetch(url, options);
    const result = JSON.parse(response.getContentText());
    
    // Check if there is an error in the response
    if (result.error) {
      return `Error: ${result.error}`;
    }

    // Return the summary (assuming result is an array of summaries)
    return result[0].summary_text;
  } catch (error) {
    return `Error: ${error.message}`;
  }
}

You only need to worry about defining two values at the top of this code.

  • apiKey: here you need to paste your Hugging Face API key. If you don’t have any yet, the middle section of this tutorial explains how to obtain it.
  • model: the name or path of the Hugging Face to invoke. It can be for instance facebook/bart-large-cnn or either one of the other example models listed before.

Once you save the script file, you are ready to go back to the main Google Sheets tab and try your summarization function.

Summarizing Text

Time to try out the summarization function we just created. The first requirement is, of course, having some data to summarize, such as the couple of example cells shown below.

Two example texts to summarize
Two example texts to summarize

Assuming these two texts are placed on cells B5 and B6, respectively, try adding the following formulae in another two cells, for instance, on C5 and C6:

=summarizeText(B5)
=summarizeText(B6)

If everything goes well, once you press intro after writing each of the two formulae, the function will execute and call the chosen BART model in Hugging Face. After a few seconds, you should see the resulting summarized text “magically” appearing on the two cells, as follows:

Summarization results
Summarization results

You might be thinking: “Well, that doesn’t look like a quite remarkable summarization…” Indeed, the summarized text length is somewhat similar to that in the original text, especially in the Usain Bolt example! Why? There are a few reasons or facts to explain this:

  • First, different language models behave differently, being trained on data following certain structures and patterns. A model trained upon scientific papers for summarization, perhaps might not work too well in summarizing press news about pop music.
  • Second, the specific model used, facebook/bart-large-cnn, has been shown to perform well on the narrative-like text like news articles with clear and distinguishable pieces of information. Seems like the Amazon rainforest example fits into this pattern slightly better.

One additional experiment worth trying is using several different models and comparing results. To do this, we recommend creating separate scripts that replicate the entire code used earlier, only replacing the model name, and also renaming the function name (e.g. summarize_bart_large_cnn, summarize_bart_large_xsum, and so on) and using different script file names if you want to allocate each function in a separate script.

This example introduces a second function — added below the original one in our original script — to summarize text using another BART model, concretely facebook/bart-large-xsum. This model has been fine-tuned to generate very short summaries, typically one sentence long. Here are the results:

Comparing summaries generated by two different BART models
Comparing summaries generated by two different BART models

The second model is more effective in terms of reduction of text length, albeit this doesn’t necessarily need it is a better result. Indeed, generating a very concise summary upon texts of a certain length may incur the loss of important information. So, at the end of the day, which model is better? It depends on your specific problem, needs, and text data at hand. Trying several models on a variety of examples of your own and deciding yourself which summaries look better suited to your needs, is a good approach.

Troubleshooting

When using the defined functions in your cell formulae and pressing intro to let them execute, you might first encounter an error with error code 503. This error means the language model is still being loaded, and it usually takes some time to load, before which Google Sheets formulae executor seems to time out. The solution is simple: wait a few seconds and retry your formula that calls the defined functions.

Leave a Reply

Your email address will not be published. Required fields are marked *