Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -3,7 +3,7 @@ import requests
|
|
3 |
import os
|
4 |
|
5 |
# Configure the endpoint and authentication
|
6 |
-
ENDPOINT_URL = os.environ.get("ENDPOINT_URL", "https://
|
7 |
# HF_API_TOKEN = os.environ.get("HF_API_TOKEN") # Get API token from environment variable
|
8 |
HF_API_TOKEN = os.environ.get("HF_API_TOKEN", "").strip() # Use strip() to remove extra whitespaces and newlines
|
9 |
|
@@ -14,58 +14,108 @@ def is_token_configured():
|
|
14 |
return "β οΈ Warning: HF_API_TOKEN is not configured. The app won't work until you add this secret in your Space settings."
|
15 |
return "β
API token is configured"
|
16 |
|
17 |
-
# Define the function to call your endpoint
|
18 |
-
def check_safety(input_text):
|
19 |
-
|
20 |
-
|
21 |
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
headers = {
|
29 |
"Content-Type": "application/json",
|
30 |
"Authorization": f"Bearer {HF_API_TOKEN}"
|
31 |
}
|
32 |
|
33 |
try:
|
34 |
-
# Make the request to your endpoint
|
35 |
response = requests.post(ENDPOINT_URL, json=payload, headers=headers, timeout=30)
|
36 |
|
37 |
-
# Check if the request was successful
|
38 |
if response.status_code == 200:
|
39 |
result = response.json()
|
40 |
|
41 |
-
# Format the result based on your endpoint's response format
|
42 |
is_safe = result.get("is_safe", False)
|
43 |
-
safety_result = result.get("safety_result",
|
44 |
-
|
|
|
|
|
|
|
|
|
45 |
if is_safe:
|
46 |
-
return f"β
{
|
47 |
else:
|
48 |
-
return f"β {
|
|
|
49 |
else:
|
50 |
-
return f"Error: Request failed with status code {response.status_code}
|
|
|
51 |
except requests.exceptions.Timeout:
|
52 |
-
return "Error: Request timed out.
|
|
|
53 |
except requests.exceptions.ConnectionError:
|
54 |
-
return "Error: Failed to connect to the endpoint.
|
|
|
55 |
except Exception as e:
|
56 |
-
return f"Error: {str(e)}"
|
57 |
-
|
58 |
-
# Define the Gradio interface
|
59 |
with gr.Blocks(title="Safety Content Classifier", css="footer {display: none !important}") as demo:
|
60 |
gr.Markdown(f"# Safety Content Classifier")
|
61 |
gr.Markdown(f"## Connected to external safety model endpoint")
|
62 |
|
63 |
-
# Add token status indicator
|
64 |
token_status = gr.Markdown(is_token_configured())
|
65 |
|
66 |
with gr.Accordion("About this demo", open=False):
|
67 |
gr.Markdown("""
|
68 |
-
This demo uses an external API endpoint to classify text based on safety policies.
|
69 |
It checks content against the following categories:
|
70 |
- Harassment
|
71 |
- Dangerous Content
|
@@ -82,29 +132,30 @@ with gr.Blocks(title="Safety Content Classifier", css="footer {display: none !im
|
|
82 |
placeholder="Type here...",
|
83 |
lines=5
|
84 |
)
|
|
|
|
|
|
|
|
|
85 |
check_button = gr.Button("Check Safety", variant="primary")
|
86 |
|
87 |
with gr.Column():
|
88 |
output = gr.Textbox(
|
89 |
label="Safety Result",
|
90 |
-
lines=
|
91 |
)
|
92 |
|
93 |
-
#
|
94 |
-
check_button.click(fn=check_safety, inputs=input_text, outputs=output)
|
95 |
-
input_text.submit(fn=check_safety, inputs=input_text, outputs=output)
|
96 |
|
97 |
-
# Example inputs
|
98 |
gr.Examples(
|
99 |
[
|
100 |
-
["Hello, how are you today?"],
|
101 |
-
["I
|
102 |
-
["
|
103 |
-
["
|
104 |
-
["Let's meet for coffee and discuss the project."],
|
105 |
],
|
106 |
-
input_text
|
107 |
)
|
108 |
|
109 |
-
# Launch the app
|
110 |
demo.launch()
|
|
|
3 |
import os
|
4 |
|
5 |
# Configure the endpoint and authentication
|
6 |
+
ENDPOINT_URL = os.environ.get("ENDPOINT_URL", "https://dz0eq6vxq3nm0uh7.us-east-1.aws.endpoints.huggingface.cloud")
|
7 |
# HF_API_TOKEN = os.environ.get("HF_API_TOKEN") # Get API token from environment variable
|
8 |
HF_API_TOKEN = os.environ.get("HF_API_TOKEN", "").strip() # Use strip() to remove extra whitespaces and newlines
|
9 |
|
|
|
14 |
return "β οΈ Warning: HF_API_TOKEN is not configured. The app won't work until you add this secret in your Space settings."
|
15 |
return "β
API token is configured"
|
16 |
|
17 |
+
# # Define the function to call your endpoint
|
18 |
+
# def check_safety(input_text):
|
19 |
+
# if not input_text.strip():
|
20 |
+
# return "Please enter some text to check"
|
21 |
|
22 |
+
# # Prepare the payload for your endpoint
|
23 |
+
# payload = {
|
24 |
+
# "inputs": input_text
|
25 |
+
# }
|
26 |
+
|
27 |
+
# # Set headers with authentication token
|
28 |
+
# headers = {
|
29 |
+
# "Content-Type": "application/json",
|
30 |
+
# "Authorization": f"Bearer {HF_API_TOKEN}"
|
31 |
+
# }
|
32 |
+
|
33 |
+
# try:
|
34 |
+
# # Make the request to your endpoint
|
35 |
+
# response = requests.post(ENDPOINT_URL, json=payload, headers=headers, timeout=30)
|
36 |
+
|
37 |
+
# # Check if the request was successful
|
38 |
+
# if response.status_code == 200:
|
39 |
+
# result = response.json()
|
40 |
+
|
41 |
+
# # Format the result based on your endpoint's response format
|
42 |
+
# is_safe = result.get("is_safe", False)
|
43 |
+
# safety_result = result.get("safety_result", "No result received")
|
44 |
+
|
45 |
+
# if is_safe:
|
46 |
+
# return f"β
{safety_result}"
|
47 |
+
# else:
|
48 |
+
# return f"β {safety_result}"
|
49 |
+
# else:
|
50 |
+
# return f"Error: Request failed with status code {response.status_code}. Details: {response.text}"
|
51 |
+
# except requests.exceptions.Timeout:
|
52 |
+
# return "Error: Request timed out. The endpoint may be overloaded or unavailable."
|
53 |
+
# except requests.exceptions.ConnectionError:
|
54 |
+
# return "Error: Failed to connect to the endpoint. Please check the endpoint URL."
|
55 |
+
# except Exception as e:
|
56 |
+
# return f"Error: {str(e)}"
|
57 |
+
def check_safety(input_text, uploaded_image):
|
58 |
+
if not input_text.strip() and uploaded_image is None:
|
59 |
+
return "β οΈ Please enter text or upload an image to check."
|
60 |
+
|
61 |
+
payload = {}
|
62 |
|
63 |
+
if input_text.strip():
|
64 |
+
payload["inputs"] = input_text
|
65 |
+
if uploaded_image is not None:
|
66 |
+
# In Gradio, uploaded_image will be a local temp file path
|
67 |
+
# Your endpoint expects a URL or base64. Here, we send as base64.
|
68 |
+
import base64
|
69 |
+
|
70 |
+
with open(uploaded_image, "rb") as img_file:
|
71 |
+
img_bytes = img_file.read()
|
72 |
+
img_base64 = base64.b64encode(img_bytes).decode('utf-8')
|
73 |
+
|
74 |
+
payload["image"] = img_base64 # Assume your backend can accept image this way
|
75 |
+
|
76 |
headers = {
|
77 |
"Content-Type": "application/json",
|
78 |
"Authorization": f"Bearer {HF_API_TOKEN}"
|
79 |
}
|
80 |
|
81 |
try:
|
|
|
82 |
response = requests.post(ENDPOINT_URL, json=payload, headers=headers, timeout=30)
|
83 |
|
|
|
84 |
if response.status_code == 200:
|
85 |
result = response.json()
|
86 |
|
|
|
87 |
is_safe = result.get("is_safe", False)
|
88 |
+
safety_result = result.get("safety_result", {})
|
89 |
+
|
90 |
+
safety = safety_result.get("Safety", "Unknown")
|
91 |
+
score = safety_result.get("Score", "")
|
92 |
+
categories = safety_result.get("Unsafe Categories", "")
|
93 |
+
|
94 |
if is_safe:
|
95 |
+
return f"β
Safe\n\nSafety: {safety}\nScore: {score}\nUnsafe Categories: {categories}"
|
96 |
else:
|
97 |
+
return f"β Unsafe\n\nSafety: {safety}\nScore: {score}\nUnsafe Categories: {categories}"
|
98 |
+
|
99 |
else:
|
100 |
+
return f"β Error: Request failed with status code {response.status_code}.\nDetails: {response.text}"
|
101 |
+
|
102 |
except requests.exceptions.Timeout:
|
103 |
+
return "β Error: Request timed out."
|
104 |
+
|
105 |
except requests.exceptions.ConnectionError:
|
106 |
+
return "β Error: Failed to connect to the endpoint."
|
107 |
+
|
108 |
except Exception as e:
|
109 |
+
return f"β Error: {str(e)}"
|
|
|
|
|
110 |
with gr.Blocks(title="Safety Content Classifier", css="footer {display: none !important}") as demo:
|
111 |
gr.Markdown(f"# Safety Content Classifier")
|
112 |
gr.Markdown(f"## Connected to external safety model endpoint")
|
113 |
|
|
|
114 |
token_status = gr.Markdown(is_token_configured())
|
115 |
|
116 |
with gr.Accordion("About this demo", open=False):
|
117 |
gr.Markdown("""
|
118 |
+
This demo uses an external API endpoint to classify text and images based on safety policies.
|
119 |
It checks content against the following categories:
|
120 |
- Harassment
|
121 |
- Dangerous Content
|
|
|
132 |
placeholder="Type here...",
|
133 |
lines=5
|
134 |
)
|
135 |
+
uploaded_image = gr.Image(
|
136 |
+
label="Upload Image to check",
|
137 |
+
type="filepath" # important: get local path
|
138 |
+
)
|
139 |
check_button = gr.Button("Check Safety", variant="primary")
|
140 |
|
141 |
with gr.Column():
|
142 |
output = gr.Textbox(
|
143 |
label="Safety Result",
|
144 |
+
lines=8
|
145 |
)
|
146 |
|
147 |
+
# Update event handlers
|
148 |
+
check_button.click(fn=check_safety, inputs=[input_text, uploaded_image], outputs=output)
|
149 |
+
input_text.submit(fn=check_safety, inputs=[input_text, uploaded_image], outputs=output)
|
150 |
|
|
|
151 |
gr.Examples(
|
152 |
[
|
153 |
+
["Hello, how are you today?", None],
|
154 |
+
["I want to learn how to make a bomb.", None],
|
155 |
+
["", "example_images/unsafe_meme.png"],
|
156 |
+
["", "example_images/normal_photo.jpg"],
|
|
|
157 |
],
|
158 |
+
inputs=[input_text, uploaded_image]
|
159 |
)
|
160 |
|
|
|
161 |
demo.launch()
|