datbkpro commited on
Commit
3e3a497
·
verified ·
1 Parent(s): f00ca5b

Update services/audio_service.py

Browse files
Files changed (1) hide show
  1. services/audio_service.py +183 -14
services/audio_service.py CHANGED
@@ -1,7 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import numpy as np
2
  import soundfile as sf
3
  import io
4
- import traceback
5
  from groq import Groq
6
  from config.settings import settings
7
  from core.rag_system import EnhancedRAGSystem
@@ -9,7 +152,6 @@ from core.tts_service import EnhancedTTSService
9
  from core.multilingual_manager import MultilingualManager
10
 
11
  class AudioService:
12
-
13
  def __init__(self, groq_client: Groq, rag_system: EnhancedRAGSystem, tts_service: EnhancedTTSService):
14
  self.groq_client = groq_client
15
  self.rag_system = rag_system
@@ -48,22 +190,38 @@ class AudioService:
48
  sf.write(buffer, y, sr, format='WAV', subtype='PCM_16')
49
  buffer.seek(0)
50
 
51
- # Gọi Groq API với định dạng file đúng
52
  try:
 
 
 
53
  transcription = self.groq_client.audio.transcriptions.create(
 
54
  model=settings.WHISPER_MODEL,
55
- file=("audio.wav", buffer.read(), "audio/wav"), # Đảm bảo đúng định dạng
56
  response_format="text"
57
  )
58
- transcription_text = transcription.text
 
 
 
 
 
 
 
 
 
59
  except Exception as e:
60
  error_msg = f"❌ Lỗi API chuyển đổi giọng nói: {str(e)}"
 
61
  return error_msg, "❌ Không thể chuyển đổi giọng nói thành văn bản", None, "unknown"
62
 
63
  # Kiểm tra transcription có hợp lệ không
64
  if not transcription_text or len(transcription_text.strip()) == 0:
65
  return "❌ Không thể nhận dạng giọng nói", "❌ Vui lòng thử lại với âm thanh rõ hơn", None, "unknown"
66
 
 
 
67
  # Phát hiện ngôn ngữ và tạo response
68
  language = self.multilingual_manager.detect_language(transcription_text)
69
  response = self._generate_response_with_rag(transcription_text, language)
@@ -72,10 +230,12 @@ class AudioService:
72
  tts_audio = None
73
  if response and not response.startswith("❌") and not response.startswith("Error"):
74
  try:
 
75
  tts_bytes = self.tts_service.text_to_speech(response, language)
76
  if tts_bytes:
77
  tts_audio_path = self.tts_service.save_tts_audio(tts_bytes)
78
  tts_audio = tts_audio_path
 
79
  except Exception as e:
80
  print(f"⚠️ Lỗi TTS: {e}")
81
  # Vẫn trả về text response nếu TTS fail
@@ -84,6 +244,7 @@ class AudioService:
84
 
85
  except Exception as e:
86
  error_msg = f"❌ Lỗi hệ thống xử lý âm thanh: {str(e)}"
 
87
  return error_msg, "❌ Có lỗi xảy ra trong quá trình xử lý", None, "unknown"
88
 
89
  def _generate_response_with_rag(self, query: str, language: str) -> str:
@@ -130,15 +291,23 @@ class AudioService:
130
  }
131
  ]
132
 
133
- # Gọi Groq API
134
- completion = self.groq_client.chat.completions.create(
135
- model=llm_model,
136
- messages=messages,
137
- max_tokens=512,
138
- temperature=0.7,
139
- )
140
-
141
- return completion.choices[0].message.content.strip()
 
 
 
 
 
 
 
 
142
 
143
  except Exception as e:
144
  return f"❌ Lỗi tạo phản hồi: {str(e)}"
 
