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

Array map to new type in TypeScript

How to array map to a different type in Typescript


In my recent Nextjs project, need to shape object array to a different type.

Mapping through the entire array in my arrow function and return the new object.

Even though the return statement work. The type is still unknown. So, I have to covert the result into array of my type.

Mapping Array Type

export type LatestInvoiceType={
id:number;
amount: number;
customer:{
name:string;
email:string;
image_url:string;
}
}

New Type

 export type LatestInvoice = {

id: string;
name: string;
image_url: string;
email: string;
amount: string;
};

Solution to the problem

Here is my solution to the problem

    const latestInvoices  = invoices.map(invoice =>  {
      return{
      id:invoice.id.toString(),
      amount:invoice.amount.toString(),
      name:invoice.customer?.name,
      email:invoice.customer?.email,
      image_url:invoice.customer?.image_url
      };
    }) as LatestInvoice[] ;

Mac Mini M2 for Windows Developers

Moving from Windows to Mac


I got Mac Mini M2 last Saturday, wow. I love the Machine it saved my Desk. It is the base Model , with 8GB ,250 GB SSD.

I would like to share some of my experiences With M2. It is incredibly fast.

Running Windows 11 with Parallel VM

I’am using Parallels 8.0.1 , successfully configured windows 11 and installed Microsoft Visual Studio and it work without any trouble. Parallels allow me switch between Windows Apps and Mac Apps with ease and peace.

I did find some kinda of hanging and black out while the Mac went to sleep and wake from sleep.

Following Not working for me – Parallels

MSSQL Server

Docker

Above mentioned Apps can’t run on VM. So I decided to run it from Docker container which is on the Mac.

Apple Silicon and Docker

Some of the Docker Images not working with M2, it could be designed for Intel chip. So we need Rosetta for using such Docker images.

Installing Rosetta

Rosetta is referred as translater for Intel Mac Apps. You need not worry about any thing at all. Just install and move on.

 softwareupdate --install-rosetta

For more guides on Rosetta please visit MacHow

If you are a developer looking for Work Station with Multiple Display capabilities. Don’t wait to grab the deal today.

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.

Zustand, a minimal store for Rreactjs

In search for a minimal store for React applications.


I have been depending on Context for passing state through components in React and eventually thinks complicated when data is become complex. Move on to beautiful Redux is a bit expensive.

For learning Redux I have spent lots of time and Redux Toolkit, easy to use Redux, saved me a lot.

Even though RTK is ok, it is not a simple library. I am fan of Svelte store and Vuex, Pinia store. Is there any such library for React?

I recently found Zustand a minimal store for React. Love it. 😍

  1. Create a store
  2. Binding
  3. Updating the state

Create a store

Create a store using the create and export the custom hook.

import create from 'zustand'

const useBearStore = create((set) => ({
  bears: 0,
  increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
  removeAllBears: () => set({ bears: 0 }),
}))

Binding

In your component use the hook. The hook accepts a n arrow functions which will access to the state.

const paw = useBearStore ((state)=>state.bears;

The above statement is Reactive, which means that the changes occurs to the state will reflects. For non reactive purposes us the getState() method.

const paw = useBearStore.getState().bears

Updating the state

For updating the state we can use the setState method.

useBearStore.setState({ bears: 1})

Layout roots in Remix

Layout routes in Remix, how to apply layouts in Remix.


Under the route folder we can create our folder-based route in Remix. The home route can be found named as index.jsx.

Sometimes we need to display same UI for all pages, for instance a navbar for every route or sidebar links for every marketing page. This is where layouts come into play.

Root

Root layout is the default layout. If you need different layout for every page leave the root.jsx alone.


//root layout
export default function App() {
  return (
    <html lang="en">
      ...
        <Nav3/>   
        <Outlet />
        ....
    </html>
  );
}

Every layout should have <Outlet/> component this is similar to <Slot/> in Vuejs and Svelte, <NuxtPage/> in Nuxt. Outlet will render the route content says, index.jsx

Folder based route / dynamic route

In Remix route blog/index.jsx we can add blog.jsx for adding route layout. The layout should saved same level as the blog 📂. All routes under the blog would apply the layout.


// blog layout
export default function Blog() {
  return (
    
    <div className="flex justify-center">       
      <div className="prose lg:prose-xl py-10">
        <Outlet />
      </div>
    </div>
  );
}

Remix also supports delimiter-based route. For more documentation on Layout please refer Remix Doc

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 use styles in Remix

How to apply CSS styles in Remix


In Reactjs and Nextjs we usually use module bases styles. Remix has its own way for handling style sheets.

links

By defining and expoerting a links funtion in any component, route, Remix will apply those styles to that file. Go head and use those classes.

I gusess that , we can use multipple style sheets since the links functions return an array of style object.

import React from "react";
import styles from "./404.css";
export const links = () =&gt; {
  return [
    {
      rel: "stylesheet",
      href: styles,
    },
  ];
};
export default function NF() {
  return (
    <div>
      <div>
        <div>
          <h3>Oops! Page not found</h3>
          <h1>
            <span>4</span>
            <span>0</span>
            <span>4</span>
          </h1>
        </div>
        <h2>we are sorry, but the page you requested was not found</h2>
      </div>
    </div>
  );
}```

Wonder how Links works? In the root(root.jsx) the Links component included so no need to worry about it.

Not found page UI in Nextjs 13

Setup a Not Found Page Nextjs 13


Nextjs 13 comes with lots of experimental features, one of them was the appDir. Let’s talk about the setup a not found page.

Suppose we want to show not found page for the non-existing route. Nextjs allow you to define a custom Not Found page in app directory.

Create a not-found.jsx/tsx file in the route path and export a component with some cool UI and that’s it.

Each time a wrong path is navigated, the page will show up.

//posts/loading.jsx
export default  function Loading() {
 
  return(
<div>
Data is loading 
</div>
  )
}