datbkpro commited on
Commit
1baee4c
·
verified ·
1 Parent(s): a42e45a

Update services/audio_service.py

Browse files
Files changed (1) hide show
  1. services/audio_service.py +92 -50
services/audio_service.py CHANGED
@@ -11,83 +11,125 @@ class AudioService:
11
 
12
  def __init__(self, groq_client: Groq, rag_system: EnhancedRAGSystem, tts_service: EnhancedTTSService):
13
  self.groq_client = groq_client
14
- self.rag_system = rag_system # Sử dụng parameter thay vì tạo mới
15
- self.tts_service = tts_service # Sử dụng parameter thay vì tạo mới
16
  self.multilingual_manager = MultilingualManager()
17
 
18
  def transcribe_audio(self, audio: tuple) -> tuple:
19
  """Chuyển đổi giọng nói thành văn bản sử dụng mô hình Whisper."""
20
  if not audio:
21
- return "Error: Audio input is empty.", "Error: Không dữ liệu âm thanh", None, "unknown"
22
 
23
- # Xử lý audio input từ Gradio
24
- if isinstance(audio, tuple):
25
- sr, y = audio
26
- else:
27
- return "Error: Invalid audio format", "Error: Định dạng âm thanh không hợp lệ", None, "unknown"
 
28
 
29
- if y.ndim > 1:
30
- y = np.mean(y, axis=1) # Chuyển đổi sang mono nếu cần
31
- y = y.astype(np.float32)
32
- y /= np.max(np.abs(y)) # Chuẩn hóa âm thanh
33
 
34
- buffer = io.BytesIO()
35
- sf.write(buffer, y, sr, format='WAV')
36
- buffer.seek(0)
 
 
 
 
 
 
 
37
 
38
- try:
39
- completion = self.groq_client.audio.transcriptions.create(
40
- model=settings.WHISPER_MODEL,
41
- file=buffer,
42
- response_format="text"
43
- )
44
- transcription = completion.text
45
- except Exception as e:
46
- transcription = f"Error trong quá trình chuyển đổi giọng nói thành văn bản: {e}"
47
 
48
- language = self.multilingual_manager.detect_language(transcription)
49
- response = self._generate_response_with_rag(transcription, language)
 
 
 
 
 
 
 
 
 
50
 
51
- tts_audio = None
52
- if response and not response.startswith("Error"):
53
- tts_bytes = self.tts_service.text_to_speech(response, language)
54
- if tts_bytes:
55
- tts_audio_path = self.tts_service.save_tts_audio(tts_bytes)
56
- tts_audio = tts_audio_path
57
-
58
- return transcription, response, tts_audio, language
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  def _generate_response_with_rag(self, query: str, language: str) -> str:
61
  """Tạo phản hồi sử dụng hệ thống RAG dựa trên truy vấn và ngôn ngữ."""
62
- if not query or query.startswith("Error"):
63
- return "Error: Truy vấn không hợp lệ để tạo phản hồi."
 
64
  try:
 
65
  rag_results = self.rag_system.semantic_search(query, top_k=3)
66
  context_text = ""
 
67
  if rag_results:
68
  for result in rag_results:
69
- context_text += result.document + "\n"
70
 
 
71
  llm_model = self.multilingual_manager.get_llm_model(language)
72
 
 
73
  if language == "vi":
74
- system_prompt = """Bạn là trợ lý AI thông minh chuyên về tiếng Việt. Hãy sử dụng thông tin từ cơ sở kiến thức được cung cấp để trả lời câu hỏi một cách chính xác và hữu ích bằng tiếng Việt.
75
- Thông tin tham khảo từ cơ sở kiến thức:
76
- {context}
77
- Nếu thông tin từ cơ sở kiến thức không đủ để trả lời, hãy dựa vào kiến thức chung của bạn. Luôn trả lời bằng tiếng Việt tự nhiên và dễ hiểu."""
 
 
78
  else:
79
- system_prompt = """You are a smart AI assistant. Please use the information from the provided knowledge base to answer questions accurately and helpfully in the same language as the user's question.
80
-
81
- Reference information from knowledge base:
82
- {context}
83
-
84
- If the information from the knowledge base is not sufficient to answer, rely on your general knowledge. Always respond in natural and easy-to-understand language matching the user's language."""
85
 
86
  messages = [
87
- {"role": "system", "content": system_prompt.format(context=context_text)},
88
- {"role": "user", "content": query}
 
 
 
 
 
 
89
  ]
