-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
184 lines (155 loc) · 5.34 KB
/
app.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
import flask
from flask import request, jsonify
import similar_articles
import json
import tldextract
import tfPred
from newspaper import fulltext
import requests
import numpy as np
with open('linkToName.json', 'r') as f:
link_to_name = json.load(f)
with open('nameToStats.json', 'r') as f:
name_to_stats = json.load(f)
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/', methods=['GET'])
def home():
return '''<h1>Political Bias API</h1>
<p>A prototype API for detecting political bias of text.</p>'''
@app.route('/vals.json', methods=['GET'])
def vals():
with open('vals.json', 'r') as f:
vals = json.load(f)['vals']
return jsonify({
"vals": vals
})
@app.route('/api/bias/', methods=['GET'])
def api_id():
if 'url' in request.args:
url = str(request.args['url'])
bb = get_bias(url)
bias = bb[0]
bias_desc = bb[1]
print(bias_desc)
if(bias_desc == 'Left'):
n = 1
elif(bias_desc == 'Moderate Left'):
n = 2
elif(bias_desc == 'Neutral'):
n = 3
elif(bias_desc == 'Moderate Right'):
n = 4
else:
n = 5
"""
f = open('C:/Users/sahil/Desktop/Files/Coding/PalyHacks-DevilsAdvocate/DevilsAdvocate/svg-doughnut-chart-with-animation-and-tooltip/dist/vals.js', 'r') # pass an appropriate path of the required file
lines = f.readlines()
lines[n-1] = str(int(lines[n].split(',')[0]) + 1) + ",\n" # n is the line number you want to edit; subtract 1 as indexing of list starts from 0
f.close() # close the file and reopen in write mode to enable writing to file; you can also open in append mode and use "seek", but you will have some unwanted old data if the new data is shorter in length.
f = open('C:/Users/sahil/Desktop/Files/Coding/PalyHacks-DevilsAdvocate/DevilsAdvocate/svg-doughnut-chart-with-animation-and-tooltip/dist/vals.js', 'w')
f.writelines(lines)
# do the remaining operations on the file
f.close()
"""
with open('vals.json', 'r') as f:
vals = json.load(f)['vals']
vals[n - 1] = vals[n - 1] + 1
with open('vals.json', 'w') as f:
json.dump({"vals": vals}, f);
try:
all_articles = similar_articles.get(url)["articles"]
except:
return jsonify({
'bias': bias_desc,
'similar_articles': {"articles": []}
})
article_biases = []
articles_biases_text = []
for article in all_articles:
print("article", article)
b = get_bias_dict(article["url"])
article_biases.append(b[0])
articles_biases_text.append(b[1])
article_biases = np.array(article_biases)
if("Right" in bias_desc):
k = min(3, len(article_biases) - 1)
bs = np.argpartition(article_biases, k)[:k]
elif("Left" in bias_desc):
k = min(3, len(article_biases) - 1)
bs = np.argpartition(-1 * article_biases, k)[:k]
if("Neutral" in bias_desc):
articles = all_articles
else:
articles = []
for b in bs:
print(tldextract.extract(all_articles[b]["url"]).registered_domain, tldextract.extract(url).registered_domain)
if not(tldextract.extract(all_articles[b]["url"]).registered_domain == tldextract.extract(url).registered_domain):
articles.append(all_articles[b])
return jsonify({
'bias': bias_desc,
'similar_articles': {"articles": articles}
}
)
else:
return "Error: No text field provided."
def get_bias(url):
#info = tldextract.extract(url)
b_dir = 0
print(url)
bias = 0
try:
html = requests.get(url).text
text = fulltext(html)
bias = tfPred.getDeepBias(text)
bias[0] = bias[0]-.1
bias[1] = bias[1]+.1
b_dir = bias.argmax()
print('b_dir: '+str(b_dir))
b_mag = bias[b_dir]
print(bias)
bias = b_mag
except:
b_dir = 1
bias = .5
#print(info.registered_domain)
try:
#bias = name_to_stats[link_to_name[info.registered_domain]]["bias"]
print('b_dir: '+str(b_dir))
if b_dir == 1:
if bias <.6:
bias_desc = 'Neutral'
elif(bias <.75):
bias_desc = 'Moderate Right'
else:
bias_desc = 'Right'
else:
if bias <.6:
bias_desc = 'Neutral'
elif(bias <.75):
bias_desc = 'Moderate Left'
else:
bias_desc = 'Left'
except KeyError:
bias_desc = 'Neutral'
return bias, bias_desc
def get_bias_dict(url):
info = tldextract.extract(url)
print(info.registered_domain)
bias = 0
try:
bias = name_to_stats[link_to_name[info.registered_domain]]["bias"]
if(bias >= 10):
bias_desc = 'Right'
elif(bias > 3):
bias_desc = 'Moderate Right'
elif(bias <= -10):
bias_desc = 'Left'
elif(bias < -3):
bias_desc = 'Moderate Left'
else:
bias_desc = 'Neutral'
except KeyError:
bias_desc = 'Neutral'
return bias, bias_desc
app.run()