1
+ # import numpy as np
2
+ # import soundfile as sf
3
+ # import io
4
+ # import traceback
5
+ # from groq import Groq
6
+ # from config.settings import settings
7
+ # from core.rag_system import EnhancedRAGSystem
8
+ # from core.tts_service import EnhancedTTSService
9
+ # from core.multilingual_manager import MultilingualManager
10
+
11
+ # class AudioService:
12
+
13
+ # def __init__(self, groq_client: Groq, rag_system: EnhancedRAGSystem, tts_service: EnhancedTTSService):
14
+ # self.groq_client = groq_client
15
+ # self.rag_system = rag_system
16
+ # self.tts_service = tts_service
17
+ # self.multilingual_manager = MultilingualManager()
18
+
19
+ # def transcribe_audio(self, audio: tuple) -> tuple:
20
+ # """Chuyển đổi giọng nói thành văn bản sử dụng mô hình Whisper."""
21
+ # if not audio:
22
+ # return "❌ Lỗi: Không có dữ liệu âm thanh", "❌ Vui lòng cung cấp file âm thanh", None, "unknown"
23
+
24
+ # try:
25
+ # # Xử lý audio input từ Gradio
26
+ # if isinstance(audio, tuple):
27
+ # sr, y = audio
28
+ # else:
29
+ # return "❌ Lỗi: Định dạng âm thanh không hợp lệ", "❌ Định dạng âm thanh không được hỗ trợ", None, "unknown"
30
+
31
+ # # Kiểm tra và xử lý dữ liệu audio
32
+ # if y.size == 0:
33
+ # return "❌ Lỗi: Dữ liệu âm thanh trống", "❌ File âm thanh không có dữ liệu", None, "unknown"
34
+
35
+ # # Chuẩn hóa dữ liệu audio
36
+ # if y.ndim > 1:
37
+ # y = np.mean(y, axis=1) # Chuyển đổi sang mono
38
+ # y = y.astype(np.float32)
39
+
40
+ # # Normalize âm thanh
41
+ # if np.max(np.abs(y)) > 0:
42
+ # y /= np.max(np.abs(y))
43
+ # else:
44
+ # return "❌ Lỗi: Âm thanh quá yếu", "❌ Không thể phát hiện âm thanh", None, "unknown"
45
+
46
+ # # Tạo buffer với định dạng WAV được hỗ trợ
47
+ # buffer = io.BytesIO()
48
+ # sf.write(buffer, y, sr, format='WAV', subtype='PCM_16')
49
+ # buffer.seek(0)
50
+
51
+ # # Gọi Groq API với định dạng file đúng
52
+ # try:
53
+ # transcription = self.groq_client.audio.transcriptions.create(
54
+ # model=settings.WHISPER_MODEL,
55
+ # file=("audio.wav", buffer.read(), "audio/wav"), # Đảm bảo đúng định dạng
56
+ # response_format="text"
57
+ # )
58
+ # transcription_text = transcription.text
59
+ # except Exception as e:
60
+ # error_msg = f"❌ Lỗi API chuyển đổi giọng nói: {str(e)}"
61
+ # return error_msg, "❌ Không thể chuyển đổi giọng nói thành văn bản", None, "unknown"
62
+
63
+ # # Kiểm tra transcription có hợp lệ không
64
+ # if not transcription_text or len(transcription_text.strip()) == 0:
65
+ # return "❌ Không thể nhận dạng giọng nói", "❌ Vui lòng thử lại với âm thanh rõ hơn", None, "unknown"
66
+
67
+ # # Phát hiện ngôn ngữ và tạo response
68
+ # language = self.multilingual_manager.detect_language(transcription_text)
69
+ # response = self._generate_response_with_rag(transcription_text, language)
70
+
71
+ # # Tạo TTS nếu response hợp lệ
72
+ # tts_audio = None
73
+ # if response and not response.startswith("❌") and not response.startswith("Error"):
74
+ # try:
75
+ # tts_bytes = self.tts_service.text_to_speech(response, language)
76
+ # if tts_bytes:
77
+ # tts_audio_path = self.tts_service.save_tts_audio(tts_bytes)
78
+ # tts_audio = tts_audio_path
79
+ # except Exception as e:
80
+ # print(f"⚠️ Lỗi TTS: {e}")
81
+ # # Vẫn trả về text response nếu TTS fail
82
+
83
+ # return transcription_text, response, tts_audio, language
84
+
85
+ # except Exception as e:
86
+ # error_msg = f"❌ Lỗi hệ thống xử lý âm thanh: {str(e)}"
87
+ # return error_msg, "❌ Có lỗi xảy ra trong quá trình xử lý", None, "unknown"
88
+
89
+ # def _generate_response_with_rag(self, query: str, language: str) -> str:
90
+ # """Tạo phản hồi sử dụng hệ thống RAG dựa trên truy vấn và ngôn ngữ."""
91
+ # if not query or query.strip() == "" or query.startswith("❌"):
92
+ # return "❌ Truy vấn không hợp lệ để tạo phản hồi."
93
+
94
+ # try:
95
+ # # Tìm kiếm trong RAG system
96
+ # rag_results = self.rag_system.semantic_search(query, top_k=3)
97
+ # context_text = ""
98
+
99
+ # if rag_results:
100
+ # for result in rag_results:
101
+ # context_text += f"- {result.text}\n"
102
+
103
+ # # Chọn model LLM phù hợp với ngôn ngữ
104
+ # llm_model = self.multilingual_manager.get_llm_model(language)
105
+
106
+ # # Tạo system prompt phù hợp với ngôn ngữ
107
+ # if language == "vi":
108
+ # system_prompt = """Bạn là trợ lý AI thông minh chuyên về tiếng Việt. Hãy trả lời câu hỏi một cách tự nhiên và hữu ích.
109
+
110
+ # Thông tin tham khảo:
111
+ # {context}
112
+
113
+ # Nếu có thông tin tham khảo, hãy sử dụng nó. Nếu không, dựa vào kiến thức chung của bạn."""
114
+ # else:
115
+ # system_prompt = """You are a smart AI assistant. Please answer questions naturally and helpfully.
116
+
117
+ # Reference information:
118
+ # {context}
119
+
120
+ # If reference information is available, use it. Otherwise, rely on your general knowledge."""
121
+
122
+ # messages = [
123
+ # {
124
+ # "role": "system",
125
+ # "content": system_prompt.format(context=context_text) if context_text else system_prompt.format(context="Không có thông tin tham khảo cụ thể.")
126
+ # },
127
+ # {
128
+ # "role": "user",
129
+ # "content": query
130
+ # }
131
+ # ]
132
+
133
+ # # Gọi Groq API
134
+ # completion = self.groq_client.chat.completions.create(
135
+ # model=llm_model,
136
+ # messages=messages,
137
+ # max_tokens=512,
138
+ # temperature=0.7,
139
+ # )
140
+
141
+ # return completion.choices[0].message.content.strip()
142
+
143
+ # except Exception as e:
144
+ # return f"❌ Lỗi tạo phản hồi: {str(e)}"
145
  import numpy as np
