sravan837 commited on
Commit
5bccccf
·
verified ·
1 Parent(s): edecd9e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +101 -107
app.py CHANGED
@@ -1,16 +1,17 @@
1
- import streamlit as st
2
  import json
3
  import asyncio
4
  import edge_tts
 
5
  from huggingface_hub import InferenceClient
6
 
7
- # Configuration
8
  EXTRACTOR_MODEL = "meta-llama/Meta-Llama-3-8B-Instruct"
9
  PERSONALITY_MODEL = "HuggingFaceH4/zephyr-7b-beta"
10
 
11
- # Synthetic Data: 30 Messages reflecting personality traits (Big Five / MBTI context)
12
- DEFAULT_CHAT_LOG = """
13
- 1. User: I feel completely drained after large social gatherings. I need alone time to recharge.
14
  2. User: I enjoy abstract theories more than practical details.
15
  3. User: My desk is always messy, but I know where everything is.
16
  4. User: I often worry that I said the wrong thing in conversations.
@@ -42,138 +43,131 @@ DEFAULT_CHAT_LOG = """
42
  30. User: I want to understand my true purpose in life.
43
  """
44
 
45
- st.set_page_config(page_title="Personality Analysis Engine", layout="wide")
46
-
47
- # Authentication Sidebar
48
- with st.sidebar:
49
- st.header("Configuration")
50
- hf_token = st.text_input("Hugging Face Token", type="password")
51
  if not hf_token:
52
- st.warning("Please enter your Hugging Face Token to proceed.")
53
- st.stop()
54
-
55
- client = InferenceClient(token=hf_token)
56
-
57
- # Module A: Memory Extraction
58
- def extract_memory(chat_logs):
59
- # System prompt designed to extract psychological profile
60
- system_prompt = """
61
- You are a Psychological Analyst. Analyze the chat logs and extract a structured user profile.
62
 
63
- Required JSON Keys:
64
- 1. "traits": Big Five or MBTI indicators (e.g., Introversion, High Openness, Agreeableness).
65
- 2. "values": What the user prioritizes (e.g., Logic, Harmony, Efficiency, Autonomy).
66
- 3. "struggles": Recurring points of friction (e.g., Social anxiety, Procrastination, Conflict avoidance).
67
 
68
- Output strictly valid JSON only.
 
 
 
69
  """
70
 
71
  prompt = f"<|system|>\n{system_prompt}</s>\n<|user|>\n{chat_logs}</s>\n<|assistant|>"
72
 
73
  try:
74
- with st.spinner("Analyzing psychological patterns..."):
75
- response = client.text_generation(
76
- model=EXTRACTOR_MODEL,
77
- prompt=prompt,
78
- max_new_tokens=600,
79
- temperature=0.1
80
- )
81
- # Parse JSON from response
82
- text = response.strip()
83
- start = text.find("{")
84
- end = text.rfind("}") + 1
85
- if start != -1 and end != -1:
86
- return json.loads(text[start:end])
87
- else:
88
- return {"error": "Failed to parse JSON output"}
89
  except Exception as e:
90
- return {"error": str(e)}
91
 
92
- # Module B: Personality Engine (Text Generation)
93
- def generate_response(message, memory, persona):
94
- # Define distinct psychological personas
95
- personas = {
96
- "Analytical Psychologist": "Role: Jungian Analyst. Tone: Objective, deep, intellectual. Focus: Unconscious patterns, archetypes, and logic.",
97
- "Empathetic Counselor": "Role: Humanistic Therapist. Tone: Warm, validating, gentle. Focus: Emotional safety, acceptance, and feelings.",
98
- "Pragmatic Coach": "Role: Behavioral Coach. Tone: Direct, action-oriented, blunt. Focus: Solutions, efficiency, and breaking habits."
 
 
 
 
 
 
 
 
 
 
99
  }
100
 
 
101
  context = f"""
102
- USER PSYCH PROFILE:
103
  - Traits: {memory.get('traits', 'Unknown')}
104
  - Values: {memory.get('values', 'Unknown')}
105
  - Struggles: {memory.get('struggles', 'Unknown')}
