Tutorials

Tutorials

Example of implementation

In this section, we take the website skeeleftea.se and implement rek.ai for the following functions:

Recommend news with custom template

Start by looking at this example

After a visitor reads a news item, we want to add additional news items for him or her to discover.

We do this easily by showing recommended news under the article.
In order to have full control over how these are displayed, we choose to render them using Javascript.
This example uses the built-in support for jQuery in SiteVision.

Add your own classes to the script to get the design you want.

<div class="output"></div>
 
<script>
  $( document ).ready(function() {
 
    // Function for rendering predictions
    function renderHTML(data) {
      var myHtml = '';
      // Create wrapper
      myHtml += '<div class="row">';
 
      // How many news do we want to print
      var added  = 0;
      var newsToPrint = 2
 
      for(var i = 0; i < data.predictions.length; i++) {
        // Are we done?
        if(added == newsToPrint) {
          break;
        }
        else {
          // Check so not current news
          var url = data.predictions[i].url;
          if(window.location.pathname != url) {
            // For each prediction we want to render
            added++;
            var ingress = data.predictions[i].ingress;
            var title = data.predictions[i].title;
            var imgurl = data.predictions[i].imgurl;
 
            myHtml += '<div class="column-6" >';
            myHtml += '<img src="' + imgurl + '">';
            myHtml += '<p clas="font-normal">';
            myHtml += '<a href="' + url + '" aria-label="' + title +'">';
            myHtml += title;
            myHtml += '</a><br>';
            myHtml += ingress;
            myHtml += '</p>';
            myHtml += '</div>';
          }
        }
      }
      myHtml += '</div>';
 
      // Replace with the div you want to append the news to
      $('.output').html(myHtml);
    }
 
    // Add for example subtree
    var options = {
      overwrite: {
        subtree: 'news',
        addcontent: true
      }
    }
 
    window.__rekai.predict(options, renderHTML);
  });
</script>

The result is that two news are added in width below the news the visitor is reading. In this way, we help our visitors discover new material.

Add recommendations to a existing list

If the webpage already contains a list of links and you wish to add a number of recommended links that should have the same style, the simplest approach is to use JavaScript. In this example, the homepage features a selection of links chosen by the editors, but we want to add three additional recommended links. However, it's important that these new links are not duplicates of the ones that already exist.

In the example below, we first retrieve all the HTML for the existing list so we can review it before adding new links. The new links have the exact same HTML structure as the existing ones, ensuring a consistent appearance.

How it looks before adding rek.ai. Add recommendations to a existing list

<script>
  $( document ).ready(function() {
 
    var totalLinksToAdd = 3;
 
    function myCallback(data) {
      // Save current links so we don´t duplicates them
      var listHtml = $('.sol-popular-pages ul').html();
      // How many new links do we want to add
      var added = 0;
 
      var html = '';
      for(var i = 0; i < data.predictions.length; i++) {
        if(added < totalLinksToAdd) {
          // Check so the new link isn´t in the current array of links
          if(listHtml.indexOf(data.predictions[i].url) === -1) {
            // Create each li to add to list
            html += '<li><a href="' + data.predictions[i].url + '" title="' + data.predictions[i].title + '">';
            html += '<i class="fal fa-arrow-right" aria-hidden="true"></i><span>' + data.predictions[i].title + '</span>';
            html += '</a></li>';
            added++;
          }
        }
      }
 
      // Add to exsiting list
      $('.sol-popular-pages ul').append(html);
    }
 
    var options = {
      overwrite: {
        nrOfHits: totalLinksToAdd * 2
      }
    }
 
    // Do recommendation with Javascript
    window.__rekai.predict(options, myCallback);
  });
</script>

After adding the links. Add recommendations to a existing list

To recommend the top page from two different categories

Should you aim to showcase the foremost article within two or more categories, it is advisable to formulate multiple recommendations, ensuring each is assigned a unique subcategory.

Aligning these recommendations within an HTML structure side by side will create an aesthetically pleasing and cohesive presentation.

Exmaple of two recommendations

Example in html

<div class="flex-wrpper">
  <div class="col-1">
    <div id="news" data-selector="#news" class="rek-prediction" data-nrofhits="1" data-subtree="/news"></div>
  </div>
  <div class="col-2">
    <div id="event" data-selector="#event" class="rek-prediction" data-nrofhits="1" data-subtree="/event"></div>
  </div>
</div>

Example in Sitevision

Use two or more modules where each module only displays one hit. Then you can make settings so that each module only shows hits within a certain category.

Exmaple of two recommendations in Sitevision

How to make intranet recommendations contain images and texts

Rek.ai automatically sends information about intranet pages to our database.

The javascript looks for <meta> tags with information about image, description, etc.

So add these tags to your HTML and the recommendations will automatically look right.

For Sitevision

If you don't already have a script to create meta tags on your intranet, we have a ready-made Velocity script for this.

It is a simple function and can only be entered under Properties (Kodtillägg i Egenskaper) in Sitevision.

Exmaple of two recommendations

If you have questions regarding this, just contact support@rek.ai

https://gist.github.com/rekai2/6873f9742cc443d6e384c3c0aa40af66 (opens in a new tab)

Examples of using custom features

Save if the visitor has passed a certain page

By saving if a visitor has passed a certain branch of the website during their session, we can create stronger recommendations.

A typical example could be if the visitor shows an interest in taking up a job.

In the example below, we save a custom feature as soon as the visitor visits a page about applying for a job.

