-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
220 lines (177 loc) · 6.2 KB
/
utils.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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
from contextlib import contextmanager
import os
import re
import pickle
import tempfile
import dateutil,dateutil.parser
# global settings
# -----------------------------------------------------------------------------
class Config(object):
# main paper information repo file
db_path = 'db.p'
# intermediate processing folders
pdf_dir = os.path.join('data', 'pdf')
txt_dir = os.path.join('data', 'txt')
thumbs_dir = os.path.join('static', 'thumbs')
# intermediate pickles
tfidf_path = 'tfidf.p'
meta_path = 'tfidf_meta.p'
sim_path = 'sim_dict.p'
user_sim_path = 'user_sim.p'
# sql database file
db_serve_path = 'db2.p' # an enriched db.p with various preprocessing info
database_path = 'as.db'
serve_cache_path = 'serve_cache.p'
beg_for_hosting_money = 1 # do we beg the active users randomly for money? 0 = no.
banned_path = 'banned.txt' # for twitter users who are banned
tmp_dir = 'tmp'
# Context managers for atomic writes courtesy of
# http://stackoverflow.com/questions/2333872/atomic-writing-to-file-with-python
@contextmanager
def _tempfile(*args, **kws):
""" Context for temporary file.
Will find a free temporary filename upon entering
and will try to delete the file on leaving
Parameters
----------
suffix : string
optional file suffix
"""
fd, name = tempfile.mkstemp(*args, **kws)
os.close(fd)
try:
yield name
finally:
try:
os.remove(name)
except OSError as e:
if e.errno == 2:
pass
else:
raise e
@contextmanager
def open_atomic(filepath, *args, **kwargs):
""" Open temporary file object that atomically moves to destination upon
exiting.
Allows reading and writing to and from the same filename.
Parameters
----------
filepath : string
the file path to be opened
fsync : bool
whether to force write the file to disk
kwargs : mixed
Any valid keyword arguments for :code:`open`
"""
fsync = kwargs.pop('fsync', False)
with _tempfile(dir=os.path.dirname(filepath)) as tmppath:
with open(tmppath, *args, **kwargs) as f:
yield f
if fsync:
f.flush()
os.fsync(f.fileno())
os.rename(tmppath, filepath)
def safe_pickle_dump(obj, fname):
with open_atomic(fname, 'wb') as f:
pickle.dump(obj, f, -1)
# arxiv utils
# -----------------------------------------------------------------------------
def strip_version(idstr):
""" identity function if arxiv id has no version, otherwise strips it. """
parts = idstr.split('v')
return parts[0]
# "1511.08198v1" is an example of a valid arxiv id that we accept
def isvalidid(pid):
return re.match('^\d+\.\d+(v\d+)?$', pid)
def print_entry(args,db,entry,filters=[]):
# render time information nicely
if not args.updatedTime:
timestruct = dateutil.parser.parse(db[entry]['published'])
else:
timestruct = dateutil.parser.parse(db[entry]['updated'])
published_time = '%s/%s/%s' % (timestruct.day, timestruct.month, timestruct.year)
authors=", ".join([author['name'] for author in db[entry]['authors']])
if 'LHCb collaboration' in authors:
authors='LHCb collaboration'
comment=db[entry]["arxiv_comment"] if "arxiv_comment" in db[entry] else ""
cat=db[entry]["arxiv_primary_category"]["term"]
text=f"""
----------------------------------------------------------
{db[entry]["title"]}
{entry} [{cat}]
{published_time}
{comment}
{authors}
{db[entry]['summary']}
"""
# Add some colour highlighting of category
print(cat)
htmlcat=gethtmlcat(cat)
htmlentry=f'<a href="https://arxiv.org/abs/{entry}">{entry}</a>'
title=db[entry]["title"]
html=f"""
<hr>
<h3>{db[entry]["title"]}</h3>
{htmlentry} {htmlcat} {published_time}<br>
<span style="font-size:0.9em;"><i>{comment}</i></span><br>
<p><b>{authors}</b></p>
<p style="font-size:0.9em;">{db[entry]['summary']}</p>
<br>
"""
# Highlight all of title if any filter is matched
ismatched=False
for filt in filters:
if filt in html:
html=html.replace(filt,f'<span style="color:red;">{filt}</span>')
title=title.replace(filt,f'<span style="color:red;">{filt}</span>')
ismatched=True
#if ismatched:
# html=html.replace(title,f'<h3 style="color:red;">{db[entry]["title"]}</h3>')
print(text)
#print(html)
return text,html,ismatched
def send_email(subject,text,html):
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# me == my email address
# you == recipient's email address
me = "[email protected]"
you = "[email protected]"
# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = subject
msg['From'] = me
msg['To'] = you
# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')
# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)
# Send the message via local SMTP server.
s = smtplib.SMTP('smtp.gmail.com',587)
#s.ehlo()
s.starttls()
s = smtplib.SMTP_SSL('smtp.gmail.com', 465)
pwfile = open('.pwfile.txt', 'r')
pwlines = pwfile.readlines()
gmail_password=pwlines[0].strip()
s.login(me, gmail_password)
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()
def gethtmlcat(cat):
htmlcat=cat
if cat=="hep-ex":
htmlcat='<span style="color:darkred;">['+cat+']</span>'
elif cat=="hep-ph":
htmlcat='<span style="color:darkgreen;">['+cat+']</span>'
elif cat=="hep-th":
htmlcat='<span style="color:darkblue;">['+cat+']</span>'
else:
htmlcat='<span style="color:gray;">['+cat+']</span>'
return htmlcat