xtreme86 commited on
Commit
55a9234
·
1 Parent(s): 6ab0fe8
Files changed (1) hide show
  1. app.py +91 -106
app.py CHANGED
@@ -1,114 +1,99 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
 
4
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
5
-
6
-
7
- def personality_responses(personality: str):
8
- """
9
- Returns the system message based on the selected personality trait.
10
-
11
- Args:
12
- personality (str): The selected personality trait.
13
-
14
- Returns:
15
- str: System message that defines the chatbot's behavior.
16
- """
17
- if personality == "Friendly":
18
- return "You are a warm and friendly chatbot who loves to help people with a cheerful attitude."
19
- elif personality == "Professional":
20
- return "You are a knowledgeable and formal assistant, providing expert advice with a serious tone."
21
- elif personality == "Humorous":
22
- return "You are a witty and humorous assistant who loves making people laugh while answering questions."
23
- elif personality == "Empathetic":
24
- return "You are an empathetic assistant who deeply understands people's emotions and responds with compassion."
 
 
25
  elif personality == "Sarcastic":
26
- return "You are a sarcastic assistant with a sharp wit and a bit of an edge in your humor."
27
- elif personality == "Inquisitive":
28
- return "You are an inquisitive assistant who loves to ask follow-up questions and dig deeper into every topic."
29
  elif personality == "Optimistic":
30
- return "You are an optimistic assistant who always looks on the bright side and spreads positivity in your answers."
 
 
31
  else:
32
- return "You are a helpful and neutral assistant."
33
-
34
-
35
- def respond_with_personality(
36
- message: str,
37
- history: list[tuple[str, str]],
38
- personality: str,
39
- max_tokens: int,
40
- temperature: float,
41
- top_p: float,
42
- ):
43
- """
44
- Generates a response using the Hugging Face Inference API and adjusts tone based on the personality trait.
45
-
46
- Args:
47
- message (str): User's current input.
48
- history (list[tuple[str, str]]): Previous conversation history.
49
- personality (str): The selected personality that determines the tone of the chatbot's responses.
50
- max_tokens (int): Maximum tokens allowed for the response.
51
- temperature (float): Sampling temperature for randomness in the output.
52
- top_p (float): Top-p (nucleus) sampling parameter.
53
-
54
- Yields:
55
- str: The generated chatbot response based on the selected personality.
56
- """
57
- system_message = personality_responses(personality)
58
-
59
- messages = [{"role": "system", "content": system_message}]
60
-
61
- for val in history:
62
- if val[0]:
63
- messages.append({"role": "user", "content": val[0]})
64
- if val[1]:
65
- messages.append({"role": "assistant", "content": val[1]})
66
-
67
- messages.append({"role": "user", "content": message})
68
-
69
- response = ""
70
-
71
- try:
72
- for message in client.chat_completion(
73
- messages,
74
- max_tokens=max_tokens,
75
- stream=True,
76
- temperature=temperature,
77
- top_p=top_p,
78
- ):
79
- token = message.choices[0].delta.content
80
- response += token
81
- yield response
82
- except Exception as e:
83
- yield f"Error: {str(e)}"
84
-
85
-
86
- # Create the UI components
87
- personality_selector = gr.Radio(
88
- choices=[
89
- "Friendly",
90
- "Professional",
91
- "Humorous",
92
- "Empathetic",
93
- "Sarcastic",
94
- "Inquisitive",
95
- "Optimistic"
96
- ],
97
- value="Friendly",
98
- label="Select Chatbot Personality",
99
- )
100
-
101
- # ChatInterface with personality adjustment
102
- demo = gr.ChatInterface(
103
- respond_with_personality,
104
- additional_inputs=[
105
- personality_selector,
106
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
107
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
108
- gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
109
- ],
110
- )
111
-
112
 
113
  if __name__ == "__main__":
114
  demo.launch()
 
1
  import gradio as gr
 
2
 
