Skip to content

Instantly share code, notes, and snippets.

@chimame
Created January 24, 2025 15:57
Show Gist options
  • Save chimame/7dd00b228fc95eda6e2d612ba2b482ec to your computer and use it in GitHub Desktop.
Save chimame/7dd00b228fc95eda6e2d612ba2b482ec to your computer and use it in GitHub Desktop.
Sample code for calling the Google Cloud Vision API from Cloudflare Workers
import { type GoogleKey } from 'cloudflare-workers-and-google-oauth'
import GoogleAuth from 'cloudflare-workers-and-google-oauth'
const SCOPES = ['https://www.googleapis.com/auth/cloud-platform']
export const execute = async <T>(
gcpServiceAccount: string,
endpoint: string,
requestInit: RequestInit,
): Promise<{ result: boolean; data: T }> => {
const googleAuth: GoogleKey = JSON.parse(gcpServiceAccount)
const oauth = new GoogleAuth(googleAuth, SCOPES)
const token = await oauth.getGoogleAuthToken()
const res = await fetch(endpoint, {
...requestInit,
headers: { ...requestInit.headers, Authorization: `Bearer ${token}` },
})
const data = await res.json<T>()
if (!res.ok) {
console.error(JSON.stringify(data))
return { result: false, data }
}
console.log(JSON.stringify(data))
return { result: true, data }
}
import { execute } from './client'
// MEMO: see https://cloud.google.com/vision/docs/reference/rest/v1/images/annotate
const SAFE_SEARCH_ENDPOINT = 'https://vision.googleapis.com/v1/images:annotate'
type Likelihood =
| 'UNKNOWN'
| 'VERY_UNLIKELY'
| 'UNLIKELY'
| 'POSSIBLE'
| 'LIKELY'
| 'VERY_LIKELY'
type SafeSearchAnnotation = {
adult: Likelihood
spoof: Likelihood
medical: Likelihood
violence: Likelihood
racy: Likelihood
}
type AnnotateImagesResponse = {
responses: [
{
safeSearchAnnotation: SafeSearchAnnotation
},
]
}
export const validSafeSearch = async (
gcServiceAccountJson: string,
imageUri: string,
): Promise<
| { result: false; detections: null }
| { result: true; detections: Array<SafeSearchAnnotation> }
> => {
const { result, data } = await execute<AnnotateImagesResponse>(
gcServiceAccountJson,
SAFE_SEARCH_ENDPOINT,
{
method: 'POST',
body: JSON.stringify({
requests: [
{
image: {
source: {
imageUri,
},
},
features: [{ type: 'SAFE_SEARCH_DETECTION' }],
},
],
}),
},
)
if (!result) {
return { result: false, detections: null }
}
return { result: true, detections: data.responses.map(res => res.safeSearchAnnotation) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment