S
S
Skyceer2020-10-15 12:14:06
Python
Skyceer, 2020-10-15 12:14:06

How to add a file to a yandex cloud bucket?

I use api yandex speech for speech recognition. The file is taken from the Yandex cloud.
Can I send a file directly? if not, how can I send a file to the cloud through requests?

# -*- coding: utf-8 -*-
# Подключаем нужные библиотеки
import requests
import time
import json
# Вставьте свой API-ключ 
key = 'AQVNsdKJKgeu[IUyRRERhjkOUiiu9Jo6'
# Вставьте свой путь к файлу в бакете. Всё, что в ссылке стоит после знака вопроса, можно стереть — сервер всё равно это проигнорирует
filelink = 'https://storage.yandexcloud.net/bucketname/speech.ogg'
# Показываем «Облаку», что мы будем распознавать именно длинное аудио
POST = "https://transcribe.api.cloud.yandex.net/speech/stt/v2/longRunningRecognize"
# Формируем сам текст запроса
body ={
    "config": {
        "specification": {
            "languageCode": "ru-RU"
        }
    },
    "audio": {
        "uri": filelink
    }
}
# Формируем заголовок запроса, в котором ссылаемся на API-ключ
header = {'Authorization': 'Api-Key {}'.format(key)}
# Отправляем запрос на распознавание
req = requests.post(POST, headers=header, json=body)
# Получаем технический ответ от сервера и выводим его
data = req.json()
print(data)
# Получаем идентификатор запроса
id = data['id']
# Запрашиваем на сервере статус операции, пока распознавание не будет завершено
while True:
    # Ждём одну секунду
    time.sleep(1)
    # Пытаемся получить ответ по нашему идентификатору запроса
    GET = "https://operation.api.cloud.yandex.net/operations/{id}"
    req = requests.get(GET.format(id=id), headers=header)
    req = req.json()
    # Если готово — выходим из цикла
    if req['done']: break
    # Если не вышли из цикла — выводим сообщение
    print("Ещё не готово")
# Выводим готовый текст 
print("Текст:")
for chunk in req['response']['chunks']:
    print(chunk['alternatives'][0]['text'])

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
PavelMos, 2020-10-15
@Skyceer

Yes, you can if the file is short. Long ones need to be placed in the cloud. Instructions are in Yandex.

import urllib.request
import json
import requests
import time
import pprint


FOLDER_ID = "......." # Идентификатор каталога, даётся при регистрации на яндекс-платформе
IAM_TOKEN = "..........." # IAM-токен, даётся при регистрации на яндекс-платформе

path1="C:\\work\\"

list1=('4.ogg', '9.ogg')

def short_audio (list1, path1): #берёт ogg-файлы по списку list1, файлы лежат в директории path1
    for a in list1:

        with open(path1+a, "rb") as f:
            data = f.read()

        params = "&".join([
            "topic=general",
            "folderId=%s" % FOLDER_ID,
            "lang=ru-RU"
        ])

        print ("params=", params, "data",data)
        url = urllib.request.Request("https://stt.api.cloud.yandex.net/speech/v1/stt:recognize?%s" % params, data=data) #пересылает содержимое ogg
        url.add_header("Authorization", "Bearer %s" % IAM_TOKEN)
        print (url)

        responseData = urllib.request.urlopen(url).read().decode('UTF-8')
        decodedData = json.loads(responseData)

        if decodedData.get("error_code") is None:
            print(decodedData.get("result"))
    return

short_audio(list1, path1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question