Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,81 +1,87 @@
|
|
1 |
import gradio as gr
|
2 |
from transformers import CLIPModel, CLIPProcessor
|
3 |
from PIL import Image
|
4 |
-
import torch
|
5 |
|
6 |
# Step 1: Load Fine-Tuned Model from Hugging Face Model Hub
|
7 |
model_name = "quadranttechnologies/retail-content-safety-clip-finetuned"
|
8 |
|
9 |
-
print("
|
|
|
10 |
try:
|
|
|
11 |
model = CLIPModel.from_pretrained(model_name, trust_remote_code=True)
|
12 |
processor = CLIPProcessor.from_pretrained(model_name)
|
13 |
-
print("Model loaded successfully.")
|
14 |
except Exception as e:
|
15 |
-
print(f"Error loading model or processor: {
|
16 |
-
raise
|
17 |
|
18 |
# Step 2: Define the Inference Function
|
19 |
def classify_image(image):
|
20 |
"""
|
21 |
-
Classify an image as 'safe' or 'unsafe'
|
22 |
|
23 |
Args:
|
24 |
-
image (PIL.Image.Image):
|
25 |
|
26 |
Returns:
|
27 |
-
dict:
|
28 |
"""
|
29 |
try:
|
30 |
-
|
|
|
|
|
31 |
if image is None:
|
32 |
-
raise ValueError("No image provided. Please upload
|
|
|
|
|
33 |
if not hasattr(image, "convert"):
|
34 |
-
raise ValueError("
|
35 |
|
36 |
-
# Define
|
37 |
-
|
38 |
|
39 |
-
# Process the image
|
40 |
print("Processing the image...")
|
41 |
-
inputs = processor(text=
|
42 |
-
print("
|
43 |
|
44 |
-
#
|
|
|
45 |
outputs = model(**inputs)
|
46 |
-
print("Model
|
47 |
|
48 |
-
#
|
49 |
logits_per_image = outputs.logits_per_image # Image-text similarity scores
|
50 |
probs = logits_per_image.softmax(dim=1) # Convert logits to probabilities
|
|
|
51 |
|
52 |
-
# Extract probabilities for
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
print(f"Safe: {safe_probability:.2f}%, Unsafe: {unsafe_probability:.2f}%")
|
57 |
|
58 |
# Return results
|
59 |
return {
|
60 |
-
"safe": f"{
|
61 |
-
"unsafe": f"{
|
62 |
}
|
63 |
|
64 |
except Exception as e:
|
65 |
-
print(f"Error during
|
66 |
return {"Error": str(e)}
|
67 |
|
68 |
# Step 3: Set Up Gradio Interface
|
69 |
iface = gr.Interface(
|
70 |
fn=classify_image,
|
71 |
inputs=gr.Image(type="pil"),
|
72 |
-
outputs=gr.
|
73 |
title="Content Safety Classification",
|
74 |
description="Upload an image to classify it as 'safe' or 'unsafe' with corresponding probabilities.",
|
75 |
)
|
76 |
|
77 |
# Step 4: Launch Gradio Interface
|
78 |
if __name__ == "__main__":
|
|
|
79 |
iface.launch()
|
80 |
|
81 |
|
@@ -96,3 +102,4 @@ if __name__ == "__main__":
|
|
96 |
|
97 |
|
98 |
|
|
|
|
1 |
import gradio as gr
|
2 |
from transformers import CLIPModel, CLIPProcessor
|
3 |
from PIL import Image
|
|
|
4 |
|
5 |
# Step 1: Load Fine-Tuned Model from Hugging Face Model Hub
|
6 |
model_name = "quadranttechnologies/retail-content-safety-clip-finetuned"
|
7 |
|
8 |
+
print("Initializing the application...")
|
9 |
+
|
10 |
try:
|
11 |
+
print("Loading the model from Hugging Face Model Hub...")
|
12 |
model = CLIPModel.from_pretrained(model_name, trust_remote_code=True)
|
13 |
processor = CLIPProcessor.from_pretrained(model_name)
|
14 |
+
print("Model and processor loaded successfully.")
|
15 |
except Exception as e:
|
16 |
+
print(f"Error loading the model or processor: {e}")
|
17 |
+
raise RuntimeError(f"Failed to load model: {e}")
|
18 |
|
19 |
# Step 2: Define the Inference Function
|
20 |
def classify_image(image):
|
21 |
"""
|
22 |
+
Classify an image as 'safe' or 'unsafe' and return probabilities.
|
23 |
|
24 |
Args:
|
25 |
+
image (PIL.Image.Image): Uploaded image.
|
26 |
|
27 |
Returns:
|
28 |
+
dict: Classification results or an error message.
|
29 |
"""
|
30 |
try:
|
31 |
+
print("Starting image classification...")
|
32 |
+
|
33 |
+
# Validate input
|
34 |
if image is None:
|
35 |
+
raise ValueError("No image provided. Please upload a valid image.")
|
36 |
+
|
37 |
+
# Validate image format
|
38 |
if not hasattr(image, "convert"):
|
39 |
+
raise ValueError("Invalid image format. Please upload a valid image (JPEG, PNG, etc.).")
|
40 |
|
41 |
+
# Define categories
|
42 |
+
categories = ["safe", "unsafe"]
|
43 |
|
44 |
+
# Process the image with the processor
|
45 |
print("Processing the image...")
|
46 |
+
inputs = processor(text=categories, images=image, return_tensors="pt", padding=True)
|
47 |
+
print(f"Processed inputs: {inputs}")
|
48 |
|
49 |
+
# Run inference with the model
|
50 |
+
print("Running model inference...")
|
51 |
outputs = model(**inputs)
|
52 |
+
print(f"Model outputs: {outputs}")
|
53 |
|
54 |
+
# Extract logits and probabilities
|
55 |
logits_per_image = outputs.logits_per_image # Image-text similarity scores
|
56 |
probs = logits_per_image.softmax(dim=1) # Convert logits to probabilities
|
57 |
+
print(f"Calculated probabilities: {probs}")
|
58 |
|
59 |
+
# Extract probabilities for each category
|
60 |
+
safe_prob = probs[0][0].item() * 100 # Safe percentage
|
61 |
+
unsafe_prob = probs[0][1].item() * 100 # Unsafe percentage
|
|
|
|
|
62 |
|
63 |
# Return results
|
64 |
return {
|
65 |
+
"safe": f"{safe_prob:.2f}%",
|
66 |
+
"unsafe": f"{unsafe_prob:.2f}%"
|
67 |
}
|
68 |
|
69 |
except Exception as e:
|
70 |
+
print(f"Error during classification: {e}")
|
71 |
return {"Error": str(e)}
|
72 |
|
73 |
# Step 3: Set Up Gradio Interface
|
74 |
iface = gr.Interface(
|
75 |
fn=classify_image,
|
76 |
inputs=gr.Image(type="pil"),
|
77 |
+
outputs=gr.Textbox(label="Output (Debug Mode)"), # Use Textbox to display errors if any occur
|
78 |
title="Content Safety Classification",
|
79 |
description="Upload an image to classify it as 'safe' or 'unsafe' with corresponding probabilities.",
|
80 |
)
|
81 |
|
82 |
# Step 4: Launch Gradio Interface
|
83 |
if __name__ == "__main__":
|
84 |
+
print("Launching the Gradio interface...")
|
85 |
iface.launch()
|
86 |
|
87 |
|
|
|
102 |
|
103 |
|
104 |
|
105 |
+
|