Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(142)

Side by Side Diff: chrome/common/translate/language_detection_util.cc

Issue 25531002: Move language detection to a component (Closed) Base URL: http://git.chromium.org/chromium/src.git@master
Patch Set: Fix compilation Created 7 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/common/translate/language_detection_util.h"
6
7 #include "base/logging.h"
8 #include "base/metrics/field_trial.h"
9 #include "base/strings/string_split.h"
10 #include "base/strings/string_util.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/time/time.h"
13 #include "chrome/common/chrome_constants.h"
14 #include "chrome/common/translate/translate_common_metrics.h"
15 #include "chrome/common/translate/translate_util.h"
16
17 #if !defined(CLD_VERSION) || CLD_VERSION==1
18 #include "third_party/cld/encodings/compact_lang_det/compact_lang_det.h"
19 #include "third_party/cld/encodings/compact_lang_det/win/cld_unicodetext.h"
20 #endif
21
22 #if !defined(CLD_VERSION) || CLD_VERSION==2
23 #include "third_party/cld_2/src/public/compact_lang_det.h"
24 #endif
25
26 namespace {
27
28 // Similar language code list. Some languages are very similar and difficult
29 // for CLD to distinguish.
30 struct SimilarLanguageCode {
31 const char* const code;
32 int group;
33 };
34
35 const SimilarLanguageCode kSimilarLanguageCodes[] = {
36 {"bs", 1},
37 {"hr", 1},
38 {"hi", 2},
39 {"ne", 2},
40 };
41
42 // Checks |kSimilarLanguageCodes| and returns group code.
43 int GetSimilarLanguageGroupCode(const std::string& language) {
44 for (size_t i = 0; i < arraysize(kSimilarLanguageCodes); ++i) {
45 if (language.find(kSimilarLanguageCodes[i].code) != 0)
46 continue;
47 return kSimilarLanguageCodes[i].group;
48 }
49 return 0;
50 }
51
52 // Well-known languages which often have wrong server configuration of
53 // Content-Language: en.
54 // TODO(toyoshim): Remove these static tables and caller functions to
55 // chrome/common/translate, and implement them as std::set<>.
56 const char* kWellKnownCodesOnWrongConfiguration[] = {
57 "es", "pt", "ja", "ru", "de", "zh-CN", "zh-TW", "ar", "id", "fr", "it", "th"
58 };
59
60 // Applies a series of language code modification in proper order.
61 void ApplyLanguageCodeCorrection(std::string* code) {
62 // Correct well-known format errors.
63 LanguageDetectionUtil::CorrectLanguageCodeTypo(code);
64
65 if (!LanguageDetectionUtil::IsValidLanguageCode(*code)) {
66 *code = std::string();
67 return;
68 }
69
70 TranslateUtil::ToTranslateLanguageSynonym(code);
71 }
72
73 int GetCLDMajorVersion() {
74 #if !defined(CLD_VERSION)
75 std::string group_name = base::FieldTrialList::FindFullName("CLD1VsCLD2");
76 if (group_name == "CLD2")
77 return 2;
78 else
79 return 1;
80 #else
81 return CLD_VERSION;
82 #endif
83 }
84
85 // Returns the ISO 639 language code of the specified |text|, or 'unknown' if it
86 // failed.
87 // |is_cld_reliable| will be set as true if CLD says the detection is reliable.
88 std::string DetermineTextLanguage(const base::string16& text,
89 bool* is_cld_reliable) {
90 std::string language = chrome::kUnknownLanguageCode;
91 int text_bytes = 0;
92 bool is_reliable = false;
93
94 // Language or CLD2::Language
95 int cld_language = 0;
96 bool is_valid_language = false;
97
98 switch (GetCLDMajorVersion()) {
99 #if !defined(CLD_VERSION) || CLD_VERSION==1
100 case 1: {
101 int num_languages = 0;
102 cld_language =
103 DetectLanguageOfUnicodeText(NULL, text.c_str(), true, &is_reliable,
104 &num_languages, NULL, &text_bytes);
105 is_valid_language = cld_language != NUM_LANGUAGES &&
106 cld_language != UNKNOWN_LANGUAGE &&
107 cld_language != TG_UNKNOWN_LANGUAGE;
108 break;
109 }
110 #endif
111 #if !defined(CLD_VERSION) || CLD_VERSION==2
112 case 2: {
113 std::string utf8_text(UTF16ToUTF8(text));
114 CLD2::Language language3[3];
115 int percent3[3];
116 cld_language =
117 CLD2::DetectLanguageSummary(utf8_text.c_str(), utf8_text.size(), true,
118 language3, percent3,
119 &text_bytes, &is_reliable);
120 is_valid_language = cld_language != CLD2::NUM_LANGUAGES &&
121 cld_language != CLD2::UNKNOWN_LANGUAGE &&
122 cld_language != CLD2::TG_UNKNOWN_LANGUAGE;
123 break;
124 }
125 #endif
126 default:
127 NOTREACHED();
128 }
129
130 if (is_cld_reliable != NULL)
131 *is_cld_reliable = is_reliable;
132
133 // We don't trust the result if the CLD reports that the detection is not
134 // reliable, or if the actual text used to detect the language was less than
135 // 100 bytes (short texts can often lead to wrong results).
136 // TODO(toyoshim): CLD provides |is_reliable| flag. But, it just says that
137 // the determined language code is correct with 50% confidence. Chrome should
138 // handle the real confidence value to judge.
139 if (is_reliable && text_bytes >= 100 && is_valid_language) {
140 // We should not use LanguageCode_ISO_639_1 because it does not cover all
141 // the languages CLD can detect. As a result, it'll return the invalid
142 // language code for tradtional Chinese among others.
143 // |LanguageCodeWithDialect| will go through ISO 639-1, ISO-639-2 and
144 // 'other' tables to do the 'right' thing. In addition, it'll return zh-CN
145 // for Simplified Chinese.
146 switch (GetCLDMajorVersion()) {
147 #if !defined(CLD_VERSION) || CLD_VERSION==1
148 case 1:
149 language =
150 LanguageCodeWithDialects(static_cast<Language>(cld_language));
151 break;
152 #endif
153 #if !defined(CLD_VERSION) || CLD_VERSION==2
154 case 2:
155 if (cld_language == CLD2::CHINESE) {
156 language = "zh-CN";
157 } else {
158 language =
159 CLD2::LanguageCode(static_cast<CLD2::Language>(cld_language));
160 }
161 break;
162 #endif
163 default:
164 NOTREACHED();
165 }
166 }
167 VLOG(9) << "Detected lang_id: " << language << ", from Text:\n" << text
168 << "\n*************************************\n";
169 return language;
170 }
171
172 // Checks if CLD can complement a sub code when the page language doesn't know
173 // the sub code.
174 bool CanCLDComplementSubCode(
175 const std::string& page_language, const std::string& cld_language) {
176 // Translate server cannot treat general Chinese. If Content-Language and
177 // CLD agree that the language is Chinese and Content-Language doesn't know
178 // which dialect is used, CLD language has priority.
179 // TODO(hajimehoshi): How about the other dialects like zh-MO?
180 return page_language == "zh" && StartsWithASCII(cld_language, "zh-", false);
181 }
182
183 } // namespace
184
185 namespace LanguageDetectionUtil {
186
187 std::string DeterminePageLanguage(const std::string& code,
188 const std::string& html_lang,
189 const base::string16& contents,
190 std::string* cld_language_p,
191 bool* is_cld_reliable_p) {
192 base::TimeTicks begin_time = base::TimeTicks::Now();
193 bool is_cld_reliable;
194 std::string cld_language = DetermineTextLanguage(contents, &is_cld_reliable);
195 TranslateCommonMetrics::ReportLanguageDetectionTime(begin_time,
196 base::TimeTicks::Now());
197
198 if (cld_language_p != NULL)
199 *cld_language_p = cld_language;
200 if (is_cld_reliable_p != NULL)
201 *is_cld_reliable_p = is_cld_reliable;
202 TranslateUtil::ToTranslateLanguageSynonym(&cld_language);
203
204 // Check if html lang attribute is valid.
205 std::string modified_html_lang;
206 if (!html_lang.empty()) {
207 modified_html_lang = html_lang;
208 ApplyLanguageCodeCorrection(&modified_html_lang);
209 TranslateCommonMetrics::ReportHtmlLang(html_lang, modified_html_lang);
210 VLOG(9) << "html lang based language code: " << modified_html_lang;
211 }
212
213 // Check if Content-Language is valid.
214 std::string modified_code;
215 if (!code.empty()) {
216 modified_code = code;
217 ApplyLanguageCodeCorrection(&modified_code);
218 TranslateCommonMetrics::ReportContentLanguage(code, modified_code);
219 }
220
221 // Adopt |modified_html_lang| if it is valid. Otherwise, adopt
222 // |modified_code|.
223 std::string language = modified_html_lang.empty() ? modified_code :
224 modified_html_lang;
225
226 // If |language| is empty, just use CLD result even though it might be
227 // chrome::kUnknownLanguageCode.
228 if (language.empty()) {
229 TranslateCommonMetrics::ReportLanguageVerification(
230 TranslateCommonMetrics::LANGUAGE_VERIFICATION_CLD_ONLY);
231 return cld_language;
232 }
233
234 if (cld_language == chrome::kUnknownLanguageCode) {
235 TranslateCommonMetrics::ReportLanguageVerification(
236 TranslateCommonMetrics::LANGUAGE_VERIFICATION_UNKNOWN);
237 return language;
238 } else if (CanCLDComplementSubCode(language, cld_language)) {
239 TranslateCommonMetrics::ReportLanguageVerification(
240 TranslateCommonMetrics::LANGUAGE_VERIFICATION_CLD_COMPLEMENT_SUB_CODE);
241 return cld_language;
242 } else if (IsSameOrSimilarLanguages(language, cld_language)) {
243 TranslateCommonMetrics::ReportLanguageVerification(
244 TranslateCommonMetrics::LANGUAGE_VERIFICATION_CLD_AGREE);
245 return language;
246 } else if (MaybeServerWrongConfiguration(language, cld_language)) {
247 TranslateCommonMetrics::ReportLanguageVerification(
248 TranslateCommonMetrics::LANGUAGE_VERIFICATION_TRUST_CLD);
249 return cld_language;
250 } else {
251 TranslateCommonMetrics::ReportLanguageVerification(
252 TranslateCommonMetrics::LANGUAGE_VERIFICATION_CLD_DISAGREE);
253 // Content-Language value might be wrong because CLD says that this page
254 // is written in another language with confidence.
255 // In this case, Chrome doesn't rely on any of the language codes, and
256 // gives up suggesting a translation.
257 return std::string(chrome::kUnknownLanguageCode);
258 }
259
260 return language;
261 }
262
263 void CorrectLanguageCodeTypo(std::string* code) {
264 DCHECK(code);
265
266 size_t coma_index = code->find(',');
267 if (coma_index != std::string::npos) {
268 // There are more than 1 language specified, just keep the first one.
269 *code = code->substr(0, coma_index);
270 }
271 TrimWhitespaceASCII(*code, TRIM_ALL, code);
272
273 // An underscore instead of a dash is a frequent mistake.
274 size_t underscore_index = code->find('_');
275 if (underscore_index != std::string::npos)
276 (*code)[underscore_index] = '-';
277
278 // Change everything up to a dash to lower-case and everything after to upper.
279 size_t dash_index = code->find('-');
280 if (dash_index != std::string::npos) {
281 *code = StringToLowerASCII(code->substr(0, dash_index)) +
282 StringToUpperASCII(code->substr(dash_index));
283 } else {
284 *code = StringToLowerASCII(*code);
285 }
286 }
287
288 bool IsValidLanguageCode(const std::string& code) {
289 // Roughly check if the language code follows /[a-zA-Z]{2,3}(-[a-zA-Z]{2})?/.
290 // TODO(hajimehoshi): How about es-419, which is used as an Accept language?
291 std::vector<std::string> chunks;
292 base::SplitString(code, '-', &chunks);
293
294 if (chunks.size() < 1 || 2 < chunks.size())
295 return false;
296
297 const std::string& main_code = chunks[0];
298
299 if (main_code.size() < 1 || 3 < main_code.size())
300 return false;
301
302 for (std::string::const_iterator it = main_code.begin();
303 it != main_code.end(); ++it) {
304 if (!IsAsciiAlpha(*it))
305 return false;
306 }
307
308 if (chunks.size() == 1)
309 return true;
310
311 const std::string& sub_code = chunks[1];
312
313 if (sub_code.size() != 2)
314 return false;
315
316 for (std::string::const_iterator it = sub_code.begin();
317 it != sub_code.end(); ++it) {
318 if (!IsAsciiAlpha(*it))
319 return false;
320 }
321
322 return true;
323 }
324
325 bool IsSameOrSimilarLanguages(const std::string& page_language,
326 const std::string& cld_language) {
327 // Language code part of |page_language| is matched to one of |cld_language|.
328 // Country code is ignored here.
329 if (page_language.size() >= 2 &&
330 cld_language.find(page_language.c_str(), 0, 2) == 0) {
331 // Languages are matched strictly. Reports false to metrics, but returns
332 // true.
333 TranslateCommonMetrics::ReportSimilarLanguageMatch(false);
334 return true;
335 }
336
337 // Check if |page_language| and |cld_language| are in the similar language
338 // list and belong to the same language group.
339 int page_code = GetSimilarLanguageGroupCode(page_language);
340 bool match = page_code != 0 &&
341 page_code == GetSimilarLanguageGroupCode(cld_language);
342
343 TranslateCommonMetrics::ReportSimilarLanguageMatch(match);
344 return match;
345 }
346
347 bool MaybeServerWrongConfiguration(const std::string& page_language,
348 const std::string& cld_language) {
349 // If |page_language| is not "en-*", respect it and just return false here.
350 if (!StartsWithASCII(page_language, "en", false))
351 return false;
352
353 // A server provides a language meta information representing "en-*". But it
354 // might be just a default value due to missing user configuration.
355 // Let's trust |cld_language| if the determined language is not difficult to
356 // distinguish from English, and the language is one of well-known languages
357 // which often provide "en-*" meta information mistakenly.
358 for (size_t i = 0; i < arraysize(kWellKnownCodesOnWrongConfiguration); ++i) {
359 if (cld_language == kWellKnownCodesOnWrongConfiguration[i])
360 return true;
361 }
362 return false;
363 }
364
365 std::string GetCLDVersion() {
366 switch (GetCLDMajorVersion()) {
367 #if !defined(CLD_VERSION) || CLD_VERSION==1
368 case 1:
369 return CompactLangDet::DetectLanguageVersion();
370 #endif
371 #if !defined(CLD_VERSION) || CLD_VERSION==2
372 case 2:
373 return CLD2::DetectLanguageVersion();
374 #endif
375 default:
376 NOTREACHED();
377 }
378 return "";
379 }
380
381 } // namespace LanguageDetectionUtil
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698