amasha03 commited on
Commit
223044c
·
verified ·
1 Parent(s): e828692

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -33
app.py CHANGED
@@ -2,17 +2,17 @@ import gradio as gr
2
  from gradio_client import Client, handle_file
3
  import os
4
 
5
- # 1. SETUP: Get your HF Token from Settings > Secrets for private access
6
  hf_token = os.environ.get("HF_TOKEN")
7
 
8
  def safe_client(space_id):
9
- """Attempt to connect to a space, return None if it fails."""
10
  try:
11
- # We use the direct hf.space URL for better stability with Docker/Custom spaces
12
  space_url = f"https://{space_id.replace('/', '-').lower()}.hf.space"
13
  return Client(space_url, hf_token=hf_token)
14
  except Exception as e:
15
- print(f"⚠️ Warning: Could not connect to {space_id}. Error: {e}")
16
  return None
17
 
18
  # 2. CONNECT TO YOUR 6 SPACES
@@ -24,11 +24,9 @@ llm_tamil = safe_client("E-motionAssistant/TherapyTamil")
24
  tts_client = safe_client("E-motionAssistant/Space3")
25
 
26
  def detect_language(text):
27
- """Simple script-based language detection."""
28
- # Check for Sinhala characters
29
  if any("\u0D80" <= char <= "\u0DFF" for char in text):
30
  return "sinhala"
31
- # Check for Tamil characters
32
  if any("\u0B80" <= char <= "\u0BFF" for char in text):
33
  return "tamil"
34
  return "english"
@@ -37,36 +35,56 @@ def main_orchestrator(audio_input, text_input, history):
37
  if history is None:
38
  history = []
39
 
 
 
 
 
 
 
 
40
  try:
41
- # A. Determine Emotion
42
- emotion = "Neutral" # Default
43
  if audio_input and speech_emo_client:
 
44
  emotion = speech_emo_client.predict(handle_file(audio_input), api_name="/predict")
45
  elif text_input and text_emo_client:
46
- emotion = text_emo_client.predict(text_input, api_name="/predict")
 
 
 
 
47
 
48
- # B. Select LLM based on Language
49
  lang = detect_language(text_input)
50
- if lang == "sinhala" and llm_sinhala:
51
  selected_llm = llm_sinhala
52
- elif lang == "tamil" and llm_tamil:
53
  selected_llm = llm_tamil
54
  else:
55
  selected_llm = llm_english
56
 
57
  if not selected_llm:
58
- return history + [["Error", "Selected LLM Space is offline."]], None
59
 
60
- # C. Call LLM (Passing history for memory)
61
- # Note: Ensure your LLM spaces accept (text, emotion, history)
62
- response_text = selected_llm.predict(text_input, emotion, history, api_name="/chat")
 
 
 
 
63
 
64
- # D. Convert to Speech
65
  audio_response = None
66
- if tts_client:
67
- audio_response = tts_client.predict(response_text, api_name="/predict")
 
 
 
68
 
69
- # E. Update Memory (State clears on refresh)
 
70
  history.append((text_input, response_text))
71
  return history, audio_response
72
 
@@ -74,25 +92,28 @@ def main_orchestrator(audio_input, text_input, history):
74
  history.append((text_input, f"System Error: {str(e)}"))
75
  return history, None
76
 
77
- # 3. THE UI
78
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
79
- gr.Markdown("# 🧠 Multi-Space Emotional Assistant")
80
- chat_history = gr.State([])
 
 
81
 
82
  with gr.Row():
83
- with gr.Column():
84
- audio_in = gr.Audio(label="Speak", type="filepath")
85
- text_in = gr.Textbox(label="Type here", placeholder="Say something...")
86
- submit_btn = gr.Button("Send", variant="primary")
87
 
88
- with gr.Column():
89
- chatbot = gr.Chatbot(label="Therapy Session")
90
- audio_out = gr.Audio(label="Assistant Voice")
91
 
 
92
  submit_btn.click(
93
  main_orchestrator,
94
- [audio_in, text_in, chat_history],
95
- [chatbot, audio_out]
96
  )
97
 
98
  demo.launch()
 
2
  from gradio_client import Client, handle_file
3
  import os
4
 
5
+ # 1. SETUP: Get your HF Token from Settings > Secrets
6
  hf_token = os.environ.get("HF_TOKEN")
7
 
8
  def safe_client(space_id):
