File: passage_embeddings_coordinator.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (238 lines) | stat: -rw-r--r-- 7,791 bytes parent folder | download | duplicates (3)
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/passage_embeddings/passage_embeddings_coordinator.h"

#include <algorithm>
#include <string>
#include <string_view>
#include <vector>

#include "base/functional/bind.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/strings/strcat.h"
#include "chrome/browser/page_content_annotations/page_content_extraction_service.h"
#include "chrome/browser/passage_embeddings/chrome_passage_embeddings_service_controller.h"
#include "components/passage_embeddings/passage_embeddings_features.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/web_contents.h"

namespace passage_embeddings {

namespace {

std::unique_ptr<WebContentsPassageEmbedder> CreateWebContentsPassageEmbedder(
    content::WebContents* web_contents,
    WebContentsPassageEmbedder::Delegate& delegate) {
  if (kUseBackgroundPassageEmbedder.Get()) {
    return std::make_unique<WebContentsBackgroundPassageEmbedder>(web_contents,
                                                                  delegate);
  }
  return std::make_unique<WebContentsImmediatePassageEmbedder>(web_contents,
                                                               delegate);
}

void CollectTextForContentNode(
    const optimization_guide::proto::ContentNode& node,
    std::vector<std::string>& text) {
  if (!node.has_content_attributes()) {
    return;
  }

  const auto& attributes = node.content_attributes();

  switch (attributes.attribute_type()) {
    case optimization_guide::proto::ContentAttributeType::
        CONTENT_ATTRIBUTE_TABLE:
      if (!attributes.table_data().table_name().empty()) {
        text.push_back(attributes.table_data().table_name());
      }
      break;

    case optimization_guide::proto::ContentAttributeType::
        CONTENT_ATTRIBUTE_TEXT:
      if (!attributes.text_data().text_content().empty()) {
        text.push_back(attributes.text_data().text_content());
      }
      break;

    case optimization_guide::proto::ContentAttributeType::
        CONTENT_ATTRIBUTE_IMAGE:
      if (!attributes.image_data().image_caption().empty()) {
        text.push_back(attributes.image_data().image_caption());
      }
      break;

    default:
      break;
  }
}

void CollectTextForContentNodesRecursively(
    const optimization_guide::proto::ContentNode& node,
    std::vector<std::string>& text) {
  CollectTextForContentNode(node, text);

  for (const auto& child : node.children_nodes()) {
    CollectTextForContentNodesRecursively(child, text);
  }
}

int CountWords(std::string_view s) {
  if (s.empty()) {
    return 0;
  }
  int word_count = (s[0] == ' ') ? 0 : 1;
  for (size_t i = 1; i < s.length(); i++) {
    if (s[i] != ' ' && s[i - 1] == ' ') {
      word_count++;
    }
  }
  return word_count;
}

// Provide a translation of APC to passages for the purposes of measuring
// embeddings performance. This translation is extremely simple and not intended
// to be a full fidelity representation or to be reused outside of this limited
// experiment.
std::vector<std::string> CreatePassagesFromAnnotatedPageContent(
    const optimization_guide::proto::AnnotatedPageContent&
        annotated_page_content) {
  std::vector<std::string> text;
  CollectTextForContentNodesRecursively(annotated_page_content.root_node(),
                                        text);

  if (text.empty()) {
    return {};
  }

  const auto append_with_whitespace_separator =
      [](std::string& str, std::string_view str_to_append) {
        if (str_to_append.empty()) {
          return;
        }

        if (str.empty() || str.back() == ' ') {
          str.append(str_to_append);
          return;
        }

        base::StrAppend(&str, {" ", str_to_append});
      };

  const int max_words_per_aggregate_passage =
      kMaxWordsPerAggregatePassage.Get();
  const int min_words_per_passage = kMinWordsPerPassage.Get();
  const int max_passages_per_page = kMaxPassagesPerPage.Get();

  std::vector<std::string> passages;
  passages.push_back("");
  int current_passage_words = 0;

  for (const std::string& item : text) {
    const int item_words = CountWords(item);

    if (current_passage_words >= max_words_per_aggregate_passage) {
      if (passages.size() >= static_cast<size_t>(max_passages_per_page)) {
        break;
      }
      passages.push_back("");
      current_passage_words = 0;
    }

    const bool should_append =
        current_passage_words < min_words_per_passage ||
        current_passage_words + item_words <= max_words_per_aggregate_passage;

    if (should_append) {
      append_with_whitespace_separator(passages.back(), item);
      current_passage_words += item_words;
    }
  }

  if (passages.back() == "") {
    passages.pop_back();
  }

  return passages;
}

}  // namespace

PassageEmbeddingsCoordinator::PassageEmbeddingsCoordinator(
    page_content_annotations::PageContentExtractionService*
        page_content_extraction_service)
    : omnibox_focus_changed_listener_(base::BindRepeating(
          &PassageEmbeddingsCoordinator::OnOmniboxFocusChanged,
          base::Unretained(this))) {
  page_content_extraction_observation_.Observe(page_content_extraction_service);
}

PassageEmbeddingsCoordinator::~PassageEmbeddingsCoordinator() = default;

void PassageEmbeddingsCoordinator::OnPageContentExtracted(
    content::Page& page,
    const optimization_guide::proto::AnnotatedPageContent& page_content) {
  std::vector<std::string> passages =
      CreatePassagesFromAnnotatedPageContent(page_content);
  VLOG(2) << "Received page content for url "
          << page_content.main_frame_data().url() << ". Generated "
          << passages.size() << " passages.";
  auto* const web_contents =
      content::WebContents::FromRenderFrameHost(&page.GetMainDocument());
  auto loc = web_contents_passage_embedders_.find(web_contents);
  if (loc == web_contents_passage_embedders_.end()) {
    loc = web_contents_passage_embedders_
              .emplace(web_contents,
                       CreateWebContentsPassageEmbedder(web_contents, *this))
              .first;
  }
  loc->second->AcceptPassages(std::move(passages));
}

Embedder::TaskId PassageEmbeddingsCoordinator::ComputePassagesEmbeddings(
    std::vector<std::string> passages,
    Embedder::ComputePassagesEmbeddingsCallback callback) {
  return ChromePassageEmbeddingsServiceController::Get()
      ->GetEmbedder()
      ->ComputePassagesEmbeddings(current_priority_, std::move(passages),
                                  std::move(callback));
}

bool PassageEmbeddingsCoordinator::TryCancel(Embedder::TaskId task_id) {
  return ChromePassageEmbeddingsServiceController::Get()
      ->GetEmbedder()
      ->TryCancel(task_id);
}

void PassageEmbeddingsCoordinator::OnWebContentsDestroyed(
    content::WebContents* web_contents) {
  web_contents_passage_embedders_.erase(web_contents);
}

void PassageEmbeddingsCoordinator::OnOmniboxFocusChanged(bool is_focused) {
  current_priority_ = is_focused ? kUrgent : kPassive;

  std::set<Embedder::TaskId> task_ids;
  for (const auto& [web_contents, web_contents_passage_embedder] :
       web_contents_passage_embedders_) {
    if (current_priority_ == kUrgent) {
      web_contents_passage_embedder
          ->MaybeProcessPendingPassagesOnPriorityIncrease();
    }

    std::optional<Embedder::TaskId> task_id =
        web_contents_passage_embedder->current_task_id();
    if (task_id) {
      task_ids.insert(*task_id);
    }
  }

  ChromePassageEmbeddingsServiceController::Get()
      ->GetEmbedder()
      ->ReprioritizeTasks(current_priority_, task_ids);
}

}  // namespace passage_embeddings