How to run HugginFace models in JavaScript

How to run HuggingFace models in Javascript


Hugging Face

Hugging face is a machine learning community where you can share pre trained models and explore other trained models, which are suited for many use cases.

Many of the models already trained well and ready to use. Without delay get started!

Initialize a node project

Initialize a node project by creating and run npm init on the terminal, this will create the basic package.json file.

Make sure that you are registered on HuggingFace and copied the TOCKEN.

No create mistel.js file for running mistrel lang model.

// mstrel.js
import { HfInference } from "@huggingface/inference";

const HF_TOKEN = "Your HugginFaceTocken";

const hf = new HfInference(HF_TOKEN);
 
const prompt ="Who am Christopher"
const res= await hf.textGeneration({
  model:"mistralai/Mixtral-8x7B-Instruct-v0.1", inputs:prompt 
})
console.log(res);

In the package.json add new script for running the file.

{
  "name": "hf",
  "type": "module",
  "version": "1.0.0",
  "description": "",
  "main": "test.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev1": "node mistrel.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@huggingface/inference": "^2.6.4"
  }
}

In this example we are using mistralai/Mixtral-8x7B-Instruct-v0.1 model. Make sure the dependency (@huggingface/inference) installed correctly using np install or yarn install

Now we are ready to test the script.

npm run dev

mistrel model will complete the sentence for you.

In this way we can accommodate ML in our React / or any JavaScript Framework projects

Create a dark mode theme switch in Nextjs 13

How to add dark theme capability in Nextjs app using next-themes


Creating React powered JavaScript application using Nextjs is easy. This example utilizes the experimental features of Nextjs 13.

I assume that you have Nextjs project ready in hand, otherwise follow the Next 13 app setup guide.

Theming the App

For theming I have been using Tailwind and for dark theme we can use a minimal library, next-themes.

Install the library using yarn or npm

$ npm install next-themes
# or
$ yarn add next-themes 

Theme Provider

First up all we need a theme provider component to pass the theme to all the component in app (experimental feature appDir of Nextjs 13) folder.

'use client'

import { ThemeProvider } from 'next-themes'

export function Providers({ children }) {
  return <ThemeProvider attribute="class">{children}</ThemeProvider>
}

Here we used the ThemeProvider of next-themes for applying the theme.

Note that we should mark the component as client component.

In Nextjs appDir feature will set all component sever side components by default.

Tailwind configuration

When we using Next-Theme with Tailwind we may need to use the Tailwind dark theme, so we can use TW class.

 /** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./app/**/*.{js,ts,jsx,tsx}",
    "./pages/**/*.{js,ts,jsx,tsx}",
    "./components/**/*.{js,ts,jsx,tsx}",
 
    // Or if using `src` directory:
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
  darkMode: 'class'
}

Root Layout

In the root layout we can wrap the body of the app with the Provider.

Theme Switcher

We need a component for switching between Light and Dark theme.

'use client'
import { useState, useEffect } from "react";
import { useTheme } from "next-themes";
import { SunIcon } from "@heroicons/react/outline";

const ThemeSwitch = () => {
  const [mounted, setMounted] = useState(false);
  const { theme, setTheme } = useTheme();
  // useEffect only runs on the client, so now we can safely show the UI
  useEffect(() => {
    setMounted(true);
  }, []);

  if (!mounted) {
    return null;
  }
  

  return (
    <div className="inline-flex items-center">
      <SunIcon className="w-4 h-4 mr-2" />
      <select
        name="themeSwitch"
        value={theme}
        onChange={e =>setTheme(e.target.value)}>
        <option value="system">System</option>
        <option value="dark">Dark</option>
        <option value="light">Light</option>
      </select>
    </div>
  );
};

Using the useTheme hook and setTheme method we can change the theme, easily from any component.

Matching a non-existing/404 route in Remix

How to define a 404 page in Remix


The route directory of Remix is the home for all of the navigation paths, or they are the individual pages.

So how should I catch a route when someone hit non existing page? A default route will fire automatically, but sometimes we need to create one. How?

Remix allow us to define a $.jsx route and export a React component which will catch all routes. So, try to create one now. See the result.

How to enable validation on visited fields in Formik

How to enable validation in visited fields in Formik


We can make form validation of our own with custom hook, but there is a good library for that already, Formik.

Formik provide useForm hook for implementing the validation into our regular form.

Visited field

