Word Cloud Generator from Given Passage
Last Updated : 06 Jun, 2024
In today's digital world, we often encounter large amounts of text data, whether it's from articles, books, social media posts, or other sources. Analyzing this text data can be overwhelming, but tools like word cloud generators can help make sense of it in a visual and engaging way.
Final OutputPrerequisites:
Project Structure:
Our word cloud generator project consists of two main parts: the frontend and the backend.
Frontend(client):
This is the part of the project that users interact with directly. It includes the user interface where users can input text and trigger the generation of the word cloud.
Frontend file structureBackend(server):
The backend serves as the intermediary between the frontend and external services. It handles requests from the frontend, interacts with external APIs (such as the QuickChart Word Cloud API), and processes data before sending it back to the frontend.
Backend file structureApproach
When a user enters text and clicks the "Generate Word Cloud" button in the frontend, the text is sent to the backend server. The backend then makes a request to the QuickChart Word Cloud API, passing the text as a parameter.
Upon receiving the word cloud data from the QuickChart API, the backend converts the binary array representation of the image data into a PNG image format. This conversion process involves reading the binary data and converting it into a base64-encoded string, which can be rendered as an image in the browser.
Frontend Code
The frontend code is responsible for capturing user input, sending it to the backend, and displaying the generated word cloud image to the user. It utilizes React.js for building the user interface and Axios for making HTTP requests to the backend server.
Setup the basic frontend code using following commands:
npx create-react-app client
Update the `App.js` code:
JavaScript import React, { useState } from 'react'; import axios from 'axios'; // Define a functional component // named WordCloudGenerator const WordCloudGenerator = () => { // State variables to store // the passage and word cloud image const [passage, setPassage] = useState(''); const [wordCloudImage, setWordCloudImage] = useState(''); // Function to generate word cloud const generateWordCloud = async () => { try { // Send a POST request to the backend // server to generate the word cloud const response = await axios.post( 'http://localhost:5000/generate-word-cloud', { text: passage }, { // Set response type to // arraybuffer to handle image data responseType: 'arraybuffer' }); // Convert the array buffer received // from the server to a base64-encoded string const arrayBufferView = new Uint8Array(response.data); const blob = new Blob([arrayBufferView], { type: 'image/png' }); const reader = new FileReader(); reader.readAsDataURL(blob); reader.onloadend = () => { const base64data = reader.result; // Set the word cloud image using the base64 string setWordCloudImage(base64data); }; } catch (error) { console.error('Error generating word cloud:', error); } }; // Return the JSX elements for // the WordCloudGenerator component return ( <div style={{ fontFamily: 'Arial, sans-serif', textAlign: 'center' }}> {/* Heading */} <h1 style={{ marginBottom: '20px', color: 'white', backgroundColor: 'green' }}>Word Cloud Generator</h1> {/* Textarea for entering the passage */} <div style={{ marginBottom: '20px' }}> <textarea value={passage} onChange={(e) => setPassage(e.target.value)} rows={10} cols={50} placeholder="Enter your passage here" style={{ fontSize: '16px', padding: '10px', width: '70%', minHeight: '200px' }} ></textarea> </div> {/* Button to trigger word cloud generation */} <div> <button onClick={generateWordCloud} style={{ padding: '10px 20px', fontSize: '16px', borderRadius: '10px', backgroundColor: 'green', color: 'white' }} > Generate Word Cloud </button> </div> {/* Display the word cloud image if available */} {wordCloudImage && ( <div style={{ marginTop: '20px' }}> <img src={wordCloudImage} alt="Word Cloud" style={{ maxWidth: '100%', maxHeight: '400px' }} /> </div> )} </div> ); }; // Export the WordCloudGenerator // component as the default export export default WordCloudGenerator;
Backend Code
The backend code, built using Node.js and Express.js, defines an endpoint to receive text data from the frontend. It then makes a POST request to the QuickChart Word Cloud API, retrieves the image data, and sends it back to the frontend for display.
Setup the backend server
npm init
npm i nodemon express cross
Update the `server.js`
JavaScript const express = require('express'); const cors = require('cors'); const axios = require('axios'); const app = express(); const PORT = 5000; app.use(cors()); app.use(express.json()); // Route for generating word cloud app.post('/generate-word-cloud', async (req, res) => { try { const { text } = req.body; // QuickChart Word Cloud API endpoint const apiUrl = 'https://quickchart.io/wordcloud'; // Set options for the request const options = { method: 'POST', url: apiUrl, data: { text: text, format: 'png', // Set the format to PNG width: 800, // Set the width of the image height: 600, // Set the height of the image fontFamily: 'Arial', // Set the font family fontWeight: 'normal', // Set the font weight fontScale: 20, // Set the font scale scale: 'linear', // Set the scale padding: 2 // Set the padding }, // Set the response type to // arraybuffer to handle image data responseType: 'arraybuffer' }; // Make a POST request // to QuickChart Word Cloud API const response = await axios(options); // Send the image data back to the frontend res.send(response.data); } catch (error) { console.error('Error generating word cloud:', error.message); res.status(500).json({ error: 'Internal server error' }); } }); app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
Output:
Conclusion
In conclusion, a word cloud generator is a useful tool for visualizing and analyzing text data in an intuitive and visually appealing way. By combining frontend and backend technologies, we can create a seamless user experience that empowers users to gain insights from their text data effortlessly. With the project structure and approach explained above, you're now equipped to build your own word cloud generator and explore the world of text analysis.