Skip to content
AI & Vectors

使用 Hugging Face 生成图片标题

Use the Hugging Face Inference API to make calls to 100,000+ Machine Learning models from Supabase Edge Functions.

我们可以把 Hugging Face 和 Supabase 存储 以及 数据库 Webhooks 结合起来,为我们上传到存储桶的任何图片自动生成字幕。

🌐 We can combine Hugging Face with Supabase Storage and Database Webhooks to automatically caption for any image we upload to a storage bucket.

关于 Hugging Face #

🌐 About Hugging Face

Hugging Face 是机器学习社区的协作平台。

Huggingface.js 提供了一种方便的方式来调用 10 万多个机器学习模型,让你轻松将 AI 功能整合到你的 Supabase Edge Functions 中。

设置 #

🌐 Setup

  • 打开你的 Supabase 项目控制面板,或创建一个新项目
  • 创建一个名为 images 的新桶
  • 从远程数据库生成 TypeScript 类型。
  • 创建一个名为 image_caption 的新数据库表。
    • 创建一个类型为 uuidid 列,引用 storage.objects.id
    • 创建一个类型为 textcaption 列。
  • 重新生成 TypeScript 类型以包含新的 image_caption 表。
  • 把这个函数部署到 Supabase:supabase functions deploy huggingface-image-captioning
  • Supabase 仪表板 中创建数据库 Webhook,以便每当向 storage.objects 表添加记录时触发 huggingface-image-captioning 函数。

生成 TypeScript 类型 #

🌐 Generate TypeScript types

要为 storage 和 public 架构生成 types.ts 文件,在终端运行以下命令:

🌐 To generate the types.ts file for the storage and public schemas, run the following command in the terminal:

1
supabase gen types typescript --project-id=your-project-ref --schema=storage,public > supabase/functions/huggingface-image-captioning/types.ts

代码 #

🌐 Code

GitHub 上查看完整代码。

🌐 Find the complete code on GitHub.

1
import { HfInference } from 'https://esm.sh/@huggingface/inference@2.3.2'
2
import { createClient } from 'npm:@supabase/supabase-js@2'
3
4
import { Database } from './types.ts'
5
6
console.log('Hello from `huggingface-image-captioning` function!')
7
8
const hf = new HfInference(Deno.env.get('HUGGINGFACE_ACCESS_TOKEN'))
9
10
type SoRecord = Database['storage']['Tables']['objects']['Row']
11
interface WebhookPayload {
12
type: 'INSERT' | 'UPDATE' | 'DELETE'
13
table: string
14
record: SoRecord
15
schema: 'public'
16
old_record: null | SoRecord
17
}
18
19
Deno.serve(async (req) => {
20
const payload: WebhookPayload = await req.json()
21
const soRecord = payload.record
22
const SUPABASE_SECRET_KEYS = JSON.parse(Deno.env.get('SUPABASE_SECRET_KEYS')!)
23
const supabaseAdminClient = createClient<Database>(
24
// Supabase API URL - env var exported by default when deployed.
25
Deno.env.get('SUPABASE_URL') ?? '',
26
// Supabase API SECRET KEY - env var exported by default when deployed.
27
SUPABASE_SECRET_KEYS['default'] ?? ''
28
)
29
30
// Construct image url from storage
31
const { data, error } = await supabaseAdminClient.storage
32
.from(soRecord.bucket_id!)
33
.createSignedUrl(soRecord.path_tokens!.join('/'), 60)
34
if (error) throw error
35
const { signedUrl } = data
36
37
// Run image captioning with Huggingface
38
const imgDesc = await hf.imageToText({
39
data: await (await fetch(signedUrl)).blob(),
40
model: 'nlpconnect/vit-gpt2-image-captioning',
41
})
42
43
// Store image caption in Database table
44
await supabaseAdminClient
45
.from('image_caption')
46
.insert({ id: soRecord.id!, caption: imgDesc.generated_text })
47
.throwOnError()
48
49
return new Response('ok')
50
})