readability.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package readability // import "miniflux.app/v2/internal/reader/readability"
  4. import (
  5. "fmt"
  6. "io"
  7. "log/slog"
  8. "strings"
  9. "miniflux.app/v2/internal/urllib"
  10. "github.com/PuerkitoBio/goquery"
  11. "golang.org/x/net/html"
  12. )
  13. const defaultTagsToScore = "section,h2,h3,h4,h5,h6,p,td,pre,div"
  14. var (
  15. strongCandidates = [...]string{"popupbody", "-ad", "g-plus"}
  16. maybeCandidate = [...]string{"and", "article", "body", "column", "main", "shadow"}
  17. unlikelyCandidate = [...]string{"banner", "breadcrumbs", "combx", "comment", "community", "cover-wrap", "disqus", "extra", "foot", "header", "legends", "menu", "modal", "related", "remark", "replies", "rss", "shoutbox", "sidebar", "skyscraper", "social", "sponsor", "supplemental", "ad-break", "agegate", "pagination", "pager", "popup", "yom-remote"}
  18. positiveKeywords = [...]string{"article", "blog", "body", "content", "entry", "h-entry", "hentry", "main", "page", "pagination", "post", "story", "text"}
  19. negativeKeywords = [...]string{"author", "banner", "byline", "com-", "combx", "comment", "contact", "dateline", "foot", "hid", "masthead", "media", "meta", "modal", "outbrain", "promo", "related", "scroll", "share", "shopping", "shoutbox", "sidebar", "skyscraper", "sponsor", "tags", "tool", "widget", "writtenby"}
  20. )
  21. type candidate struct {
  22. selection *goquery.Selection
  23. score float32
  24. }
  25. func (c *candidate) Node() *html.Node {
  26. if c.selection.Length() == 0 {
  27. return nil
  28. }
  29. return c.selection.Get(0)
  30. }
  31. func (c *candidate) String() string {
  32. node := c.Node()
  33. if node == nil {
  34. return fmt.Sprintf("empty => %f", c.score)
  35. }
  36. id, _ := c.selection.Attr("id")
  37. class, _ := c.selection.Attr("class")
  38. switch {
  39. case id != "" && class != "":
  40. return fmt.Sprintf("%s#%s.%s => %f", node.DataAtom, id, class, c.score)
  41. case id != "":
  42. return fmt.Sprintf("%s#%s => %f", node.DataAtom, id, c.score)
  43. case class != "":
  44. return fmt.Sprintf("%s.%s => %f", node.DataAtom, class, c.score)
  45. }
  46. return fmt.Sprintf("%s => %f", node.DataAtom, c.score)
  47. }
  48. type candidateList map[*html.Node]*candidate
  49. func (c candidateList) String() string {
  50. var output []string
  51. for _, candidate := range c {
  52. output = append(output, candidate.String())
  53. }
  54. return strings.Join(output, ", ")
  55. }
  56. // ExtractContent returns relevant content.
  57. func ExtractContent(page io.Reader) (baseURL string, extractedContent string, err error) {
  58. document, err := goquery.NewDocumentFromReader(page)
  59. if err != nil {
  60. return "", "", err
  61. }
  62. if hrefValue, exists := document.FindMatcher(goquery.Single("head base")).Attr("href"); exists {
  63. hrefValue = strings.TrimSpace(hrefValue)
  64. if urllib.IsAbsoluteURL(hrefValue) {
  65. baseURL = hrefValue
  66. }
  67. }
  68. document.Find("script,style").Remove()
  69. transformMisusedDivsIntoParagraphs(document)
  70. removeUnlikelyCandidates(document)
  71. candidates := getCandidates(document)
  72. topCandidate := getTopCandidate(document, candidates)
  73. slog.Debug("Readability parsing",
  74. slog.String("base_url", baseURL),
  75. slog.Any("candidates", candidates),
  76. slog.Any("topCandidate", topCandidate),
  77. )
  78. extractedContent = getArticle(topCandidate, candidates)
  79. return baseURL, extractedContent, nil
  80. }
  81. func getSelectionLength(s *goquery.Selection) int {
  82. var getLengthOfTextContent func(*html.Node) int
  83. getLengthOfTextContent = func(n *html.Node) int {
  84. total := 0
  85. if n.Type == html.TextNode {
  86. total += len(n.Data)
  87. }
  88. if n.FirstChild != nil {
  89. for c := n.FirstChild; c != nil; c = c.NextSibling {
  90. total += getLengthOfTextContent(c)
  91. }
  92. }
  93. return total
  94. }
  95. sum := 0
  96. for _, n := range s.Nodes {
  97. sum += getLengthOfTextContent(n)
  98. }
  99. return sum
  100. }
  101. // Now that we have the top candidate, look through its siblings for content that might also be related.
  102. // Things like preambles, content split by ads that we removed, etc.
  103. func getArticle(topCandidate *candidate, candidates candidateList) string {
  104. var output strings.Builder
  105. output.WriteString("<div>")
  106. siblingScoreThreshold := max(10, topCandidate.score/5)
  107. topCandidate.selection.Siblings().Union(topCandidate.selection).Each(func(i int, s *goquery.Selection) {
  108. append := false
  109. tag := "div"
  110. node := s.Get(0)
  111. topNode := topCandidate.Node()
  112. if topNode != nil && node == topNode {
  113. append = true
  114. } else if c, ok := candidates[node]; ok && c.score >= siblingScoreThreshold {
  115. append = true
  116. } else if s.Is("p") {
  117. tag = node.Data
  118. linkDensity := getLinkDensity(s)
  119. contentLength := getSelectionLength(s)
  120. if contentLength >= 80 {
  121. if linkDensity < .25 {
  122. append = true
  123. }
  124. } else {
  125. if linkDensity == 0 {
  126. // It's a small selection, so .Text doesn't impact performances too much.
  127. content := s.Text()
  128. if containsSentence(content) {
  129. append = true
  130. }
  131. }
  132. }
  133. }
  134. if append {
  135. html, _ := s.Html()
  136. output.WriteString("<" + tag + ">" + html + "</" + tag + ">")
  137. }
  138. })
  139. output.WriteString("</div>")
  140. return output.String()
  141. }
  142. func shouldRemoveCandidate(str string) bool {
  143. str = strings.ToLower(str)
  144. // Those candidates have no false-positives, no need to check against `maybeCandidate`
  145. for _, strongCandidate := range strongCandidates {
  146. if strings.Contains(str, strongCandidate) {
  147. return true
  148. }
  149. }
  150. for _, unlikelyCandidate := range unlikelyCandidate {
  151. if strings.Contains(str, unlikelyCandidate) {
  152. // Do we have a false positive?
  153. for _, maybe := range maybeCandidate {
  154. if strings.Contains(str, maybe) {
  155. return false
  156. }
  157. }
  158. // Nope, it's a true positive!
  159. return true
  160. }
  161. }
  162. return false
  163. }
  164. func removeUnlikelyCandidates(document *goquery.Document) {
  165. document.Find("*").Each(func(i int, s *goquery.Selection) {
  166. if s.Length() == 0 || s.Get(0).Data == "html" || s.Get(0).Data == "body" {
  167. return
  168. }
  169. // Don't remove elements within code blocks (pre or code tags)
  170. if s.Closest("pre, code").Length() > 0 {
  171. return
  172. }
  173. if class, ok := s.Attr("class"); ok && shouldRemoveCandidate(class) {
  174. s.Remove()
  175. } else if id, ok := s.Attr("id"); ok && shouldRemoveCandidate(id) {
  176. s.Remove()
  177. }
  178. })
  179. }
  180. func getTopCandidate(document *goquery.Document, candidates candidateList) *candidate {
  181. var best *candidate
  182. for _, c := range candidates {
  183. if best == nil {
  184. best = c
  185. } else if best.score < c.score {
  186. best = c
  187. }
  188. }
  189. if best == nil {
  190. best = &candidate{document.Find("body"), 0}
  191. }
  192. return best
  193. }
  194. // Loop through all paragraphs, and assign a score to them based on how content-y they look.
  195. // Then add their score to their parent node.
  196. // A score is determined by things like number of commas, class names, etc.
  197. func getCandidates(document *goquery.Document) candidateList {
  198. candidates := make(candidateList)
  199. document.Find(defaultTagsToScore).Each(func(i int, s *goquery.Selection) {
  200. textLen := getSelectionLength(s)
  201. // If this paragraph is less than 25 characters, don't even count it.
  202. if textLen < 25 {
  203. return
  204. }
  205. parent := s.Parent()
  206. parentNode := parent.Get(0)
  207. grandParent := parent.Parent()
  208. var grandParentNode *html.Node
  209. if grandParent.Length() > 0 {
  210. grandParentNode = grandParent.Get(0)
  211. }
  212. if _, found := candidates[parentNode]; !found {
  213. candidates[parentNode] = scoreNode(parent)
  214. }
  215. if grandParentNode != nil {
  216. if _, found := candidates[grandParentNode]; !found {
  217. candidates[grandParentNode] = scoreNode(grandParent)
  218. }
  219. }
  220. // Add a point for the paragraph itself as a base.
  221. contentScore := float32(1.0)
  222. // Add points for any commas within this paragraph.
  223. text := s.Text()
  224. contentScore += float32(strings.Count(text, ",") + 1)
  225. // For every 100 characters in this paragraph, add another point. Up to 3 points.
  226. contentScore += float32(min(textLen/100.0, 3))
  227. candidates[parentNode].score += contentScore
  228. if grandParentNode != nil {
  229. candidates[grandParentNode].score += contentScore / 2.0
  230. }
  231. })
  232. // Scale the final candidates score based on link density. Good content
  233. // should have a relatively small link density (5% or less) and be mostly
  234. // unaffected by this operation
  235. for _, candidate := range candidates {
  236. candidate.score *= (1 - getLinkDensity(candidate.selection))
  237. }
  238. return candidates
  239. }
  240. func scoreNode(s *goquery.Selection) *candidate {
  241. c := &candidate{selection: s, score: 0}
  242. // Check if selection is empty to avoid panic
  243. if s.Length() == 0 {
  244. return c
  245. }
  246. switch s.Get(0).DataAtom.String() {
  247. case "div":
  248. c.score += 5
  249. case "pre", "td", "blockquote", "img":
  250. c.score += 3
  251. case "address", "ol", "ul", "dl", "dd", "dt", "li", "form":
  252. c.score -= 3
  253. case "h1", "h2", "h3", "h4", "h5", "h6", "th":
  254. c.score -= 5
  255. }
  256. c.score += getClassWeight(s)
  257. return c
  258. }
  259. // Get the density of links as a percentage of the content
  260. // This is the amount of text that is inside a link divided by the total text in the node.
  261. func getLinkDensity(s *goquery.Selection) float32 {
  262. sum := getSelectionLength(s)
  263. if sum == 0 {
  264. return 0
  265. }
  266. linkLength := getSelectionLength(s.Find("a"))
  267. return float32(linkLength) / float32(sum)
  268. }
  269. // Get an elements class/id weight. Uses regular expressions to tell if this
  270. // element looks good or bad.
  271. func getClassWeight(s *goquery.Selection) float32 {
  272. weight := 0
  273. if class, ok := s.Attr("class"); ok {
  274. weight += getWeight(class)
  275. }
  276. if id, ok := s.Attr("id"); ok {
  277. weight += getWeight(id)
  278. }
  279. return float32(weight)
  280. }
  281. func getWeight(s string) int {
  282. s = strings.ToLower(s)
  283. for _, keyword := range negativeKeywords {
  284. if strings.Contains(s, keyword) {
  285. return -25
  286. }
  287. }
  288. for _, keyword := range positiveKeywords {
  289. if strings.Contains(s, keyword) {
  290. return +25
  291. }
  292. }
  293. return 0
  294. }
  295. func transformMisusedDivsIntoParagraphs(document *goquery.Document) {
  296. document.Find("div").Each(func(i int, s *goquery.Selection) {
  297. nodes := s.Children().Nodes
  298. if len(nodes) == 0 {
  299. node := s.Get(0)
  300. node.Data = "p"
  301. return
  302. }
  303. for _, node := range nodes {
  304. switch node.Data {
  305. case "a", "blockquote", "div", "dl",
  306. "img", "ol", "p", "pre",
  307. "table", "ul":
  308. return
  309. default:
  310. currentNode := s.Get(0)
  311. currentNode.Data = "p"
  312. }
  313. }
  314. })
  315. }
  316. func containsSentence(content string) bool {
  317. return strings.HasSuffix(content, ".") || strings.Contains(content, ". ")
  318. }