Spaces:
Paused
Paused
Download app.py from hukraken07/chatbot: direct link, hf CLI and curl.
- Browser
- Download file 10.8 kB
-
https://huggingface.co/spaces/hukraken07/chatbot/resolve/main/app.py
- Command line
-
hf download hf://spaces/hukraken07/chatbot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/hukraken07/chatbot/resolve/main/app.py
10.8 kB
| import subprocess | |
| import os | |
| os.environ["HF_HUB_ENABLE_HF_TRANSFER"] = "1" | |
| os.environ["GRADIO_ANALYTICS_ENABLED"] = "False" | |
| print(os.getcwd()) | |
| print(os.listdir()) | |
| MODEL_NAME = "./lora_model" | |
| print("Installing packages for 🦥 Unsloth Studio ... Please wait 1 minute ...") | |
| install_first = [ | |
| "pip", "install", | |
| "huggingface_hub", "hf_transfer", "triton", | |
| ] | |
| install_first = subprocess.Popen(install_first) | |
| install_first.wait() | |
| install_second = [ | |
| "pip", "install", | |
| "gradio", | |
| "unsloth[colab-new]@git+https://github.com/unslothai/unsloth.git", | |
| ] | |
| install_second = subprocess.Popen(install_second) | |
| import warnings | |
| warnings.filterwarnings(action = "ignore", category = UserWarning, module = "torch") | |
| warnings.filterwarnings(action = "ignore", category = UserWarning, module = "huggingface_hub") | |
| warnings.filterwarnings(action = "ignore", category = FutureWarning, module = "huggingface_hub") | |
| warnings.filterwarnings(action = "ignore", category = RuntimeWarning, module = "subprocess") | |
| warnings.filterwarnings(action = "ignore", category = UserWarning, module = "transformers") | |
| warnings.filterwarnings(action = "ignore", category = FutureWarning, module = "accelerate") | |
| warnings.filterwarnings(action = "ignore", category = RuntimeWarning, module = "multiprocessing") | |
| warnings.filterwarnings(action = "ignore", category = RuntimeWarning, module = "multiprocess") | |
| from huggingface_hub.utils import disable_progress_bars | |
| disable_progress_bars() | |
| install_second.wait() | |
| install_dependencies = [ | |
| "pip", "install", "--no-deps", | |
| "xformers", "trl", "peft", "accelerate", "bitsandbytes", | |
| ] | |
| install_dependencies = subprocess.Popen(install_dependencies) | |
| install_dependencies.wait() | |
| import logging | |
| logging.getLogger("transformers.utils.hub").setLevel(logging.CRITICAL+1) | |
| print("Loading model ... Please wait 1 more minute! ...") | |
| from unsloth import FastLanguageModel | |
| import torch | |
| model, tokenizer = FastLanguageModel.from_pretrained( | |
| model_name = MODEL_NAME, | |
| max_seq_length = None, | |
| dtype = None, | |
| load_in_4bit = True, | |
| ) | |
| # model2, tokenizer2 = FastLanguageModel.from_pretrained( | |
| # model_name = MODEL_NAME, | |
| # max_seq_length = None, | |
| # dtype = None, | |
| # load_in_4bit = True, | |
| # ) | |
| FastLanguageModel.for_inference(model) | |
| # FastLanguageModel.for_inference(model2) | |
| import gradio | |
| gradio.strings.en["SHARE_LINK_DISPLAY"] = "" | |
| from transformers import StoppingCriteria | |
| from threading import Thread | |
| class StopOnTokens(StoppingCriteria): | |
| def __init__(self, stop_token_ids): | |
| self.stop_token_ids = tuple(set(stop_token_ids)) | |
| pass | |
| def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool: | |
| return input_ids[0][-1].item() in self.stop_token_ids | |
| pass | |
| pass | |
| import gradio as gr | |
| import torch | |
| # Updated traits and behavioral metrics | |
| additional_traits = ["Empathy", "Curiosity", "Assertiveness"] | |
| all_traits = ["Openness", "Conscientiousness", "Extraversion", "Agreeableness", "Neuroticism"] + additional_traits | |
| # Expanded prompt template | |
| alpaca_prompt = """#### INSTRUCTION: REPLY LIKE A HUMAN BASED ON THE GIVEN PERSONALITY TRAITS, BEHAVIORAL METRICS, MOODS, STYLES, AND PROFILE INFO: | |
| LANGUAGE: {language}, SOCIOECONOMIC STATUS: {socioeconomic_status}, BIG FIVE TRAITS: {big_five}, ADDITIONAL TRAITS: {additional_traits}, MBTI: {mbti}, FORMALITY: {formality}, | |
| INTEREST: {interest}, CONFIDENCE: {confidence}, ATTRACTIVENESS: {attractiveness}, INTELLIGENCE: {intelligence}, | |
| LISTENING SKILLS: {listening_skills}, HUMOR: {humor}, MOOD: {mood}, STYLE: {style}, PROFILE: {profile_info} - | |
| ### PREVIOUS CONVERSATION: | |
| {conversation_history} | |
| ### INPUT: {message} | |
| ### Response: | |
| """ | |
| # Traits detection function (placeholder for ML-based logic) | |
| def detect_traits(conversation): | |
| # Example logic (Replace with actual NLP-based estimation) | |
| detected_traits = {"Empathy": 70, "Curiosity": 60, "Assertiveness": 80} | |
| print("Detected Traits:", detected_traits) | |
| return detected_traits | |
| # Conversation history | |
| conversation_history = [] | |
| # Generate bot-bot conversation | |
| # def bot_to_bot_conversation(): | |
| # print("Starting Bot-to-Bot Mode") | |
| # bot1 = "Hello, how are you?" | |
| # conversation = [f"Bot1: {bot1}"] | |
| # bot1_input = tokenizer(bot1, return_tensors="pt").to("cuda") | |
| # bot2_response_old = bot1 | |
| # for _ in range(5): # Define the number of exchanges | |
| # print(f"Bot2: {bot2_response_old}\n") | |
| # conversation.append(f"Bot2: {bot2_response_old}\n") | |
| # bot2_output = model.generate(bot1_input["input_ids"], max_new_tokens=32, repetition_penalty=1.2, temperature=0.7, top_p=0.9, top_k=50) | |
| # bot2_response = tokenizer.decode(bot2_output[0], skip_special_tokens=True) | |
| # bot2_input = tokenizer2(bot2_response[len(bot2_response_old):], return_tensors="pt").to("cuda") | |
| # bot1_response_old = bot2_response[len(bot2_response_old):] | |
| # print(f"Bot1: {bot1_response_old}\n") | |
| # conversation.append(f"Bot1: {bot1_response_old}\n") | |
| # bot1_output = model2.generate(bot2_input["input_ids"], max_new_tokens=32, repetition_penalty=1.2, temperature=0.7, top_p=0.9, top_k=50) | |
| # bot1_response = tokenizer2.decode(bot1_output[0], skip_special_tokens=True) | |
| # bot1_input = tokenizer(bot1_response[len(bot1_response_old):], return_tensors="pt").to("cuda") | |
| # bot2_response_old = bot1_response[len(bot1_response_old):] | |
| # return "\n".join(conversation) | |
| # Generate response function | |
| def generate_response( | |
| message, language, socioeconomic_status, openness, conscientiousness, extraversion, agreeableness, neuroticism, | |
| empathy, curiosity, assertiveness, mbti, formality, interest, confidence, | |
| attractiveness, intelligence, listening_skills, humor, mood_happiness, mood_sadness, mood_anger, | |
| mood_fear, mood_surprise, mood_disgust, style_cooperative, style_competitive, style_assertive, | |
| profile_info,conversation_mode, clear_conversation, feedback=None | |
| ): | |
| if clear_conversation: | |
| global conversation_history | |
| conversation_history = [] | |
| return 'Conversation Cleared' | |
| # Handle bot-to-bot conversation | |
| if conversation_mode == "Bot-Bot": | |
| return 'Pending' | |
| # return bot_to_bot_conversation() | |
| # Prepare mood and style values | |
| mood = f"Happiness: {mood_happiness}, Sadness: {mood_sadness}, Anger: {mood_anger}, Fear: {mood_fear}, Surprise: {mood_surprise}, Disgust: {mood_disgust}" | |
| style = f"Cooperative: {style_cooperative}, Competitive: {style_competitive}, Assertive: {style_assertive}" | |
| # Prepare the prompt | |
| big_five = f"Openness: {openness}, Conscientiousness: {conscientiousness}, Extraversion: {extraversion}, Agreeableness: {agreeableness}, Neuroticism: {neuroticism}" | |
| additional_traits = f"Empathy: {empathy}, Curiosity: {curiosity}, Assertiveness: {assertiveness}" | |
| prompt = alpaca_prompt.format( | |
| message=message, | |
| language=language, | |
| socioeconomic_status=socioeconomic_status, | |
| big_five=big_five, | |
| additional_traits=additional_traits, | |
| mbti=mbti, | |
| formality=formality, | |
| interest=interest, | |
| confidence=confidence, | |
| attractiveness=attractiveness, | |
| intelligence=intelligence, | |
| listening_skills=listening_skills, | |
| humor=humor, | |
| mood=mood, | |
| style=style, | |
| profile_info=profile_info, | |
| conversation_history="\n".join(conversation_history) | |
| ) | |
| inputs = tokenizer(prompt, return_tensors="pt").to("cuda") | |
| outputs = model.generate( | |
| **inputs, | |
| max_new_tokens=128, | |
| repetition_penalty=1.2, | |
| temperature=0.7, | |
| top_p=0.9, | |
| top_k=50, | |
| length_penalty=1.0, | |
| ) | |
| response = tokenizer.decode(outputs[0], skip_special_tokens=True) | |
| # Generate response using the model (placeholder logic for now) | |
| response = f"Processed response based on: {response}" | |
| conversation_history.append(f"User: {message}") | |
| conversation_history.append(f"Bot: {response}") | |
| # Handle feedback | |
| if feedback: | |
| print("Feedback Received:", feedback) | |
| return response | |
| # Gradio interface with sliders for all traits, moods, and conversation styles | |
| interface = gr.Interface( | |
| fn=generate_response, | |
| inputs=[ | |
| gr.Textbox(label="Message", placeholder="Enter your message here..."), | |
| gr.Dropdown(choices=["English", "Spanish", "French"], label="Language"), | |
| gr.Dropdown(choices=["Low", "Middle", "High"], label="Socioeconomic Status"), | |
| gr.Slider(0, 100, value=50, step=1, label="Openness"), | |
| gr.Slider(0, 100, value=50, step=1, label="Conscientiousness"), | |
| gr.Slider(0, 100, value=50, step=1, label="Extraversion"), | |
| gr.Slider(0, 100, value=50, step=1, label="Agreeableness"), | |
| gr.Slider(0, 100, value=50, step=1, label="Neuroticism"), | |
| gr.Slider(0, 100, value=50, step=1, label="Empathy"), | |
| gr.Slider(0, 100, value=50, step=1, label="Curiosity"), | |
| gr.Slider(0, 100, value=50, step=1, label="Assertiveness"), | |
| gr.Dropdown(choices=["INTJ", "INFP", "ENTJ", "ENFP", "ISFJ", "ESFP", "ISTP", "ESTJ"], label="MBTI Type"), | |
| gr.Slider(0, 100, value=50, step=1, label="Formality"), | |
| gr.Slider(0, 100, value=50, step=1, label="Interest"), | |
| gr.Slider(0, 100, value=50, step=1, label="Confidence"), | |
| gr.Slider(0, 100, value=50, step=1, label="Attractiveness"), | |
| gr.Slider(0, 100, value=50, step=1, label="Intelligence"), | |
| gr.Slider(0, 100, value=50, step=1, label="Listening Skills"), | |
| gr.Slider(0, 100, value=50, step=1, label="Humor"), | |
| gr.Slider(0, 100, value=50, step=1, label="Mood: Happiness"), | |
| gr.Slider(0, 100, value=50, step=1, label="Mood: Sadness"), | |
| gr.Slider(0, 100, value=50, step=1, label="Mood: Anger"), | |
| gr.Slider(0, 100, value=50, step=1, label="Mood: Fear"), | |
| gr.Slider(0, 100, value=50, step=1, label="Mood: Surprise"), | |
| gr.Slider(0, 100, value=50, step=1, label="Mood: Disgust"), | |
| gr.Slider(0, 100, value=50, step=1, label="Style: Cooperative"), | |
| gr.Slider(0, 100, value=50, step=1, label="Style: Competitive"), | |
| gr.Slider(0, 100, value=50, step=1, label="Style: Assertive"), | |
| gr.Textbox(label="Profile Info", value="Name: Anonymous, Age: Unknown, Interests: None specified"), | |
| gr.Radio(["Human-Bot", "Bot-Bot"], label="Conversation Mode"), | |
| gr.Checkbox(label="Clear Conversation"), | |
| gr.Radio(["Positive", "Neutral", "Negative"], label="Feedback") | |
| ], | |
| outputs="text", | |
| title="Enhanced Chatbot with Customization and Bot-to-Bot Mode", | |
| description="Interact with a chatbot tailored to various personality traits, moods, and behavioral metrics. Includes bot-to-bot conversation mode." | |
| ) | |
| # Launch the interface | |
| interface.launch(share=True) | |