JS通过@huggingface/inference库轻松调用HuggingFace平台上的各种AI模型

36 阅读2分钟

Hugging Face是什么?

Hugging Face 是当今最流行的 AI 社区和平台,托管了超过数十万个预训练模型,涵盖自然语言处理(NLP)、计算机视觉(CV)、音频处理等多个领域。虽然 Python 是 AI 领域的主流语言,但 JavaScript 生态(尤其是 Web 和 Node.js 后端)同样有巨大的集成需求。

@huggingface/inference 就是这个需求的产物。它作为官方 SDK,将 Hugging Face Inference API 的功能封装成了一个易于使用的 JS 库。

注册一个 Hugging Face 账户 并获取 Access Token

3223340c-2745-469d-9099-a360ab61ec5f.jpeg

img_v3_02s6_a90e4a07-024a-4ea2-8180-2d6ead1fb23g.jpg

  • 要注意选择的Token type类型,默认的无法调用成功。

安装@huggingface/inference

npm  install  @huggingface/inference

实现功能

调用指定模型实现图片转文字

import { InferenceClient } from "@huggingface/inference"
import fs from 'fs'

const HUGGINGFACE_API_KEY = 'hf_XXXXXX' 
const client = new InferenceClient(HUGGINGFACE_API_KEY);
export async function imageToText(image_url) {
  const image = fs.readFileSync(image_url);
  // console.log(image)
  // 将Buffer转化为data
  const base64Image = Buffer.from(image).toString('base64');
  const data = `data:image/jpeg;base64,${base64Image}`
 //  console.log(data)
  const chatCompletion = await client.chatCompletion({
    model: "google/gemma-3-27b-it:nebius",
    messages: [
        {
            role: "user",
            content: [
                {
                    type: "text",
                    text: "Identify the English text in the image and output it in English",
                },
                {
                    type: "image_url",
                    image_url: {
                        url:  data,
                    },
                },
            ],
        },
    ],
  });


  console.log(chatCompletion.choices[0].message.content);
  return chatCompletion.choices[0].message  
}

await imageToText("test.jpg")

实现文字转音频

async function tts(inputs) {
  console.log("输入的文本:" + inputs)
  const client = new InferenceClient(HUGGINGFACE_API_KEY)
  const output = await client.textToSpeech({
       provider: "replicate",
        model: "hexgrad/Kokoro-82M",
        inputs
  });
  console.log(output);
}

await tts("The answer to the universe is 42")

实现音频转文字

async function speechToText(blob, inputText) {
    if(blob) {

    } else {
      const data = fs.readFileSync("output.wav");
      blob = new Blob([data], { type: "audio/wav" });
    }
    
    const output = await client.automaticSpeechRecognition({
      data: blob,
      model: "openai/whisper-large-v3",
      // provider: "replicate", //replicate、hf-inference 提供商是免费的, fal提供商是收费的
      provider: "hf-inference",
    });
     console.log(output);
     // 结合文字转音频功能,判断下输入输出的文本是不是一致
     if (inputText) {
      if (trimText(inputText) === trimText(output.text)) {
        console.log("识别正常")
      } else {
        console.log("识别失败")
        console.log(trimText(inputText))
        console.log(trimText(output.text))
      }
     }
  }

  function trimText(text) {
    return text.trim().toLowerCase().trim().replaceAll(" ", "").replaceAll(".", "").replaceAll(",", "")
  }
  • whisper-large-v3调用几次后,就需要收费了

img_v3_02s6_57e7b8c1-e42e-4444-a29e-82198bc0db9g.jpg