Add1E commited on
Commit
e266815
·
verified ·
1 Parent(s): d775d1c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +368 -369
app.py CHANGED
@@ -1,370 +1,369 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import xml.etree.ElementTree as ET
4
- import requests
5
- from datetime import datetime
6
- import pytz
7
- import hmac
8
- import os
9
- import time
10
- from PIL import Image
11
- from trend_crawl import get_trends
12
-
13
- import re
14
-
15
- TREND_TOPICS = {
16
- 1: "Autos and Vehicles",
17
- 2: "Beauty and Fashion",
18
- 3: "Business and Finance",
19
- 20: "Climate",
20
- 4: "Entertainment",
21
- 5: "Food and Drink",
22
- 6: "Games",
23
- 7: "Health",
24
- 8: "Hobbies and Leisure",
25
- 9: "Jobs and Education",
26
- 10: "Law and Government",
27
- 11: "Other",
28
- 13: "Pets and Animals",
29
- 14: "Politics",
30
- 15: "Science",
31
- 16: "Shopping",
32
- 17: "Sports",
33
- 18: "Technology",
34
- 19: "Travel and Transportation"
35
- }
36
- os.environ["PASSWORD"] = "heute_123"
37
-
38
- def parse_url(url):
39
- response = requests.get(url)
40
-
41
- root = ET.fromstring(response.content)
42
- return root
43
-
44
- def convert_into_dict(req_json):
45
- result = {}
46
-
47
- # Iterate over each category in the JSON data
48
- for category, entries in req_json.items():
49
- # Initialize the category if not already in result
50
- if category not in result:
51
- result[category] = {}
52
-
53
- for entry in entries:
54
- # Extract 'entityName' and 'searchQueries' from 'static_data'
55
- static_data = entry.get("static_data", [])
56
- if static_data and len(static_data[0]) >= 4:
57
- entity_name = static_data[0][0] # First element
58
- search_queries = static_data[0][3] # Fourth element
59
- else:
60
- entity_name = None
61
- search_queries = None
62
-
63
- # Initialize the entity under the category if not already present
64
- if entity_name:
65
- if entity_name not in result[category]:
66
- result[category][entity_name] = {
67
- "searchQueries": search_queries,
68
- "articles": []
69
- }
70
-
71
- # Extract articles from 'dynamic_data'
72
- articles = entry.get("dynamic_data", {}).get("article", [])
73
- for article in articles:
74
- href = article.get("href")
75
- article_title = article.get("title")
76
-
77
- # Append the article information to the corresponding entity's article list
78
- result[category][entity_name]["articles"].append({
79
- "href": href,
80
- "title": article_title
81
- })
82
-
83
- return result
84
-
85
-
86
- def find_details(req_json, gewünschter_titel):
87
- gewünschte_details = []
88
- for trend_info in req_json:
89
- if trend_info['title'] == gewünschter_titel:
90
-
91
- for article in trend_info['articles']:
92
- article_details = {
93
- 'url': article['url'],
94
- 'snippet': article['snippet'],
95
- 'articleTitle': article['articleTitle'],
96
- 'time': article['time'],
97
- 'source' : article['source']
98
- }
99
-
100
- gewünschte_details.append(article_details)
101
- return gewünschte_details
102
-
103
- def find_details2(req_json):
104
- gewünschte_details = []
105
-
106
- for article in req_json:
107
- article_details = {
108
- 'url': article['url'],
109
- 'snippet': article['snippet'],
110
- 'articleTitle': article['title'],
111
- 'source' : article['source']
112
-
113
- }
114
-
115
- gewünschte_details.append(article_details)
116
- return gewünschte_details
117
-
118
- if 'reset' not in st.session_state:
119
- st.session_state.reset = False
120
-
121
- def display_trends_from_yesterday():
122
- checkbox_statuses = {}
123
- urls = []
124
-
125
- timezone = 'Europe/Vienna'
126
- today = datetime.now(pytz.timezone(timezone)).date()
127
- feed = parse_url(feed_url1)
128
- entries = []
129
- ns = {'ht': 'https://trends.google.de/trends/trendingsearches/daily'} # Define namespace
130
- for item in feed.findall('.//item'):
131
- pubDate = datetime.strptime(item.find('pubDate').text, '%a, %d %b %Y %H:%M:%S %z').date()
132
- # Filter: Überspringe, wenn pubDate heute ist
133
- if pubDate == today:
134
- continue
135
- entry = {
136
- 'title': item.find('title').text,
137
- 'pubDate': item.find('pubDate').text,
138
- 'approx_traffic': item.find('ht:approx_traffic', ns).text if item.find('ht:approx_traffic', ns) is not None else None,
139
- 'news_items': []
140
- }
141
- for news_item in item.findall('ht:news_item', ns):
142
- news_details = {
143
- 'title': news_item.find('ht:news_item_title', ns).text,
144
- 'snippet': news_item.find('ht:news_item_snippet', ns).text,
145
- 'url': news_item.find('ht:news_item_url', ns).text,
146
- 'source': news_item.find('ht:news_item_source', ns).text
147
- }
148
- entry['news_items'].append(news_details)
149
- entries.append(entry)
150
-
151
- count = 1
152
- for entry in entries:
153
- with st.expander(f"{count}• {entry['title']} | Generated Traffic: {entry['approx_traffic']}"):
154
- st.write(f"Veröffentlichungsdatum : {entry['pubDate']}")
155
- for count2, link in enumerate(entry['news_items'], start=1):
156
- checkbox_label = f"yesterday_{count}_{count2}"
157
- if st.session_state.reset:
158
- st.session_state[checkbox_label] = False
159
- checkbox_statuses[checkbox_label] = st.session_state.get(checkbox_label, False)
160
- checkbox_statuses[checkbox_label] = st.checkbox(
161
- f"{count2}• {link['title']} | {link['source']} | [Go To →]({link['url']})",
162
- value=checkbox_statuses[checkbox_label],
163
- key=checkbox_label
164
- )
165
- if checkbox_statuses[checkbox_label]:
166
- urls.append(link['url'])
167
-
168
- # Button am Ende des Expanders
169
- base_url = os.getenv("url")
170
- query_params = "&".join([f"article-links[]={url}" for url in urls])
171
- full_url = f"{base_url}{query_params}"
172
- st.link_button("Open All Links" , url= full_url)
173
- count += 1
174
-
175
-
176
-
177
- # Function to display articles for a specific category
178
- def display_articles_for_category(category):
179
- checkbox_statuses = {}
180
- urls = []
181
-
182
- trending_data = st.session_state["real_trending_searches"][selected_country][selected_country][category]
183
- #st.write(trending_data)
184
- if st.session_state.get("reset", False):
185
- for idx, (topic, data) in enumerate(trending_data.items()):
186
- for article_index, _ in enumerate(data["articles"]):
187
- checkbox_label = f"{category}_{idx}_{article_index + 1}"
188
- st.session_state[checkbox_label] = False
189
-
190
- for idx, (topic, data) in enumerate(trending_data.items()):
191
-
192
-
193
- with st.expander(f"{idx + 1}• {topic} | Generated Traffic: {data['searchQueries']}"):
194
-
195
- for article_index, article in enumerate(data["articles"], start=1):
196
- checkbox_label = f"{category}_{idx}_{article_index}"
197
-
198
-
199
- current_value = st.session_state.get(checkbox_label, False)
200
- checkbox_statuses[checkbox_label] = current_value
201
-
202
-
203
- disabled = (not current_value) and (sum(checkbox_statuses.values()) >= MAX_CHECKED)
204
-
205
- checkbox_statuses[checkbox_label] = st.checkbox(
206
- f"{article_index}• {article['title']} | [Go To →]({article['href']})",
207
- value=current_value,
208
- key=checkbox_label,
209
- disabled=disabled
210
- )
211
-
212
- if checkbox_statuses[checkbox_label]:
213
- urls.append(article["href"])
214
-
215
- base_url = os.getenv("url", "https://example.com/?")
216
- query_params = "&".join([f"article-links[]={u}" for u in urls])
217
- full_url = f"{base_url}{query_params}"
218
- st.link_button("Open All Links", url=full_url)
219
-
220
- # Funktion zum Rendern von Artikeln für heute
221
- def display_articles_for_today(count, index):
222
- checkbox_statuses = {}
223
- urls = []
224
- # Dictionary zur Verwaltung des Status jeder Checkbox
225
- for count2, url in enumerate(index['articles'], start=1):
226
- checkbox_label = f"today_{count}_{count2}"
227
- if st.session_state.reset:
228
- st.session_state[checkbox_label] = False
229
- checkbox_statuses[checkbox_label] = st.session_state.get(checkbox_label, False)
230
-
231
-
232
- with st.expander(f"{count+1}• {index['title']['query']} | Generated Traffic: {index['formattedTraffic']}"):
233
- articles = find_details2(index['articles'])
234
- for count2, url in enumerate(articles, start=1):
235
- checkbox_label = f"today_{count}_{count2}"
236
- disabled = not checkbox_statuses[checkbox_label] and sum(checkbox_statuses.values()) >= MAX_CHECKED
237
- checkbox_statuses[checkbox_label] = st.checkbox(
238
- f"{count2}• {url['articleTitle']} | {url['source']} | [Go To →]({url['url']})",
239
- value=checkbox_statuses[checkbox_label],
240
- key=checkbox_label,
241
- disabled=disabled
242
- )
243
- if checkbox_statuses[checkbox_label]:
244
- urls.append(url['url'])
245
-
246
- # Button am Ende des Expanders
247
- base_url = os.getenv("url")
248
- query_params = "&".join([f"article-links[]={url}" for url in urls])
249
- full_url = f"{base_url}{query_params}"
250
- st.link_button("Open All Links" , url= full_url)
251
-
252
-
253
- country_list = {
254
- "Germamy" : "DE",
255
- "Austria" : "AT"
256
- }
257
-
258
- if 'base_load_finished' not in st.session_state:
259
- st.session_state["real_trending_searches"] = {}
260
- st.session_state["base_data"] = {}
261
- st.session_state["pn"] = "AT"
262
- print(st.session_state.reset)
263
- if 'base_load_finished' not in st.session_state or st.session_state.reset:
264
- with st.spinner("Loading Trends"):
265
- st.session_state["today"] = {}
266
- st.session_state["base"] = {}
267
- for country_name, pn_option in country_list.items():
268
- st.session_state["base_data"][pn_option] = {}
269
- st.session_state["real_trending_searches"][pn_option] = {}
270
- st.session_state["real_trending_searches"][pn_option] = get_trends([pn_option])
271
-
272
- st.session_state["base_load_finished"]= True
273
-
274
-
275
- MAX_CHECKED = 3
276
-
277
- def check_password():
278
- """Returns `True` if the user had the correct password."""
279
-
280
- def password_entered():
281
- """Checks whether a password entered by the user is correct."""
282
- if hmac.compare_digest(st.session_state["password"], os.environ.get("PASSWORD")):
283
- st.session_state["password_correct"] = True
284
-
285
- del st.session_state["password"] # Don't store the password.
286
- else:
287
- st.session_state["password_correct"] = False
288
-
289
-
290
- # Return True if the password is validated.
291
- if st.session_state.get("password_correct", False):
292
- return True
293
-
294
- # Show input for password.
295
- st.text_input(
296
- "Password", type="password", on_change=password_entered, key="password"
297
- )
298
- if "password_correct" in st.session_state:
299
- st.error("😕 Password incorrect")
300
- return False
301
-
302
-
303
- if not check_password():
304
- st.stop() # Do not continue if check_password is not True.
305
-
306
- fixed_order = [
307
- "All categories",
308
- "Autos and Vehicles",
309
- "Beauty and Fashion",
310
- "Business and Finance",
311
- "Climate",
312
- "Entertainment",
313
- "Food and Drink",
314
- "Games",
315
- "Health",
316
- "Hobbies and Leisure",
317
- "Jobs and Education",
318
- "Law and Government",
319
- "Other",
320
- "Pets and Animals",
321
- "Politics",
322
- "Science",
323
- "Shopping",
324
- "Sports",
325
- "Technology",
326
- "Travel and Transportation",
327
- ]
328
-
329
- if 'selected_option' not in st.session_state:
330
- st.session_state['selected_option'] = "default_value"
331
-
332
- img = Image.open(r"heute_tensora.png")
333
- st.sidebar.image(img)
334
-
335
- # Selectbox to choose a country
336
- selected_country = st.sidebar.selectbox("Choose a Country", ["AT", "DE"])
337
- feed_url1 = f'https://trends.google.de/trends/trendingsearches/daily/rss?geo={selected_country}'
338
-
339
- # Button to trigger actions
340
- if st.sidebar.button("Change Country"):
341
- if selected_country == "AT":
342
- st.session_state["pn"] = selected_country
343
- elif selected_country == "DE":
344
- st.session_state["pn"] = selected_country
345
-
346
- selected_option = st.sidebar.radio("Choose an option", ["Realzeit Anfragen", "Trends von Gestern"])#, "Tagesaktuelle Anfragen"
347
- st.warning("Die aufgelisteten Keywörter für erhöhte Reichweite in den Überschriften verwenden")
348
-
349
- #if selected_option == "Tagesaktuelle Anfragen":
350
- #
351
- # for count, index in enumerate(st.session_state["today"][selected_country], start=0):
352
- # try:
353
- # display_articles_for_today(count, index)
354
- # except Exception as e:
355
- # st.code(e)
356
- # continue
357
- if selected_option == "Realzeit Anfragen":
358
- available_topics = st.session_state["real_trending_searches"][selected_country][selected_country].keys()
359
- filtered_topics = [topic for topic in TREND_TOPICS.values() if topic in available_topics]
360
- all_topics = ["All categories"] + filtered_topics
361
- auswahl = st.selectbox("Select Ressort", all_topics, index=0)
362
-
363
- display_articles_for_category(auswahl)
364
-
365
- elif selected_option == "Trends von Gestern":
366
- st.error("Aktuell nicht Erreichbar")
367
- #display_trends_from_yesterday()
368
-
369
- if st.session_state.reset:
370
  st.session_state["reset"] = False
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import xml.etree.ElementTree as ET
4
+ import requests
5
+ from datetime import datetime
6
+ import pytz
7
+ import hmac
8
+ import os
9
+ import time
10
+ from PIL import Image
11
+ from trend_crawl import get_trends
12
+
13
+ import re
14
+
15
+ TREND_TOPICS = {
16
+ 1: "Autos and Vehicles",
17
+ 2: "Beauty and Fashion",
18
+ 3: "Business and Finance",
19
+ 20: "Climate",
20
+ 4: "Entertainment",
21
+ 5: "Food and Drink",
22
+ 6: "Games",
23
+ 7: "Health",
24
+ 8: "Hobbies and Leisure",
25
+ 9: "Jobs and Education",
26
+ 10: "Law and Government",
27
+ 11: "Other",
28
+ 13: "Pets and Animals",
29
+ 14: "Politics",
30
+ 15: "Science",
31
+ 16: "Shopping",
32
+ 17: "Sports",
33
+ 18: "Technology",
34
+ 19: "Travel and Transportation"
35
+ }
36
+
37
+ def parse_url(url):
38
+ response = requests.get(url)
39
+
40
+ root = ET.fromstring(response.content)
41
+ return root
42
+
43
+ def convert_into_dict(req_json):
44
+ result = {}
45
+
46
+ # Iterate over each category in the JSON data
47
+ for category, entries in req_json.items():
48
+ # Initialize the category if not already in result
49
+ if category not in result:
50
+ result[category] = {}
51
+
52
+ for entry in entries:
53
+ # Extract 'entityName' and 'searchQueries' from 'static_data'
54
+ static_data = entry.get("static_data", [])
55
+ if static_data and len(static_data[0]) >= 4:
56
+ entity_name = static_data[0][0] # First element
57
+ search_queries = static_data[0][3] # Fourth element
58
+ else:
59
+ entity_name = None
60
+ search_queries = None
61
+
62
+ # Initialize the entity under the category if not already present
63
+ if entity_name:
64
+ if entity_name not in result[category]:
65
+ result[category][entity_name] = {
66
+ "searchQueries": search_queries,
67
+ "articles": []
68
+ }
69
+
70
+ # Extract articles from 'dynamic_data'
71
+ articles = entry.get("dynamic_data", {}).get("article", [])
72
+ for article in articles:
73
+ href = article.get("href")
74
+ article_title = article.get("title")
75
+
76
+ # Append the article information to the corresponding entity's article list
77
+ result[category][entity_name]["articles"].append({
78
+ "href": href,
79
+ "title": article_title
80
+ })
81
+
82
+ return result
83
+
84
+
85
+ def find_details(req_json, gewünschter_titel):
86
+ gewünschte_details = []
87
+ for trend_info in req_json:
88
+ if trend_info['title'] == gewünschter_titel:
89
+
90
+ for article in trend_info['articles']:
91
+ article_details = {
92
+ 'url': article['url'],
93
+ 'snippet': article['snippet'],
94
+ 'articleTitle': article['articleTitle'],
95
+ 'time': article['time'],
96
+ 'source' : article['source']
97
+ }
98
+
99
+ gewünschte_details.append(article_details)
100
+ return gewünschte_details
101
+
102
+ def find_details2(req_json):
103
+ gewünschte_details = []
104
+
105
+ for article in req_json:
106
+ article_details = {
107
+ 'url': article['url'],
108
+ 'snippet': article['snippet'],
109
+ 'articleTitle': article['title'],
110
+ 'source' : article['source']
111
+
112
+ }
113
+
114
+ gewünschte_details.append(article_details)
115
+ return gewünschte_details
116
+
117
+ if 'reset' not in st.session_state:
118
+ st.session_state.reset = False
119
+
120
+ def display_trends_from_yesterday():
121
+ checkbox_statuses = {}
122
+ urls = []
123
+
124
+ timezone = 'Europe/Vienna'
125
+ today = datetime.now(pytz.timezone(timezone)).date()
126
+ feed = parse_url(feed_url1)
127
+ entries = []
128
+ ns = {'ht': 'https://trends.google.de/trends/trendingsearches/daily'} # Define namespace
129
+ for item in feed.findall('.//item'):
130
+ pubDate = datetime.strptime(item.find('pubDate').text, '%a, %d %b %Y %H:%M:%S %z').date()
131
+ # Filter: Überspringe, wenn pubDate heute ist
132
+ if pubDate == today:
133
+ continue
134
+ entry = {
135
+ 'title': item.find('title').text,
136
+ 'pubDate': item.find('pubDate').text,
137
+ 'approx_traffic': item.find('ht:approx_traffic', ns).text if item.find('ht:approx_traffic', ns) is not None else None,
138
+ 'news_items': []
139
+ }
140
+ for news_item in item.findall('ht:news_item', ns):
141
+ news_details = {
142
+ 'title': news_item.find('ht:news_item_title', ns).text,
143
+ 'snippet': news_item.find('ht:news_item_snippet', ns).text,
144
+ 'url': news_item.find('ht:news_item_url', ns).text,
145
+ 'source': news_item.find('ht:news_item_source', ns).text
146
+ }
147
+ entry['news_items'].append(news_details)
148
+ entries.append(entry)
149
+
150
+ count = 1
151
+ for entry in entries:
152
+ with st.expander(f"{count}• {entry['title']} | Generated Traffic: {entry['approx_traffic']}"):
153
+ st.write(f"Veröffentlichungsdatum : {entry['pubDate']}")
154
+ for count2, link in enumerate(entry['news_items'], start=1):
155
+ checkbox_label = f"yesterday_{count}_{count2}"
156
+ if st.session_state.reset:
157
+ st.session_state[checkbox_label] = False
158
+ checkbox_statuses[checkbox_label] = st.session_state.get(checkbox_label, False)
159
+ checkbox_statuses[checkbox_label] = st.checkbox(
160
+ f"{count2}• {link['title']} | {link['source']} | [Go To →]({link['url']})",
161
+ value=checkbox_statuses[checkbox_label],
162
+ key=checkbox_label
163
+ )
164
+ if checkbox_statuses[checkbox_label]:
165
+ urls.append(link['url'])
166
+
167
+ # Button am Ende des Expanders
168
+ base_url = os.getenv("url")
169
+ query_params = "&".join([f"article-links[]={url}" for url in urls])
170
+ full_url = f"{base_url}{query_params}"
171
+ st.link_button("Open All Links" , url= full_url)
172
+ count += 1
173
+
174
+
175
+
176
+ # Function to display articles for a specific category
177
+ def display_articles_for_category(category):
178
+ checkbox_statuses = {}
179
+ urls = []
180
+
181
+ trending_data = st.session_state["real_trending_searches"][selected_country][selected_country][category]
182
+ #st.write(trending_data)
183
+ if st.session_state.get("reset", False):
184
+ for idx, (topic, data) in enumerate(trending_data.items()):
185
+ for article_index, _ in enumerate(data["articles"]):
186
+ checkbox_label = f"{category}_{idx}_{article_index + 1}"
187
+ st.session_state[checkbox_label] = False
188
+
189
+ for idx, (topic, data) in enumerate(trending_data.items()):
190
+
191
+
192
+ with st.expander(f"{idx + 1}• {topic} | Generated Traffic: {data['searchQueries']}"):
193
+
194
+ for article_index, article in enumerate(data["articles"], start=1):
195
+ checkbox_label = f"{category}_{idx}_{article_index}"
196
+
197
+
198
+ current_value = st.session_state.get(checkbox_label, False)
199
+ checkbox_statuses[checkbox_label] = current_value
200
+
201
+
202
+ disabled = (not current_value) and (sum(checkbox_statuses.values()) >= MAX_CHECKED)
203
+
204
+ checkbox_statuses[checkbox_label] = st.checkbox(
205
+ f"{article_index}• {article['title']} | [Go To →]({article['href']})",
206
+ value=current_value,
207
+ key=checkbox_label,
208
+ disabled=disabled
209
+ )
210
+
211
+ if checkbox_statuses[checkbox_label]:
212
+ urls.append(article["href"])
213
+
214
+ base_url = os.getenv("url", "https://example.com/?")
215
+ query_params = "&".join([f"article-links[]={u}" for u in urls])
216
+ full_url = f"{base_url}{query_params}"
217
+ st.link_button("Open All Links", url=full_url)
218
+
219
+ # Funktion zum Rendern von Artikeln für heute
220
+ def display_articles_for_today(count, index):
221
+ checkbox_statuses = {}
222
+ urls = []
223
+ # Dictionary zur Verwaltung des Status jeder Checkbox
224
+ for count2, url in enumerate(index['articles'], start=1):
225
+ checkbox_label = f"today_{count}_{count2}"
226
+ if st.session_state.reset:
227
+ st.session_state[checkbox_label] = False
228
+ checkbox_statuses[checkbox_label] = st.session_state.get(checkbox_label, False)
229
+
230
+
231
+ with st.expander(f"{count+1}• {index['title']['query']} | Generated Traffic: {index['formattedTraffic']}"):
232
+ articles = find_details2(index['articles'])
233
+ for count2, url in enumerate(articles, start=1):
234
+ checkbox_label = f"today_{count}_{count2}"
235
+ disabled = not checkbox_statuses[checkbox_label] and sum(checkbox_statuses.values()) >= MAX_CHECKED
236
+ checkbox_statuses[checkbox_label] = st.checkbox(
237
+ f"{count2}• {url['articleTitle']} | {url['source']} | [Go To →]({url['url']})",
238
+ value=checkbox_statuses[checkbox_label],
239
+ key=checkbox_label,
240
+ disabled=disabled
241
+ )
242
+ if checkbox_statuses[checkbox_label]:
243
+ urls.append(url['url'])
244
+
245
+ # Button am Ende des Expanders
246
+ base_url = os.getenv("url")
247
+ query_params = "&".join([f"article-links[]={url}" for url in urls])
248
+ full_url = f"{base_url}{query_params}"
249
+ st.link_button("Open All Links" , url= full_url)
250
+
251
+
252
+ country_list = {
253
+ "Germamy" : "DE",
254
+ "Austria" : "AT"
255
+ }
256
+
257
+ if 'base_load_finished' not in st.session_state:
258
+ st.session_state["real_trending_searches"] = {}
259
+ st.session_state["base_data"] = {}
260
+ st.session_state["pn"] = "AT"
261
+ print(st.session_state.reset)
262
+ if 'base_load_finished' not in st.session_state or st.session_state.reset:
263
+ with st.spinner("Loading Trends"):
264
+ st.session_state["today"] = {}
265
+ st.session_state["base"] = {}
266
+ for country_name, pn_option in country_list.items():
267
+ st.session_state["base_data"][pn_option] = {}
268
+ st.session_state["real_trending_searches"][pn_option] = {}
269
+ st.session_state["real_trending_searches"][pn_option] = get_trends([pn_option])
270
+
271
+ st.session_state["base_load_finished"]= True
272
+
273
+
274
+ MAX_CHECKED = 3
275
+
276
+ def check_password():
277
+ """Returns `True` if the user had the correct password."""
278
+
279
+ def password_entered():
280
+ """Checks whether a password entered by the user is correct."""
281
+ if hmac.compare_digest(st.session_state["password"], os.environ.get("PASSWORD")):
282
+ st.session_state["password_correct"] = True
283
+
284
+ del st.session_state["password"] # Don't store the password.
285
+ else:
286
+ st.session_state["password_correct"] = False
287
+
288
+
289
+ # Return True if the password is validated.
290
+ if st.session_state.get("password_correct", False):
291
+ return True
292
+
293
+ # Show input for password.
294
+ st.text_input(
295
+ "Password", type="password", on_change=password_entered, key="password"
296
+ )
297
+ if "password_correct" in st.session_state:
298
+ st.error("😕 Password incorrect")
299
+ return False
300
+
301
+
302
+ if not check_password():
303
+ st.stop() # Do not continue if check_password is not True.
304
+
305
+ fixed_order = [
306
+ "All categories",
307
+ "Autos and Vehicles",
308
+ "Beauty and Fashion",
309
+ "Business and Finance",
310
+ "Climate",
311
+ "Entertainment",
312
+ "Food and Drink",
313
+ "Games",
314
+ "Health",
315
+ "Hobbies and Leisure",
316
+ "Jobs and Education",
317
+ "Law and Government",
318
+ "Other",
319
+ "Pets and Animals",
320
+ "Politics",
321
+ "Science",
322
+ "Shopping",
323
+ "Sports",
324
+ "Technology",
325
+ "Travel and Transportation",
326
+ ]
327
+
328
+ if 'selected_option' not in st.session_state:
329
+ st.session_state['selected_option'] = "default_value"
330
+
331
+ img = Image.open(r"heute_tensora.png")
332
+ st.sidebar.image(img)
333
+
334
+ # Selectbox to choose a country
335
+ selected_country = st.sidebar.selectbox("Choose a Country", ["AT", "DE"])
336
+ feed_url1 = f'https://trends.google.de/trends/trendingsearches/daily/rss?geo={selected_country}'
337
+
338
+ # Button to trigger actions
339
+ if st.sidebar.button("Change Country"):
340
+ if selected_country == "AT":
341
+ st.session_state["pn"] = selected_country
342
+ elif selected_country == "DE":
343
+ st.session_state["pn"] = selected_country
344
+
345
+ selected_option = st.sidebar.radio("Choose an option", ["Realzeit Anfragen", "Trends von Gestern"])#, "Tagesaktuelle Anfragen"
346
+ st.warning("Die aufgelisteten Keywörter für erhöhte Reichweite in den Überschriften verwenden")
347
+
348
+ #if selected_option == "Tagesaktuelle Anfragen":
349
+ #
350
+ # for count, index in enumerate(st.session_state["today"][selected_country], start=0):
351
+ # try:
352
+ # display_articles_for_today(count, index)
353
+ # except Exception as e:
354
+ # st.code(e)
355
+ # continue
356
+ if selected_option == "Realzeit Anfragen":
357
+ available_topics = st.session_state["real_trending_searches"][selected_country][selected_country].keys()
358
+ filtered_topics = [topic for topic in TREND_TOPICS.values() if topic in available_topics]
359
+ all_topics = ["All categories"] + filtered_topics
360
+ auswahl = st.selectbox("Select Ressort", all_topics, index=0)
361
+
362
+ display_articles_for_category(auswahl)
363
+
364
+ elif selected_option == "Trends von Gestern":
365
+ st.error("Aktuell nicht Erreichbar")
366
+ #display_trends_from_yesterday()
367
+
368
+ if st.session_state.reset:
 
369
  st.session_state["reset"] = False