amasha03 commited on
Commit
ef6d3e8
·
verified ·
1 Parent(s): 6453fef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -37
app.py CHANGED
@@ -7,42 +7,27 @@ hf_token = os.environ.get("HF_TOKEN")
7
 
8
  def safe_client(space_id):
9
  try:
10
- # Use 'token' for older client versions
11
  return Client(space_id, token=hf_token)
12
  except Exception as e:
13
  print(f"⚠️ Connection failed for {space_id}: {e}")
14
  return None
15
 
16
- # Initializing clients
17
  speech_emo_client = safe_client("E-motionAssistant/ser-wav2vec")
18
  text_emo_client = safe_client("E-motionAssistant/Space4")
19
  llm_english = safe_client("E-motionAssistant/TherapyEnglish")
20
- llm_tamil = safe_client("E-motionAssistant/TherapyTamil")
21
  tts_client = safe_client("E-motionAssistant/Space3")
22
 
23
- def detect_language(text):
24
- if any("\u0D80" <= char <= "\u0DFF" for char in text): return "sinhala"
25
- if any("\u0B80" <= char <= "\u0BFF" for char in text): return "tamil"
26
- return "english"
27
-
28
  def main_orchestrator(audio_input, text_input, history):
29
  if history is None:
30
  history = []
31
 
32
- # Select LLM based on language
33
- lang = detect_language(text_input)
34
- if lang == "sinhala":
35
- selected_llm = llm_sinhala
36
- elif lang == "tamil":
37
- selected_llm = llm_tamil
38
- else:
39
- selected_llm = llm_english
40
-
41
- # Check if the selected space is actually online
42
- if not selected_llm:
43
- return history + [[text_input, "⚠️ This language model is currently offline. Please try English."]], None
44
 
45
- # Get Emotion
46
  emotion = "Neutral"
47
  try:
48
  if audio_input:
@@ -52,29 +37,30 @@ def main_orchestrator(audio_input, text_input, history):
52
  except:
53
  emotion = "Neutral"
54
 
55
- # --- THE TRANSLATION STEP ---
56
- # 1. Convert local UI history [[u,b]] to API history [{'role':'user','content':'...'}]
57
  api_history = []
58
  for user_msg, bot_msg in history:
59
  api_history.append({"role": "user", "content": user_msg})
60
  api_history.append({"role": "assistant", "content": bot_msg})
61
 
62
- # 2. Format the current message as a dictionary
63
- bundled_text = f"Context: User is {emotion}. Message: {text_input}"
 
64
  current_message = {"role": "user", "content": bundled_text}
65
 
 
66
  try:
67
- # 3. Call LLM with the formatted dictionary
68
- response_text = selected_llm.predict(
69
  message=current_message,
70
  history=api_history,
71
  api_name="/chat"
72
  )
73
  except Exception as e:
74
  print(f"LLM API Error: {e}")
75
- response_text = "I'm having trouble connecting to the therapy space. Please try again in a moment."
76
 
77
- # TTS
78
  audio_res = None
79
  if tts_client and response_text:
80
  try:
@@ -82,25 +68,24 @@ def main_orchestrator(audio_input, text_input, history):
82
  except:
83
  audio_res = None
84
 
85
- # Update history in List-of-Lists format for the UI Chatbot
 
86
  history.append([text_input, response_text])
87
  return history, audio_res
88
 
89
- # --- UI ---
90
  with gr.Blocks() as demo:
91
- gr.Markdown("# 🧠 E-motion Therapy Orchestrator")
92
 
93
- # State stores history as [[user, bot]] for the local UI
94
  chat_state = gr.State([])
95
 
96
  with gr.Row():
97
  with gr.Column():
98
- audio_in = gr.Audio(label="Voice Input", type="filepath")
99
- text_in = gr.Textbox(label="Text Input")
100
  submit_btn = gr.Button("Send", variant="primary")
101
 
102
  with gr.Column():
