-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathheatedworld.py
198 lines (148 loc) · 6.11 KB
/
heatedworld.py
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
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
#############################################################################
# Author: Ahmad M. Osman #
# Date: 04/17/2018 #
# #
# Project: HeatedWorld #
# Purpose: World News' Heated Map. #
# #
# https://www.heated.world #
# https://github.com/Ahmad-Magdy-Osman/HeatedWorld #
# #
# Filename: heatedworld.py #
# File overview: This file executes all necessary steps to prepare #
# the news to be visualized on Heated.World #
# #
#############################################################################
import logging
import time
import json
import requests
import atexit
import os
import datetime
from collections import Counter
from flask import Flask, Response, render_template, request, jsonify
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
from reddit import Reddit
# Disables tensorflow warnings - doesn't enable AVX/FMA
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
app = Flask(__name__)
def heatmap_json(day, week):
logging.info("Ongoing...")
# Combining votes for countries from the day's submissions and the week's (weighed) submissions
votes = Counter(day.countries) + Counter(week.countries)
with open('data/votes.json', 'w') as outfile:
json.dump(votes, outfile)
def news_json(day, week):
logging.info("Ongoing...")
# Combining day's submissions and week's into one dictionary
news = day.headlines
for key, value in week.headlines.items():
if key in news.keys():
news[key] += value
else:
news[key] = value
with open('data/news.json', 'w') as outfile:
json.dump(news, outfile)
def submissions_json(day, week):
logging.info("Ongoing...")
# Combining day's submissions and week's into one dictionary
submissions = {**day.submissions, **week.submissions}
with open('data/submissions.json', 'w') as outfile:
json.dump(submissions, outfile)
def heatedworld():
logging.info("--------------------")
logging.info("-------------")
logging.info("Script starting...\n")
logging.info("Initiating client for the day's submssions...")
# subreddit followed by day/week
redditDay = Reddit("worldnews", "day")
logging.info("Client initiated.")
logging.info("Fetching...")
redditDay.fetch(40) # 40
logging.info("Fetched.")
logging.info("Getting context...")
redditDay.get_context()
logging.info("Context saved.")
logging.info("Getting countries' headlines...")
redditDay.country_news()
logging.info("Countries' news saved....")
logging.info("Saving daily data to CSV and JSON...")
redditDay.save_csv()
with open('data/day.json', 'w') as outfile:
json.dump(redditDay.submissions, outfile)
logging.info("Saved day's submissions.\n")
logging.info("----------------------------------------------\n")
logging.info("Initiating client for the week's submssions...")
# subreddit followed by day/week
redditWeek = Reddit("worldnews", "week")
logging.info("Client initiated.")
logging.info("Fetching...")
redditWeek.fetch(120) # 120
logging.info("Fetched.")
logging.info("Getting context...")
redditWeek.get_context()
logging.info("Context saved.")
logging.info("Getting countries' headlines...")
redditWeek.country_news()
logging.info("Countries' news saved....")
logging.info("Saving weekly data to CSV and JSON...")
redditWeek.save_csv()
with open('data/week.json', 'w') as outfile:
json.dump(redditWeek.submissions, outfile)
logging.info("Saved week's submissions.\n")
logging.info("----------------------------------------------\n")
logging.info("Saving heatmap values to JSON file...")
heatmap_json(redditDay, redditWeek)
logging.info(("Saved votes JSON file.\n"))
logging.info("----------------------------------------------\n")
logging.info("Saving countries' headlines to JSON file...")
news_json(redditDay, redditWeek)
logging.info(("Saved news JSON file.\n"))
logging.info("----------------------------------------------\n")
logging.info("Saving submissions to JSON file...")
submissions_json(redditDay, redditWeek)
logging.info(("Saved submissions JSON file.\n"))
logging.info("Script finished.")
logging.info("-------------")
logging.info("--------------------\n")
logging.basicConfig(filename='data/heatedworld.log', level=logging.INFO,
format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
if not os.path.exists("data"):
os.mkdir("data")
scheduler = BackgroundScheduler()
scheduler.start()
scheduler.add_job(
func=heatedworld,
trigger=IntervalTrigger(hours=3),
next_run_time=datetime.datetime.now(),
id='getting_elements',
name='getting elements',
replace_existing=True)
# Shut down the scheduler when exiting the app
atexit.register(lambda: scheduler.shutdown())
@app.route('/')
def homepage():
return render_template("index.html")
@app.route('/votes')
def fetch_votes():
f = open("data/votes.json", "r")
content = f.read()
f.close()
return content
@app.route('/news')
def fetch_country_news():
f = open("data/news.json", "r")
content = f.read()
f.close()
return content
@app.route('/submissions')
def fetch_submissions():
f = open("data/submissions.json", "r")
content = f.read()
f.close()
return content
if __name__ == '__main__':
# heatedworld()
app.run(debug=True, port=5001, use_reloader=False)