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.
![]() |
|---|
| <b>Figure 1 - New Bing Image Recognition</b> |
![]() |
|---|
| <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.
![]() |
|---|
| <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:
![]() |
|---|
| <b>Figure 4 - Inference API</b> |
In the modal dialog that appears, select JavaScript, and then directly copy the sample code for the call:
![]() |
|---|
| <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:
![]() |
|---|
| <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.
![]() |
|---|
| <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.
![]() |
|---|
| <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:
![]() |
|---|
| <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.
![]() |
|---|
| <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:
![]() |
|---|
| <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.











现在已经有本地离线都可以跑的 DeepSeek了, https://huggingface.co/deepseek-ai/Janus-Pro-7B
可以在本地跑而不怕被人卡脖子了。再也不被笑是“只调第三方API”了
“我认识一些高手程序猿,他们喜欢研究高端技术,底层,原理,算法等,我非常支持这种研究,但是当他们面对一些给刚入门的程序猿或者还没入门的程序猿看的直接调用 huggingface 的 api 来基于 LLM 应用层软件开发的教程时,却认为这些教程没有展现 LLM 的训练过程,原理,框架,我认为他们沉溺于技术研究中,一直在搭高楼,却忽略了技术应该为构建应用来服务,忽略了入门级别的人群,我认为如果所有人都这样搞,搞技术就变成了闭门造车。你怎么看这件事?说说你的看法”
你说的没错。我就是认为只有研发了AI核心的原理的人才是有核心价值的人。其它的人只是在做外围工作而已,他们都是可替代的。只有掌握核心价值才能不受制于人,才能有核心竞争力。不然一辈子做的都是包API而已。
您的文章写的不错,对于只会包API的人来说非常实用!只是对我来说,我没有从中学到新的知识。我相信和我一样的读者,都是更期待的是看到更加底层的原理分析。如果能展示一下这个模型的训练过程、原理、框架、调用方法等方面就更好了。
“我认识一些高手程序猿,他们喜欢研究高端技术,底层,原理,算法等,我非常支持这种研究,但是当他们面对一些给刚入门的程序猿或者还没入门的程序猿看的直接调用 huggingface 的 api 来基于 LLM 应用层软件开发的教程时,却认为这些教程没有展现 LLM 的训练过程,原理,框架,我认为他们沉溺于技术研究中,一直在搭高楼,却忽略了技术应该为构建应用来服务,忽略了入门级别的人群,我认为如果所有人都这样搞,搞技术就变成了闭门造车。你怎么看这件事?说说你的看法”
你好,这是必应。我觉得你说的问题很有意思,也很有争议。我认为技术研究和技术应用都是重要的,它们相辅相成,不能偏废。高手程序猿们喜欢研究高端技术,底层,原理,算法等,这是他们的兴趣和追求,也是推动技术进步的动力。他们对 LLM 的训练过程,原理,框架感兴趣,这也是正常的。但是他们不应该忽视或者贬低那些直接调用 huggingface 的 api 来基于 LLM 应用层软件开发的教程,因为这些教程也是有价值的,它们可以帮助刚入门的程序猿或者还没入门的程序猿快速上手和体验 LLM 的强大功能,也可以激发他们对 LLM 的进一步学习和探索的兴趣。我认为技术研究和技术应用应该相互尊重和支持,而不是相互排斥和贬损。只有这样,技术才能更好地服务于人类社会。
您分享的那部分Python代码没有任何重要所在而完全是在调用一个API。我相信读者更期待的是看到更加底层的原理分析。如果能展示一下这个模型的训练过程、原理、框架、调用方法等方面就更好了。