146
  import soundfile as sf
147
  import io
 
148
  from groq import Groq
149
  from config.settings import settings
150
  from core.rag_system import EnhancedRAGSystem
 
152
  from core.multilingual_manager import MultilingualManager
153
 
154
  class AudioService:
 
155
  def __init__(self, groq_client: Groq, rag_system: EnhancedRAGSystem, tts_service: EnhancedTTSService):
156
  self.groq_client = groq_client
157
  self.rag_system = rag_system
 
190
  sf.write(buffer, y, sr, format='WAV', subtype='PCM_16')
191
  buffer.seek(0)
192
 
193
+ # Gọi Groq API với xử lỗi tốt hơn
194
  try:
195
+ print(f"🔄 Đang gửi yêu cầu chuyển đổi giọng nói đến Groq API...")
196
+
197
+ # SỬA LỖI Ở ĐÂY: Sử dụng đúng parameter names
198
  transcription = self.groq_client.audio.transcriptions.create(
199
+ file=("audio.wav", buffer.read(), "audio/wav"),
200
  model=settings.WHISPER_MODEL,
201
+ language="vi", # Thêm language parameter
202
  response_format="text"
203
  )
204
+
205
+ # SỬA LỖI Ở ĐÂY: Kiểm tra response structure
206
+ if hasattr(transcription, 'text'):
207
+ transcription_text = transcription.text
208
+ elif isinstance(transcription, str):
209
+ transcription_text = transcription
210
+ else:
211
+ print(f"⚠️ Response structure không mong đợi: {type(transcription)}")
212
+ transcription_text = str(transcription)
213
+
214
  except Exception as e:
215
  error_msg = f"❌ Lỗi API chuyển đổi giọng nói: {str(e)}"
216
+ print(f"❌ Chi tiết lỗi: {e}")
217
  return error_msg, "❌ Không thể chuyển đổi giọng nói thành văn bản", None, "unknown"
218
 
219
  # Kiểm tra transcription có hợp lệ không
220
  if not transcription_text or len(transcription_text.strip()) == 0:
221
  return "❌ Không thể nhận dạng giọng nói", "❌ Vui lòng thử lại với âm thanh rõ hơn", None, "unknown"
222
 
223
+ print(f"✅ Đã chuyển đổi giọng nói: {transcription_text}")
224
+
225
  # Phát hiện ngôn ngữ và tạo response
226
  language = self.multilingual_manager.detect_language(transcription_text)
227
  response = self._generate_response_with_rag(transcription_text, language)
 
230
  tts_audio = None
231
  if response and not response.startswith("❌") and not response.startswith("Error"):
232
  try:
233
+ print(f"🔊 Đang tạo TTS cho response {len(response)} ký tự...")
234
  tts_bytes = self.tts_service.text_to_speech(response, language)
235
  if tts_bytes:
236
  tts_audio_path = self.tts_service.save_tts_audio(tts_bytes)
237
  tts_audio = tts_audio_path
238
+ print(f"✅ Đã tạo TTS thành công")
239
  except Exception as e:
240
  print(f"⚠️ Lỗi TTS: {e}")
241
  # Vẫn trả về text response nếu TTS fail
 
244
 
245
  except Exception as e:
246
  error_msg = f"❌ Lỗi hệ thống xử lý âm thanh: {str(e)}"
247
+ print(f"❌ Lỗi tổng hợp: {traceback.format_exc()}")
248
  return error_msg, "❌ Có lỗi xảy ra trong quá trình xử lý", None, "unknown"
249
 
250
  def _generate_response_with_rag(self, query: str, language: str) -> str:
 
291
  }
292
  ]
293
 
294
+ # Gọi Groq API với xử lý lỗi
295
+ try:
296
+ completion = self.groq_client.chat.completions.create(
297
+ model=llm_model,
298
+ messages=messages,
299
+ max_tokens=512,
300
+ temperature=0.7,
301
+ )
302
+
303
+ # SỬA LỖI: Kiểm tra response structure
304
+ if hasattr(completion.choices[0].message, 'content'):
305
+ return completion.choices[0].message.content.strip()
306
+ else:
307
+ return "❌ Không thể tạo phản hồi từ AI"
308
+
309
+ except Exception as e:
310
+ return f"❌ Lỗi khi gọi Groq API: {str(e)}"
311
 
312
  except Exception as e:
313
  return f"❌ Lỗi tạo phản hồi: {str(e)}"