Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat: add huggingface example and guide.

thorwebdev77441f52e2c4
diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
index 64a9995d9f9..9652598fcb8 100644
--- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
+++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
@@ -751,6 +751,7 @@ export const functions: NavMenuConstant = {
items: [
{ name: 'Dart Edge on Supabase', url: '/guides/functions/dart-edge' },
{ name: 'Browserless.io', url: '/guides/functions/examples/screenshots' },
+ { name: 'Hugging Face', url: '/guides/functions/examples/huggingface-image-captioning' },
{ name: 'OpenAI API', url: '/guides/functions/examples/openai' },
{ name: 'Upstash Redis', url: '/guides/functions/examples/upstash-redis' },
{ name: 'Type-Safe SQL with Kysely', url: '/guides/functions/kysely-postgres' },
diff --git a/apps/docs/pages/guides/functions.mdx b/apps/docs/pages/guides/functions.mdx
index 43766eb0b21..bb8157e871b 100644
--- a/apps/docs/pages/guides/functions.mdx
+++ b/apps/docs/pages/guides/functions.mdx
@@ -113,6 +113,11 @@ export const examples = [
description: `Request Routing with Oak server middleware.`,
href: 'https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/oak-server',
},
+ {
+ name: 'Hugging Face',
+ description: `Access 100,000+ Machine Learning models.`,
+ href: '/guides/functions/examples/huggingface-image-captioning',
+ },
{
name: 'OpenAI',
description: `Using OpenAI in Edge Functions.`,
diff --git a/apps/docs/pages/guides/functions/examples/huggingface-image-captioning.mdx b/apps/docs/pages/guides/functions/examples/huggingface-image-captioning.mdx
new file mode 100644
index 00000000000..087567f9650
--- /dev/null
+++ b/apps/docs/pages/guides/functions/examples/huggingface-image-captioning.mdx
@@ -0,0 +1,104 @@
+import Layout from '~/layouts/DefaultGuideLayout'
+
+export const meta = {
+ title: 'Hugging Face',
+ description:
+ 'Use the Hugging Face Inference API to make calls to 100,000+ Machine Learning models from Supabase Edge Functions.',
+ video: 'https://www.youtube.com/v/OgnYxRkxEUw',
+ tocVideo: 'OgnYxRkxEUw',
+}
+
+[Hugging Face](https://huggingface.co/) is the collaboration platform for the machine learning community.
+
+[Huggingface.js](https://huggingface.co/docs/huggingface.js/index) 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](https://supabase.com/edge-functions).
+
+Putting this together with [Supabase Storage](https://supabase.com/storage) and [Database Webhooks](https://supabase.com/docs/guides/database/webhooks) we can easily put together a service that automatically generates captions for any image we upload to a storage bucket.
+
+<div class="video-container">
+ <iframe
+ src="https://www.youtube-nocookie.com/embed/OgnYxRkxEUw"
+ frameBorder="1"
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
+ allowFullScreen
+ ></iframe>
+</div>
+
+## Setup
+
+- Open your Supabase project dashboard or [create a new project](https://app.supabase.com/projects).
+- [Create a new bucket](https://app.supabase.com/project/_/storage/buckets) called `images`.
+- Generate TypeScript types from remote Database.
+- Create a new Database table called `image_caption`.
+ - Create `id` column of type `uuid` which references `storage.objects.id`.
+ - Create a `caption` column of type `text`.
+- Regenerate TypeScript types to include new `image_caption` table.
+- Deploy the function to Supabase: `supabase functions deploy huggingface-image-captioning`.
+- Create the Database Webhook in the [Supabase Dashboard](https://app.supabase.com/project/_/database/hooks) to trigger the `huggingface-image-captioning` function anytime a record is added to the `storage.objects` table.
+
+## Generate TypeScript Types
+
+To generate the types.ts file for the storage and public schemas, run the following command in the terminal:
+
+```bash
+supabase gen types typescript --project-id=your-project-ref --schema=storage,public > supabase/functions/huggingface-image-captioning/types.ts
+```
+
+## Code
+
+Find the complete code on [GitHub](https://github.com/supabase/supabase/tree/master/examples/edge-functions/supabase/functions/huggingface-image-captioning).
+
+```ts
+import { serve } from 'https://deno.land/[email protected]/http/server.ts'
+import { HfInference } from 'https://esm.sh/@huggingface/[email protected]'
+import { createClient } from 'https://esm.sh/@supabase/[email protected]'
+import { Database } from './types.ts'
+
+console.log('Hello from `huggingface-image-captioning` function!')
+
+const hf = new HfInference(Deno.env.get('HUGGINGFACE_ACCESS_TOKEN'))
+
+type SoRecord = Database['storage']['Tables']['objects']['Row']
+interface WebhookPayload {
+ type: 'INSERT' | 'UPDATE' | 'DELETE'
+ table: string
+ record: SoRecord
+ schema: 'public'
+ old_record: null | SoRecord
+}
+
+serve(async (req) => {
+ const payload: WebhookPayload = await req.json()
+ const soRecord = payload.record
+ const supabaseAdminClient = createClient<Database>(
+ // Supabase API URL - env var exported by default when deployed.
+ Deno.env.get('SUPABASE_URL') ?? '',
+ // Supabase API SERVICE ROLE KEY - env var exported by default when deployed.
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
+ )
+
+ // Construct image url from storage
+ const { data, error } = await supabaseAdminClient.storage
+ .from(soRecord.bucket_id!)
+ .createSignedUrl(soRecord.path_tokens!.join('/'), 60)
+ if (error) throw error
+ const { signedUrl } = data
+
+ // Run image captioning with Huggingface
+ const imgDesc = await hf.imageToText({
+ data: await (await fetch(signedUrl)).blob(),
+ model: 'nlpconnect/vit-gpt2-image-captioning',
+ })
+
+ // Store image caption in Database table
+ await supabaseAdminClient
+ .from('image_caption')
+ .insert({ id: soRecord.id!, caption: imgDesc.generated_text })
+ .throwOnError()
+
+ return new Response('ok')
+})
+```
+
+export const Page = ({ children }) => <Layout meta={meta} children={children} />
+
+export default Page
diff --git a/examples/edge-functions/supabase/functions/huggingface-image-captioning/README.md b/examples/edge-functions/supabase/functions/huggingface-image-captioning/README.md
new file mode 100644
index 00000000000..ff9f36b6229
--- /dev/null
+++ b/examples/edge-functions/supabase/functions/huggingface-image-captioning/README.md
@@ -0,0 +1,29 @@
+# Image Captioning with Supabase Storage and Huggingface.js
+
+[Hugging Face](https://huggingface.co/) is the collaboration platform for the machine learning community.
+
+[Huggingface.js](https://huggingface.co/docs/huggingface.js/index) 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](https://supabase.com/edge-functions).
+
+Putting this together with [Supabase Storage](https://supabase.com/storage) and [Database Webhooks](https://supabase.com/docs/guides/database/webhooks) we can easily put together a service that automatically generates captions for any image we upload to a storage bucket.
+
+## Setup
+
+1. Open your Supabase project dashboard or [create a new project](https://app.supabase.com/projects).
+2. [Create a new bucket](https://app.supabase.com/project/_/storage/buckets) called `images`.
+3. Generate TypeScript types from remote Database.
+4. Create a new Database table called `image_caption`.
+
+- Create `id` column of type `uuid` which references `storage.objects.id`.
+- Create a `caption` column of type `text`.
+
+5. Regenerate TypeScript types to include new `image_caption` table.
+6. Deploy the function to Supabase: `supabase functions deploy huggingface-image-captioning`.
+7. Create the Database Webhook in the [Supabase Dashboard](https://app.supabase.com/project/_/database/hooks) to trigger the `huggingface-image-captioning` function anytime a record is added to the `storage.objects` table.
+
+## Generate TypeScript Types
+
+To generate the types.ts file for the storage and public schemas, run the following command in the terminal:
+
+```bash
+supabase gen types typescript --project-id=your-project-ref --schema=storage,public > supabase/functions/huggingface-image-captioning/types.ts
+```
diff --git a/examples/edge-functions/supabase/functions/huggingface-image-captioning/index.ts b/examples/edge-functions/supabase/functions/huggingface-image-captioning/index.ts
new file mode 100644
index 00000000000..c13121c1f8b
--- /dev/null
+++ b/examples/edge-functions/supabase/functions/huggingface-image-captioning/index.ts
@@ -0,0 +1,49 @@
+import { serve } from 'https://deno.land/[email protected]/http/server.ts'
+import { HfInference } from 'https://esm.sh/@huggingface/[email protected]'
+import { createClient } from '@supabase/supabase-js'
+import { Database } from './types.ts'
+
+console.log('Hello from `huggingface-image-captioning` function!')
+
+const hf = new HfInference(Deno.env.get('HUGGINGFACE_ACCESS_TOKEN'))
+
+type SoRecord = Database['storage']['Tables']['objects']['Row']
+interface WebhookPayload {
+ type: 'INSERT' | 'UPDATE' | 'DELETE'
+ table: string
+ record: SoRecord
+ schema: 'public'
+ old_record: null | SoRecord
+}
+
+serve(async (req) => {
+ const payload: WebhookPayload = await req.json()
+ const soRecord = payload.record
+ const supabaseAdminClient = createClient<Database>(
+ // Supabase API URL - env var exported by default when deployed.
+ Deno.env.get('SUPABASE_URL') ?? '',
+ // Supabase API SERVICE ROLE KEY - env var exported by default when deployed.
+ Deno.env.get('SUPABASE_SERVICE_ROLE_KEY') ?? ''
+ )
+
+ // Construct image url from storage
+ const { data, error } = await supabaseAdminClient.storage
+ .from(soRecord.bucket_id!)
+ .createSignedUrl(soRecord.path_tokens!.join('/'), 60)
+ if (error) throw error
+ const { signedUrl } = data
+
+ // Run image captioning with Huggingface
+ const imgDesc = await hf.imageToText({
+ data: await (await fetch(signedUrl)).blob(),
+ model: 'nlpconnect/vit-gpt2-image-captioning',
+ })
+
+ // Store image caption in Database table
+ await supabaseAdminClient
+ .from('image_caption')
+ .insert({ id: soRecord.id!, caption: imgDesc.generated_text })
+ .throwOnError()
+
+ return new Response('ok')
+})
diff --git a/examples/edge-functions/supabase/functions/huggingface-image-captioning/types.ts b/examples/edge-functions/supabase/functions/huggingface-image-captioning/types.ts
new file mode 100644
index 00000000000..1746c5e5335
--- /dev/null
+++ b/examples/edge-functions/supabase/functions/huggingface-image-captioning/types.ts
@@ -0,0 +1,202 @@
+export type Json =
+ | string
+ | number
+ | boolean
+ | null
+ | { [key: string]: Json }
+ | Json[];
+
+export interface Database {
+ public: {
+ Tables: {
+ image_caption: {
+ Row: {
+ caption: string;
+ id: string;
+ };
+ Insert: {
+ caption: string;
+ id: string;
+ };
+ Update: {
+ caption?: string;
+ id?: string;
+ };
+ };
+ };
+ Views: {
+ [_ in never]: never;
+ };
+ Functions: {
+ [_ in never]: never;
+ };
+ Enums: {
+ [_ in never]: never;
+ };
+ CompositeTypes: {
+ [_ in never]: never;
+ };
+ };
+ storage: {
+ Tables: {
+ buckets: {
+ Row: {
+ allowed_mime_types: string[] | null;
+ avif_autodetection: boolean | null;
+ created_at: string | null;
+ file_size_limit: number | null;
+ id: string;
+ name: string;
+ owner: string | null;
+ public: boolean | null;
+ updated_at: string | null;
+ };
+ Insert: {
+ allowed_mime_types?: string[] | null;
+ avif_autodetection?: boolean | null;
+ created_at?: string | null;
+ file_size_limit?: number | null;
+ id: string;
+ name: string;
+ owner?: string | null;
+ public?: boolean | null;
+ updated_at?: string | null;
+ };
+ Update: {
+ allowed_mime_types?: string[] | null;
+ avif_autodetection?: boolean | null;
+ created_at?: string | null;
+ file_size_limit?: number | null;
+ id?: string;
+ name?: string;
+ owner?: string | null;
+ public?: boolean | null;
+ updated_at?: string | null;
+ };
+ };
+ migrations: {
+ Row: {
+ executed_at: string | null;
+ hash: string;
+ id: number;
+ name: string;
+ };
+ Insert: {
+ executed_at?: string | null;
+ hash: string;
+ id: number;
+ name: string;
+ };
+ Update: {
+ executed_at?: string | null;
+ hash?: string;
+ id?: number;
+ name?: string;
+ };
+ };
+ objects: {
+ Row: {
+ bucket_id: string | null;
+ created_at: string | null;
+ id: string;
+ last_accessed_at: string | null;
+ metadata: Json | null;
+ name: string | null;
+ owner: string | null;
+ path_tokens: string[] | null;
+ updated_at: string | null;
+ version: string | null;
+ };
+ Insert: {
+ bucket_id?: string | null;
+ created_at?: string | null;
+ id?: string;
+ last_accessed_at?: string | null;
+ metadata?: Json | null;
+ name?: string | null;
+ owner?: string | null;
+ path_tokens?: string[] | null;
+ updated_at?: string | null;
+ version?: string | null;
+ };
+ Update: {
+ bucket_id?: string | null;
+ created_at?: string | null;
+ id?: string;
+ last_accessed_at?: string | null;
+ metadata?: Json | null;
+ name?: string | null;
+ owner?: string | null;
+ path_tokens?: string[] | null;
+ updated_at?: string | null;
+ version?: string | null;
+ };
+ };
+ };
+ Views: {
+ [_ in never]: never;
+ };
+ Functions: {
+ can_insert_object: {
+ Args: {
+ bucketid: string;
+ name: string;
+ owner: string;
+ metadata: Json;
+ };
+ Returns: undefined;
+ };
+ extension: {
+ Args: {
+ name: string;
+ };
+ Returns: string;
+ };
+ filename: {
+ Args: {
+ name: string;
+ };
+ Returns: string;
+ };
+ foldername: {
+ Args: {
+ name: string;
+ };
+ Returns: unknown;
+ };
+ get_size_by_bucket: {
+ Args: Record<PropertyKey, never>;
+ Returns: {
+ size: number;
+ bucket_id: string;
+ }[];
+ };
+ search: {
+ Args: {
+ prefix: string;
+ bucketname: string;
+ limits?: number;
+ levels?: number;
+ offsets?: number;
+ search?: string;
+ sortcolumn?: string;
+ sortorder?: string;
+ };
+ Returns: {
+ name: string;
+ id: string;
+ updated_at: string;
+ created_at: string;
+ last_accessed_at: string;
+ metadata: Json;
+ }[];
+ };
+ };
+ Enums: {
+ [_ in never]: never;
+ };
+ CompositeTypes: {
+ [_ in never]: never;
+ };
+ };
+}