103
- # No 'type="messages"' here so it won't crash on older Gradio
104
  chatbot_ui = gr.Chatbot(label="Chat History")
105
  audio_out = gr.Audio(label="AI Voice", autoplay=True)
106
 
@@ -110,5 +95,5 @@ with gr.Blocks() as demo:
110
  outputs=[chatbot_ui, audio_out]
111
  )
112
 
113
- # Theme passed to launch to fix the UserWarning
114
  demo.launch(theme=gr.themes.Soft())
 
7
 
8
  def safe_client(space_id):
9
  try:
10
+ # Using 'token' for older client versions to avoid keyword errors
11
  return Client(space_id, token=hf_token)
12
  except Exception as e:
13
  print(f"⚠️ Connection failed for {space_id}: {e}")
14
  return None
15
 
16
+ # Initializing clients (English Only)
17
  speech_emo_client = safe_client("E-motionAssistant/ser-wav2vec")
18
  text_emo_client = safe_client("E-motionAssistant/Space4")
19
  llm_english = safe_client("E-motionAssistant/TherapyEnglish")
 
20
  tts_client = safe_client("E-motionAssistant/Space3")
21
 
 
 
 
 
 
22
  def main_orchestrator(audio_input, text_input, history):
23
  if history is None:
24
  history = []
25
 
26
+ # Check if the English space is online
27
+ if not llm_english:
28
+ return history + [[text_input, "⚠️ English Therapy Space is currently offline."]], None
 
 
 
 
 
 
 
 
 
29
 
30
+ # --- 1. GET EMOTION ---
31
  emotion = "Neutral"
32
  try:
33
  if audio_input:
 
37
  except:
38
  emotion = "Neutral"
39
 
40
+ # --- 2. FORMAT DATA FOR GRADIO API ---
41
+ # Convert UI history [[u,b]] to the Dictionary format the API requires
42
  api_history = []
43
  for user_msg, bot_msg in history:
44
  api_history.append({"role": "user", "content": user_msg})
45
  api_history.append({"role": "assistant", "content": bot_msg})
46
 
47
+ # Prepare current message as a dictionary (Role/Content format)
48
+ # We bundle the detected emotion here as context
49
+ bundled_text = f"Context: User is feeling {emotion}. User says: {text_input}"
50
  current_message = {"role": "user", "content": bundled_text}
51
 
52
+ # --- 3. CALL LLM ---
53
  try:
54
+ response_text = llm_english.predict(
 
55
  message=current_message,
56
  history=api_history,
57
  api_name="/chat"
58
  )
59
  except Exception as e:
60
  print(f"LLM API Error: {e}")
61
+ response_text = "I'm having trouble connecting to my therapy space. Please check the sub-space status."
62
 
63
+ # --- 4. TEXT TO SPEECH ---
64
  audio_res = None
65
  if tts_client and response_text:
66
  try:
 
68
  except:
69
  audio_res = None
70
 
71
+ # --- 5. UPDATE UI ---
72
+ # Return List-of-Lists format for the local Chatbot UI
73
  history.append([text_input, response_text])
74
  return history, audio_res
75
 
76
+ # --- THE USER INTERFACE ---
77
  with gr.Blocks() as demo:
78
+ gr.Markdown("# 🧠 English Emotional Therapy AI")
79
 
 
80
  chat_state = gr.State([])
81
 
82
  with gr.Row():
83
  with gr.Column():
84
+ audio_in = gr.Audio(label="Voice Input (Speech Emotion)", type="filepath")
85
+ text_in = gr.Textbox(label="Message", placeholder="Talk to your therapist...")
86
  submit_btn = gr.Button("Send", variant="primary")
87
 
88
  with gr.Column():
 
89
  chatbot_ui = gr.Chatbot(label="Chat History")
90
  audio_out = gr.Audio(label="AI Voice", autoplay=True)
91
 
 
95
  outputs=[chatbot_ui, audio_out]
96
  )
97
 
98
+ # Launching with theme in the correct place
99
  demo.launch(theme=gr.themes.Soft())