Kdeveloper1029 commited on
Commit
afc213f
·
verified ·
1 Parent(s): bb2473d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +92 -21
app.py CHANGED
@@ -1,64 +1,135 @@
1
  from transformers import AutoModelForSequenceClassification, AutoTokenizer
 
2
  import torch
3
  import gradio as gr
4
 
5
  # Load Personality_LM model and tokenizer
6
- model = AutoModelForSequenceClassification.from_pretrained("KevSun/Personality_LM", ignore_mismatched_sizes=True)
7
- tokenizer = AutoTokenizer.from_pretrained("KevSun/Personality_LM")
 
 
 
 
8
 
9
  def analyze_personality(text):
10
- """Analyze personality traits from input text."""
11
- encoded_input = tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=512)
12
- model.eval()
 
 
 
 
 
 
 
 
 
13
  with torch.no_grad():
14
- outputs = model(**encoded_input)
 
15
 
 
16
  predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
17
  predicted_scores = predictions[0].tolist()
18
 
 
19
  trait_names = ["agreeableness", "openness", "conscientiousness", "extraversion", "neuroticism"]
 
 
20
  personality_traits = {trait: score for trait, score in zip(trait_names, predicted_scores)}
21
 
22
  return personality_traits
23
 
24
- def adjust_response(response, traits):
25
- """Adjust chatbot response based on personality traits."""
26
- if traits["agreeableness"] > 0.5:
27
- response = f"{response} 😊 I'm so glad we get along well!"
28
- if traits["neuroticism"] > 0.5:
29
- response += " But I'm feeling a bit worried about what might happen..."
30
- if traits["extraversion"] > 0.5:
31
- response += " Let's keep chatting! I love interacting with you."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  return response
33
 
34
  def respond(user_message, history, personality_text):
35
- """Generate chatbot response based on user input and personality."""
 
 
 
 
 
 
 
 
 
36
  traits = analyze_personality(personality_text)
37
- base_response = f"Hi! You said: {user_message}"
38
- final_response = adjust_response(base_response, traits)
 
39
 
 
40
  history.append((user_message, final_response))
 
41
  return history, history
42
 
43
  def personality_demo():
44
- """Create the Gradio interface for the chatbot with personality training."""
 
 
 
 
45
  with gr.Blocks() as demo:
 
46
  gr.Markdown("### Personality-Based Chatbot")
47
 
 
48
  personality_textbox = gr.Textbox(
49
  label="Define Personality Text (Use direct input if no file)",
50
  placeholder="Type personality description or paste a sample text here."
51
  )
52
 
53
- chatbot = gr.Chatbot()
54
- msg = gr.Textbox(label="User Input", placeholder="Say something to the chatbot...")
55
- clear = gr.Button("Clear Chat")
 
56
 
 
57
  msg.submit(respond, [msg, chatbot, personality_textbox], [chatbot, chatbot])
 
 
58
  clear.click(lambda: ([], []), None, [chatbot, chatbot])
59
 
60
  return demo
61
 
62
  if __name__ == "__main__":
 
63
  demo = personality_demo()
64
  demo.launch()
 
1
  from transformers import AutoModelForSequenceClassification, AutoTokenizer
2
+ from huggingface_hub import InferenceClient
3
  import torch
4
  import gradio as gr
5
 
6
  # Load Personality_LM model and tokenizer
7
+ # The model is pre-trained to evaluate personality traits based on text input
8
+ personality_model = AutoModelForSequenceClassification.from_pretrained("KevSun/Personality_LM", ignore_mismatched_sizes=True)
9
+ personality_tokenizer = AutoTokenizer.from_pretrained("KevSun/Personality_LM")
10
+
11
+ # Initialize the LLM client (HuggingFaceH4/zephyr-7b-beta)
12
+ llm_client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
13
 
14
  def analyze_personality(text):
15
+ """
16
+ Analyze personality traits from input text using the Personality_LM model.
17
+ Args:
18
+ text (str): The input text used for personality analysis.
19
+ Returns:
20
+ dict: A dictionary with personality traits and their corresponding scores.
21
+ """
22
+ # Encode the input text for the model
23
+ encoded_input = personality_tokenizer(text, return_tensors='pt', padding=True, truncation=True, max_length=512)
24
+
25
+ # Set the model to evaluation mode
26
+ personality_model.eval()
27
  with torch.no_grad():
