Build a News Summarizer App Using Frontend and Backend
Step-by-Step Tutorial Beginner Level Tutorial
This tutorial is designed for complete beginners—even if you have little or no programming experience.
We will create a simple web app that takes a long news article and returns a short summary.
The frontend (what you see on the website) will be made with HTML, CSS, and JavaScript, while the backend (the part that processes the text) will use Python with Flask.
Follow these steps closely, and by the end, you’ll have a working News Summarizer app ready to deploy!
Below is the file structure for your project.
You can create these files and folders in Visual Studio Code:
news_summarizer_app/
├── app/
│ ├── __init__.py # Initializes the Flask app and configuration
│ ├── routes.py # Contains all route definitions (API endpoints)
│ └── summarizer.py # Python module with text cleaning and summarization functions
├── static/
│ ├── css/
│ │ └── styles.css # CSS file for styling the webpage
│ └── js/
│ └── script.js # JavaScript file connecting the frontend with the backend
├── templates/
│ └── index.html # HTML file for the web interface (frontend view)
├── venv/ # Virtual environment folder (auto-generated)
├── app.py # Entry point to run the Flask application
├── requirements.txt # List of Python dependencies
└── README.md # Project documentation and instructions
This structure will help keep your project organized and makes it easy to manage and deploy your News Summarizer app. Enjoy coding!
1. Setting Up Your Environment
Before writing any code, you need a working environment:
Install Python:
Download and install Python (version 3.7 or later) from python.org.
Tip: Follow the installation instructions on the website.
Create a Project Folder:
Create a folder on your computer named
news_summarizer_app
. This folder will hold all your project files.Open a Text Editor:
Use a simple text editor like Visual Studio Code, Sublime Text, or even Notepad to create and edit your files.
2. Installing Python and Flask
We will use Flask—a simple web framework for Python—to build the backend of our app.
Open a Terminal or Command Prompt:
Navigate to your project folder:
cd path/to/your/news_summarizer_app
Create a Virtual Environment (Optional but Recommended):
python -m venv venv
Activate the virtual environment:
On Windows:
venv\\Scripts\\activate
On macOS/Linux:
source venv/bin/activate
Install Flask and Other Libraries:
In your terminal, run the following command:
pip install flask transformers torch nltk
These libraries do the following:
flask: Runs the web server.
transformers & torch: Help with the summarization using a pre-trained model.
nltk: Helps with text processing.
3. Creating the Python Backend
3.1 Writing the Summarization Code
We will use a pre-trained model from Hugging Face (T5) to summarize text.
Create a File Called
summarizer.py
:In your project folder, create a file named
summarizer.py
and copy the following code into it:
# summarizer.py
import re
import nltk
from nltk.tokenize import sent_tokenize
from transformers import T5ForConditionalGeneration, T5Tokenizer
# Download necessary NLTK data
nltk.download('punkt')
def clean_text(text):
"""Clean the text by removing HTML tags and extra spaces."""
text = re.sub(r'<[^>]+>', '', text)
text = re.sub(r'\\s+', ' ', text)
text = text.encode("ascii", "ignore").decode()
return text.strip()
def load_model(model_name="t5-small"):
"""Load the pre-trained T5 model and tokenizer."""
tokenizer = T5Tokenizer.from_pretrained(model_name)
model = T5ForConditionalGeneration.from_pretrained(model_name)
return tokenizer, model
def summarize_text(text, tokenizer, model, max_length=150, min_length=40):
"""Summarize text using the T5 model."""
input_text = "summarize: " + text
input_ids = tokenizer.encode(input_text, return_tensors="pt", truncation=True)
summary_ids = model.generate(
input_ids,
max_length=max_length,
min_length=min_length,
length_penalty=2.0,
num_beams=4,
early_stopping=True
)
summary = tokenizer.decode(summary_ids[0], skip_special_tokens=True)
return summary
def process_and_summarize(text):
"""Full pipeline: clean the text, load model, and generate summary."""
cleaned_text = clean_text(text)
tokenizer, model = load_model()
return summarize_text(cleaned_text, tokenizer, model)
Save the File:
Save
summarizer.py
in your project folder.
3.2 Creating the Flask API
Now, we will create a simple Flask server that accepts a news article and returns the summary.
Create a File Called
app.py
:In your project folder, create a file named
app.py
and copy the following code:
# app.py
from flask import Flask, request, jsonify
from summarizer import process_and_summarize
app = Flask(__name__)
@app.route('/summarize', methods=['POST'])
def summarize():
try:
data = request.get_json()
article_text = data.get('article', '')
if not article_text:
return jsonify({'error': 'No article text provided'}), 400
summary = process_and_summarize(article_text)
return jsonify({'summary': summary})
except Exception as e:
return jsonify({'error': str(e)}), 500
if __name__ == '__main__':
app.run(debug=True)
Save the File:
Save
app.py
in your project folder.Testing the API:
In your terminal, run:
python app.py
Your server will start at
http://127.0.0.1:5000
. You can test it using a tool like Postman or by using the next section when we connect the frontend.
4. Building the Frontend
The frontend will be built using HTML, CSS, and JavaScript. It will send the news article to the Flask backend and display the summary.
4.1 HTML: The Structure
Create a File Called
index.html
:In your project folder, create a file named
index.html
and copy the following code:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>News Article Summarizer</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<h1>News Article Summarizer</h1>
<p>Paste your news article below and click "Summarize" to get a short summary.</p>
<textarea id="article" placeholder="Paste your news article here..." rows="10"></textarea>
<button id="summarizeBtn">Summarize</button>
<h2>Summary:</h2>
<div id="summary"></div>
</div>
<script src="script.js"></script>
</body>
</html>
Save the File:
Save
index.html
in your project folder.
4.2 CSS: Styling Your Page
Create a File Called
styles.css
:In your project folder, create a file named
styles.css
and copy the following code:
/* styles.css */
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 20px;
}
.container {
max-width: 800px;
margin: auto;
background: white;
padding: 20px;
border-radius: 5px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
h1, h2 {
text-align: center;
}
textarea {
width: 100%;
padding: 10px;
margin: 10px 0;
font-size: 16px;
}
button {
display: block;
width: 100%;
padding: 10px;
background: #007BFF;
color: white;
border: none;
font-size: 18px;
cursor: pointer;
margin-bottom: 20px;
border-radius: 5px;
}
button:hover {
background: #0056b3;
}
#summary {
background: #e9ecef;
padding: 15px;
border-radius: 5px;
min-height: 50px;
}
Save the File:
Save
styles.css
in your project folder.
4.3 JavaScript: Connecting Frontend to Backend
Create a File Called
script.js
:In your project folder, create a file named
script.js
and copy the following code:
// script.js
document.getElementById('summarizeBtn').addEventListener('click', function () {
const articleText = document.getElementById('article').value;
if (!articleText) {
alert('Please paste a news article first.');
return;
}
// Send the article text to the Flask backend
fetch('<http://127.0.0.1:5000/summarize>', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ article: articleText })
})
.then(response => response.json())
.then(data => {
if (data.summary) {
document.getElementById('summary').innerText = data.summary;
} else {
document.getElementById('summary').innerText = 'Error: ' + data.error;
}
})
.catch(error => {
document.getElementById('summary').innerText = 'An error occurred: ' + error;
});
});
Save the File:
Save
script.js
in your project folder.
5. Testing Your App Locally
Start the Flask Backend:
In your terminal, make sure you are in your project folder and your virtual environment is activated. Run:
python app.py
Your Flask server will start at
http://127.0.0.1:5000
.
Open the Frontend in Your Browser:
Open the
index.html
file in your web browser (you can simply double-click it).Paste a news article into the text area.
Click the "Summarize" button.
The summary will appear on the page.
6. Troubleshooting and Next Steps
Backend Not Running:
Ensure your virtual environment is activated and all libraries are installed.
CORS Issues:
If you experience issues with cross-origin requests, you might need to install and configure Flask-CORS:
pip install flask-cors
Then, update
app.py
by adding:
from flask_cors import CORS
CORS(app)
Improving Summaries:
Experiment with the parameters in
summarize_text
(likemax_length
andmin_length
) to get the desired summary length.Learning More:
As you become more comfortable, consider learning about deploying your app online using platforms like Heroku or Render.
Congratulations! 🎉
By following these steps, you've built a fully functional News Summarizer app using HTML, CSS, and JavaScript for the frontend and Python with Flask for the backend.
Now you have a working application that takes a long news article and produces a short, clear summary.
Enjoy your new tool and keep experimenting to learn more!
More projects on the way.
Manas xx! 🥂