Views
No views yet
1from transformers import pipeline
2from PIL import Image
3
4img = Image.open("<path_to_image_file>")
5predict = pipeline("image-classification", model="AdamCodd/vit-base-nsfw-detector")
6predict(img)1from transformers import ViTImageProcessor, AutoModelForImageClassification
2from PIL import Image
3import requests
4
5url = 'http://images.cocodataset.org/val2017/000000039769.jpg'
6image = Image.open(requests.get(url, stream=True).raw)
7processor = ViTImageProcessor.from_pretrained('AdamCodd/vit-base-nsfw-detector')
8model = AutoModelForImageClassification.from_pretrained('AdamCodd/vit-base-nsfw-detector')
9inputs = processor(images=image, return_tensors="pt")
10outputs = model(**inputs)
11logits = outputs.logits
12
13predicted_class_idx = logits.argmax(-1).item()
14print("Predicted class:", model.config.id2label[predicted_class_idx])
15# Predicted class: sfw1/* Instructions:
2* - Place this script in an HTML file using the <script type="module"> tag.
3* - Ensure the HTML file is served over a local or remote server (e.g., using Python's http.server, Node.js server, or similar).
4* - Replace 'https://example.com/path/to/image.jpg' in the classifyImage function call with the URL of the image you want to classify.
5*
6* Example of how to include this script in HTML:
7* <script type="module" src="path/to/this_script.js"></script>
8*
9* This setup ensures that the script can use imports and perform network requests without CORS issues.
10*/
11import { pipeline, env } from 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.1';
12
13// Since we will download the model from HuggingFace Hub, we can skip the local model check
14env.allowLocalModels = false;
15
16// Load the image classification model
17const classifier = await pipeline('image-classification', 'AdamCodd/vit-base-nsfw-detector');
18
19// Function to fetch and classify an image from a URL
20async function classifyImage(url) {
21 try {
22 const response = await fetch(url);
23 if (!response.ok) throw new Error('Failed to load image');
24
25 const blob = await response.blob();
26 const image = new Image();
27 const imagePromise = new Promise((resolve, reject) => {
28 image.onload = () => resolve(image);
29 image.onerror = reject;
30 image.src = URL.createObjectURL(blob);
31 });
32
33 const img = await imagePromise; // Ensure the image is loaded
34 const classificationResults = await classifier([img.src]); // Classify the image
35 console.log('Predicted class: ', classificationResults[0].label);
36 } catch (error) {
37 console.error('Error classifying image:', error);
38 }
39}
40
41// Example usage
42classifyImage('https://example.com/path/to/image.jpg');
43// Predicted class: sfw