import os import requests import gradio as gr from gradio_client import Client import matplotlib.pyplot as plt import io from PIL import Image import base64 # Fetch the dynamic endpoint dynamic_endpoint = "https://duchaba-friendly-text-moderation.hf.space/api/predict" def moderate_text(text, safer_value): """ Moderates the given text using the Hugging Face API and returns the result and moderation pie chart. Args: text (str): The text to be moderated. safer_value (float): The safer value for text moderation. Returns: result (dict): The moderation result. img (PIL.Image): The moderation pie chart. """ try: result = client.predict( text, safer_value, api_name="/censor_me" ) # Example structure of the result base64_data = result.get('plot', '').split(',')[1] # 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: print(f"Error during moderation: {e}") return {"error": "Failed to moderate text"}, 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.", theme="compact" ) # 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()