Найти - Пользователи
Полная версия: распознаем речь с помощью google
Начало » Python для новичков » распознаем речь с помощью google
1
ks
http://mikepultz.com/2011/03/accessing-google-speech-api-chrome-11/
и часть статьи - http://habrahabr.ru/blogs/hardware/129936/

во второй есть часть статьи на перле
sub toText
{
my $num = shift;

print "+OK - Trying recognize text\n";

my $curl = WWW::Curl::Easy->new;

$curl->setopt(CURLOPT_HEADER,1);
$curl->setopt(CURLOPT_POST,1);
#$curl->setopt(CURLOPT_VERBOSE, 1);

my @myheaders=();
$myheaders[0] = "Content-Type: audio/x-flac; rate=16000";

$curl->setopt(CURLOPT_HTTPHEADER, \@myheaders);
$curl->setopt(CURLOPT_URL, 'https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=ru-RU');

my $curlf = WWW::Curl::Form->new;
$curlf->formaddfile("data/input-$num.flac", 'myfile', "audio/x-flac");
$curl->setopt(CURLOPT_HTTPPOST, $curlf);

my $response_body;
$curl->setopt(CURLOPT_WRITEDATA,\$response_body);

# Starts the actual request
my $retcode = $curl->perform;

# Looking at the results...
if ($retcode == 0) {

$response_body =~ /\n\r\n(.*)/g;
my $json = $1;

my $json_xs = JSON::XS->new();
$json_xs->utf8(1);
my @hypo = $json_xs->decode($json)->{'hypotheses'};

my $dost = $hypo[0][0]{'confidence'};
my $text = $hypo[0][0]{'utterance'};

$dost = 0.0 if !defined $dost;
$text = "" if !defined $text;

print "+OK - Text is: \"$text\", confidence is: $dost\n";

if($dost > 0.5)
{
checkcmd($text);
}
{
print "+ERR - Confidence is lower, then 0.5\n";
#sayText("Комманда не распознана!");
}

} else {
# Error code, type of error, error message
print("+ERR - $retcode ".$curl->strerror($retcode)." ".$curl->errbuf);
}

system("rm data/input-$num.flac");

}
, которую надо перевести на python

я пишу следующим образом
>>> conn = httplib.HTTPSConnection('www.google.com')
>>> d = open('demo.flac', 'rb')
>>> data = d.read()
>>> headers = {"Content-Type": "audio/x-flac; rate=16000", "User-Agent":"Mozilla/5.0 (X11; U; Linux i686; en-US) AppleWe
bKit/533.3 (KHTML, like Gecko) Chrome/5.0.360.0 Safari/533.3"}
>>> conn.request("POST", 'speech-api/v1/recognize?xjerr=1&client=chromium&lang=ru-RU', data, headers)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "D:\Python27\lib\httplib.py", line 955, in request
self._send_request(method, url, body, headers)
File "D:\Python27\lib\httplib.py", line 989, in _send_request
self.endheaders(body)
File "D:\Python27\lib\httplib.py", line 951, in endheaders
self._send_output(message_body)
File "D:\Python27\lib\httplib.py", line 811, in _send_output
self.send(msg)
File "D:\Python27\lib\httplib.py", line 787, in send
self.sock.sendall(data)
File "D:\Python27\lib\ssl.py", line 220, in sendall
v = self.send(data[count:])
File "D:\Python27\lib\ssl.py", line 189, in send
v = self._sslobj.write(data)
socket.error: [Errno 10054]
>>>
а как нужно?
ks
А нужно-то было в request(“POST”, ‘Здесь поставить слеш вначале! - и все заработало.. спасибо python.conference(gigimon’у)
ks
Но и это ещё не все - проблема не кончилась. Теперь отправленный файл он распознает как, {u'status': 0, u'hypotheses': , u'id': u'9fb654465c0413c497c2d3b3df7089ff-1'} , тоесть говорит на мое “I want to eat” в файле, что я ему сказал “mmm mmm mmm” - соответственно сабж немного меняется - как сделать так чтоб в POST'е ему доходил именно тот файл, который я шлю, а не МММ МММ МММ?
pupkin2
вебсервисы не оперируют бинарными данными. есть подозрение что отправлять файл нужно энкодированным в base64.
sanodin
Если можно продолжить тему…
# -*- coding: utf-8 -*-
import urllib2
FileNameTmp    = ('tmp.flac')
url = "https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=ru-RU"
flac=open(FileNameTmp,"rb").read()
header = {'Content-Type' : 'audio/x-flac; rate=16000'}
req = urllib2.Request(url, flac, header)
data = urllib2.urlopen(req)
print data.read()
Должен прийти ответ в таком виде
{"status":0,"id":"7674547113739066bc749e93c652f48d-1","hypotheses":[{"utterance":"привет","confidence":0.9145509}]}
но приходит в таком
{"status":0,"id":"909da8194eb10f6c892615a15399d990-1","hypotheses":[{"utterance":"мммм мммм жж","confidence":0.45388022}]}
кто-то наверняка делал что то подобное…подскажите


http://ammo1.livejournal.com/243026.html
sanodin
Сейчас нормально,но распознавание слабое,может запись файла играет роль?
# -*- coding: utf-8 -*-
import urllib2
FileNameTmp    = ('my1.flac')
url = "https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=ru-RU"
flac=open(FileNameTmp,"rb").read()
header = {'Content-Type' : 'audio/x-flac; rate=16000'}
req = urllib2.Request(url, flac, header)
data = urllib2.urlopen(req)
t=data.read()
print t.decode('utf-8')
doza_and
sanodin
запись файла играет роль
В каком смысле? Я гонял ее с разными дикторами и разными микрофонами. Надо следит за уровнем записи, говорить погромче микрофон поближе к источнику звука. От самого микрофона похоже качество распознавания мало зависит.
sanodin
Это да,проверил…
Застрял на преобразовании wav to flac, библиотека pyflac есть но не получилось установить и документации не нашел
здесь http://pastebin.com/K8B3dADM кодирование делают но я не разобрался
sanodin
ujson пробовал

приходит ответ в таком виде
{"status":0,"id":"f4b11eb5953d1293a5a8f75b38375b7a-1","hypotheses":[{"utterance":"купить велосипед","confidence":0.8852786}]}

sanodin
Спасибо cryptspirit

# -*- coding: utf-8 -*-
import urllib2
import json
FileNameTmp    = ('message.flac')
url = "https://www.google.com/speech-api/v1/recognize?xjerr=1&client=chromium&lang=ru-RU"
flac=open(FileNameTmp,"rb").read()
header = {'Content-Type' : 'audio/x-flac; rate=16000'}
req = urllib2.Request(url, flac, header)
data = urllib2.urlopen(req)
t=data.read()
#print t.decode('utf-8')
txt=t.decode('utf-8')
for i in json.loads(txt)['hypotheses']:
     k = i.keys()
     print i['utterance']
     #for j in k:
         #print  i[j]
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB