sravan837 commited on
Commit
ee943fa
·
verified ·
1 Parent(s): a3ac33a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +179 -0
app.py CHANGED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.
17
+ 5. User: I prefer planning everything weeks in advance. Spontaneity stresses me out.
18
+ 6. User: I find it hard to sympathize with people who are overly emotional.
19
+ 7. User: I love exploring new ideas and hobbies, even if I don't finish them.
20
+ 8. User: Criticism hits me really hard, even if it's constructive.
21
+ 9. User: I tend to take charge in group projects because I want things done right.
22
+ 10. User: I value logic and truth over sparing someone's feelings.
23
+ 11. User: I often get lost in my own thoughts and forget my surroundings.
24
+ 12. User: I hate conflict. I will do anything to keep the peace.
25
+ 13. User: I feel a strong need to help others, sometimes at my own expense.
26
+ 14. User: I get bored easily with routine tasks.
27
+ 15. User: I am very skeptical until I see concrete evidence.
28
+ 16. User: I love meeting new people and being the center of attention.
29
+ 17. User: I struggle to express my emotions verbally.
30
+ 18. User: I often procrastinate until the very last minute.
31
+ 19. User: I feel deeply moved by art and music.
32
+ 20. User: I prefer a few close friends over a large group of acquaintances.
33
+ 21. User: I have a hard time saying "no" to people.
34
+ 22. User: I am constantly analyzing why people do what they do.
35
+ 23. User: I value tradition and established rules.
36
+ 24. User: I am often described as "intense" or "serious."
37
+ 25. User: I feel energetic when I'm debating intellectual topics.
38
+ 26. User: I worry a lot about the future.
39
+ 27. User: I trust my gut instincts more than data sometimes.
40
+ 28. User: I prefer to work alone rather than in a team.
41
+ 29. User: I am very competitive and hate losing.
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")