Views
No views yet

{
"test_loss": 0.05508904904127121,
"test_accuracy": 0.9923283699296264,
"test_runtime": 167.1844,
"test_samples_per_second": 198.039,
"test_steps_per_second": 6.191
}pip install -q transformers torch Pillow accelerate1import torch
2from PIL import Image as PILImage
3from transformers import AutoImageProcessor, SiglipForImageClassification
4
5MODEL_IDENTIFIER = r"Ateeqq/ai-vs-human-image-detector"
6
7# Device: Use GPU if available, otherwise CPU
8device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
9print(f"Using device: {device}")
10
11# Load Model and Processor
12try:
13 print(f"Loading processor from: {MODEL_IDENTIFIER}")
14 processor = AutoImageProcessor.from_pretrained(MODEL_IDENTIFIER)
15
16 print(f"Loading model from: {MODEL_IDENTIFIER}")
17 model = SiglipForImageClassification.from_pretrained(MODEL_IDENTIFIER)
18 model.to(device)
19 model.eval()
20 print("Model and processor loaded successfully.")
21
22except Exception as e:
23 print(f"Error loading model or processor: {e}")
24 exit()
25
26# Load and Preprocess the Image
27
28IMAGE_PATH = r"/content/images.jpg"
29try:
30 print(f"Loading image: {IMAGE_PATH}")
31 image = PILImage.open(IMAGE_PATH).convert("RGB")
32except FileNotFoundError:
33 print(f"Error: Image file not found at {IMAGE_PATH}")
34 exit()
35except Exception as e:
36 print(f"Error opening image: {e}")
37 exit()
38
39print("Preprocessing image...")
40# Use the processor to prepare the image for the model
41inputs = processor(images=image, return_tensors="pt").to(device)
42
43# Perform Inference
44print("Running inference...")
45with torch.no_grad(): # Disable gradient calculations for inference
46 outputs = model(**inputs)
47 logits = outputs.logits
48
49# Interpret the Results
50# Get the index of the highest logit score -> this is the predicted class ID
51predicted_class_idx = logits.argmax(-1).item()
52
53# Use the model's config to map the ID back to the label string ('ai' or 'hum')
54predicted_label = model.config.id2label[predicted_class_idx]
55
56# Optional: Get probabilities using softmax
57probabilities = torch.softmax(logits, dim=-1)
58predicted_prob = probabilities[0, predicted_class_idx].item()
59
60print("-" * 30)
61print(f"Image: {IMAGE_PATH}")
62print(f"Predicted Label: {predicted_label}")
63print(f"Confidence Score: {predicted_prob:.4f}")
64print("-" * 30)
65
66# You can also print the scores for all classes:
67print("Scores per class:")
68for i, label in model.config.id2label.items():
69 print(f" - {label}: {probabilities[0, i].item():.4f}")Using device: cpu
Model and processor loaded successfully.
Loading image: /content/images.jpg
Preprocessing image...
Running inference...
------------------------------
Image: /content/images.jpg
Predicted Label: ai
Confidence Score: 0.9996
------------------------------
Scores per class:
- ai: 0.9996
- hum: 0.0004