SHAFI commited on
Commit
d3e3e7e
Β·
1 Parent(s): 82bd507

updated freshnews logic

Browse files
app/services/news_providers.py CHANGED
@@ -1,6 +1,6 @@
1
  import httpx
2
  from typing import List, Optional, Dict
3
- from datetime import datetime
4
  from abc import ABC, abstractmethod
5
  from app.models import Article
6
  import os
@@ -86,12 +86,22 @@ class GNewsProvider(NewsProvider):
86
  try:
87
  query = self.category_map.get(category, category)
88
  url = f"{self.base_url}/search"
 
 
 
 
 
 
 
 
89
  params = {
90
  'q': query,
91
  'lang': 'en',
92
  'country': 'us',
93
  'max': min(limit, 10), # GNews free tier max 10
94
- 'apikey': self.api_key
 
 
95
  }
96
 
97
  async with httpx.AsyncClient(timeout=10.0) as client:
@@ -184,12 +194,18 @@ class NewsAPIProvider(NewsProvider):
184
  try:
185
  query = self.category_keywords.get(category, category)
186
  url = f"{self.base_url}/everything"
 
 
 
 
 
187
  params = {
188
  'q': query,
189
  'language': 'en',
190
  'sortBy': 'publishedAt',
191
  'pageSize': min(limit, 20),
192
- 'apiKey': self.api_key
 
193
  }
194
 
195
  async with httpx.AsyncClient(timeout=10.0) as client:
@@ -273,11 +289,16 @@ class NewsDataProvider(NewsProvider):
273
  try:
274
  query = self.category_keywords.get(category, category)
275
  url = f"{self.base_url}/news"
 
 
 
 
276
  params = {
277
  'q': query,
278
  'language': 'en',
279
  'country': 'us',
280
- 'apikey': self.api_key
 
281
  }
282
 
283
  async with httpx.AsyncClient(timeout=10.0) as client:
 
1
  import httpx
2
  from typing import List, Optional, Dict
3
+ from datetime import datetime, timezone, timedelta
4
  from abc import ABC, abstractmethod
5
  from app.models import Article
6
  import os
 
86
  try:
87
  query = self.category_map.get(category, category)
88
  url = f"{self.base_url}/search"
89
+
90
+ # Build a window from midnight UTC today to right now.
91
+ # This is a strict CALENDAR DAY filter, not a rolling 24-hour window.
92
+ # A job running at 11:59 PM will still only fetch today's articles,
93
+ # not anything from yesterday.
94
+ _now = datetime.now(timezone.utc)
95
+ _cutoff = _now.replace(hour=0, minute=0, second=0, microsecond=0) # 00:00:00 UTC today
96
+
97
  params = {
98
  'q': query,
99
  'lang': 'en',
100
  'country': 'us',
101
  'max': min(limit, 10), # GNews free tier max 10
102
+ 'apikey': self.api_key,
103
+ 'from': _cutoff.strftime('%Y-%m-%dT%H:%M:%SZ'),
104
+ 'to': _now.strftime('%Y-%m-%dT%H:%M:%SZ'),
105
  }
106
 
107
  async with httpx.AsyncClient(timeout=10.0) as client:
 
194
  try:
195
  query = self.category_keywords.get(category, category)
196
  url = f"{self.base_url}/everything"
197
+
198
+ # Ask NewsAPI for articles published since midnight UTC today.
199
+ # Calendar day window: resets cleanly at 00:00:00 UTC every day.
200
+ _cutoff = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
201
+
202
  params = {
203
  'q': query,
204
  'language': 'en',
205
  'sortBy': 'publishedAt',
206
  'pageSize': min(limit, 20),
207
+ 'apiKey': self.api_key,
208
+ 'from': _cutoff.strftime('%Y-%m-%dT%H:%M:%SZ'),
209
  }
210
 
211
  async with httpx.AsyncClient(timeout=10.0) as client:
 
289
  try:
290
  query = self.category_keywords.get(category, category)
291
  url = f"{self.base_url}/news"
292
+
293
+ # NewsData has a built-in 'timeframe' parameter (in hours).
294
+ # Setting it to 24 tells their server: "only send today's articles".
295
+ # This is the cleanest approach β€” no date maths needed on our side.
296
  params = {
297
  'q': query,
298
  'language': 'en',
299
  'country': 'us',
300
+ 'apikey': self.api_key,
301
+ 'timeframe': 24,
302
  }
