from transformers import AutoModelForCausalLM, AutoTokenizer import torchaudio from…
- User
from transformers import AutoModelForCausalLM, AutoTokenizer import torchaudio from transformers import Wav2Vec2ForCTC, Wav2Vec2Tokenizer from gtts import gTTS import os import tempfile import torch import gradio as gr
Device configuration
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
Load conversational language model
language_model_name = "microsoft/DialoGPT-medium" # Changed from BioGPT to DialoGPT tokenizer = AutoTokenizer.from_pretrained(language_model_name) language_model = AutoModelForCausalLM.from_pretrained(language_model_name).to(device)
Load Speech-to-Text (Wav2Vec2) model
stt_model_name = "facebook/wav2vec2-base-960h" stt_tokenizer = Wav2Vec2Tokenizer.from_pretrained(stt_model_name) stt_model = Wav2Vec2ForCTC.from_pretrained(stt_model_name).to(device)
Conversation history for context
chat_history_ids = None
def transcribe_audio(audio_path): waveform, sample_rate = torchaudio.load(audio_path)
# Resample to 16000 if necessary if sample_rate != 16000: resampler = torchaudio.transforms.Resample(orig_freq=sample_rate, new_freq=16000) waveform = resampler(waveform) input_values = stt_tokenizer(waveform.squeeze().numpy(), return_tensors="pt", sampling_rate=16000).input_values.to(device) with torch.no_grad(): logits = stt_model(input_values).logits predicted_ids = torch.argmax(logits, dim=-1) transcription = stt_tokenizer.batch_decode(predicted_ids)[0] return transcription.lower()def get_bot_response(user_input): global chat_history_ids
# Encode the user input and append to chat history new_user_input_ids = tokenizer.encode(user_input + tokenizer.eos_token, return_tensors='pt').to(device) if chat_history_ids is not None: bot_input_ids = torch.cat([chat_history_ids, new_user_input_ids], dim=-1) else: bot_input_ids = new_user_input_ids # Generate response chat_history_ids = language_model.generate( bot_input_ids, max_length=1000, pad_token_id=tokenizer.eos_token_id, no_repeat_ngram_size=3, do_sample=True, top_p=0.95, temperature=0.7 ) # Decode the response response = tokenizer.decode(chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True) return responsedef text_to_speech(text): tts = gTTS(text=text, lang='en') with tempfile.NamedTemporaryFile(delete=True, suffix=".mp3") as fp: tts.save(fp.name) return fp.name
def chatbot_interface(audio): if audio is None: return "Please provide an audio input.", None
try: # Step 1: Transcribe audio to text user_input = transcribe_audio(audio) if not user_input.strip(): return "Sorry, I could not understand the audio.", None except Exception as e: return f"Error in transcription: {str(e)}", None try: # Step 2: Get bot response bot_response = get_bot_response(user_input) if not bot_response.strip(): bot_response = "I'm sorry, I don't have an answer to that. Please consult a professional." except Exception as e: bot_response = f"Error in generating response: {str(e)}" try: # Step 3: Convert bot response to speech audio_file = text_to_speech(bot_response) except Exception as e: return f"Error in generating speech: {str(e)}", None return f"You: {user_input}", (bot_response, audio_file) - Assistant
The error you're seeing arises from using an incorrect keyword argument with
gr.Audio. In the version of Gradio you are using, it appears that thesourceargument is not recognized or has been replaced. In newer Gradio versions, this parameter was used to specify the source of the audio, which could be"microphone"or"upload". However, if it's raising an error, it indicates a mismatch with your current Gradio version.Here's how you can fix this issue:
- User
Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/gradio/queueing.py", line 532, in process_events response = await route_utils.call_process_api( File "/usr/local/lib/python3.10/site-packages/gradio/route_utils.py", line 276, in call_process_api output = await app.get_blocks().process_api( File "/usr/local/lib/python3.10/site-packages/gradio/blocks.py", line 1938, in process_api data = await self.postprocess_data(block_fn, result["prediction"], state) File "/usr/local/lib/python3.10/site-packages/gradio/blocks.py", line 1711, in postprocess_data self.validate_outputs(block_fn, predictions) # type: ignore File "/usr/local/lib/python3.10/site-packages/gradio/blocks.py", line 1685, in validate_outputs raise ValueError( ValueError: An event handler (chatbot_interface) didn't receive enough output values (needed: 3, received: 2). Wanted outputs: [<gradio.components.textbox.Textbox object at 0x7f9da6cc9db0>, <gradio.components.textbox.Textbox object at 0x7f9da6cc9e40>, <gradio.components.audio.Audio object at 0x7f9da6ccb2b0>] Received outputs: ["You: i don't feel well what should i do", ('What do you do?', '/tmp/tmpy5b332k_.mp3')]
- Assistant
The error you're encountering suggests that the function
chatbot_interfaceis expected to return three separate values to align with the specified outputs in Gradio, but it's returning two.