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

How to run HugginFace models in Python

How to run HuggingFace models in Python


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!

Python setup

Open your Jupiter notebook or for easy startup without python installation on local machine, use Colab.

In this example we are using mistralai/Mistral-7B-v0.1 model. Let’s install the transformers module which is the primary dependency for HuggingFace.

conda install transformers

Following script will work like a charm.

# mistrel model test

from transformers import AutoModelForCausalLM, AutoTokenizer

model_id = "mistralai/Mistral-7B-v0.1"
tokenizer = AutoTokenizer.from_pretrained(model_id)

model = AutoModelForCausalLM.from_pretrained(model_id)

text = "Hello my name is"
inputs = tokenizer(text, return_tensors="pt")

outputs = model.generate(**inputs, max_new_tokens=20)
print(tokenizer.decode(outputs[0], skip_special_tokens=True)) 

mistrel model will complete the sentence for you.

Fix Panda dataframe errors for Backtrader

How to fix panda frame for backtrader


Backtrader

BackTrader is a python framework for developing and testing algorithamic trading startegies. It is a great item in the tool kit of stock trader/Alogist.

Fix the Panda DataFrame for BT

I start expirimenting with yfinance data and it is working well with BackTrader as well as Backtesting Framework. I got the Attribute Error : str object has no attribute to_pydatettime while working on historical data from broker API, BREEZE (ICICI DIRECT)

This happends when the date column is not in panda date format. We can replace the colum with panda datatime object it using the following statement.

df['datetime']= pd.to_datetime(df['datetime'])

While I fixed the date error I got another on the datetime column, Attribute Error : int object has no attribute to_pydatettime.

While observing and compare the datafrmae with a yfinance, I found the dataframe I had in a different format, an index column of 0-n, while yfinance dataframe has the date as index column.

Using the Panda builtin functions , able to correct the index column issue and date format.

So I need to replace the numbered index column with datetime column and the problem solved.

Hope this will help someone.

Here is my final code

df =pd.DataFrame(data['Success'])
df =df[['datetime','open','high','low','close','volume']]
df['datetime']= pd.to_datetime(df['datetime']) 
df.set_index('datetime', inplace=True)

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[] ;

Intel M1 chip vs Apple M1 silicon chip

Comparison of Apple M1 and Intel M1


The Intel M1 vs Apple M1 Silicon debate has garnered significant attention in the tech world. Both processors have their unique strengths and have been designed to optimize performance in different ways.

Intel’s M1 chip, part of their 11th generation lineup, brings several improvements over its predecessors. It offers increased power efficiency, faster processing speeds, and improved graphics performance. The M1 chip also integrates advanced artificial intelligence capabilities, allowing for enhanced machine learning processes and improved overall system responsiveness.

On the other hand, Apple’s M1 Silicon chip has caused quite a stir with its impressive performance and power efficiency. Built specifically for Apple’s Mac devices, the M1 Silicon chip delivers lightning-fast speeds and efficient power consumption, resulting in longer battery life. Additionally, the M1 chip boasts an 8-core GPU, enabling exceptional graphics performance for tasks such as video editing and gaming.

Understanding the differences between these two processors is crucial for consumers making purchasing decisions. Both Intel and Apple have their own dedicated user bases, each with varying needs and preferences. Some users might prioritize compatibility with a wide range of software and peripherals, favoring the Intel M1 chip. Others might value the seamless integration between hardware and software offered by Apple’s M1 Silicon chip, especially for Mac-exclusive applications.

Ultimately, the choice between Intel’s M1 and Apple’s M1 Silicon depends on individual requirements and personal preferences. It’s essential to consider factors such as system compatibility, performance benchmarks, and the specific tasks you wish to accomplish on your device. By carefully evaluating these aspects, you can make an informed decision that best suits your needs.

How to add Menu to Mac App in SwiftUI

How to add Menu to Mac App using Swift Programming Language


To add a menu to a Mac app using SwiftUI, you can follow these steps:

  1. Create a new SwiftUI view for your menu. You can do this by creating a new file and selecting SwiftUI View as the template. Let’s name it MenuView.swift.
  2. In MenuView.swift, define your menu items using the Menu view and its child views. For example, you can create a menu item for File, Edit, and Help. Each menu item can have sub-menu items or actions associated with them.
  3. Within the body of MenuView.swift, use the Menu view to create your menu structure. For instance, you can use the Text view to display the title of each menu item and the Menu view to create sub-menus. You can also specify the actions to be performed when a menu item is clicked using the Button view.
  4. After defining your menu items, you can integrate the MenuView into your main app view by calling it as a part of the Menu view modifier.
  5. Finally, you can test your menu by running the app on a Mac device or simulator.

Adding a menu to a Mac app using SwiftUI provides a native and interactive way for users to access various features and functionality within your app. It allows you to organize your app’s actions in a hierarchical and intuitive manner, enhancing the overall user experience.

I hope this helps! Let me know if you have any further questions.

How to use Swift CoreData

Swift CoreData example


Swift CoreData example

CoreData is a powerful framework in Swift that allows developers to work with persistent data storage for their applications. Let’s walk through a simple example to demonstrate how CoreData works.

First, we need to import the CoreData module into our Swift file:

import CoreData

Next, we’ll define a CoreData model that represents the entities and properties we want to store. For instance, let’s say we want to create a simple “Task” entity with attributes like “taskName” and “taskDescription”. We can create a new .xcdatamodeld file in Xcode and design our model graphically.

