DEV Community

akash2819
akash2819

Posted on

How to Create a Text Summarizer Using GPT API: A Step-by-Step Guide with Code

Are you tired of reading lengthy articles and documents, and wish to quickly understand their essence? A text summarizer is a tool that can help you achieve that. In this technical blog, we will explain how to create a text summarizer using GPT API. GPT (Generative Pre-trained Transformer) is an advanced language model developed by OpenAI that can generate human-like text. With the help of GPT API, we can create a text summarizer that can quickly summarize large documents into concise and meaningful summaries.

Before we dive into the technical details, let's first understand what a text summarizer is and why it's useful. A text summarizer is a program that can automatically create a summary of a large text document or article. The summary is typically a shorter version of the original text that contains the most important information. Text summarizers are useful for several reasons. They can save time and effort for readers who need to quickly understand the content of a document. They can also help writers and editors to identify the most important parts of a text and improve its readability.

Now, let's move on to the technical part of creating a text summarizer using GPT API.To get started with GPT-3 API, you will first need to sign up for an API key on the OpenAI website. Once you have the API key, you can use it to send requests to the API and receive responses in JSON format.

Now let's move on to creating the React TypeScript web application. First, we need to install the required dependencies. Open your terminal and run the following command:

npm install react react-dom typescript @types/react @types/react-dom axios tailwindcss postcss-cli autoprefixer

Next, we need to create a new React TypeScript app. Run the following command in your terminal:
npx create-react-app my-app --template typescript

This will create a new React TypeScript app in the my-app directory. Next, we need to set up Tailwind CSS. Create a new file called tailwind.css in the src directory and add the following code:

@tailwind base;
@tailwind components;
@tailwind utilities;

Enter fullscreen mode Exit fullscreen mode

This imports the base, component, and utility styles from Tailwind CSS. Next, we need to configure PostCSS to process the Tailwind CSS file. Create a new file called postcss.config.js in the root directory and add the following code:

module.exports = {
  plugins: [
    require('tailwindcss'),
    require('autoprefixer'),
  ],
};

Enter fullscreen mode Exit fullscreen mode

Now we are ready to start building the application. First, let's create a simple form where the user can enter the text they want to summarize. Create a new file called Summarizer.tsx in the src directory and add the following code:

import React, { useState } from 'react';
import axios from 'axios';

const Summarizer: React.FC = () => {
  const [inputText, setInputText] = useState('');
  const [summaryText, setSummaryText] = useState('');

  const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    setInputText(event.target.value);
  };

  const handleFormSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();

    const response = await axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', {
      prompt: `Summarize the following text:\n${inputText}`,
      max_tokens: 60,
      n: 1,
      stop: ['\n']
    }, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`
      }
    });

    setSummaryText(response.data.choices[0].text.trim());
  };

  return (
    <div className="mx-auto max-w-2xl">
      <h1 className="text-2xl font-bold mb-4">Text Summarizer</h1>
      <form onSubmit={handleFormSubmit}>
<textarea
       className="w-full h-64 px-3 py-2 border border-gray-300 rounded-md resize-none mb-4"
       placeholder="Enter text to summarize"
       value={inputText}
       onChange={handleInputChange}
     />
<button
       className="bg-blue-500 text-white py-2 px-4 rounded hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
       type="submit"
     >
Summarize
</button>
{summaryText && (
<div className="border border-gray-300 rounded-md px-3 py-2 mt-4">
<p>{summaryText}</p>
</div>
)}
</form>
</div>
);
};

export default Summarizer;

Enter fullscreen mode Exit fullscreen mode

This creates a simple form with a textarea for inputting the text to be summarized, and a button for triggering the summarization. When the form is submitted, we use the axios library to send a POST request to the GPT-3 API with the input text as the prompt. We set the max_tokens parameter to limit the length of the summary, and the stop parameter to ensure that the summary ends with a complete sentence. Once we receive a response from the API, we set the summary text in the component state and render it on the page.

Finally, we need to add the Summarizer component to the main App component. Open the App.tsx file in the src directory and replace the existing code with the following:

import React from 'react';
import Summarizer from './Summarizer';

const App: React.FC = () => {
  return (
    <div className="bg-gray-100 min-h-screen py-8">
      <div className="container mx-auto px-4">
        <Summarizer />
      </div>
    </div>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

This sets up the main App component with the Summarizer component as the main content.
That's it! We have created a text summarizer web application using GPT-3 API, React TypeScript, and Tailwind CSS. This application can help users quickly summarize large text documents and articles, saving them time and effort. With some additional features and enhancements, this application can be further optimized for search engine rankings and user engagement.

You Can Checkout The Advance Summarizer Created By Me: SummarizeAi

Top comments (3)

Collapse
 
reuel5 profile image
reuel5

shy45sj09

Collapse
 
akash2819 profile image
akash2819

Hey ,
Your App Seems to be nice let me test it for some time we'll give you feedback then

Collapse
 
yrsingh profile image
Yash Raj Singh

nice project man
can u share the repo link ??