import gradio as gr from transformers import pipeline, AutoModelForCausalLM, AutoTokenizer # Load your model and tokenizer tokenizer = AutoTokenizer.from_pretrained("allenai/llama") model = AutoModelForCausalLM.from_pretrained("allenai/llama") # Load a content moderation pipeline moderation_pipeline = pipeline("text-classification", model="typeform/mobilebert-uncased-mnli") # Function to load bad words from a file def load_bad_words(filepath): with open(filepath, 'r', encoding='utf-8') as file: return [line.strip().lower() for line in file] # Load bad words list bad_words = load_bad_words('badwords.txt') # Adjust the path to your bad words file def is_inappropriate_or_offtopic(message, topics): # Check for inappropriate content using the loaded bad words list if any(bad_word in message.lower() for bad_word in bad_words): return True # Check if off-topic if topics and not any(topic.lower() in message.lower() for topic in topics if topic): return True return False def check_content(message): predictions = moderation_pipeline(message) if predictions[0]['label'] == 'LABEL_1': # Adjust based on the model's output return True return False def generate_response(prompt, topic1, topic2, topic3): topics = [topic1, topic2, topic3] # Collect user-defined topics if is_inappropriate_or_offtopic(prompt, topics): return "Sorry, let's try to keep our conversation focused on positive and relevant topics!" if check_content(prompt): return "I'm here to provide a safe and friendly conversation. Let's talk about something else." inputs = tokenizer.encode(prompt, return_tensors="pt") outputs = model.generate(inputs, max_length=50, do_sample=True) response = tokenizer.decode(outputs[0], skip_special_tokens=True) return response # Define Gradio interface with topic inputs iface = gr.Interface(fn=generate_response, inputs=[gr.inputs.Textbox(lines=2, placeholder="Type your message here..."), gr.inputs.Textbox(label="Topic 1", placeholder="Optional", default=""), gr.inputs.Textbox(label="Topic 2", placeholder="Optional", default=""), gr.inputs.Textbox(label="Topic 3", placeholder="Optional", default="")], outputs="text", title="Child-Safe Chatbot", description="A chatbot that stays on topic and filters inappropriate content. Define up to three topics.") # Run the app if __name__ == "__main__": iface.launch()