Generate image captions using Hugging Face
Use the Hugging Face Inference API to make calls to 100,000+ Machine Learning models from Supabase Edge Functions.
A guide from Supabase
Apps on Plentiful run on Supabase's open-source database, sign-in, file storage and live updates, so most of this guide applies. The differences: your app reaches its database through its own server — not Supabase's data API (supabase.from(…)) — there are no Edge Functions (your app's server does that work), and scheduled work uses Jobs. Where it says "Supabase dashboard", use your app's Dashboard. Ask the builder when in doubt.
We can combine Hugging Face with Supabase Storage and Database Webhooks to automatically caption for any image we upload to a storage bucket.
About Hugging Face#
Hugging Face is the collaboration platform for the machine learning community.
Huggingface.js provides a convenient way to make calls to 100,000+ Machine Learning models, making it easy to incorporate AI functionality into your Supabase Edge Functions.
Setup#
- Open your Supabase project dashboard or create a new project.
- Create a new bucket called
images. - Generate TypeScript types from remote Database.
- Create a new Database table called
image_caption.- Create
idcolumn of typeuuidwhich referencesstorage.objects.id. - Create a
captioncolumn of typetext.
- Create
- Regenerate TypeScript types to include new
image_captiontable. - Deploy the function to Supabase:
supabase functions deploy huggingface-image-captioning. - Create the Database Webhook in the Supabase Dashboard to trigger the
huggingface-image-captioningfunction anytime a record is added to thestorage.objectstable.
Generate TypeScript types#
To generate the types.ts file for the storage and public schemas, run the following command in the terminal:
1supabase gen types typescript --project-id=your-project-ref --schema=storage,public > supabase/functions/huggingface-image-captioning/types.tsCode#
Find the complete code on GitHub.
1import { HfInference } from 'https://esm.sh/@huggingface/inference@2.3.2'2import { createClient } from 'npm:@supabase/supabase-js@2'34import { Database } from './types.ts'56console.log('Hello from `huggingface-image-captioning` function!')78const hf = new HfInference(Deno.env.get('HUGGINGFACE_ACCESS_TOKEN'))910type SoRecord = Database['storage']['Tables']['objects']['Row']11interface WebhookPayload {12 type: 'INSERT' | 'UPDATE' | 'DELETE'13 table: string14 record: SoRecord15 schema: 'public'16 old_record: null | SoRecord17}1819Deno.serve(async (req) => {20 const payload: WebhookPayload = await req.json()21 const soRecord = payload.record22 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 )2930 // Construct image url from storage31 const { data, error } = await supabaseAdminClient.storage32 .from(soRecord.bucket_id!)33 .createSignedUrl(soRecord.path_tokens!.join('/'), 60)34 if (error) throw error35 const { signedUrl } = data3637 // Run image captioning with Huggingface38 const imgDesc = await hf.imageToText({39 data: await (await fetch(signedUrl)).blob(),40 model: 'nlpconnect/vit-gpt2-image-captioning',41 })4243 // Store image caption in Database table44 await supabaseAdminClient45 .from('image_caption')46 .insert({ id: soRecord.id!, caption: imgDesc.generated_text })47 .throwOnError()4849 return new Response('ok')50})