File: lens_overlay_proto_converter.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; 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,811; 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 (463 lines) | stat: -rw-r--r-- 19,132 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
// Copyright 2024 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/ui/lens/lens_overlay_proto_converter.h"

#include <optional>
#include <vector>

#include "base/containers/span.h"
#include "base/strings/utf_string_conversions.h"
#include "base/types/optional_ref.h"
#include "chrome/browser/lens/core/mojom/geometry.mojom.h"
#include "chrome/browser/lens/core/mojom/overlay_object.mojom.h"
#include "chrome/browser/lens/core/mojom/polygon.mojom.h"
#include "chrome/browser/lens/core/mojom/text.mojom-forward.h"
#include "chrome/browser/lens/core/mojom/text.mojom.h"
#include "components/optimization_guide/content/browser/page_content_proto_provider.h"
#include "components/optimization_guide/content/browser/page_context_eligibility_api.h"
#include "third_party/icu/source/common/unicode/unistr.h"
#include "third_party/lens_server_proto/lens_overlay_deep_gleam_data.pb.h"
#include "third_party/lens_server_proto/lens_overlay_geometry.pb.h"
#include "third_party/lens_server_proto/lens_overlay_polygon.pb.h"
#include "third_party/lens_server_proto/lens_overlay_server.pb.h"
#include "third_party/lens_server_proto/lens_overlay_service_deps.pb.h"
#include "third_party/lens_server_proto/lens_overlay_text.pb.h"
#include "ui/gfx/font_list.h"
#include "ui/gfx/geometry/point_f.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/text_utils.h"

