Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,16 +1,17 @@
|
|
| 1 |
-
import
|
| 2 |
import json
|
| 3 |
import asyncio
|
| 4 |
import edge_tts
|
|
|
|
| 5 |
from huggingface_hub import InferenceClient
|
| 6 |
|
| 7 |
-
#
|
| 8 |
EXTRACTOR_MODEL = "meta-llama/Meta-Llama-3-8B-Instruct"
|
| 9 |
PERSONALITY_MODEL = "HuggingFaceH4/zephyr-7b-beta"
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
1. User: I feel completely drained after large social gatherings.
|
| 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 |
-
|
| 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 |
-
|
| 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 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
| 69 |
"""
|
| 70 |
|
| 71 |
prompt = f"<|system|>\n{system_prompt}</s>\n<|user|>\n{chat_logs}</s>\n<|assistant|>"
|
| 72 |
|
| 73 |
try:
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 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 |
-
#
|
| 93 |
-
def
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
}
|
| 100 |
|
|
|
|
| 101 |
context = f"""
|
| 102 |
-
USER
|
| 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"{
|
| 110 |
{"role": "user", "content": message}
|
| 111 |
]
|
| 112 |
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 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 |
-
"
|
| 129 |
-
"
|
| 130 |
-
"
|
| 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 |
-
|
| 139 |
-
|
| 140 |
-
# Main UI Layout
|
| 141 |
-
st.title("Human Personality Engine")
|
| 142 |
|
| 143 |
-
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
#
|
| 146 |
-
with
|
| 147 |
-
|
| 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 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
# Right Column: Interaction
|
| 160 |
-
with col2:
|
| 161 |
-
st.subheader("2. Agent Interaction")
|
| 162 |
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 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 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|