106
  """
107
 
108
  messages = [
109
- {"role": "system", "content": f"{personas[persona]}\n\n{context}"},
110
  {"role": "user", "content": message}
111
  ]
112
 
113
- try:
114
- res = client.chat_completion(
115
- model=PERSONALITY_MODEL,
116
- messages=messages,
117
- max_tokens=250,
118
- temperature=0.7
119
- )
120
- return res.choices[0].message.content
121
- except Exception as e:
122
- return f"Error generating text: {e}"
123
-
124
- # Module C: Audio Engine (Edge-TTS)
125
- async def generate_audio(text, persona):
126
- # Map personas to suitable voice types
127
  voice_map = {
128
- "Analytical Psychologist": "en-US-ChristopherNeural", # Deep, serious male voice
129
- "Empathetic Counselor": "en-US-AvaNeural", # Soft, soothing female voice
130
- "Pragmatic Coach": "en-US-EricNeural" # Energetic, firm male voice
131
  }
132
 
133
- voice = voice_map.get(persona, "en-US-AriaNeural")
134
  output_file = "response.mp3"
135
-
136
- communicate = edge_tts.Communicate(text, voice)
137
  await communicate.save(output_file)
138
- return output_file
139
-
140
- # Main UI Layout
141
- st.title("Human Personality Engine")
142
 
143
- col1, col2 = st.columns([1, 1])
 
 
144
 
145
- # Left Column: Data Analysis
146
- with col1:
147
- st.subheader("1. Profile Extraction")
148
- with st.expander("View Raw Chat Logs"):
149
- st.text(DEFAULT_CHAT_LOG)
150
-
151
- if st.button("Analyze User Profile"):
152
- memory_data = extract_memory(DEFAULT_CHAT_LOG)
153
- st.session_state['memory'] = memory_data
154
- st.success("Analysis Complete")
155
 
156
- if 'memory' in st.session_state:
157
- st.json(st.session_state['memory'])
158
-
159
- # Right Column: Interaction
160
- with col2:
161
- st.subheader("2. Agent Interaction")
162
 
163
- if 'memory' not in st.session_state:
164
- st.info("Please analyze the user profile first.")
165
- else:
166
- user_input = st.text_input("Input Message:", "I feel overwhelmed by all the details.")
167
- persona = st.selectbox("Select Agent Persona:", ["Analytical Psychologist", "Empathetic Counselor", "Pragmatic Coach"])
168
-
169
- if st.button("Generate Response"):
170
- # Generate Text
171
- with st.spinner("Generating text response..."):
172
- reply = generate_response(user_input, st.session_state['memory'], persona)
173
- st.markdown(f"**{persona}:** {reply}")
174
 
175
- # Generate Audio
176
- with st.spinner("Synthesizing speech..."):
177
- asyncio.run(generate_audio(reply, persona))
 
 
 
 
 
 
 
 
 
178
 
179
- st.audio("response.mp3")
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
  import json
3
  import asyncio
4
  import edge_tts
5
+ import os
6
  from huggingface_hub import InferenceClient
7
 
8
+ # --- CONFIGURATION ---
9
  EXTRACTOR_MODEL = "meta-llama/Meta-Llama-3-8B-Instruct"
10
  PERSONALITY_MODEL = "HuggingFaceH4/zephyr-7b-beta"
11
 
12
+ # Default Data: 30 Personality-focused messages
13
+ DEFAULT_LOGS = """
14
+ 1. User: I feel completely drained after large social gatherings.
15
  2. User: I enjoy abstract theories more than practical details.
16
  3. User: My desk is always messy, but I know where everything is.
17
  4. User: I often worry that I said the wrong thing in conversations.
 
43
  30. User: I want to understand my true purpose in life.
44
  """
45
 
46
+ # --- LOGIC: MEMORY EXTRACTION ---
47
+ def extract_memory(chat_logs, hf_token):
 
 
 
 
48
  if not hf_token:
49
+ return json.dumps({"error": "Missing HF Token"}, indent=2)
 
 
 
 
 
 
 
 
 
50
 
51
+ client = InferenceClient(token=hf_token)
 
 
 
52
 
53
+ system_prompt = """
54
+ Analyze the chat logs and extract a psychological profile.
55
+ JSON KEYS: "traits" (Big Five/MBTI), "values" (Logic, Harmony, etc), "struggles" (Anxiety, Procrastination).
56
+ OUTPUT: Valid JSON only.
57
  """
58
 
59
  prompt = f"<|system|>\n{system_prompt}</s>\n<|user|>\n{chat_logs}</s>\n<|assistant|>"
60
 
61
  try:
62
+ response = client.text_generation(
63
+ model=EXTRACTOR_MODEL,
64
+ prompt=prompt,
65
+ max_new_tokens=600,
66
+ temperature=0.1
67
+ )
68
+ # Parse JSON
69
+ text = response.strip()
70
+ start = text.find("{")
71
+ end = text.rfind("}") + 1
72
+ return json.dumps(json.loads(text[start:end]), indent=2)
 
 
 
 
73
  except Exception as e:
74
+ return json.dumps({"error": str(e)}, indent=2)
75
 
76
+ # --- LOGIC: PERSONALITY RESPONSE ---
77
+ async def generate_response_and_audio(message, memory_json, persona, hf_token):
78
+ if not hf_token:
79
+ return "Please enter HF Token.", None
80
+
81
+ client = InferenceClient(token=hf_token)
82
+
83
+ try:
84
+ memory = json.loads(memory_json)
85
+ except:
86
+ memory = {}
87
+
88
+ # 1. Define Persona Prompts
89
+ prompts = {
90
+ "Calm Mentor": "Role: Mentor. Tone: Calm, wise, patient. Focus: Growth, long-term perspective. Voice: Deep & Slow.",
91
+ "Witty Friend": "Role: Friend. Tone: Witty, casual, sarcastic, fun. Focus: Relatability, humor. Voice: Fast & Energetic.",
92
+ "Therapist-style": "Role: Therapist. Tone: Empathetic, soft, validating. Focus: Emotions, safety. Voice: Soft & Warm."
93
  }
94
 
95
+ # 2. Context Injection
96
  context = f"""
