Why does my bot give an error: Expecting value: line 1 column 1 (char 0)

Code:

# Обработчик голосовых сообщений
@bot.message_handler(content_types=['voice'])
def handle_voice(message):
    try:
        # Получаем информацию о файле
        file_info = bot.get_file(message.voice.file_id)
        file_path = file_info.file_path

        # Скачиваем голосовое сообщение
        downloaded_file = bot.download_file(file_path)

        # Сохраняем голосовое сообщение в формате MP3 на диск
        with open("voice.mp3", "wb") as voice_file:
            voice_file.write(downloaded_file)

        # Транскрибируем голосовое сообщение с помощью OpenAI Whisper API
        transcript = transcribe_audio("voice.mp3")

        if transcript is not None:
            bot.send_message(message.chat.id, "Текст из голосового сообщения:\n" + transcript)
        else:
            bot.send_message(message.chat.id, "Не удалось распознать голосовое сообщение.")
    except Exception as e:
        bot.send_message(message.chat.id, f"Произошла ошибка при обработке голосового сообщения: {str(e)}")

def transcribe_audio(audio_file_path):
    try:
        with open(audio_file_path, "rb") as audio_file:
            # Отправляем аудиофайл на транскрибацию с помощью OpenAI Whisper API
            headers = {
                "Authorization": f"Bearer {openai.api_key}",
            }
            files = {"file": audio_file}
            data = {
                "model": "whisper-1",  # Укажите желаемую модель Whisper API
                "response_format": "text",  # Формат вывода текста
                "language": "ru",  # Укажите язык входного аудио, если известен
                "prompt": "Прошу транскрибировать следующее аудио: ",
            }

            response = requests.post("https://api.openai.com/v1/audio/transcriptions", headers=headers, data=data, files=files)
            if response.status_code == 200:
                transcription_data = response.json()
                transcript = transcription_data.get("text")
                return transcript
            else:
                return f"Произошла ошибка при транскрибации голосового сообщения: {response.text}"
    except Exception as e:
        return str(e)

Do you have a question?

Can you format your code correctly? It would help us help you.

Thanks.

1 Like

It’ll do? Yes. I need help, I don’t understand what’s causing the error.

Hi,

You have not told us what the error is. It would be very helpful to know what information you have, output logs, error messages, anything you have that will help others to assist.

1 Like

Whisper: try sending 30 seconds or less of audio.
Ensure that the file format is one that can be understood.

Start with more simple API code that simply sends a small audio file and receives a transcription. See that you audio encoding format is compatible.

A traceback would be more informative, letting you know the line of code or library detecting the problem.

gpt-4 answer:

The error message “Expecting value: line 1 column 1 (char 0)” is typically raised when you are trying to parse an empty document or response. In this case, it seems like the response from the OpenAI Whisper API is empty.

Here are a few things you can do to debug this issue:

  1. Check the status code of the response: You are already doing this in your code. If the status code is not 200, it means there was an error with your request. The error message should give you more information about what went wrong.

  2. Print the response content: Before trying to parse the response content with response.json(), print the response content to see what you are actually receiving. You can do this with print(response.content).

  3. Check your request: Make sure that the audio file you are sending is not empty and that all the required headers and data are correctly set.

  4. Check the OpenAI Whisper API documentation: Make sure that you are using the API correctly. The documentation should tell you what kind of responses to expect and how to handle them.

  5. Handle the exception: You can modify your exception handling code to print the exception message and the response content. This will give you more information about what is causing the error. Here is an example:

except Exception as e:
    print(f"Exception: {str(e)}")
    print(f"Response content: {response.content}")
    return str(e)

By doing these steps, you should be able to identify what is causing the error and how to fix it.