summaryrefslogtreecommitdiffstats
path: root/chrome/browser/speech/speech_recognition_request.cc
blob: e17f69b1f09c2275cb31f54d1e97647c00602773 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/speech/speech_recognition_request.h"

#include "app/l10n_util.h"
#include "base/json/json_reader.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/common/net/url_request_context_getter.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_status.h"

namespace {

const char* const kDefaultSpeechRecognitionUrl =
    "http://www.google.com/speech-api/v1/recognize?client=chromium&";
const char* const kHypothesesString = "hypotheses";
const char* const kUtteranceString = "utterance";
const char* const kConfidenceString = "confidence";

bool ParseServerResponse(const std::string& response_body,
                         speech_input::SpeechInputResultArray* result) {
  if (response_body.empty()) {
    LOG(WARNING) << "ParseServerResponse: Response was empty.";
    return false;
  }
  DVLOG(1) << "ParseServerResponse: Parsing response " << response_body;

  // Parse the response, ignoring comments.
  std::string error_msg;
  scoped_ptr<Value> response_value(base::JSONReader::ReadAndReturnError(
      response_body, false, NULL, &error_msg));
  if (response_value == NULL) {
    LOG(WARNING) << "ParseServerResponse: JSONReader failed : " << error_msg;
    return false;
  }

  if (!response_value->IsType(Value::TYPE_DICTIONARY)) {
    VLOG(1) << "ParseServerResponse: Unexpected response type "
            << response_value->GetType();
    return false;
  }
  const DictionaryValue* response_object =
      static_cast<DictionaryValue*>(response_value.get());

  // Get the hypotheses
  Value* hypotheses_value = NULL;
  if (!response_object->Get(kHypothesesString, &hypotheses_value)) {
    VLOG(1) << "ParseServerResponse: Missing hypotheses attribute.";
    return false;
  }
  DCHECK(hypotheses_value);
  if (!hypotheses_value->IsType(Value::TYPE_LIST)) {
    VLOG(1) << "ParseServerResponse: Unexpected hypotheses type "
            << hypotheses_value->GetType();
    return false;
  }
  const ListValue* hypotheses_list = static_cast<ListValue*>(hypotheses_value);
  if (hypotheses_list->GetSize() == 0) {
    VLOG(1) << "ParseServerResponse: hypotheses list is empty.";
    return false;
  }

  size_t index = 0;
  for (; index < hypotheses_list->GetSize(); ++index) {
    Value* hypothesis = NULL;
    if (!hypotheses_list->Get(index, &hypothesis)) {
      LOG(WARNING) << "ParseServerResponse: Unable to read hypothesis value.";
      break;
    }
    DCHECK(hypothesis);
    if (!hypothesis->IsType(Value::TYPE_DICTIONARY)) {
      LOG(WARNING) << "ParseServerResponse: Unexpected value type "
                   << hypothesis->GetType();
      break;
    }

    const DictionaryValue* hypothesis_value =
        static_cast<DictionaryValue*>(hypothesis);
    string16 utterance;
    if (!hypothesis_value->GetString(kUtteranceString, &utterance)) {
      LOG(WARNING) << "ParseServerResponse: Missing utterance value.";
      break;
    }

    // It is not an error if the 'confidence' field is missing.
    double confidence = 0.0;
    hypothesis_value->GetReal(kConfidenceString, &confidence);

    result->push_back(speech_input::SpeechInputResultItem(utterance,
                                                          confidence));
  }

  if (index < hypotheses_list->GetSize()) {
    result->clear();
    return false;
  }

  return true;
}

}  // namespace

namespace speech_input {

int SpeechRecognitionRequest::url_fetcher_id_for_tests = 0;

SpeechRecognitionRequest::SpeechRecognitionRequest(
    URLRequestContextGetter* context, Delegate* delegate)
    : url_context_(context),
      delegate_(delegate) {
  DCHECK(delegate);
}

SpeechRecognitionRequest::~SpeechRecognitionRequest() {}

bool SpeechRecognitionRequest::Send(const std::string& language,
                                    const std::string& grammar,
                                    const std::string& content_type,
                                    const std::string& audio_data) {
  DCHECK(!url_fetcher_.get());

  std::vector<std::string> parts;
  if (!language.empty()) {
    parts.push_back("lang=" + EscapeQueryParamValue(language, true));
  } else {
    std::string app_locale = l10n_util::GetApplicationLocale("");
    parts.push_back("lang=" + EscapeQueryParamValue(app_locale, true));
  }

  if (!grammar.empty())
    parts.push_back("grammar=" + EscapeQueryParamValue(grammar, true));
  GURL url(std::string(kDefaultSpeechRecognitionUrl) + JoinString(parts, '&'));

  url_fetcher_.reset(URLFetcher::Create(url_fetcher_id_for_tests,
                                        url,
                                        URLFetcher::POST,
                                        this));
  url_fetcher_->set_upload_data(content_type, audio_data);
  url_fetcher_->set_request_context(url_context_);

  // The speech recognition API does not require user identification as part
  // of requests, so we don't send cookies or auth data for these requests to
  // prevent any accidental connection between users who are logged into the
  // domain for other services (e.g. bookmark sync) with the speech requests.
  url_fetcher_->set_load_flags(
      net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES |
      net::LOAD_DO_NOT_SEND_AUTH_DATA);
  url_fetcher_->Start();
  return true;
}

void SpeechRecognitionRequest::OnURLFetchComplete(
    const URLFetcher* source,
    const GURL& url,
    const URLRequestStatus& status,
    int response_code,
    const ResponseCookies& cookies,
    const std::string& data) {
  DCHECK_EQ(url_fetcher_.get(), source);

  bool error = !status.is_success() || response_code != 200;
  SpeechInputResultArray result;
  if (!error)
    error = !ParseServerResponse(data, &result);
  url_fetcher_.reset();

  DVLOG(1) << "SpeechRecognitionRequest: Invoking delegate with result.";
  delegate_->SetRecognitionResult(error, result);
}

}  // namespace speech_input