<script>
  try {
    if(window.location.pathname.indexOf('Work with us') > -1) {
      sessionStorage.setItem('rekf1', 1);
    }
  } catch(It is) {}
</script>

More advanced example for a real estate company

In the example below, we use a fictitious real estate company that wants to make use of real estate recommendations.

In order for the recommendations to be as good as possible, we want to add knowledge to the model in the form of:

  • Number of rooms
  • Price category
  • Property type

Property type fits as a string metadata and should therefore use f21. While the other two fit as numerical.

Since the model can only handle numeric values ​​between -1 and 1, we have to translate the values ​​ourselves. Here you can use your business knowledge to do the translation.

Examples of translation can then be:

On the property object template, we add the following code to send the values ​​to our system.

In the example, we let the values ​​come from a server-side velocity script; and is therefore printed with "$" before the name.

<script>
  var nrOfRooms = $nrOfRooms;
  var price = $price;
  var type = $type;
 
  function setRectCookie(name,value,days) {
    var expires = "";
    if (days) {
      var date = new Date();
      date.setTime(date.getTime() + (days*24*60*60*1000));
      expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
  }
 
  // Transform to AI-feature in range -1 to 1
  // Transform nrOfRooms
  function transformNrOfRooms(nrOfRoomsInput) {
    switch(nrOfRoomsInput) {
      case 1:
      nrOfRoomsInput = -1;
      break;
      case 2:
      nrOfRoomsInput = -0.5;
      break;
      case 3:
      nrOfRoomsInput = 0;
      break;
      case 4:
      nrOfRoomsInput = 0.5;
      break;
      default:
      nrOfRoomsInput = 1;
    }
    return nrOfRoomsInput;
  }
 
  // Transform price
  function transformPrice(priceInput) {
    if(priceInput < 500000) {
      priceInput = -1;
    }
    else if(priceInput < 1000000) {
      priceInput = -0.75;
    }
    else if(priceInput < 2000000) {
      priceInput = -0.5;
    }
    else if(priceInput < 3000000) {
      priceInput = 0;
    }
    else if(priceInput < 4000000) {
      priceInput = 0.5;
    }
    else if(priceInput < 5000000) {
      priceInput = 0.75;
    }
    else if(priceInput < 7000000) {
      priceInput = 0.85;
    }
    else {
      priceInput = 1;
    }
    return priceInput;
  }
 
  // Save custom features to cookies
  var days = 30;
  setRekCookie('rekf1', transformNrOfRooms(nrOfRooms), days);
  setRekCookie('rekf2', transformNrOfRooms(price), days);
  setRekCookie('rekf21', type, days);
</script>

There may be a point in saving in a cookie (as in the example) what type of residence a visitor has visited before.

This means that we can already show relevant recommendations on the home page without the visitor looking at an ad.

Other ways to store it are possible to.

Use how long a person has been employed as a custom feature

By adding the knowledge of length of employment, we can reinforce how our AI model recommends pages.

To do this, the number of days needs to be converted to a number between -1 and 1.

We also need to determine a maximum ceiling for the length of employment.

<script>
  // Gets the value -1 to 1 from a percent
  function percentToNormalized(p) {
    if(p > 0.5) {
      p = p - 0.5;
      p = p * 2;
    } else {
      p = (1 - (p*2)) * -1;
    } // No lower or higher then -1 to 1
    if(p < -1) {
      p = -1;
    } else if(p > 1) {
      p = 1;
    }
    // Four decimal places
    p = Math.round((p + Number.EPSILON) * 10000) / 10000;
    return p;
  }
  // Gets diff in months
  function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;
    months -= d1.getMonth();
    months += d2.getMonth();
    return months <= 0 ? 0 : months;
  }
 
  // This date comes from backend
  var startDate = new Date('2020-01-15');
  var today = new Date();
  // Ten years
  var maxmonths = 10 * 12;
  var monthsEmployeed = Math.min(monthDiff(startDate, today), maxmonths);
  var percentAsFeature = percentToNormalized(monthsEmployeed / maxmonths);
 
  // Init object if not existing
  window.rek_customfeature = window.rek_customfeature || [];
  // Custom feature 1 is for employee
  window.rek_customfeature['f1'] = percentAsFeature;
</script>

Add your own search box to the search results page

If you have an external index in your AI model, you can display hits from this on your search results page.

Below is an example of a possible implementation.

<script>
  function transformRequestString(params) {
    // Get searchterm
    var searchTermName = 'query';
    var searchTerm = '';
 
    try {
      // Get query from a complex search parameter combination
      searchTermName += '=';
      var windowSearch = window.location.search;
      var searchTermNameEndPos = windowSearch.indexOf(searchTermName) + searchTermName.length;
      searchTerm = windowSearch.substring( searchTermNameEndPos + 1);
      if(searchTerm.indexOf('&') > -1) {
        searchTerm = searchTerm.substring(0, searchTerm.indexOf('&'));
      }
    }
    catch(e) {}
 
    params += '&term=' + searchTerm;
    return params;
  }
 
  window.__rekai = window.__rekai || {};
  window.__rekai.transformRequestString = transformRequestString;
 
  // Add event for reload when clicking "search". This exmple uses jQuery
  $( document ).ready(function() {
    $("input[name='submitButton']").on('click', function() {
      // Reloads all predictions
      window.__rekai.checkAndCreatePredictions( window.__rekai.customer );
    });
  });
</script>
 
<div class="rek-prediction" data-domain="YOUR-EXTERNAL-WEB"></div>