0. Why This Blog Post Exists

Recently, the buzz around AI tools like ChatGPT and Stable Diffusion has cooled off outside the tech community, but enthusiasm within the community remains strong. LLM tools primarily focus on question-answering and text generation, while tools like Stable Diffusion and Midjourney mainly handle text-to-image and image-to-image generation. It seems there’s a gap in open-source tools that can recognize images and generate textual descriptions, yet this is clearly a widespread need. New Bing recently launched this feature, allowing you to upload an image and ask questions about it—remarkably powerful! However, it is not open-source. Today, I’m sharing an open-source solution that can be set up in just 3 minutes.

Figure 1 - New Bing Image Recognition
<b>Figure 1 - New Bing Image Recognition</b>
Figure 2 - My Image-to-Text Tool
<b>Figure 2 - My Image-to-Text Tool</b>

1. Selecting an Appropriate Model on HuggingFace

Since I am currently unemployed and do not have the funds to purchase server resources, I am unable to deploy the model myself. Therefore, I have chosen to use the HuggingFace API for free. If you have sufficient budget to purchase GPU resources, you are fully capable of deploying the model to your own server. Below, I will demonstrate how to call the HuggingFace API. If you prefer to see instructions for self-deployment, please wait until I can afford a GPU, and I will write a blog post covering that then. 😢

First, you need to register for a Hugging Face account. The Hugging Face website is located at: https://huggingface.co/

After registering and logging in, click your profile picture in the top-right corner. Follow the steps shown in the image below to navigate to the Access Tokens page, generate a Token, and copy it.

Figure 3 - Get Access Token
<b>Figure 3 - Get Access Token</b>

Then we choose a suitable image-to-text model. In this case, I selected Salesforce's blip-image-captioning-large model: https://huggingface.co/Salesforce/blip-image-captioning-large

Go to this page, click Deploy, and then click Inference API:

Figure 4 - Inference API
<b>Figure 4 - Inference API</b>

In the modal dialog that appears, select JavaScript, and then directly copy the sample code for the call:

Figure 5 - Copy sample code
<b>Figure 5 - Copy sample code</b>

As I mentioned earlier, I don't have server resources. So, I plan to leverage Laf for free. Laf is a cloud development platform that integrates functions, databases, and storage, allowing you to deploy and go live anytime, anywhere. In this project, I utilize its JavaScript cloud function feature. Therefore, I have chosen to copy the JavaScript sample code. If you prefer to use Python or cURL and other languages or tools for API calls, you can copy the corresponding sample code.

My Laf account has a certain amount of free quota provided by the official Laf, which is great for me to use for free. Excellent! 🎉

Laf provides services in both mainland China and overseas. The domain for mainland China is https://laf.run/, and the domain for overseas is https://laf.dev/. Since I need to call the HuggingFace API, I have chosen to use the overseas version. However, I have not tested whether the mainland China version can access the HuggingFace API. It might actually work.

2. Create a Laf Cloud Function for Image to Text Conversion

First, go to https://laf.dev/ to register a Laf account. After registration, go to the dashboard and create a new Laf application:

Figure 6 - Create New Laf Application
<b>Figure 6 - Create New Laf Application</b>

Pick any name you like, then select the specifications. We don't need a high-performance configuration here, since we're only making relay calls to the HuggingFace API.

After creating the app, you can see the newly created app on this page. Click the three dots on the right and select Run App. Then, click "Development" in the action bar on the right to enter the cloud function development page.

Figure 7 - Setting the Token Environment Variable
<b>Figure 7 - Setting the Token Environment Variable</b>

As shown in the image above, first click the settings button in the bottom-left corner, select environment variables, and add a HUGGINGFACE_TOKEN environment variable. Paste the HuggingFace Access Token we copied earlier as a string value.

Figure 8 - Create img2text Cloud Function
<b>Figure 8 - Create img2text Cloud Function</b>

As shown in the image above, click the plus sign to create a cloud function. I named mine img2text and only checked the POST method.

Here is the code for my cloud function. My JavaScript skills are average since I primarily work with .NET backends, so please bear with me. I've added comments to the more critical parts.

Specifically, we retrieve the HUGGINGFACE_TOKEN environment variable we set from process.env, and get the uploaded files from ctx. We take the 0th item as the file, which is the image we plan to convert to text, and store it in the file variable. Then, we perform some basic validation on the name, type, and size.

The img2text function is the JavaScript calling example code we previously copied from HuggingFace, with some minor adjustments made by me.

import cloud from '@lafjs/cloud'

const fs = require("fs")

