readingtime.go 1.0 KB

12345678910111213141516171819202122232425262728293031
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. // Package readtime provides a function to estimate the reading time of an article.
  4. package readingtime
  5. import (
  6. "math"
  7. "strings"
  8. "unicode/utf8"
  9. "miniflux.app/v2/internal/reader/sanitizer"
  10. "github.com/abadojack/whatlanggo"
  11. )
  12. // EstimateReadingTime returns the estimated reading time of an article in minute.
  13. func EstimateReadingTime(content string, defaultReadingSpeed, cjkReadingSpeed int) int {
  14. sanitizedContent := sanitizer.StripTags(content)
  15. langInfo := whatlanggo.Detect(sanitizedContent)
  16. var timeToReadInt int
  17. if langInfo.IsReliable() && (langInfo.Lang == whatlanggo.Jpn || langInfo.Lang == whatlanggo.Cmn || langInfo.Lang == whatlanggo.Kor) {
  18. timeToReadInt = int(math.Ceil(float64(utf8.RuneCountInString(sanitizedContent)) / float64(cjkReadingSpeed)))
  19. } else {
  20. nbOfWords := len(strings.Fields(sanitizedContent))
  21. timeToReadInt = int(math.Ceil(float64(nbOfWords) / float64(defaultReadingSpeed)))
  22. }
  23. return timeToReadInt
  24. }