Il rilevamento tramite SafeSearch rileva contenuti espliciti, come quelli per adulti o violenti, all'interno di un'immagine. Questa funzionalità utilizza cinque categorie
(adult
, spoof
, medical
, violence
e racy
) e restituisce la probabilità che ciascuna sia
presente in una determinata immagine. Per informazioni dettagliate su questi campi, consulta la pagina
SafeSearchAnnotation.
Richieste di rilevamento di SafeSearch
Configura il progetto Google Cloud e l'autenticazione
Se non hai creato un Google Cloud progetto, fallo ora. Espandi questa sezione per le istruzioni.
- Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Vision API.
-
Install the Google Cloud CLI.
-
Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.
-
Per inizializzare gcloud CLI, esegui questo comando:
gcloud init
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
-
Verify that billing is enabled for your Google Cloud project.
-
Enable the Vision API.
-
Install the Google Cloud CLI.
-
Se utilizzi un provider di identità (IdP) esterno, devi prima accedere a gcloud CLI con la tua identità federata.
-
Per inizializzare gcloud CLI, esegui questo comando:
gcloud init
- BASE64_ENCODED_IMAGE: la rappresentazione in Base64 (stringa ASCII) dei dati dell'immagine binaria. Questa stringa dovrebbe essere simile alla
seguente:
/9j/4QAYRXhpZgAA...9tAVx/zDQDlGxn//2Q==
- PROJECT_ID: il tuo ID progetto Google Cloud .
- CLOUD_STORAGE_IMAGE_URI: il percorso di un file immagine valido in un bucket Cloud Storage. Devi disporre almeno dei privilegi di lettura per il file.
Esempio:
gs://my-storage-bucket/img/image1.png
- PROJECT_ID: il tuo ID progetto Google Cloud .
Rilevamento di contenuti espliciti in un'immagine locale
Puoi utilizzare l'API Vision per eseguire il rilevamento delle funzionalità su un file immagine locale.
Per le richieste REST, invia i contenuti del file immagine come stringa codificata in base64 nel corpo della richiesta.
Per le richieste gcloud
e delle librerie client, specifica il percorso di un'immagine locale nella tua richiesta.
REST
Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:
Metodo HTTP e URL:
POST https://vision.googleapis.com/v1/images:annotate
Corpo JSON della richiesta:
{ "requests": [ { "image": { "content": "BASE64_ENCODED_IMAGE" }, "features": [ { "type": "SAFE_SEARCH_DETECTION" }, ] } ] }
Per inviare la richiesta, scegli una di queste opzioni:
curl
Salva il corpo della richiesta in un file denominato request.json
,
ed esegui questo comando:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://vision.googleapis.com/v1/images:annotate"
PowerShell
Salva il corpo della richiesta in un file denominato request.json
,
quindi esegui il comando seguente:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_ID" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/images:annotate" | Select-Object -Expand Content
Dovresti ricevere una risposta JSON simile alla seguente:
{ "responses": [ { "safeSearchAnnotation": { "adult": "UNLIKELY", "spoof": "VERY_UNLIKELY", "medical": "VERY_UNLIKELY", "violence": "LIKELY", "racy": "POSSIBLE" } } ] }
Go
Prima di provare questo esempio, segui le istruzioni di configurazione di Go nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Go.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
// detectSafeSearch gets image properties from the Vision API for an image at the given file path.
func detectSafeSearch(w io.Writer, file string) error {
ctx := context.Background()
client, err := vision.NewImageAnnotatorClient(ctx)
if err != nil {
return err
}
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
image, err := vision.NewImageFromReader(f)
if err != nil {
return err
}
props, err := client.DetectSafeSearch(ctx, image, nil)
if err != nil {
return err
}
fmt.Fprintln(w, "Safe Search properties:")
fmt.Fprintln(w, "Adult:", props.Adult)
fmt.Fprintln(w, "Medical:", props.Medical)
fmt.Fprintln(w, "Racy:", props.Racy)
fmt.Fprintln(w, "Spoofed:", props.Spoof)
fmt.Fprintln(w, "Violence:", props.Violence)
return nil
}
Java
Prima di provare questo esempio, segui le istruzioni di configurazione di Java nella guida rapida dell'API Vision che utilizza le librerie client. Per saperne di più, consulta la documentazione di riferimento di Vision API Java.
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.SafeSearchAnnotation;
import com.google.protobuf.ByteString;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DetectSafeSearch {
public static void detectSafeSearch() throws IOException {
// TODO(developer): Replace these variables before running the sample.
String filePath = "path/to/your/image/file.jpg";
detectSafeSearch(filePath);
}
// Detects whether the specified image has features you would want to moderate.
public static void detectSafeSearch(String filePath) throws IOException {
List<AnnotateImageRequest> requests = new ArrayList<>();
ByteString imgBytes = ByteString.readFrom(new FileInputStream(filePath));
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Feature.Type.SAFE_SEARCH_DETECTION).build();
AnnotateImageRequest request =
AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.format("Error: %s%n", res.getError().getMessage());
return;
}
// For full list of available annotations, see http://g.co/cloud/vision/docs
SafeSearchAnnotation annotation = res.getSafeSearchAnnotation();
System.out.format(
"adult: %s%nmedical: %s%nspoofed: %s%nviolence: %s%nracy: %s%n",
annotation.getAdult(),
annotation.getMedical(),
annotation.getSpoof(),
annotation.getViolence(),
annotation.getRacy());
}
}
}
}
Node.js
Prima di provare questo esempio, segui le istruzioni di configurazione di Node.js nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Node.js.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
const vision = require('@google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
/**
* TODO(developer): Uncomment the following line before running the sample.
*/
// const fileName = 'Local image file, e.g. /path/to/image.png';
// Performs safe search detection on the local file
const [result] = await client.safeSearchDetection(fileName);
const detections = result.safeSearchAnnotation;
console.log('Safe search:');
console.log(`Adult: ${detections.adult}`);
console.log(`Medical: ${detections.medical}`);
console.log(`Spoof: ${detections.spoof}`);
console.log(`Violence: ${detections.violence}`);
console.log(`Racy: ${detections.racy}`);
Python
Prima di provare questo esempio, segui le istruzioni di configurazione di Python nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Python.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
def detect_safe_search(path):
"""Detects unsafe features in the file."""
from google.cloud import vision
client = vision.ImageAnnotatorClient()
with open(path, "rb") as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.safe_search_detection(image=image)
safe = response.safe_search_annotation
# Names of likelihood from google.cloud.vision.enums
likelihood_name = (
"UNKNOWN",
"VERY_UNLIKELY",
"UNLIKELY",
"POSSIBLE",
"LIKELY",
"VERY_LIKELY",
)
print("Safe search:")
print(f"adult: {likelihood_name[safe.adult]}")
print(f"medical: {likelihood_name[safe.medical]}")
print(f"spoofed: {likelihood_name[safe.spoof]}")
print(f"violence: {likelihood_name[safe.violence]}")
print(f"racy: {likelihood_name[safe.racy]}")
if response.error.message:
raise Exception(
"{}\nFor more info on error messages, check: "
"https://cloud.google.com/apis/design/errors".format(response.error.message)
)
Rilevamento di contenuti espliciti in un'immagine remota
Puoi utilizzare l'API Vision per eseguire il rilevamento delle funzionalità su un file immagine remoto che si trova in Cloud Storage o sul web. Per inviare una richiesta di file remoto, specifica l'URL web del file o l'URI Cloud Storage nel corpo della richiesta.
REST
Prima di utilizzare i dati della richiesta, apporta le seguenti sostituzioni:
Metodo HTTP e URL:
POST https://vision.googleapis.com/v1/images:annotate
Corpo JSON della richiesta:
{ "requests": [ { "image": { "source": { "imageUri": "CLOUD_STORAGE_IMAGE_URI" } }, "features": [ { "type": "SAFE_SEARCH_DETECTION" } ] } ] }
Per inviare la richiesta, scegli una di queste opzioni:
curl
Salva il corpo della richiesta in un file denominato request.json
,
ed esegui questo comando:
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: PROJECT_ID" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://vision.googleapis.com/v1/images:annotate"
PowerShell
Salva il corpo della richiesta in un file denominato request.json
,
quindi esegui il comando seguente:
$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "PROJECT_ID" }
Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/images:annotate" | Select-Object -Expand Content
Dovresti ricevere una risposta JSON simile alla seguente:
{ "responses": [ { "safeSearchAnnotation": { "adult": "UNLIKELY", "spoof": "VERY_UNLIKELY", "medical": "VERY_UNLIKELY", "violence": "LIKELY", "racy": "POSSIBLE" } } ] }
Go
Prima di provare questo esempio, segui le istruzioni di configurazione di Go nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Go.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
// detectSafeSearch gets image properties from the Vision API for an image at the given file path.
func detectSafeSearchURI(w io.Writer, file string) error {
ctx := context.Background()
client, err := vision.NewImageAnnotatorClient(ctx)
if err != nil {
return err
}
image := vision.NewImageFromURI(file)
props, err := client.DetectSafeSearch(ctx, image, nil)
if err != nil {
return err
}
fmt.Fprintln(w, "Safe Search properties:")
fmt.Fprintln(w, "Adult:", props.Adult)
fmt.Fprintln(w, "Medical:", props.Medical)
fmt.Fprintln(w, "Racy:", props.Racy)
fmt.Fprintln(w, "Spoofed:", props.Spoof)
fmt.Fprintln(w, "Violence:", props.Violence)
return nil
}
Java
Prima di provare questo esempio, segui le istruzioni di configurazione di Java nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Java.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Feature.Type;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageSource;
import com.google.cloud.vision.v1.SafeSearchAnnotation;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class DetectSafeSearchGcs {
public static void detectSafeSearchGcs() throws IOException {
// TODO(developer): Replace these variables before running the sample.
String filePath = "gs://your-gcs-bucket/path/to/image/file.jpg";
detectSafeSearchGcs(filePath);
}
// Detects whether the specified image on Google Cloud Storage has features you would want to
// moderate.
public static void detectSafeSearchGcs(String gcsPath) throws IOException {
List<AnnotateImageRequest> requests = new ArrayList<>();
ImageSource imgSource = ImageSource.newBuilder().setGcsImageUri(gcsPath).build();
Image img = Image.newBuilder().setSource(imgSource).build();
Feature feat = Feature.newBuilder().setType(Type.SAFE_SEARCH_DETECTION).build();
AnnotateImageRequest request =
AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
// Initialize client that will be used to send requests. This client only needs to be created
// once, and can be reused for multiple requests. After completing all of your requests, call
// the "close" method on the client to safely clean up any remaining background resources.
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.format("Error: %s%n", res.getError().getMessage());
return;
}
// For full list of available annotations, see http://g.co/cloud/vision/docs
SafeSearchAnnotation annotation = res.getSafeSearchAnnotation();
System.out.format(
"adult: %s%nmedical: %s%nspoofed: %s%nviolence: %s%nracy: %s%n",
annotation.getAdult(),
annotation.getMedical(),
annotation.getSpoof(),
annotation.getViolence(),
annotation.getRacy());
}
}
}
}
Node.js
Prima di provare questo esempio, segui le istruzioni di configurazione di Node.js nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Node.js.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
// Imports the Google Cloud client libraries
const vision = require('@google-cloud/vision');
// Creates a client
const client = new vision.ImageAnnotatorClient();
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// const bucketName = 'Bucket where the file resides, e.g. my-bucket';
// const fileName = 'Path to file within bucket, e.g. path/to/image.png';
// Performs safe search property detection on the remote file
const [result] = await client.safeSearchDetection(
`gs://${bucketName}/${fileName}`
);
const detections = result.safeSearchAnnotation;
console.log(`Adult: ${detections.adult}`);
console.log(`Spoof: ${detections.spoof}`);
console.log(`Medical: ${detections.medical}`);
console.log(`Violence: ${detections.violence}`);
Python
Prima di provare questo esempio, segui le istruzioni di configurazione di Python nella guida rapida di Vision per l'utilizzo delle librerie client. Per saperne di più, consulta la documentazione di riferimento dell'API Vision Python.
Per eseguire l'autenticazione in Vision, configura le Credenziali predefinite dell'applicazione. Per ulteriori informazioni, consulta Configura l'autenticazione per un ambiente di sviluppo locale.
def detect_safe_search_uri(uri):
"""Detects unsafe features in the file located in Google Cloud Storage or
on the Web."""
from google.cloud import vision
client = vision.ImageAnnotatorClient()
image = vision.Image()
image.source.image_uri = uri
response = client.safe_search_detection(image=image)
safe = response.safe_search_annotation
# Names of likelihood from google.cloud.vision.enums
likelihood_name = (
"UNKNOWN",
"VERY_UNLIKELY",
"UNLIKELY",
"POSSIBLE",
"LIKELY",
"VERY_LIKELY",
)
print("Safe search:")
print(f"adult: {likelihood_name[safe.adult]}")
print(f"medical: {likelihood_name[safe.medical]}")
print(f"spoofed: {likelihood_name[safe.spoof]}")
print(f"violence: {likelihood_name[safe.violence]}")
print(f"racy: {likelihood_name[safe.racy]}")
if response.error.message:
raise Exception(
"{}\nFor more info on error messages, check: "
"https://cloud.google.com/apis/design/errors".format(response.error.message)
)
gcloud
Per eseguire il rilevamento di SafeSearch, utilizza il comando
gcloud ml vision detect-safe-search
come mostrato nell'esempio seguente:
gcloud ml vision detect-safe-search gs://my_bucket/input_file