Building an Intelligent Event Cost Prediction System with MindsDB, Typeform, and Node.js

Building an Intelligent Event Cost Prediction System with MindsDB, Typeform, and Node.js

Unlock the Secrets: A Comprehensive Guide to Building Your Own Event Cost Prediction App

ยท

8 min read

Introduction

Lost in event planning costs? Stressed about budgets? Say goodbye to the guesswork! We built a magic trick called the Intelligent Event Cost Prediction System. Think fancy budget fairy powered by AI.

Just answer some questions about your dream event โ€“ venue, guests, type of event, fireworks (sure!) โ€“ and our AI maestro, MindsDB, analyzes past events like a data detective. It then whispers the cost prediction to your server, Node.js, who translates it into plain English for you. No more spreadsheet nightmares!

Imagine:

  • Stress-free planning: Ditch the budget anxiety and focus on making memories.

  • Dream big: No more worrying about if you can afford that extra sparkle. Go for it!

  • Inclusive celebrations: Everyone deserves a special occasion, big or small. AI helps make it happen.

This is just the beginning of AI's magic. It's here to help us live better, celebrate brighter, and maybe even predict where to find the tastiest cake.

So, ready to skip the budget blues and let AI orchestrate your perfect event? Dive in and let the fun begin!

Technologies Used

MindsDB

A robust repository for historical event data and the genius behind accurate cost predictions. MindsDB ensures your budget aligns with reality.

Typeform

An intuitive form powered by Typeform captures user event specifics, paving the way for customized predictions and eliminating the chaos of guess-based planning.

Node.js

The backbone of server-side logic, data processing, and seamless interaction between MindsDB and Typeform. Node.js makes the magic happen.

Project Architecture

Visualize the data dance:

  1. Users express their event vision via Typeform.

  2. Data flows to Node.js through webhooks.

  3. Node.js queries MindsDB, the prediction powerhouse.

  4. MindsDB processes, predicts, and delivers a tailored cost estimate.

  5. Node.js packages predictions into user-friendly emails, sent with a click.

Setting Up MindsDB

Prerequisite: Go through the Predict Home Rental Prices "Learning Hub" in the local MindsDB web console.

No coding headaches here:

  1. Launch MindsDB Cloud for a smooth setup.

    Create a mindsdb account at https://cloud.mindsdb.com/editor, make sure you get your email and password.

  2. Connect your Node.js application to MindsDB.

    Create node js application then install mindsdb js sdk.If you haven't already, make sure to create a MindsDB account to use with the SDK.

     npm install --save mindsdb-js-sdk
    

    Connect by providing mindsdb user credentials using the code below:

     try {
        MindsDB.connect({
         user: 'your-email@gmail.com',
         password: '*********'
       });
       console.log('Connected to Mindsdb Cloud');
     } catch(error) {
       // Failed to authenticate.
       console.log('Failed to authenticate to Mindsdb Cloud');
     }
    
  3. Adding dataset to mindsdb web console.

    Click "Add" from the console then upload your event historical data csv file.

Typeform Integration

Simplicity in every step:

  1. Open Typeform and create a form to get event data from the user. Capture user email, name, event type, number of attendees ,duration, location and theme of event.

  2. Expose your local server using ngrok for Typeform accessibility.

      ngrok http 3000                           # secure public URL for port 3000 web server
    
  3. Configure Typeform webhooks, ensuring seamless data flow to Node.js.

    1. In your Typeform workspace, go to the form you want to configure.

    2. Navigate to the "Connect" tab and select "Webhooks."

    3. Add a new webhook and enter the URL of your server (either the local one or the ngrok-exposed one).

    4. Configure the webhook to send responses when the form is submitted.

    5. Save your webhook configuration.

Model Training

Coding made easy:

Employ MindsDB's JavaScript SDK for model training.

Importing Dependencies: Import necessary modules: express for creating the server, body-parser for JSON parsing, and mindsdb-js-sdk for MindsDB interaction.

// app.js
const express = require('express');
const bodyParser = require('body-parser');
const MindsDB = require("mindsdb-js-sdk").default;

Setting Up the Server: Create an Express application and define a port (defaulting to 3000).

const app = express();
const PORT = process.env.PORT || 3000;

// Parse JSON requests
app.use(bodyParser.json());

Connecting to MindsDB Cloud: Attempt a connection to MindsDB Cloud using provided credentials, and log the connection status.'

try {
  MindsDB.connect({
    user: 'your-email@gmail.com',
    password: '*********'
  });
  console.log('Connected to Mindsdb Cloud');
} catch (error) {
  // Failed to authenticate.
  console.log('Failed to authenticate to Mindsdb Cloud');
}

Handling Webhook Requests: Define a POST route /webhook to handle incoming Typeform webhook requests. Process the payload asynchronously and log any errors.

// Define a route to handle webhook requests
app.post('/webhook', async (req, res) => {
  try {
    // Process the incoming webhook payload from Typeform
    const webhookData = req.body;

Training MindsDB Model: Specify training options, such as the data source and integration method. Train a MindsDB model for predicting event costs based on historical data.'

Fetching Existing Model: Retrieve an existing MindsDB model, which can be useful for reusing a pre-trained model.

Waiting for Model Training: Implement a loop to wait until the model training is complete or encounters an error. This ensures the server proceeds only when the model is ready for predictions.

Starting the Server: Launch the server, and it starts listening on the specified port.

    // Add your custom logic here (e.g., trigger MindsDB prediction)
    const regressionTrainingOptions = {
      select: 'SELECT * FROM files.event_data',
      integration: 'files'
    };

    // Either create a model from scratch or use an existing model

    // Train the model asynchronously
    let eventCostModel = await MindsDB.Models.trainModel(
      'event_cost_model',
      'cost',
      'mindsdb',
      regressionTrainingOptions
    );

    // Fetch the existing model
    eventCostModel = await MindsDB.Models.getModel('event_costs_model', 'mindsdb');

    // Wait for the training to be complete (consider adding a timeout mechanism)
    while (eventCostModel.status !== 'complete' && eventCostModel.status !== 'error') {
      await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for 1 second
      eventCostModel = await MindsDB.Models.getModel('event_costs_model', 'mindsdb');
    }
  } catch (error) {
    console.error('Error processing webhook:', error);
  }
});

// Start the server
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Webhook Data Processing

Unleash the predictions:

  1. Capture Typeform webhook data in your Node.js app. Add this code to your try catch statement, get the field id from typeform payload or access it form node js console. Run node app.js then send test request in typeform to access the payload.

    function getValueByFieldId( fieldId) {


          for (let answer of webhookData.form_response.answers) {
            if (answer.field && answer.field.id === fieldId) {
              if (answer.type === 'email') {
                return answer.email;
              } else if (answer.type === 'phone_number') {
                return answer.phone_number;
              } else if (answer.type === 'number') {
                return answer.number;
              } else if (answer.type === 'text') {
                return answer.text;
              }
            }
          }

          return null; // Return null or appropriate value if not found
        }
    // Define query options

    const eventType = getValueByFieldId('2bABtJQgJfA9');
    const location = getValueByFieldId('fzgCinjspKFf');
    const attendees = getValueByFieldId('wbjnYzwsqmKa');
    const decorationTheme = getValueByFieldId('v0ioNij9bfgm');
    const duration = getValueByFieldId('YmJe1PakNxAb');
    const userName = getValueByFieldId('ugyT5lEXjYO1');

        const queryOptions = {
          where: [
            `event_type = "${eventType}"`,
            `location = "${location}"`,
            `attendees = ${attendees}`,
            `decorationtheme = "${decorationTheme}"`,
            `duration = ${duration}`
          ]
      };
      console.log('webhookData.answers:', webhookData.form_response.answers);
        // Query the model for predictions
        const eventCostPrediction = await eventCostModel.query(queryOptions);
        console.log('Predicted Cost:', eventCostPrediction.value);
        console.log('Explanation:', eventCostPrediction.explain);
        console.log('Raw Data:', eventCostPrediction.data);
  1. From the avove code Process and prep the data for MindsDB queries

    and Send the data to MindsDB and unveil the event cost prediction.

Sending Predictions to Users

Share the joy:

  1. Extract user emails from Typeform responses.
     const userEmailAnswer = webhookData.form_response.answers.find(answer => 
     answer.type === 'email');


      if (!userEmailAnswer || !userEmailAnswer.email) {
        console.error('User email not found in answers array.');
        res.status(400).send('Bad Request');
        return;
      }

      const userEmail = userEmailAnswer.email;

Using nodemailer to send predicted cost to the user.

  1. First, install Nodemailer by running the following command in your terminal:

     npm install nodemailer
    
  2. After installing Nodemailer, you can update your existing code to include email sending logic. Below is an example modification to your code:

     const nodemailer = require('nodemailer');
    
     // Send email with the predicted cost
      const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
          user: 'your-email@gmail.com', // replace with your email
          pass: '***********' // replace with your email password or app-specific password
        }
      });

      const mailOptions = {
        from: 'your-email@gmail.com',
        to: userEmail,
        subject: '๐ŸŽ‰ Your Predicted Event Cost',
       // text: `The predicted cost of your event is: $${eventCostPrediction.value}`,
        text: `
    Dear ${userName},

    We hope this message finds you well! ๐ŸŒŸ

    Thank you for using our service to predict the cost of your upcoming event. Based on the details you provided, our prediction model has estimated the cost for your event.

    Predicted Event Cost: $${eventCostPrediction.value}

    Please note that this is an estimate, and actual costs may vary. If you have any further questions or need assistance with planning your event, feel free to reach out to us.

    We appreciate your trust in our service and wish you a fantastic and memorable event!

    Best regards,

    MindsEvents
      `
      };

      transporter.sendMail(mailOptions, (error, info) => {
        if (error) {
          console.error('Failed to send email:', error);
        } else {
          console.log('Email sent:', info.response);
        }
      });

Output

Video Walkthrough

  1. Typeform link

  2. Github code

Conclusion

In wrapping up, this journey to create a smart event cost prediction system goes beyond techโ€”it's about embracing the joy of celebrations. As we explore MindsDB, Typeform, and Node.js, it's not just about coding but about connecting with the excitement of turning unknowns into well-calculated estimates. This project isn't just about algorithms; it touches the emotional side of event planning. It offers more than predictions; it gives a feeling of control and confidence. Technology becomes a tool for empowerment, ensuring the focus stays on the beauty of the moment, not the complexities. Whether you're a seasoned planner or a dreamer picturing the perfect event, dive into event cost prediction knowing that tech, used thoughtfully, turns dreams into reality. Cheers to creating enduring moments!

Let's build smarter, predict efficiently, and celebrate life's joyous occasions with technology as our ally!