File: content_extraction_utils.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (176 lines) | stat: -rw-r--r-- 7,754 bytes parent folder | download | duplicates (7)
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 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/ash/components/local_search_service/content_extraction_utils.h"

#include <memory>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>

#include "base/check.h"
#include "base/containers/fixed_flat_set.h"
#include "base/i18n/case_conversion.h"
#include "base/i18n/transliterator.h"
#include "base/i18n/unicodestring.h"
#include "base/memory/ptr_util.h"
#include "base/no_destructor.h"
#include "base/strings/utf_string_conversions.h"
#include "chromeos/ash/components/string_matching/tokenized_string.h"

namespace ash::local_search_service {

namespace {

using string_matching::TokenizedString;

std::unique_ptr<base::i18n::Transliterator> CreateDiacriticRemover() {
  // Adds a rule to remove diacritic from text. Adds a few characters that are
  // not handled by ICU (ł > l; ø > o; đ > d).
  return base::i18n::CreateTransliteratorFromRules(
      "RemoveDiacritic",
      "::NFD; ::[:Nonspacing Mark:] Remove;::NFC; ł > l; ø > o; đ > d;");
}

std::unique_ptr<base::i18n::Transliterator> CreateHyphenRemover() {
  // Hyphen characters list is taken from here: http://jkorpela.fi/dashes.html
  // U+002D(-), U+007E(~), U+058A(֊), U+05BE(־), U+1806(᠆), U+2010(‐),
  // U+2011(‑), U+2012(‒), U+2013(–), U+2014(—), U+2015(―), U+2053(⁓),
  // U+207B(⁻), U+208B(₋), U+2212(−), U+2E3A(⸺ ), U+2E3B(⸻  ), U+301C(〜),
  // U+3030(〰), U+30A0(゠), U+FE58(﹘), U+FE63(﹣), U+FF0D(-).
  return base::i18n::CreateTransliteratorFromRules(
      "RemoveHyphen", "::[-~֊־᠆‐‑‒–—―⁓⁻₋−⸺⸻〜〰゠﹘﹣-] Remove;");
}

}  // namespace

std::vector<Token> ConsolidateToken(const std::vector<Token>& tokens) {
  std::unordered_map<std::u16string, std::vector<WeightedPosition>> dictionary;
  for (const auto& token : tokens) {
    dictionary[token.content].insert(dictionary[token.content].end(),
                                     token.positions.begin(),
                                     token.positions.end());
  }

  std::vector<Token> results;
  for (const auto& item : dictionary) {
    results.push_back(Token(item.first, item.second));
  }
  return results;
}

std::vector<Token> ExtractContent(const std::string& content_id,
                                  const std::u16string& text,
                                  double weight,
                                  const std::string& locale) {
  // Use two different string tokenizing algorithms for Latin and non Latin
  // locale.
  TokenizedString::Mode mode;
  if (IsNonLatinLocale(locale)) {
    mode = TokenizedString::Mode::kCamelCase;
  } else {
    mode = TokenizedString::Mode::kWords;
  }

  const TokenizedString tokenized_string(text, mode);
  DCHECK(tokenized_string.tokens().size() ==
         tokenized_string.mappings().size());

  const size_t num_tokens = tokenized_string.tokens().size();
  std::vector<Token> tokens;

  for (size_t i = 0; i < num_tokens; i++) {
    const std::u16string word = Normalizer(tokenized_string.tokens()[i]);
    if (IsStopword(word, locale))
      continue;
    tokens.push_back(Token(
        word,
        {WeightedPosition(
            weight, Position(content_id, tokenized_string.mappings()[i].start(),
                             tokenized_string.mappings()[i].end() -
                                 tokenized_string.mappings()[i].start()))}));
  }

  return tokens;
}

bool IsNonLatinLocale(const std::string& locale) {
  static constexpr auto kNonLatinLocales =
      base::MakeFixedFlatSet<std::string_view>(
          {"am", "ar", "be", "bg", "bn", "el", "fa", "gu", "hi", "hy", "iw",
           "ja", "ka", "kk", "km", "kn", "ko", "ky", "lo", "mk", "ml", "mn",
           "mr", "my", "pa", "ru", "sr", "ta", "te", "th", "uk", "zh"});
  return kNonLatinLocales.contains(locale.substr(0, 2));
}

bool IsStopword(const std::u16string& word, const std::string& locale) {
  // TODO(thanhdng): Currently we support stopword list for English only. In the
  // future, when we need to support other languages, creates resource files to
  // store the stopwords.
  if (locale.substr(0, 2) != "en")
    return false;

  // A set of stopwords in English. This set is taken from NLTK library.
  static constexpr auto kEnglishStopWords =
      base::MakeFixedFlatSet<std::string_view>(
          {"i",         "me",         "my",        "myself",  "we",
           "our",       "ours",       "ourselves", "you",     "you're",
           "you've",    "you'll",     "you'd",     "your",    "yours",
           "yourself",  "yourselves", "he",        "him",     "his",
           "himself",   "she",        "she's",     "her",     "hers",
           "herself",   "it",         "it's",      "its",     "itself",
           "they",      "them",       "their",     "theirs",  "themselves",
           "what",      "which",      "who",       "whom",    "this",
           "that",      "that'll",    "these",     "those",   "am",
           "is",        "are",        "was",       "were",    "be",
           "been",      "being",      "have",      "has",     "had",
           "having",    "do",         "does",      "did",     "doing",
           "a",         "an",         "the",       "and",     "but",
           "if",        "or",         "because",   "as",      "until",
           "while",     "of",         "at",        "by",      "for",
           "with",      "about",      "against",   "between", "into",
           "through",   "during",     "before",    "after",   "above",
           "below",     "to",         "from",      "up",      "down",
           "in",        "out",        "on",        "off",     "over",
           "under",     "again",      "further",   "then",    "once",
           "here",      "there",      "when",      "where",   "why",
           "how",       "all",        "any",       "both",    "each",
           "few",       "more",       "most",      "other",   "some",
           "such",      "no",         "nor",       "not",     "only",
           "own",       "same",       "so",        "than",    "too",
           "very",      "s",          "t",         "can",     "will",
           "just",      "don",        "don't",     "should",  "should've",
           "now",       "d",          "ll",        "m",       "o",
           "re",        "ve",         "y",         "ain",     "aren",
           "aren't",    "couldn",     "couldn't",  "didn",    "didn't",
           "doesn",     "doesn't",    "hadn",      "hadn't",  "hasn",
           "hasn't",    "haven",      "haven't",   "isn",     "isn't",
           "ma",        "mightn",     "mightn't",  "mustn",   "mustn't",
           "needn",     "needn't",    "shan",      "shan't",  "shouldn",
           "shouldn't", "wasn",       "wasn't",    "weren",   "weren't",
           "won",       "won't",      "wouldn",    "wouldn't"});
  return kEnglishStopWords.contains(base::UTF16ToUTF8(word));
}

std::u16string Normalizer(const std::u16string& word, bool remove_hyphen) {
  // Case folding.
  std::u16string case_folded = base::i18n::FoldCase(word);

  // Removes diacritic.
  static base::NoDestructor<std::unique_ptr<base::i18n::Transliterator>>
      diacritic_remover(CreateDiacriticRemover());
  std::u16string diacritic_removed =
      (*diacritic_remover)->Transliterate(case_folded);

  // Removes hyphen.
  if (remove_hyphen) {
    static base::NoDestructor<std::unique_ptr<base::i18n::Transliterator>>
        hyphen_remover(CreateHyphenRemover());
    return (*hyphen_remover)->Transliterate(diacritic_removed);
  }
  return diacritic_removed;
}

}  // namespace ash::local_search_service