Spaces:
Runtime error
Runtime error
File size: 3,514 Bytes
809b1fe ad77051 f76e239 4dd6ed2 5cd3519 4dd6ed2 1e13411 4dd6ed2 5cd3519 4dd6ed2 1e13411 4dd6ed2 ad77051 1e13411 8fd1381 4dd6ed2 8fd1381 ad77051 8fd1381 ad77051 8fd1381 ad77051 8fd1381 f76e239 8fd1381 ad77051 27cad67 ad77051 1e13411 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
import gradio as gr
from gradio_client import Client
import matplotlib.pyplot as plt
import numpy as np
import io
from PIL import Image
import base64
import os
import requests
from tenacity import retry, wait_exponential, stop_after_attempt
# Load Hugging Face token from environment variable
HF_TOKEN = os.getenv("HF_TOKEN")
if not HF_TOKEN:
raise ValueError("Hugging Face token not found in environment variables.")
@retry(wait=wait_exponential(multiplier=1, min=4, max=10), stop=stop_after_attempt(5))
def get_dynamic_endpoint():
"""
Fetch the dynamic endpoint using the Hugging Face API.
Returns:
str: The current dynamic endpoint.
"""
api_url = "https://api.huggingface.co/space/duchaba/friendly-text-moderation"
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
response = requests.get(api_url, headers=headers)
response.raise_for_status() # Raise an error for bad status codes
# Extract the endpoint from the response
data = response.json()
endpoint = data.get("url")
if not endpoint:
raise ValueError("Endpoint URL not found in the response.")
return endpoint
def moderate_text(text, safer_value):
"""
Moderate the given text using the Hugging Face API.
Args:
text (str): The text to be moderated.
safer_value (float): The safer value to be used for moderation.
Returns:
tuple: A tuple containing the moderation result and the generated image.
"""
try:
# Fetch the dynamic endpoint
dynamic_endpoint = get_dynamic_endpoint()
# Initialize the client with the dynamic endpoint
client = Client(dynamic_endpoint, hf_token=HF_TOKEN)
result = client.predict(
text,
safer_value,
api_name="/censor_me"
)
# Ensure the result contains the expected data
base64_data = result.get('plot', '').split(',')[1] if 'plot' in result else None
if not base64_data:
raise ValueError("Expected plot data not found in the result.")
# Decode base64 to bytes
img_data = base64.b64decode(base64_data)
# Convert bytes to PIL Image
img = Image.open(io.BytesIO(img_data))
return result, img
except Exception as e:
# Log the error for debugging purposes
print(f"Error occurred: {e}")
return str(e), None
# Define the Gradio interface
demo = gr.Interface(
fn=moderate_text,
inputs=[
gr.Textbox(label="Enter Text:", placeholder="Type your text here...", lines=5),
gr.Slider(minimum=0.005, maximum=0.1, value=0.005, label="Personalize Safer Value: (larger value is less safe)")
],
outputs=[gr.Textbox(label="Moderated Text:", lines=5), gr.Image(type="pil", label="Moderation Pie Chart")],
title="Friendly Text Moderator",
description="Enter text to be moderated and adjust the safer value to see how it affects the moderation."
)
# Customize the CSS
custom_css = """
body {
background-color: #f5f5f5;
font-family: Arial, sans-serif;
}
.gradio-container {
max-width: 800px;
margin: auto;
padding: 20px;
background-color: white;
border: 1px solid #ddd;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.gr-button {
background-color: #4CAF50;
color: white;
}
.gr-button:hover {
background-color: #45a049;
}
"""
# Add the custom CSS to the Gradio app
demo.css = custom_css
# Launch the app
demo.launch() |