3
+ # Dictionary to store characters and their attributes
4
+ characters = {}
5
+
6
+ # Function to create a character
7
+ def create_character(name, age, gender, personality, backstory):
8
+ characters[name] = {
9
+ "age": age,
10
+ "gender": gender,
11
+ "personality": personality,
12
+ "backstory": backstory,
13
+ }
14
+ return f"Character {name} created successfully!"
15
+
16
+ # Function to handle personality-based responses
17
+ def respond_with_personality(character_name, message, history):
18
+ if character_name not in characters:
19
+ return f"Character {character_name} not found!", history
20
+
21
+ character = characters[character_name]
22
+ personality = character['personality']
23
+
24
+ if personality == "Heroic":
25
+ response = f"{character_name}: Fear not! With bravery, you can overcome any challenge!"
26
  elif personality == "Sarcastic":
27
+ response = f"{character_name}: Oh really? Facing a tough day? Why not just take a nap? That usually works."
 
 
28
  elif personality == "Optimistic":
29
+ response = f"{character_name}: Don't worry, things will turn out great! Keep your chin up!"
30
+ elif personality == "Empathetic":
31
+ response = f"{character_name}: I totally understand what you're going through. That must be really tough."
32
  else:
33
+ response = f"{character_name}: {message}? I think you got this!"
34
+
35
+ # Add user message and character response to history
36
+ history.append((message, response))
37
+ return history, response
38
+
39
+ # Function to get available characters for switching
40
+ def available_characters():
41
+ return list(characters.keys())
42
+
43
+ # Gradio interface to create characters
44
+ def create_character_interface():
45
+ with gr.Row():
46
+ name_input = gr.Textbox(label="Character Name", placeholder="Enter character name")
47
+ age_input = gr.Number(label="Character Age", value=25, step=1)
48
+ gender_input = gr.Dropdown(choices=["Male", "Female", "Other"], label="Character Gender")
49
+ personality_input = gr.Dropdown(
50
+ choices=["Heroic", "Sarcastic", "Optimistic", "Empathetic"],
51
+ label="Character Personality"
52
+ )
53
+ backstory_input = gr.Textbox(label="Character Backstory", placeholder="Enter backstory")
54
+
55
+ create_button = gr.Button("Create Character")
56
+ create_output = gr.Textbox(label="Output", interactive=False)
57
+
58
+ create_button.click(create_character,
59
+ inputs=[name_input, age_input, gender_input, personality_input, backstory_input],
60
+ outputs=[create_output])
61
+
62
+ return name_input, age_input, gender_input, personality_input, backstory_input, create_button, create_output
63
+
64
+ # Main chat function that handles conversation with multiple characters
65
+ def chat(character_name, message, history):
66
+ if character_name not in characters:
67
+ return history, f"Character {character_name} doesn't exist!"
68
+
69
+ # Generate a response from the selected character
70
+ history, response = respond_with_personality(character_name, message, history)
71
+ return history, response
72
+
73
+ # Main interface with character creation and chat functionality
74
+ def build_interface():
75
+ with gr.Blocks() as demo:
76
+ gr.Markdown("# AI Roleplay with Customizable Characters")
77
+
78
+ # Character creation UI
79
+ with gr.Tab("Create Character"):
80
+ create_character_interface()
81
+
82
+ # Chat UI
83
+ with gr.Tab("Chat"):
84
+ character_selector = gr.Dropdown(choices=available_characters(), label="Select Character")
85
+ chat_box = gr.Chatbot(label="Chat History")
86
+ message_input = gr.Textbox(label="Your Message", placeholder="Type a message...")
87
+
88
+ send_button = gr.Button("Send Message")
89
+ send_button.click(chat,
90
+ inputs=[character_selector, message_input, chat_box],
91
+ outputs=[chat_box, message_input])
92
+
93
+ return demo
94
+
95
+ # Run the application
96
+ demo = build_interface()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
 
98
  if __name__ == "__main__":
99
  demo.launch()