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

Side by Side Diff: third_party/WebKit/Source/core/dom/DocumentStatisticsCollector.cpp

Issue 1419033004: Add feature extraction for distillability to Blink (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: address esprehn's comments Created 5 years, 1 month 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 2015 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 "config.h"
6 #include "DocumentStatisticsCollector.h"
7
8 #include "core/HTMLNames.h"
9 #include "core/InputTypeNames.h"
10 #include "core/dom/ElementTraversal.h"
11 #include "core/dom/NodeComputedStyle.h"
12 #include "core/dom/Text.h"
13 #include "core/frame/FrameHost.h"
14 #include "core/html/HTMLHeadElement.h"
15 #include "core/html/HTMLInputElement.h"
16 #include "core/html/HTMLMetaElement.h"
17 #include "public/platform/Platform.h"
18 #include "public/platform/WebDistillability.h"
19
20 namespace blink {
21
22 using namespace HTMLNames;
23
24 namespace {
25
26 // Saturate the length of a paragraph to save time.
27 const int kTextContentLengthSaturation = 1000;
28
29 // Filter out short P elements. The threshold is set to around 2 English sentenc es.
30 const unsigned kParagraphLengthThreshold = 140;
31
32 // Saturate the scores to save time. The max is the score of 6 long paragraphs.
33 const double kMozScoreSaturation = 175.954539583; // 6 * sqrt(kTextContentLength Saturation - kParagraphLengthThreshold)
34 const double kMozScoreAllSqrtSaturation = 189.73665961; // 6 * sqrt(kTextContent LengthSaturation);
35 const double kMozScoreAllLinearSaturation = 6 * kTextContentLengthSaturation;
36
37 unsigned textContentLengthSaturated(Element& root)
38 {
39 unsigned length = 0;
40 // This skips shadow DOM intentionally, to match the JavaScript implementati on.
41 // We would like to use the same statistics extracted by the JavaScript impl ementation
42 // on iOS, and JavaScript cannot peek deeply into shadow DOM except on moder n Chrome
43 // versions.
44 // Given shadow DOM rarely appears in <P> elements in long-form articles, th e overall
45 // accuracy should not be largely affected.
46 for (Node& node : NodeTraversal::inclusiveDescendantsOf(root)) {
47 if (!node.isTextNode()) {
48 continue;
49 }
50 length += toText(node).length();
51 if (length > kTextContentLengthSaturation) {
52 return kTextContentLengthSaturation;
53 }
54 }
55 return length;
56 }
57
58 bool isVisible(const Element& element)
59 {
60 const ComputedStyle* style = element.computedStyle();
61 if (!style)
62 return false;
63 return (
64 style->display() != NONE
65 && style->visibility() != HIDDEN
66 && style->opacity() != 0
67 );
68 }
69
70 bool matchAttributes(const Element& element, const Vector<String>& words)
71 {
72 const String& classes = element.getClassAttribute();
73 const String& id = element.getIdAttribute();
74 for (const String& word : words) {
75 if (classes.findIgnoringCase(word) != WTF::kNotFound
76 || id.findIgnoringCase(word) != WTF::kNotFound) {
77 return true;
78 }
79 }
80 return false;
81 }
82
83 bool isGoodForScoring(const WebDistillabilityFeatures& features, const Element& element)
84 {
85 DEFINE_STATIC_LOCAL(Vector<String>, unlikelyCandidates, ());
86 if (unlikelyCandidates.isEmpty()) {
87 auto words = {
88 "banner",
89 "combx",
90 "comment",
91 "community",
92 "disqus",
93 "extra",
94 "foot",
95 "header",
96 "menu",
97 "related",
98 "remark",
99 "rss",
100 "share",
101 "shoutbox",
102 "sidebar",
103 "skyscraper",
104 "sponsor",
105 "ad-break",
106 "agegate",
107 "pagination",
108 "pager",
109 "popup"
110 };
111 for (auto word : words) {
112 unlikelyCandidates.append(word);
113 }
114 }
115 DEFINE_STATIC_LOCAL(Vector<String>, highlyLikelyCandidates, ());
116 if (highlyLikelyCandidates.isEmpty()) {
117 auto words = {
118 "and",
119 "article",
120 "body",
121 "column",
122 "main",
123 "shadow"
124 };
125 for (auto word : words) {
126 highlyLikelyCandidates.append(word);
127 }
128 }
129
130 if (!isVisible(element))
131 return false;
132 if (features.mozScore >= kMozScoreSaturation
133 && features.mozScoreAllSqrt >= kMozScoreAllSqrtSaturation
134 && features.mozScoreAllLinear >= kMozScoreAllLinearSaturation)
135 return false;
136 if (matchAttributes(element, unlikelyCandidates)
137 && !matchAttributes(element, highlyLikelyCandidates))
138 return false;
139 return true;
140 }
141
142 // underListItem denotes that at least one of the ancesters is <li> element.
143 void collectFeatures(Element& root, WebDistillabilityFeatures& features, bool un derListItem = false)
144 {
145 for (Node& node : NodeTraversal::childrenOf(root)) {
146 if (!node.isElementNode()) {
147 continue;
148 }
149
150 features.elementCount++;
151 Element& element = toElement(node);
152 if (element.hasTagName(aTag)) {
153 features.anchorCount++;
154 } else if (element.hasTagName(formTag)) {
155 features.formCount++;
156 } else if (element.hasTagName(inputTag)) {
157 const HTMLInputElement& input = toHTMLInputElement(element);
158 if (input.type() == InputTypeNames::text) {
159 features.textInputCount++;
160 } else if (input.type() == InputTypeNames::password) {
161 features.passwordInputCount++;
162 }
163 } else if (element.hasTagName(pTag) || element.hasTagName(preTag)) {
164 if (element.hasTagName(pTag)) {
165 features.pCount++;
166 } else {
167 features.preCount++;
168 }
169 if (!underListItem && isGoodForScoring(features, element)) {
170 unsigned length = textContentLengthSaturated(element);
171 if (length >= kParagraphLengthThreshold) {
172 features.mozScore += sqrt(length - kParagraphLengthThreshold );
173 features.mozScore = std::min(features.mozScore, kMozScoreSat uration);
174 }
175 features.mozScoreAllSqrt += sqrt(length);
176 features.mozScoreAllSqrt = std::min(features.mozScoreAllSqrt, kM ozScoreAllSqrtSaturation);
177
178 features.mozScoreAllLinear += length;
179 features.mozScoreAllLinear = std::min(features.mozScoreAllLinear , kMozScoreAllLinearSaturation);
180 }
181 } else if (element.hasTagName(liTag)) {
182 underListItem = true;
183 }
184 collectFeatures(element, features, underListItem);
185 }
186 }
187
188 bool hasOpenGraphArticle(const Element& head)
189 {
190 DEFINE_STATIC_LOCAL(AtomicString, ogType, ("og:type"));
191 DEFINE_STATIC_LOCAL(AtomicString, propertyAttr, ("property"));
192 for (const Element* child = ElementTraversal::firstChild(head); child; child = ElementTraversal::nextSibling(*child)) {
193 if (!isHTMLMetaElement(*child))
194 continue;
195 const HTMLMetaElement& meta = toHTMLMetaElement(*child);
196
197 if (meta.name() == ogType || meta.getAttribute(propertyAttr) == ogType) {
198 if (equalIgnoringCase(meta.content(), "article")) {
199 return true;
200 }
201 }
202 }
203 return false;
204 }
205
206 bool isMobileFriendly(Document& document)
207 {
208 if (FrameHost* frameHost = document.frameHost())
209 return frameHost->visualViewport().shouldDisableDesktopWorkarounds();
210 return false;
211 }
212
213 } // namespace
214
215 WebDistillabilityFeatures DocumentStatisticsCollector::collectStatistics(Documen t& document)
216 {
217 TRACE_EVENT0("blink", "DocumentStatisticsCollector::collectStatistics");
218
219 WebDistillabilityFeatures features = WebDistillabilityFeatures();
220
221 if (!document.frame() || !document.frame()->isMainFrame())
222 return features;
223
224 ASSERT(document.hasFinishedParsing());
225
226 HTMLElement* body = document.body();
227 HTMLElement* head = document.head();
228
229 if (!body || !head)
230 return features;
231
232 if (isMobileFriendly(document)) {
233 features.isMobileFriendly = true;
234 // We only trigger Reader Mode on non-mobile-friendly pages for now.
235 return features;
236 }
237
238 double startTime = monotonicallyIncreasingTime();
239
240 // This should be cheap since collectStatistics is only called right after l ayout.
241 document.updateLayoutTreeIfNeeded();
242
243 // Traverse the DOM tree and collect statistics.
244 collectFeatures(*body, features);
245 features.openGraph = hasOpenGraphArticle(*head);
246
247 double elapsedTime = monotonicallyIncreasingTime() - startTime;
248 Platform::current()->histogramCustomCounts("WebCore.DistillabilityUs", stati c_cast<int>(1e6 * elapsedTime), 1, 1000000, 50);
249
250 return features;
251 }
252
253 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698