28
+ # Perform prediction
29
+ outputs = personality_model(**encoded_input)
30
 
31
+ # Apply softmax to get probabilities for each trait
32
  predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
33
  predicted_scores = predictions[0].tolist()
34
 
35
+ # Define trait names corresponding to the model's output indices
36
  trait_names = ["agreeableness", "openness", "conscientiousness", "extraversion", "neuroticism"]
37
+
38
+ # Map traits to their respective scores
39
  personality_traits = {trait: score for trait, score in zip(trait_names, predicted_scores)}
40
 
41
  return personality_traits
42
 
43
+ def generate_response(user_message, traits):
44
+ """
45
+ Generate a chatbot response using the LLM and personality traits.
46
+ Args:
47
+ user_message (str): The user's input message.
48
+ traits (dict): The personality traits with their scores.
49
+ Returns:
50
+ str: The chatbot response.
51
+ """
52
+ # Create a system message to guide the LLM behavior
53
+ system_message = (
54
+ "You are a chatbot with the following personality traits: "
55
+ f"Agreeableness: {traits['agreeableness']:.2f}, "
56
+ f"Openness: {traits['openness']:.2f}, "
57
+ f"Conscientiousness: {traits['conscientiousness']:.2f}, "
58
+ f"Extraversion: {traits['extraversion']:.2f}, "
59
+ f"Neuroticism: {traits['neuroticism']:.2f}."
60
+ " Respond to the user's message in a way that reflects these traits."
61
+ )
62
+
63
+ # Generate a response using the LLM
64
+ messages = [
65
+ {"role": "system", "content": system_message},
66
+ {"role": "user", "content": user_message}
67
+ ]
68
+
69
+ response = ""
70
+ for message in llm_client.chat_completion(
71
+ messages,
72
+ max_tokens=256,
73
+ stream=True,
74
+ temperature=0.7,
75
+ top_p=0.95
76
+ ):
77
+ token = message.choices[0].delta.content
78
+ response += token
79
+
80
  return response
81
 
82
  def respond(user_message, history, personality_text):
83
+ """
84
+ Generate a chatbot response based on user input and personality traits.
85
+ Args:
86
+ user_message (str): The user's input message.
87
+ history (list): A list of message-response tuples to maintain conversation history.
88
+ personality_text (str): The text defining the chatbot's personality.
89
+ Returns:
90
+ tuple: Updated conversation history.
91
+ """
92
+ # Analyze personality traits from the provided text
93
  traits = analyze_personality(personality_text)
94
+
95
+ # Generate a response using the LLM and personality traits
96
+ final_response = generate_response(user_message, traits)
97
 
98
+ # Append the new interaction to the conversation history
99
  history.append((user_message, final_response))
100
+
101
  return history, history
102
 
103
  def personality_demo():
104
+ """
105
+ Create the Gradio interface for the chatbot with personality-based adjustments.
106
+ Returns:
107
+ gr.Blocks: The Gradio interface object.
108
+ """
109
  with gr.Blocks() as demo:
110
+ # Header for the chatbot interface
111
  gr.Markdown("### Personality-Based Chatbot")
112
 
113
+ # Textbox for defining personality traits via input text
114
  personality_textbox = gr.Textbox(
115
  label="Define Personality Text (Use direct input if no file)",
116
  placeholder="Type personality description or paste a sample text here."
117
  )
118
 
119
+ # Chatbot UI elements
120
+ chatbot = gr.Chatbot() # Chat display area
121
+ msg = gr.Textbox(label="User Input", placeholder="Say something to the chatbot...") # User input box
122
+ clear = gr.Button("Clear Chat") # Button to clear chat history
123
 
124
+ # Link user input submission to the chatbot response function
125
  msg.submit(respond, [msg, chatbot, personality_textbox], [chatbot, chatbot])
126
+
127
+ # Link clear button to reset the chat history
128
  clear.click(lambda: ([], []), None, [chatbot, chatbot])
129
 
130
  return demo
131
 
132
  if __name__ == "__main__":
133
+ # Launch the Gradio demo interface
134
  demo = personality_demo()
135
  demo.launch()