9
+ """Connect to a space via its direct URL for better Docker/Gradio compatibility."""
10
  try:
11
+ # Converts "User/Space-Name" to "https://user-space-name.hf.space"
12
  space_url = f"https://{space_id.replace('/', '-').lower()}.hf.space"
13
  return Client(space_url, hf_token=hf_token)
14
  except Exception as e:
15
+ print(f"⚠️ Could not connect to {space_id}: {e}")
16
  return None
17
 
18
  # 2. CONNECT TO YOUR 6 SPACES
 
24
  tts_client = safe_client("E-motionAssistant/Space3")
25
 
26
  def detect_language(text):
27
+ """Detects Sinhala, Tamil, or English based on character ranges."""
 
28
  if any("\u0D80" <= char <= "\u0DFF" for char in text):
29
  return "sinhala"
 
30
  if any("\u0B80" <= char <= "\u0BFF" for char in text):
31
  return "tamil"
32
  return "english"
 
35
  if history is None:
36
  history = []
37
 
38
+ # --- STEP A: Format History for the LLM API (List of Dicts) ---
39
+ # This fixes the "Data incompatible" error for Gradio 5/6
40
+ api_history = []
41
+ for user_msg, bot_msg in history:
42
+ api_history.append({"role": "user", "content": user_msg})
43
+ api_history.append({"role": "assistant", "content": bot_msg})
44
+
45
  try:
46
+ # --- STEP B: Determine Emotion ---
47
+ emotion = "Neutral"
48
  if audio_input and speech_emo_client:
49
+ # Use handle_file for local temporary audio files
50
  emotion = speech_emo_client.predict(handle_file(audio_input), api_name="/predict")
51
  elif text_input and text_emo_client:
52
+ # If Space4 is Docker and fails, we wrap this in a try/except
53
+ try:
54
+ emotion = text_emo_client.predict(text_input, api_name="/predict")
55
+ except:
56
+ emotion = "Neutral (Space4 Connection Issues)"
57
 
58
+ # --- STEP C: Select LLM & Language ---
59
  lang = detect_language(text_input)
60
+ if lang == "sinhala":
61
  selected_llm = llm_sinhala
62
+ elif lang == "tamil":
63
  selected_llm = llm_tamil
64
  else:
65
  selected_llm = llm_english
66
 
67
  if not selected_llm:
68
+ return history + [[text_input, "Target LLM Space is offline."]], None
69
 
70
+ # --- STEP D: Call the LLM ---
71
+ # We pass 'message' and 'history' (as dictionaries)
72
+ response_text = selected_llm.predict(
73
+ message=text_input,
74
+ history=api_history,
75
+ api_name="/chat"
76
+ )
77
 
78
+ # --- STEP E: Generate Speech (Optional) ---
79
  audio_response = None
80
+ if tts_client and response_text:
81
+ try:
82
+ audio_response = tts_client.predict(response_text, api_name="/predict")
83
+ except:
84
+ audio_response = None
85
 
86
+ # --- STEP F: Update Local UI Memory ---
87
+ # Gradio's Chatbot UI still needs the List-of-Lists format
88
  history.append((text_input, response_text))
89
  return history, audio_response
90
 
 
92
  history.append((text_input, f"System Error: {str(e)}"))
93
  return history, None
94
 
95
+ # --- STEP 3: THE GRADIO INTERFACE ---
96
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
97
+ gr.Markdown("# 🌍 Multilingual Emotional Therapy Hub")
98
+ gr.Markdown("Memory is active for this session. Refreshing the page will clear history.")
99
+
100
+ session_history = gr.State([])
101
 
102
  with gr.Row():
103
+ with gr.Column(scale=1):
104
+ audio_in = gr.Audio(label="Voice Input (Speech Emotion)", type="filepath")
105
+ text_in = gr.Textbox(label="Text Input", placeholder="Type in English, සිංහල, or தமிழ்...")
106
+ submit_btn = gr.Button("Send Message", variant="primary")
107
 
108
+ with gr.Column(scale=2):
109
+ chatbot = gr.Chatbot(label="Conversation History")
110
+ audio_out = gr.Audio(label="Assistant Response (Voice)", autoplay=True)
111
 
112
+ # Connecting the logic
113
  submit_btn.click(
114
  main_orchestrator,
115
+ inputs=[audio_in, text_in, session_history],
116
+ outputs=[chatbot, audio_out]
117
  )
118
 
119
  demo.launch()