amasha03 commited on
Commit
762b961
·
verified ·
1 Parent(s): 8f109ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -27
app.py CHANGED
@@ -2,12 +2,12 @@ import gradio as gr
2
  from gradio_client import Client, handle_file
3
  import os
4
 
5
- # 1. SETUP: Use 'token' instead of 'hf_token' for compatibility
6
  hf_token = os.environ.get("HF_TOKEN")
7
 
8
  def safe_client(space_id):
9
  try:
10
- # Changed 'hf_token' to '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}")
@@ -30,66 +30,88 @@ def main_orchestrator(audio_input, text_input, history):
30
  if history is None:
31
  history = []
32
 
33
- # Select LLM
34
  lang = detect_language(text_input)
35
- selected_llm = llm_sinhala if lang == "sinhala" else llm_tamil if lang == "tamil" else llm_english
 
 
 
 
 
36
 
37
  if not selected_llm:
38
- return history + [["System", "LLM Space Offline"]], None
39
 
40
- # Get Emotion
41
  emotion = "Neutral"
42
  try:
43
  if audio_input:
 
44
  emotion = speech_emo_client.predict(handle_file(audio_input), api_name="/predict")
45
  elif text_input:
46
  emotion = text_emo_client.predict(text_input, api_name="/predict")
47
  except:
48
  emotion = "Neutral"
49
 
50
- # Bundle message for LLM
51
- bundled_payload = f"Emotion: {emotion}\nMessage: {text_input}"
 
 
 
 
 
 
 
52
 
 
53
  try:
54
- # Calling LLM with the 'message' dictionary
55
  response_text = selected_llm.predict(
56
- message={"text": bundled_payload, "files": []},
57
  api_name="/chat"
58
  )
59
  except:
60
- # Fallback for older API versions
61
- response_text = selected_llm.predict(bundled_payload, api_name="/predict")
 
 
 
62
 
63
- # TTS
64
  audio_res = None
65
- if tts_client:
66
  try:
67
  audio_res = tts_client.predict(response_text, api_name="/predict")
68
  except:
69
  audio_res = None
70
 
71
- # Update history in OLD format [[user, bot]]
72
  history.append([text_input, response_text])
73
  return history, audio_res
74
 
75
- # --- UI ---
76
- # Removed 'theme' from here to fix the warning
77
  with gr.Blocks() as demo:
78
- gr.Markdown("# 🧠 E-motion Therapy Orchestrator (Legacy Fix)")
79
 
80
- state = gr.State([]) # List of lists
 
81
 
82
  with gr.Row():
83
  with gr.Column():
84
- audio_in = gr.Audio(label="Voice Emotion", type="filepath")
85
- text_in = gr.Textbox(label="Message")
86
- btn = gr.Button("Send", variant="primary")
 
87
  with gr.Column():
88
- # Removed 'type="messages"' to fix the TypeError
89
- chat = gr.Chatbot()
90
- audio_out = gr.Audio(autoplay=True)
91
 
92
- btn.click(main_orchestrator, [audio_in, text_in, state], [chat, audio_out])
 
 
 
 
93
 
94
- # Theme passed to launch() as requested by Gradio 6 warning
95
  demo.launch(theme=gr.themes.Soft())
 
2
  from gradio_client import Client, handle_file
3
  import os
4
 
5
+ # 1. SETUP: Using 'token' for compatibility with older gradio_client versions
6
  hf_token = os.environ.get("HF_TOKEN")
7
 
8
  def safe_client(space_id):
9
  try:
10
+ # Note: 'token' is the correct argument 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}")
 
30
  if history is None:
31
  history = []
32
 
33
+ # --- 1. SELECT LLM ---
34
  lang = detect_language(text_input)
35
+ if lang == "sinhala":
36
+ selected_llm = llm_sinhala
37
+ elif lang == "tamil":
38
+ selected_llm = llm_tamil
39
+ else:
40
+ selected_llm = llm_english
41
 
42
  if not selected_llm:
43
+ return history + [["System", "Target LLM is offline."]], None
44
 
45
+ # --- 2. EMOTION DETECTION ---
46
  emotion = "Neutral"
47
  try:
48
  if audio_input:
49
+ # Use handle_file for the audio path
50
  emotion = speech_emo_client.predict(handle_file(audio_input), api_name="/predict")
51
  elif text_input:
52
  emotion = text_emo_client.predict(text_input, api_name="/predict")
53
  except:
54
  emotion = "Neutral"
55
 
56
+ # --- 3. BUNDLE MESSAGE (Context Injection) ---
57
+ # Since the LLM takes one parameter, we put everything in the string
58
+ context_message = f"User Emotion: {emotion}\n"
59
+ if len(history) > 0:
60
+ context_message += "Past Context:\n"
61
+ for user_msg, bot_msg in history[-2:]: # Last 2 exchanges
62
+ context_message += f"User: {user_msg}\nAI: {bot_msg}\n"
63
+
64
+ final_input = f"{context_message}\nCurrent Message: {text_input}"
65
 
66
+ # --- 4. CALL LLM (The Dictionary Wrap Fix) ---
67
  try:
68
+ # Wrapping in the Gradio 5/6 expected dictionary
69
  response_text = selected_llm.predict(
70
+ message={"text": final_input, "files": []},
71
  api_name="/chat"
72
  )
73
  except:
74
+ # Fallback for older space APIs that just take a string
75
+ try:
76
+ response_text = selected_llm.predict(final_input, api_name="/predict")
77
+ except Exception as e:
78
+ response_text = f"LLM Error: {str(e)}"
79
 
80
+ # --- 5. TEXT TO SPEECH ---
81
  audio_res = None
82
+ if tts_client and response_text:
83
  try:
84
  audio_res = tts_client.predict(response_text, api_name="/predict")
85
  except:
86
  audio_res = None
87
 
88
+ # --- 6. UPDATE HISTORY (List of Lists Format) ---
89
  history.append([text_input, response_text])
90
  return history, audio_res
91
 
92
+ # --- 3. THE UI ---
 
93
  with gr.Blocks() as demo:
94
+ gr.Markdown("# 🧠 E-motion Therapy Orchestrator")
95
 
96
+ # State stores history as [[user, bot], [user, bot]]
97
+ chat_state = gr.State([])
98
 
99
  with gr.Row():
100
  with gr.Column():
101
+ audio_in = gr.Audio(label="Voice Input", type="filepath")
102
+ text_in = gr.Textbox(label="Text Input", placeholder="Type here...")
103
+ submit_btn = gr.Button("Send", variant="primary")
104
+
105
  with gr.Column():
106
+ # Standard Chatbot (No 'type' argument to avoid TypeError)
107
+ chatbot_ui = gr.Chatbot(label="Chat History")
108
+ audio_out = gr.Audio(label="AI Voice", autoplay=True)
109
 
110
+ submit_btn.click(
111
+ main_orchestrator,
112
+ inputs=[audio_in, text_in, chat_state],
113
+ outputs=[chatbot_ui, audio_out]
114
+ )
115
 
116
+ # Theme is passed to launch() to resolve the UserWarning
117
  demo.launch(theme=gr.themes.Soft())