Spaces:
Sleeping
Sleeping
import gradio as gr | |
import openai | |
from dotenv import load_dotenv | |
import os | |
# Load environment variables from .env file | |
load_dotenv() | |
# Set OpenAI API key from environment variable | |
openai.api_key = os.getenv("OPENAI_API_KEY") | |
def moderate_text(text): | |
text = str(text).strip() if text else "" | |
if not text: | |
return "Input text is empty. Please enter valid text." | |
try: | |
response = openai.Moderation.create( | |
input=text | |
) | |
moderation_categories = response["results"][0]["categories"] | |
moderation_flagged = response["results"][0]["flagged"] | |
if moderation_flagged: | |
flagged_categories = [category for category, flagged in moderation_categories.items() if flagged] | |
return f"The text is flagged for moderation due to: {', '.join(flagged_categories)}" | |
else: | |
return "The text is not flagged for any moderation issues." | |
except Exception as e: | |
return f"An error occurred: {e}" | |
iface = gr.Interface( | |
fn=moderate_text, | |
inputs=gr.Textbox(lines=2, placeholder="Enter text here..."), | |
outputs="text", | |
title="Text Moderation Tool", | |
description="Paste some text, and this tool will use OpenAI's Moderation API to determine if it contains sensitive or flagged content." | |
) | |
if __name__ == "__main__": | |
iface.launch() |