97
+ USER PROFILE:
98
  - Traits: {memory.get('traits', 'Unknown')}
99
  - Values: {memory.get('values', 'Unknown')}
100
  - Struggles: {memory.get('struggles', 'Unknown')}
101
  """
102
 
103
  messages = [
104
+ {"role": "system", "content": f"{prompts[persona]}\n\n{context}"},
105
  {"role": "user", "content": message}
106
  ]
107
 
108
+ # 3. Generate Text
109
+ res = client.chat_completion(
110
+ model=PERSONALITY_MODEL,
111
+ messages=messages,
112
+ max_tokens=250,
113
+ temperature=0.7
114
+ )
115
+ text_reply = res.choices[0].message.content
116
+
117
+ # 4. Generate Audio (Edge-TTS)
 
 
 
 
118
  voice_map = {
119
+ "Calm Mentor": "en-US-ChristopherNeural",
120
+ "Witty Friend": "en-US-EricNeural",
121
+ "Therapist-style": "en-US-AvaNeural"
122
  }
123
 
 
124
  output_file = "response.mp3"
125
+ communicate = edge_tts.Communicate(text_reply, voice_map.get(persona, "en-US-AriaNeural"))
 
126
  await communicate.save(output_file)
127
+
128
+ return text_reply, output_file
 
 
129
 
130
+ # Wrapper for Gradio (handling async)
131
+ def process_interaction(message, memory_json, persona, hf_token):
132
+ return asyncio.run(generate_response_and_audio(message, memory_json, persona, hf_token))
133
 
134
+ # --- GRADIO UI ---
135
+ with gr.Blocks(title="Personality Engine") as demo:
136
+ gr.Markdown("# Personality Engine: Tones")
 
 
 
 
 
 
 
137
 
138
+ with gr.Row():
139
+ token_input = gr.Textbox(label="Hugging Face Token", type="password", placeholder="hf_...")
 
 
 
 
140
 
141
+ with gr.Row():
142
+ # Left Column: Memory
143
+ with gr.Column(scale=1):
144
+ gr.Markdown("### 1. Memory Extraction")
145
+ logs_input = gr.Textbox(label="Chat Logs (Input)", value=DEFAULT_LOGS, lines=10)
146
+ extract_btn = gr.Button("Analyze Profile")
147
+ memory_output = gr.Code(label="Extracted Memory (JSON)", language="json")
 
 
 
 
148
 
149
+ extract_btn.click(extract_memory, inputs=[logs_input, token_input], outputs=memory_output)
150
+
151
+ # Right Column: Interaction
152
+ with gr.Column(scale=1):
153
+ gr.Markdown("### 2. Personality Interaction")
154
+ user_msg = gr.Textbox(label="Your Message", value="I'm feeling overwhelmed by the future.")
155
+ persona_select = gr.Radio(
156
+ ["Calm Mentor", "Witty Friend", "Therapist-style"],
157
+ label="Select Tone",
158
+ value="Calm Mentor"
159
+ )
160
+ generate_btn = gr.Button("Generate Response")
161
 
162
+ with gr.Group():
163
+ text_output = gr.Markdown(label="Response Text")
164
+ audio_output = gr.Audio(label="Voice Response")
165
+
166
+ generate_btn.click(
167
+ process_interaction,
168
+ inputs=[user_msg, memory_output, persona_select, token_input],
169
+ outputs=[text_output, audio_output]
170
+ )
171
+
172
+ if __name__ == "__main__":
173
+ demo.queue().launch()