In input fields in a form get validated using onChange handler provided by the hook, for visited fields Fomik provides onBlur handler.

   const formik = useFormik({
    initialValues: {
      email: '',
      name: '',
      password: 'foobar',
      cid: '',
      lid: ''
    },
    validate,
  onSubmit: (values) => {

In the form field we can use handler as

 <TextField
                    
                    onBlur={formik.handleBlur}
                    
                    error={formik.touched.name && Boolean(formik.errors.name)}
                    helperText={formik.touched.name && formik.errors.name}
                    autoFocus
                  />

Integrating Formik with Form and Mui so easy, isn’t it? Follow posts may help you learn more on the go.

Integrate Formik validation with Mui Form in React

How integrate Mui with React


We can make form validation of our own with custom hook, but there is a good library for that already, Formik.

Formik provide useForm hook for implementing the validation into our regular form. The first step of using Formik is installing the dependency, lol, also we need a validator function to perform validation.

const validate = values => {
  const errors = {};

  if (!values.password) {
    errors.password = 'Required';
  } else if (values.password.length < 6) {
    errors.password = 'Must be must be 6 or more characters';
  }
  if (!values.name) {
    errors.name = 'Name Required';
  } else if (values.name.length < 1) {
    errors.name = 'Minimum of 2 characters';
  }
}

It is just another JavaScript function, which check the parameter value and return some object.

useFormik

Let’s create Formik object,

const formik = useFormik({
    initialValues: {
      email: 'martin@gmail.com',
      name: 'Martin Thomas',   
    },
    validate,
    onSubmit: (values) => {
       alert(JSON.stringify(values, null, 2));
    },
  });

The useForm hook provide handleSubmit, handleChange, handleBlur, isSubmiting event handlers and properties’ , where handleBlur watching the revisited input change and the isSubmiting return true if there is no error.

Initial values

Create initial values for the form input, it can be expressed as simple object

Validate

Validation can be schema , or a function, we can also use external libraries such as yum for schema generation. For our case it is a function

const validate = values => {
  const errors = {};

  if (!values.password) {
    errors.password = 'Required';
  } else if (values.password.length < 6) {
    errors.password = 'Must be must be 6 or more characters';
  }
  if (!values.name) {
    errors.name = 'Name Required';
  } else if (values.name.length < 1) {
    errors.name = 'Minimum of 2 characters';
  }
  if (!values.email) {
    errors.email = 'Required';
  } else if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(values.email)) {
    errors.email = 'Invalid email address';
  }
  if (!values.lid) {
    errors.lid = 'Required';
  }

  if (!values.cid) {
    errors.cid = 'Required';
  }

  return errors;
};

onSubmit

We can wrap submission logic in this handler.

Add validation to the form

In the form section we can us the handlers as formik.handlerName also the value can can be accessed from the value Object. The error object can be use to display the error messages.

import React from 'react';
import { useFormik } from 'formik';
import Button from "@mui/material/Button"; 
import CssBaseline from "@mui/material/CssBaseline";
import TextField from "@mui/material/TextField"; 
import Grid from "@mui/material/Grid";
import Box from "@mui/material/Box"; 
import Typography from "@mui/material/Typography";
import Container from "@mui/material/Container";
import { createTheme, ThemeProvider } from "@mui/material/styles";

 
.... 
const formik = useFormik({
    initialValues: {
      email: 'martin@gmail.com',
      name: 'Martin Thomas',   
    },
    validate,
    onSubmit: (values) => {
       alert(JSON.stringify(values, null, 2));
    },
  });
<div>
      <ThemeProvider theme={theme}>
        <Container component="main" maxWidth="xs">
          <CssBaseline />
          <Box
            sx={{
              marginTop: 8,
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
            }}
          >
            
            <Box
              component="form"
              onSubmit={formik.handleSubmit}
              sx={{ mt: 3 }}
            >

              <Grid container spacing={2}>
                <Grid item xs={12} sm={12}>
                  <TextField
                    autoComplete="given-name"
                    name="name"
                    required
                    fullWidth
                    id="name"
                    label="Name"
                    onBlur={formik.handleBlur}
                    value={formik.values.name}
                    onChange={formik.handleChange}
                    error={formik.touched.name && Boolean(formik.errors.name)}
                    helperText={formik.touched.name && formik.errors.name}
                    autoFocus
                  />
                </Grid>

                <Grid item xs={12}>
                  <TextField
                    required
                    fullWidth
                    id="email"
                    onBlur={formik.handleBlur}
                    label="Email Address"
                    name="email"
                    autoComplete="email"
                    value={formik.values.email}
                    onChange={formik.handleChange}
                    error={formik.touched.email && Boolean(formik.errors.email)}
                    helperText={formik.touched.email && formik.errors.email}
                  />
                </Grid>
                  
              
              <Button
                type="submit"
                 disabled={formik.isSubmitting}
                fullWidth
                variant="contained"
                sx={{ mt: 3, mb: 2 }}
              >
                Sign Up
              </Button>
              

            </Box>
          </Box>      
        </Container>
      </ThemeProvider>       
    </div>

Integrating Formik with Form and Mui so easy.