Spaces:
Running
Running
File size: 2,818 Bytes
56cfe41 d775d1c d28e0f9 2d60cc9 56cfe41 f16f664 489b3d9 122d3b3 56cfe41 122d3b3 56cfe41 122d3b3 7af931a 289ca7f 7af931a 122d3b3 56cfe41 122d3b3 56cfe41 00b85ba 56cfe41 d775d1c 00b85ba 56cfe41 2d60cc9 56cfe41 d775d1c 56cfe41 d775d1c f16f664 56cfe41 2d60cc9 56cfe41 00b85ba 2d60cc9 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
from trendspy import Trends
import streamlit as st
from datetime import datetime, timezone, timedelta
tr = Trends()
TREND_TOPICS = {
1: "Autos and Vehicles",
2: "Beauty and Fashion",
3: "Business and Finance",
20: "Climate",
4: "Entertainment",
5: "Food and Drink",
6: "Games",
7: "Health",
8: "Hobbies and Leisure",
9: "Jobs and Education",
10: "Law and Government",
11: "Other",
13: "Pets and Animals",
14: "Politics",
15: "Science",
16: "Shopping",
17: "Sports",
18: "Technology",
19: "Travel and Transportation"
}
trends_json = {}
def process_trends_for_country(country_code, trends_list):
if country_code not in trends_json:
trends_json[country_code] = {"All categories" : {}}
for trend in trends_list:
timestamp = convert_to_datetime(trend.started_timestamp[0])
current_time = datetime.now(timezone.utc)
print(current_time - timestamp)
if current_time - timestamp > timedelta(days=2):
continue
category = None
for topic_id in trend.topics:
if topic_id in TREND_TOPICS:
category = TREND_TOPICS[topic_id]
break
if category is None:
category = TREND_TOPICS[11]
if category not in trends_json[country_code]:
trends_json[country_code][category] = {}
topic_name = trend.keyword
try:
news = tr.trending_now_news_by_ids(trend.news_tokens, max_news=3)
articles = [
{"title": article.title, "href": article.url}
for article in news
]
except Exception as e:
articles=[]
trends_json[country_code]["All categories"][topic_name] = {
"searchQueries": trend.volume,
"articles": articles,
"is_trend_finished": trend.is_trend_finished,
}
trends_json[country_code][category][topic_name] = {
"searchQueries": trend.volume,
"articles": articles,
}
def convert_to_datetime( raw_time):
"""Converts time in seconds to a datetime object with UTC timezone, if it exists."""
return datetime.fromtimestamp(raw_time, tz=timezone.utc) if raw_time else None
def get_trends(countries: list):
for country in countries:
trends = tr.trending_now(geo=country)
process_trends_for_country(country, trends)
all_categories = trends_json[country]["All categories"]
# sorted_all_categories = dict(
# sorted(all_categories.items(), key=lambda x: x[1]["searchQueries"], reverse=True)
# )
#trends_json[country]["All categories"] = sorted_all_categories
return trends_json
|