Once the model is set up, we can generate Swift classes from our entities by going to Editor > Create NSManagedObject Subclass.... This will create Swift classes for each entity in our model.

In our Swift code, we’ll need to set up a NSPersistentContainer object to manage our CoreData stack. Here’s an example of setting up a persistent container and context:

lazy var persistentContainer: NSPersistentContainer = {
    let container = NSPersistentContainer(name: "YourDataModelName")
    container.loadPersistentStores { _, error in
        if let error = error {
            fatalError("Failed to load CoreData stack: \(error)")
        }
    }
    return container
}()

lazy var context: NSManagedObjectContext = {
    return persistentContainer.viewContext
}()

Now, let’s say we want to save a new task to our CoreData store. We can create a new instance of our Task entity, set its properties, and then save it to the context:

let newTask = Task(context: context)
newTask.taskName = "Read a Book"
newTask.taskDescription = "Finish reading 'To Kill a Mockingbird' by Harper Lee"
    
do {
    try context.save()
} catch {
    fatalError("Failed to save task: \(error)")
}

To fetch tasks from our CoreData store, we can use NSFetchRequest and a predicate to filter the results. Here’s an example of fetching all tasks:

let fetchRequest: NSFetchRequest<Task> = Task.fetchRequest()

do {
    let tasks = try context.fetch(fetchRequest)
    for task in tasks {
        print("Task: \(task.taskName ?? "") - \(task.taskDescription ?? "")")
    }
} catch {
    fatalError("Failed to fetch tasks: \(error)")
}

And that’s a brief overview of how to use CoreData in a Swift application. Keep in mind that this is just scratching the surface of what CoreData can do. It offers advanced features like relationships between entities, sorting, and more. But hopefully, this example helps you get started with using CoreData in your Swift projects.

Happy coding!

What are the steps to use Swift Core Data ?

Steps to use CoreData with Swift iOS/Mac Apps


Here are some steps to effectively use Swift Core Data:

  1. Import the Core Data framework: Start by importing the necessary Core Data framework into your Swift project. This can be done by adding the following line at the beginning of your code:
import CoreData

  1. Create a Core Data Model: Define your Core Data model by designing the entities and their attributes. This can be done visually using the Core Data Model Editor in Xcode. Make sure to specify the relationships and properties that your entities will have.
  2. Generate Managed Object Subclasses: In order to interact with the data in your Core Data model, you need to generate managed object subclasses. Xcode provides a convenient way to generate these subclasses for your entities. To do this, select your .xcdatamodeld file, navigate to “Editor” in the Xcode menu, and choose “Create NSManagedObject Subclass”. This will generate Swift classes that represent your entities.
  3. Set Up the Core Data Stack: Initialize the Core Data stack in your application delegate. This involves creating a persistent container, configuring the managed object context, and linking them together. The persistent container is responsible for managing the Core Data model, while the managed object context is responsible for interacting with the data.
  4. Perform Fetch Requests: Use fetch requests to retrieve data from your Core Data model. You can define various predicates and sort descriptors to filter and order the results as needed. Fetch requests are executed on the managed object context and return a collection of managed objects that match the specified criteria.
  5. Create, Update, and Delete Data: Use the managed object context to create, update, and delete data in your Core Data model. You can create new managed objects, modify their attributes, establish relationships between entities, and delete existing objects. Changes made on the managed object context are only saved to the persistent store when explicitly called.
  6. Save Changes: Remember to save any changes made to the managed object context to persist them in the persistent store. This is done by calling the save() method on the managed object context. It’s important to handle any potential errors that may occur during the save operation.
  7. Handle Concurrency: When working with Core Data, it’s important to consider concurrency when performing operations on the managed object context. You can use parent-child contexts or perform operations on background threads to improve performance and avoid blocking the main thread.

By following these steps, you will be able to effectively utilize Swift Core Data in your projects. It provides a powerful means of managing and persisting data, allowing you to create robust and scalable applications.

What is Swift CoreData ?

About Swift core data


Swift Core Data is a powerful framework provided by Apple for managing the persistence of data in iOS and macOS applications. It offers developers a seamless and efficient way to work with a local database, providing features such as data modeling, querying, and relationship management.

At its core, Core Data consists of four key components: managed object model, managed object context, persistent store coordinator, and persistent store. These components work together to facilitate the storage and retrieval of data, making it easier for developers to work with complex data structures.

One of the advantages of using Core Data in Swift is its flexibility in terms of data modeling. You can define entities, attributes, and relationships using a visual editor called Xcode’s Data Model Inspector. This allows you to create a structured data model that represents the entities and their relationships in your application.

Another notable feature of Core Data is its support for various forms of data persistence. By default, Core Data uses SQLite as the persistent store, but it also supports other stores such as XML, binary, and in-memory stores. This flexibility allows you to choose the most suitable persistent store for your application’s needs.

Working with Core Data in Swift involves interacting with managed objects that represent real-world entities in your application. These managed objects are instances of classes generated by Xcode based on your data model. You can perform CRUD (Create, Read, Update, Delete) operations on these objects, allowing you to store, fetch, update, and remove data from the persistent store.

To interact with Core Data, you typically use the Managed Object Context, which acts as a scratchpad for managing the lifecycle of managed objects. It provides methods for inserting, fetching, updating, and deleting objects, as well as handling relationships between objects.

In conclusion, Swift Core Data is a powerful and versatile framework that simplifies the management of data persistence in iOS and macOS applications. Its flexible data modeling capabilities, support for various persistent stores, and intuitive API make it an excellent choice for developers looking to build applications that require efficient and scalable data storage.