Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
Word Cloud Generator from Given Passage
Next article icon

Word Cloud Generator from Given Passage

Last Updated : 06 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

Screenshot-2567-05-26-at-105256-(1)
Final Output

Prerequisites:

  • ReactJs
  • Nodejs

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.

Screenshot-2567-05-26-at-112000
Frontend file structure

Backend(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.

Screenshot-2567-05-26-at-112011
Backend file structure

Approach

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.


Next Article
Word Cloud Generator from Given Passage

P

pk9918705
Improve
Article Tags :
  • Project
  • Web Technologies
  • ReactJS

Similar Reads

    JavaScript Generator() Constructor
    In JavaScript, there is no particular Generator() constructor but instead, we can use generator function declaration to construct a Generator object which is iterable as the Generator object is a subclass of the Iterable class. Generators are usually used to create functions that can be exited and r
    1 min read
    Get Value From Generator Function in Python
    Generator functions in Python are powerful tools for efficiently working with large datasets or generating sequences of values on the fly. They are different from regular functions as they use the yield keyword to produce a series of values, allowing the generator to pause its execution and resume w
    3 min read
    Get Current Value Of Generator In Python
    Python generators are powerful constructs that allow lazy evaluation of data, enabling efficient memory usage and improved performance. When working with generators, it's essential to have tools to inspect their current state. In this article, we'll explore some different methods to get the current
    3 min read
    Create A Pandas Dataframe From Generator
    A Pandas DataFrame is a 2D data structure like a table with rows and columns. The values in the data frame are mutable and can be modified. Data frames are mostly used in data analysis and data manipulation. DataFrames store data in table form like databases and Excel sheets. We can easily perform a
    3 min read
    JavaScript Generator constructor Property
    JavaScript Generator constructor property is used to return the Generator constructor function for the object. The function which is returned by this property is just the reference to this function, not a Generator containing the function’s name. The JavaScript number constructor, string constructor
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences