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