303
 
304
  async with httpx.AsyncClient(timeout=10.0) as client:
app/utils/data_validation.py CHANGED
@@ -8,9 +8,10 @@ EMERGENCY HOTFIX (2026-01-23): Fixed AttributeError 'Article' object has no attr
8
  """
9
 
10
  from typing import Dict, Optional, List, Union
11
- from datetime import datetime
12
  import re
13
  from urllib.parse import urlparse
 
14
 
15
 
16
  def is_valid_article(article: Union[Dict, 'Article']) -> bool:
@@ -64,10 +65,49 @@ def is_valid_article(article: Union[Dict, 'Article']) -> bool:
64
  except Exception:
65
  return False
66
 
67
- # Required: Published date
68
- if not (article_dict.get('publishedAt') or article_dict.get('published_at')):
 
69
  return False
70
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
  # Optional but validate if present: Image URL
72
  # Handle both 'image' (raw API) and 'image_url' (Pydantic/DB)
73
  image_url = article_dict.get('image') or article_dict.get('image_url')
@@ -77,7 +117,7 @@ def is_valid_article(article: Union[Dict, 'Article']) -> bool:
77
  # Invalid image URL - remove both keys to be safe
78
  if 'image' in article_dict: article_dict['image'] = None
79
  if 'image_url' in article_dict: article_dict['image_url'] = None
80
-
81
  return True
82
 
83
 
 
8
  """
9
 
10
  from typing import Dict, Optional, List, Union
11
+ from datetime import datetime, timezone, timedelta
12
  import re
13
  from urllib.parse import urlparse
14
+ from dateutil import parser as dateutil_parser
15
 
16
 
17
  def is_valid_article(article: Union[Dict, 'Article']) -> bool:
 
65
  except Exception:
66
  return False
67
 
68
+ # Required: Published date must exist.
69
+ raw_date = article_dict.get('publishedAt') or article_dict.get('published_at')
70
+ if not raw_date:
71
  return False
72
+
73
+ # ── FRESHNESS GATE ────────────────────────────────────────────────────────
74
+ # We only want articles published within the last 24 hours.
75
+ #
76
+ # CRITICAL ORDER: This check runs on the RAW date string, before
77
+ # normalize_article_date() gets a chance to run. That function has a
78
+ # silent fallback: if a date is unparseable it stamps the article with
79
+ # 'right now'. Without this guard, a 3-day-old article with a broken
80
+ # date string would survive normalization and appear fresh.
81
+ #
82
+ # Here we do the opposite: if we cannot confidently parse the date,
83
+ # we reject the article. No date = no entry.
84
+ try:
85
+ if isinstance(raw_date, datetime):
86
+ pub_dt = raw_date
87
+ else:
88
+ pub_dt = dateutil_parser.parse(str(raw_date))
89
+
90
+ # Make timezone-aware if the provider gave us a naive datetime.
91
+ if pub_dt.tzinfo is None:
92
+ pub_dt = pub_dt.replace(tzinfo=timezone.utc)
93
+
94
+ # Midnight UTC today β€” strict calendar day, not a rolling 24h window.
95
+ # Example: at 11:59 PM, this is still 00:00:00 of the current day,
96
+ # so only today's articles pass. Yesterday's articles are rejected
97
+ # regardless of what time the job fires.
98
+ cutoff = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
99
+
100
+ if pub_dt < cutoff:
101
+ # Article is older than 24 hours β€” reject it here before any
102
+ # keyword matching or Redis dedup call wastes time on it.
103
+ return False
104
+
105
+ except Exception:
106
+ # If we genuinely cannot parse the date, we reject the article.
107
+ # Better to miss one article than to save a zombie with a fake date.
108
+ return False
109
+ # ──────────────────────────────────────────────────────────────────────────
110
+
111
  # Optional but validate if present: Image URL
112
  # Handle both 'image' (raw API) and 'image_url' (Pydantic/DB)
113
  image_url = article_dict.get('image') or article_dict.get('image_url')
 
117
  # Invalid image URL - remove both keys to be safe
118
  if 'image' in article_dict: article_dict['image'] = None
119
  if 'image_url' in article_dict: article_dict['image_url'] = None
120
+
121
  return True
122
 
123