namespace lens {

namespace {

lens::mojom::Polygon_VertexOrdering ProtoToMojo(
    lens::Polygon::VertexOrdering vertex_ordering) {
  switch (vertex_ordering) {
    case lens::Polygon::VERTEX_ORDERING_UNSPECIFIED:
      return lens::mojom::Polygon_VertexOrdering::kUnspecified;
    case lens::Polygon::CLOCKWISE:
      return lens::mojom::Polygon_VertexOrdering::kClockwise;
    case lens::Polygon::COUNTER_CLOCKWISE:
      return lens::mojom::Polygon_VertexOrdering::kCounterClockwise;
    default:
      // This default case is needed because two dummy enums that should not be
      // used are created by the proto compiler.
      NOTREACHED() << "Unknown vertex ordering.";
  }
}

lens::mojom::Polygon_CoordinateType ProtoToMojo(
    lens::CoordinateType coordinate_type) {
  switch (coordinate_type) {
    case lens::COORDINATE_TYPE_UNSPECIFIED:
      return lens::mojom::Polygon_CoordinateType::kUnspecified;
    case lens::NORMALIZED:
      return lens::mojom::Polygon_CoordinateType::kNormalized;
    case lens::IMAGE:
      return lens::mojom::Polygon_CoordinateType::kImage;
    default:
      // This default case is needed because two dummy enums that should not be
      // used are created by the proto compiler.
      NOTREACHED() << "Unknown coordinate type.";
  }
}

lens::mojom::Alignment ProtoToMojo(lens::Alignment text_alignment) {
  switch (text_alignment) {
    case lens::Alignment::DEFAULT_LEFT_ALIGNED:
      return lens::mojom::Alignment::kDefaultLeftAlgined;
    case lens::Alignment::RIGHT_ALIGNED:
      return lens::mojom::Alignment::kRightAligned;
    case lens::Alignment::CENTER_ALIGNED:
      return lens::mojom::Alignment::kCenterAligned;
    default:
      // This default case is needed because two dummy enums that should not be
      // used are created by the proto compiler.
      NOTREACHED() << "Unknown text alignment.";
  }
}

lens::mojom::PolygonPtr CreatePolygonMojomFromProto(
    const lens::Polygon& proto_polygon) {
  lens::mojom::PolygonPtr polygon = lens::mojom::Polygon::New();

  std::vector<lens::mojom::VertexPtr> vertices;
  for (const auto& vertex : proto_polygon.vertex()) {
    vertices.push_back(lens::mojom::Vertex::New(vertex.x(), vertex.y()));
  }
  polygon->vertex = std::move(vertices);
  polygon->vertex_ordering = ProtoToMojo(proto_polygon.vertex_ordering());
  polygon->coordinate_type = ProtoToMojo(proto_polygon.coordinate_type());

  return polygon;
}

lens::mojom::GeometryPtr CreateGeometryMojomFromProto(
    const lens::Geometry& response_geometry,
    base::optional_ref<const lens::ZoomedCrop> region_crop_box) {
  lens::mojom::GeometryPtr geometry = lens::mojom::Geometry::New();
  if (!response_geometry.has_bounding_box()) {
    return geometry;
  }

  // If the `region_crop_box` was provided, scale the resulting geometry mojom
  // by the region in order for it to be normalized by the full image instead.
  const float width_scale =
      region_crop_box.has_value() ? region_crop_box->crop().width() : 1;
  const float height_scale =
      region_crop_box.has_value() ? region_crop_box->crop().height() : 1;
  const float zoom_scale =
      region_crop_box.has_value() ? region_crop_box->zoom() : 1;

  auto bounding_box_response = response_geometry.bounding_box();
  lens::mojom::CenterRotatedBoxPtr center_rotated_box =
      lens::mojom::CenterRotatedBox::New();
  gfx::SizeF box_size(
      bounding_box_response.width() * width_scale * zoom_scale,
      bounding_box_response.height() * height_scale * zoom_scale);
  // TODO(b/333562179): Replace this setting of the origin with just a point and
  // size that is passed to the WebUI.
  gfx::PointF center_point =
      gfx::PointF(bounding_box_response.center_x() * width_scale * zoom_scale,
                  bounding_box_response.center_y() * height_scale * zoom_scale);
  center_rotated_box->box.set_origin(center_point);
  center_rotated_box->box.set_size(box_size);
  center_rotated_box->coordinate_type =
      lens::mojom::CenterRotatedBox_CoordinateType(
          bounding_box_response.coordinate_type());
  center_rotated_box->rotation = bounding_box_response.rotation_z();

  geometry->bounding_box = std::move(center_rotated_box);

  std::vector<lens::mojom::PolygonPtr> polygons;
  for (const auto& polygon : response_geometry.segmentation_polygon()) {
    polygons.push_back(CreatePolygonMojomFromProto(polygon));
  }
  geometry->segmentation_polygon = std::move(polygons);

  return geometry;
}

lens::mojom::WordPtr CreateWordMojomFromProto(
    const lens::TextLayout_Word& proto_word,
    base::optional_ref<const lens::ZoomedCrop> region_crop_box,
    lens::WritingDirection writing_direction) {
  lens::mojom::WordPtr word = lens::mojom::Word::New();
  word->plain_text = proto_word.plain_text();
  if (proto_word.has_text_separator()) {
    word->text_separator = proto_word.text_separator();
  }
  if (proto_word.has_geometry()) {
    word->geometry =
        CreateGeometryMojomFromProto(proto_word.geometry(), region_crop_box);
  }
  if (proto_word.has_formula_metadata()) {
    lens::mojom::FormulaMetadataPtr metadata =
        lens::mojom::FormulaMetadata::New();
    metadata->latex = proto_word.formula_metadata().latex();
    word->formula_metadata = std::move(metadata);
  }
  word->writing_direction = lens::mojom::WritingDirection(writing_direction);
  return word;
}

lens::mojom::LinePtr CreateLineMojomFromProto(
    const lens::TextLayout_Line& proto_line,
    base::optional_ref<const lens::ZoomedCrop> region_crop_box,
    lens::WritingDirection writing_direction) {
  lens::mojom::LinePtr line = lens::mojom::Line::New();
  std::vector<lens::mojom::WordPtr> words;
  for (const auto& word : proto_line.words()) {
    words.push_back(
        CreateWordMojomFromProto(word, region_crop_box, writing_direction));
  }
  line->words = std::move(words);
  if (proto_line.has_geometry()) {
    line->geometry =
        CreateGeometryMojomFromProto(proto_line.geometry(), region_crop_box);
  }
  return line;
}

lens::mojom::BackgroundImageDataPtr CreateBackgroundImageDataMojomFromProto(
    lens::TranslationData_BackgroundImageData background_image_data) {
  lens::mojom::BackgroundImageDataPtr image_data =
      lens::mojom::BackgroundImageData::New();
  gfx::Size image_size = gfx::Size(background_image_data.image_width(),
                                   background_image_data.image_height());
  image_data->image_size = std::move(image_size);
  image_data->vertical_padding = background_image_data.vertical_padding();
  image_data->horizontal_padding = background_image_data.horizontal_padding();

  // Create vector for `background_image_data`.
  image_data->background_image =
      base::as_byte_span(background_image_data.background_image());

  // Create vector for `text_mask`.
  image_data->text_mask = base::as_byte_span(background_image_data.text_mask());

  return image_data;
}

lens::mojom::WordPtr CreateTranslatedWordMojomFromProto(
    const std::string& translated_text,
    const std::string& text_separator,
    lens::WritingDirection writing_direction) {
  // The geometry of the word needs to be calculated in the typescript where we
  // find the font size needed for the line.
  lens::mojom::WordPtr word = lens::mojom::Word::New();
  word->plain_text = translated_text;
  word->text_separator = text_separator;
  word->writing_direction = lens::mojom::WritingDirection(writing_direction);
  return word;
}

lens::mojom::TranslatedLinePtr CreateTranslatedLineMojomFromProto(
    const lens::TextLayout_Line& proto_line,
    const lens::TranslationData_Line& translated_line,
    const std::optional<lens::TranslationData_Line>& next_translated_line,
    const std::string& line_translation,
    lens::WritingDirection writing_direction) {
  lens::mojom::TranslatedLinePtr line = lens::mojom::TranslatedLine::New();

  // We can have a different amount of words in the detected text line and
  // translated text line. The translated words can also be different sizes than
  // the detected words. Because of this, we need to recalculate the geometry
  // of the translated words (it is not provided in server response). If there
  // is no line geometry, we cannot translate this line.
  if (!proto_line.has_geometry()) {
    return line;
  }
  line->geometry =
      CreateGeometryMojomFromProto(proto_line.geometry(), std::nullopt);

  // Create the mojo word objects from the proto response.
  std::vector<mojom::WordPtr> words;
  for (int i = 0; i < translated_line.word_size(); i++) {
    const auto& translated_proto_word = translated_line.word()[i];
    int substring_length =
        translated_proto_word.end() - translated_proto_word.start();

    // We need to convert the string to a unicode string in case there are
    // multi-byte characters that we need to substring.
    icu::UnicodeString unicode_translation(line_translation.c_str());

    // The separator following this word, used when concatenating selected text.
    // This needs to be the separator to the logically next word. For
    // bidirectional text, this separator might not be visually adjacent to the
    // word.
    icu::UnicodeString unicode_separator = "";
    if (i < translated_line.word_size() - 1) {
      const auto& next_translated_proto_word = translated_line.word()[i + 1];
      const auto length =
          next_translated_proto_word.start() - translated_proto_word.end();
      unicode_separator = unicode_translation.tempSubString(
          translated_proto_word.end(), length);
    } else if (i == translated_line.word_size() - 1 &&
               next_translated_line.has_value() &&
               next_translated_line->word_size() > 0) {
      const auto next_line_start = next_translated_line->word()[0].start();
      const auto length = next_line_start - translated_proto_word.end();
      unicode_separator = unicode_translation.tempSubString(
          translated_proto_word.end(), length);
    }

    const icu::UnicodeString unicode_translation_substr =
        unicode_translation.tempSubString(translated_proto_word.start(),
                                          substring_length);

    // Convert the unicode substring back into UTF-8 strings to send to WebUI.
    std::string translation;
    unicode_translation_substr.toUTF8String(translation);
    std::string separator;
    unicode_separator.toUTF8String(separator);

    words.push_back(CreateTranslatedWordMojomFromProto(translation, separator,
                                                       writing_direction));
  }

  if (translated_line.has_background_image_data()) {
    line->background_image_data = CreateBackgroundImageDataMojomFromProto(
        translated_line.background_image_data());
  }
  line->translation = line_translation;
  line->background_primary_color =
      translated_line.style().background_primary_color();
  line->text_color = translated_line.style().text_color();
  line->words = std::move(words);
  return line;
}

lens::mojom::TranslatedParagraphPtr CreateTranslatedParagraphMojomFromProto(
    const lens::TextLayout_Paragraph& proto_paragraph,
    const lens::DeepGleamData& deep_gleam,
    const gfx::Size& resized_bitmap_size) {
  lens::mojom::TranslatedParagraphPtr paragraph;
  // If there is no deep gleam translation for this paragraph, just return
  // empty.
  if (!deep_gleam.has_translation()) {
    return paragraph;
  }

  auto translation_data = deep_gleam.translation();
  // We need a status code so we can know if the translation was successful.
  if (!translation_data.has_status() &&
      translation_data.status().code() !=
          lens::TranslationData::Status::SUCCESS) {
    return paragraph;
  }

  // We should have the same amount of translated lines in the detected text
  // and the translated text data.
  if (proto_paragraph.lines_size() != translation_data.line_size()) {
    return paragraph;
  }

  paragraph = lens::mojom::TranslatedParagraph::New();
  std::vector<lens::mojom::TranslatedLinePtr> lines;
  for (int line_index = 0; line_index < translation_data.line_size();
       line_index++) {
    auto proto_line = proto_paragraph.lines()[line_index];
    auto translated_line = translation_data.line()[line_index];
    std::optional<TranslationData_Line> next_translated_line = std::nullopt;
    if (line_index + 1 < translation_data.line().size()) {
      next_translated_line = translation_data.line()[line_index + 1];
    }
    lines.push_back(CreateTranslatedLineMojomFromProto(
        proto_line, translated_line, next_translated_line,
        translation_data.translation(), translation_data.writing_direction()));
  }

  paragraph->lines = std::move(lines);
  paragraph->resized_bitmap_size = gfx::Size(resized_bitmap_size);
  paragraph->content_language = translation_data.target_language();
  paragraph->alignment = ProtoToMojo(translation_data.alignment());
  paragraph->writing_direction =
      lens::mojom::WritingDirection(translation_data.writing_direction());
  return paragraph;
}

lens::mojom::ParagraphPtr CreateParagraphMojomFromProto(
    const lens::TextLayout_Paragraph& proto_paragraph,
    base::optional_ref<const lens::DeepGleamData> deep_gleam,
    base::optional_ref<const lens::ZoomedCrop> region_crop_box,
    const gfx::Size& resized_bitmap_size) {
  lens::mojom::ParagraphPtr paragraph = lens::mojom::Paragraph::New();
  paragraph->content_language = proto_paragraph.content_language();
  std::vector<lens::mojom::LinePtr> lines;
  for (const auto& line : proto_paragraph.lines()) {
    lines.push_back(CreateLineMojomFromProto(
        line, region_crop_box, proto_paragraph.writing_direction()));
  }
  paragraph->lines = std::move(lines);

  if (proto_paragraph.has_geometry()) {
    paragraph->geometry = CreateGeometryMojomFromProto(
        proto_paragraph.geometry(), region_crop_box);
  }
  paragraph->writing_direction =
      lens::mojom::WritingDirection(proto_paragraph.writing_direction());

  if (deep_gleam.has_value() && deep_gleam->has_translation()) {
    paragraph->translation = CreateTranslatedParagraphMojomFromProto(
        proto_paragraph, deep_gleam.value(), resized_bitmap_size);
  }

  return paragraph;
}

lens::mojom::TextPtr CreateTextMojomFromProto(
    const lens::Text& response_text,
    const ::google::protobuf::RepeatedPtrField<::lens::DeepGleamData>
        deep_gleams,
    base::optional_ref<const lens::ZoomedCrop> region_crop_box,
    const gfx::Size& resized_bitmap_size) {
  lens::mojom::TextPtr text = lens::mojom::Text::New();
  text->content_language = response_text.content_language();
  if (response_text.has_text_layout()) {
    const lens::TextLayout response_layout = response_text.text_layout();
    lens::mojom::TextLayoutPtr text_layout = lens::mojom::TextLayout::New();
    std::vector<lens::mojom::ParagraphPtr> paragraphs;

    for (int i = 0; i < response_text.text_layout().paragraphs_size(); i++) {
      const auto& response_paragraph =
          response_text.text_layout().paragraphs()[i];
      lens::DeepGleamData deep_gleam_data;
      // The translated paragraphs should correspond to each paragraph of
      // detected text and deep gleam data. That is, there should be the same
      // amount of deep gleam data as paragraphs.
      if (i < deep_gleams.size()) {
        deep_gleam_data = deep_gleams[i];
      }
      paragraphs.push_back(
          CreateParagraphMojomFromProto(response_paragraph, deep_gleam_data,
                                        region_crop_box, resized_bitmap_size));
    }
    text_layout->paragraphs = std::move(paragraphs);
    text->text_layout = std::move(text_layout);
  }
  return text;
}

}  // namespace

std::vector<lens::mojom::OverlayObjectPtr>
CreateObjectsMojomArrayFromServerResponse(
    const lens::LensOverlayServerResponse& response) {
  std::vector<lens::mojom::OverlayObjectPtr> object_array;
  if (!response.has_objects_response() ||
      response.objects_response().overlay_objects().empty()) {
    return object_array;
  }

  auto response_objects = response.objects_response().overlay_objects();
  for (const auto& response_object : response_objects) {
    if (!response_object.has_interaction_properties() ||
        !response_object.interaction_properties().select_on_tap()) {
      continue;
    }
    lens::mojom::OverlayObjectPtr overlay_object =
        lens::mojom::OverlayObject::New();
    overlay_object->id = std::string(response_object.id());
    if (response_object.has_geometry()) {
      overlay_object->geometry = CreateGeometryMojomFromProto(
          response_object.geometry(), std::nullopt);
    }
    object_array.push_back(std::move(overlay_object));
  }

  return object_array;
}

lens::mojom::TextPtr CreateTextMojomFromServerResponse(
    const lens::LensOverlayServerResponse& response,
    const gfx::Size resized_bitmap_size) {
  // If the server response lacks text, then return an empty vector.
  if (!response.has_objects_response() ||
      !response.objects_response().has_text()) {
    return lens::mojom::TextPtr();
  }

  return CreateTextMojomFromProto(response.objects_response().text(),
                                  response.objects_response().deep_gleams(),
                                  std::nullopt, resized_bitmap_size);
}

lens::mojom::TextPtr CreateTextMojomFromInteractionResponse(
    const lens::LensOverlayInteractionResponse& response,
    const lens::ZoomedCrop& region_crop_box,
    const gfx::Size& resized_bitmap_size) {
  if (!response.has_text()) {
    return lens::mojom::TextPtr();
  }

  return CreateTextMojomFromProto(
      response.text(),
      ::google::protobuf::RepeatedPtrField<::lens::DeepGleamData>(),
      region_crop_box, resized_bitmap_size);
}

}  // namespace lens