export default async function (ctx: FunctionContext) {
  // 获取到所有 file
  const _files = ctx.files;
  // 从环境变量中获取到 HUGGINGFACE_TOKEN
  const apiKey = process.env['HUGGINGFACE_TOKEN'];

  // 校验 start
  console.log('uploadFile->files', _files);

  // 取 _files 中的第 0 个作为我们要处理的文件
  const file = _files[0];
  if (!_files || _files.length == 0) {
    return '未上传文件!';
  }
  const fileInfo = _files[0];
  if (!fileInfo.filename) {
    return '文件名称为空!';
  }
  if (!fileInfo.mimetype) {
    return '文件类型为空!';
  }
  const mimetype = file.mimetype;
  console.log(mimetype);
  if (!mimetype.startsWith("image/")) {
    return '不合法的图片文件!';
  }
  if (!fileInfo.size || fileInfo.size > 5 * 1024 * 1024) {
    return '文件大小不能超过5M!';
  }
  // 校验 end

  // 获取上传文件的对象
  let fileData = await fs.readFileSync(fileInfo.path);

  // 调用 HuggingFace 接口获取图片转文本的结果
  const img2textResp = await img2text(fileData, apiKey);

  // 取到 Response 中的 generated_text 字段,即图片转文字后的字符串
  const imgText = img2textResp[0].generated_text
  return imgText;
}

// 调用 HuggingFace API 实现图片转文本
async function img2text(fileData, apiKey) {
  const response = await fetch(
    "https://api-inference.huggingface.co/models/Salesforce/blip-image-captioning-large",
    {
      headers: { Authorization: `Bearer ${apiKey}` },
      method: "POST",
      body: fileData,
    }
  );

  // 将得到的结果反序列化并返回后
  const result = await response.json();
  return result;
}

The format of the result returned by calling the HuggingFace interface is as follows:

[{"generated_text": "a close up of a small black and yellow animal wearing a bee costume"}]

So in the img2text function, I use const result = await response.json(); to deserialize and return the result. Then, in the main function, I use const imgText = img2textResp[0].generated_text to extract the generated_text field into the imgText variable and return it. Ultimately, we return a simple string of text converted from the image. If the image uploaded by the user fails validation, an error message will be returned.

We can use the debugging section on the right side of laf to debug:

Figure 9 - Debugging Cloud Functions
<b>Figure 9 - Debugging Cloud Functions</b>

In sequence, select Interface Debugging, the POST request method, and the form data parameter passing method for the Body. Click the upload button to select an image for upload, and then click Run to view the execution results in the result window below. You can check the logs in the Console.

After debugging is complete, click "Publish" in the upper right corner to publish the cloud function. Next to it is the cloud function's address, which you can copy.

Figure 10 - Publishing Cloud Functions
<b>Figure 10 - Publishing Cloud Functions</b>

3. Implementing a Simple Frontend Using Laf Cloud Functions

I plan to fully embrace the "free tier" approach and directly return a string of frontend code from the cloud function. This eliminates the need for a separate server to host the frontend code.

So, following the steps I used earlier to create a cloud function, I created a cloud function using the GET method and named it do. I wrote some basic styles and frontend code, which serves as the return value string for this cloud function, and returned it directly:

import cloud from '@lafjs/cloud'

export default async function (ctx: FunctionContext) {
  console.log('Hello World')
  return `
  <style>
    body {
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

    input {
      width: 300px;
      border: 1px solid gray;
      padding: 5px;
      margin: 10px;
    }

    button {
      width: 100px;
      height: 30px;
      background-color: blue;
      color: white;
      border: none;
      padding: 5px;
      margin: 10px;
    }

    button:hover {
      background-color: darkblue;
    }

    div {
      width: 300px;
      height: 100px;
      border: 1px solid gray;
      padding: 5px;
      margin: 10px;
      text-align: center;
    }

    img {
      max-width: 500px;
    }
  </style>
  <input type="file" id="imageInput" accept="image/*" onchange="showImage()">
  <button onclick="uploadImage()">图片转文字</button>
  <div id="result"></div>
  <script>
    function uploadImage() {
      var input = document.getElementById("imageInput");
      var file = input.files[0];
      var formData = new FormData();
      formData.append("image", file);
      var xhr = new XMLHttpRequest();
      // open 的第二个参数填入前面复制的第一个云函数的地址
      xhr.open("POST", "https://i6giyd.laf.dev/img2text");
      xhr.onload = function() {
        if (xhr.status === 200) {
          var responseText = xhr.responseText;
          var result = document.getElementById("result");
          result.textContent = responseText;
        } else {
          alert("Upload failed: " + xhr.statusText);
        }
      };
      xhr.send(formData);
    }
    function showImage() {
      var input = document.getElementById("imageInput");
      var file = input.files[0];
      var reader = new FileReader();
      reader.onload = function() {
        var dataURL = reader.result;
        var img = document.createElement("img");
        img.src = dataURL;
        var body = document.body;
        body.insertBefore(img, body.firstChild);
      };
      reader.readAsDataURL(file);
    }
  </script>
  `;
}

Fill the second argument of open with the address of the first cloud function copied earlier. I have already marked this in the code with comments. This is all basic front-end code, so I won't provide a detailed explanation.

Then, publish the cloud function, copy its address, and access it directly in the browser:

Figure 11 - Image Recognition Result Display
<b>Figure 11 - Image Recognition Result Display</b>

The image recognition results are in English. You can either connect a translation API to translate them into Chinese and return them to the user, or replace Salesforce's blip-image-captioning-large model with a Chinese-supporting image recognition model. You have now mastered the basic development methods. For future features, feel free to add whatever your imagination suggests.