25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

59 satır
2.5 KiB

  1. import logging
  2. from urllib.parse import urlparse
  3. from services.similarity import cosine_lists
  4. logger = logging.getLogger(__name__)
  5. class Headline:
  6. display_text: str
  7. normalized_text: list[str]
  8. source_url: str
  9. domain: str
  10. published_at: object
  11. def __init__(self, display_text: str, normalized_text: list[str], source_url: str = "", published_at=None):
  12. self.display_text = display_text
  13. self.normalized_text = normalized_text
  14. self.source_url = source_url
  15. self.domain = self._extract_domain(source_url)
  16. self.published_at = published_at
  17. logger.debug(
  18. "Initialized Headline instance (display_text=%r, token_count=%d, source=%r, domain=%r, published_at=%r)",
  19. self.display_text, len(self.normalized_text), self.source_url, self.domain, self.published_at,
  20. )
  21. @staticmethod
  22. def _extract_domain(url: str):
  23. """Return a normalized outlet domain for a source URL, or None if absent.
  24. Strips scheme, surrounding whitespace and a leading ``www.`` so that
  25. ``https://www.cnn.com/us`` and ``https://cnn.com/politics`` both resolve
  26. to ``cnn.com`` — i.e. one outlet counts once, regardless of section URL.
  27. """
  28. if not url or not isinstance(url, str) or not url.strip():
  29. return None
  30. host = urlparse(url.strip()).netloc.lower()
  31. if not host:
  32. return None
  33. if host.startswith("www."):
  34. host = host[4:]
  35. return host
  36. def compare_headlines(self, other_headline):
  37. if not isinstance(other_headline, Headline):
  38. logger.warning("Comparing Headline %r with incompatible object of type %s: %r",
  39. self.display_text, type(other_headline).__name__, other_headline)
  40. logger.debug("Comparing Headline %r against %r",
  41. self.display_text, getattr(other_headline, 'display_text', repr(other_headline)))
  42. try:
  43. score = cosine_lists(self.normalized_text, other_headline.normalized_text)
  44. logger.debug("Headline comparison score: %.4f between %r and %r",
  45. score, self.display_text, getattr(other_headline, 'display_text', repr(other_headline)))
  46. return score
  47. except Exception as e:
  48. logger.error("Error comparing headlines (%r vs %r): %s",
  49. self.display_text, getattr(other_headline, 'display_text', repr(other_headline)), e, exc_info=True)
  50. raise