90
 
 
91
  completion = self.groq_client.chat.completions.create(
92
  model=llm_model,
93
  messages=messages,
@@ -98,4 +140,4 @@ class AudioService:
98
  return completion.choices[0].message.content.strip()
99
 
100
  except Exception as e:
101
- return f"Error trong quá trình tạo phản hồi với RAG: {e}"
 
11
 
12
  def __init__(self, groq_client: Groq, rag_system: EnhancedRAGSystem, tts_service: EnhancedTTSService):
13
  self.groq_client = groq_client
14
+ self.rag_system = rag_system
15
+ self.tts_service = tts_service
16
  self.multilingual_manager = MultilingualManager()
17
 
18
  def transcribe_audio(self, audio: tuple) -> tuple:
19
  """Chuyển đổi giọng nói thành văn bản sử dụng mô hình Whisper."""
20
  if not audio:
21
+ return "❌ Lỗi: Không dữ liệu âm thanh", " Vui lòng cung cấp file âm thanh", None, "unknown"
22
 
23
+ try:
24
+ # Xử lý audio input từ Gradio
25
+ if isinstance(audio, tuple):
26
+ sr, y = audio
27
+ else:
28
+ 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"
29
 
30
+ # Kiểm tra và xử lý dữ liệu audio
31
+ if y.size == 0:
32
+ return "❌ Lỗi: Dữ liệu âm thanh trống", "❌ File âm thanh không có dữ liệu", None, "unknown"
 
33
 
34
+ # Chuẩn hóa dữ liệu audio
35
+ if y.ndim > 1:
36
+ y = np.mean(y, axis=1) # Chuyển đổi sang mono
37
+ y = y.astype(np.float32)
38
+
39
+ # Normalize âm thanh
40
+ if np.max(np.abs(y)) > 0:
41
+ y /= np.max(np.abs(y))
42
+ else:
43
+ return "❌ Lỗi: Âm thanh quá yếu", "❌ Không thể phát hiện âm thanh", None, "unknown"
44
 
45
+ # Tạo buffer với định dạng WAV được hỗ trợ
46
+ buffer = io.BytesIO()
47
+ sf.write(buffer, y, sr, format='WAV', subtype='PCM_16')
48
+ buffer.seek(0)
 
 
 
 
 
49
 
50
+ # Gọi Groq API với định dạng file đúng
51
+ try:
52
+ transcription = self.groq_client.audio.transcriptions.create(
53
+ model=settings.WHISPER_MODEL,
54
+ file=("audio.wav", buffer.read(), "audio/wav"), # Đảm bảo đúng định dạng
55
+ response_format="text"
56
+ )
57
+ transcription_text = transcription.text
58
+ except Exception as e:
59
+ error_msg = f"❌ Lỗi API chuyển đổi giọng nói: {str(e)}"
60
+ return error_msg, "❌ Không thể chuyển đổi giọng nói thành văn bản", None, "unknown"
61
 
62
+ # Kiểm tra transcription có hợp lệ không
63
+ if not transcription_text or len(transcription_text.strip()) == 0:
64
+ 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"
65
+
66
+ # Phát hiện ngôn ngữ và tạo response
67
+ language = self.multilingual_manager.detect_language(transcription_text)
68
+ response = self._generate_response_with_rag(transcription_text, language)
69
+
70
+ # Tạo TTS nếu response hợp lệ
71
+ tts_audio = None
72
+ if response and not response.startswith("❌") and not response.startswith("Error"):
73
+ try:
74
+ tts_bytes = self.tts_service.text_to_speech(response, language)
75
+ if tts_bytes:
76
+ tts_audio_path = self.tts_service.save_tts_audio(tts_bytes)
77
+ tts_audio = tts_audio_path
78
+ except Exception as e:
79
+ print(f"⚠️ Lỗi TTS: {e}")
80
+ # Vẫn trả về text response nếu TTS fail
81
+
82
+ return transcription_text, response, tts_audio, language
83
+
84
+ except Exception as e:
85
+ error_msg = f"❌ Lỗi hệ thống xử lý âm thanh: {str(e)}"
86
+ return error_msg, "❌ Có lỗi xảy ra trong quá trình xử lý", None, "unknown"
87
 
88
  def _generate_response_with_rag(self, query: str, language: str) -> str:
89
  """Tạo phản hồi sử dụng hệ thống RAG dựa trên truy vấn và ngôn ngữ."""
90
+ if not query or query.strip() == "" or query.startswith(""):
91
+ return " Truy vấn không hợp lệ để tạo phản hồi."
92
+
93
  try:
94
+ # Tìm kiếm trong RAG system
95
  rag_results = self.rag_system.semantic_search(query, top_k=3)
96
  context_text = ""
97
+
98
  if rag_results:
99
  for result in rag_results:
100
+ context_text += f"- {result.text}\n"
101
 
102
+ # Chọn model LLM phù hợp với ngôn ngữ
103
  llm_model = self.multilingual_manager.get_llm_model(language)
104
 
105
+ # Tạo system prompt phù hợp với ngôn ngữ
106
  if language == "vi":
107
+ 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.
108
+
109
+ Thông tin tham khảo:
110
+ {context}
111
+
112
+ 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."""
113
  else:
114
+ system_prompt = """You are a smart AI assistant. Please answer questions naturally and helpfully.
115
+
116
+ Reference information:
117
+ {context}
118
+
119
+ If reference information is available, use it. Otherwise, rely on your general knowledge."""
120
 
121
  messages = [
122
+ {
123
+ "role": "system",
124
+ "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ể.")
125
+ },
126
+ {
127
+ "role": "user",
128
+ "content": query
129
+ }
130
  ]
131
 
132
+ # Gọi Groq API
133
  completion = self.groq_client.chat.completions.create(
134
  model=llm_model,
135
  messages=messages,
 
140
  return completion.choices[0].message.content.strip()
141
 
142
  except Exception as e:
143
+ return f" Lỗi tạo phản hồi: {str(e)}"