-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathanalyze_telegramgate_script.py
299 lines (188 loc) · 8.94 KB
/
analyze_telegramgate_script.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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
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
import classifier as spanish_sentiment_analysis
from spellchecker import SpellChecker
#---------------------------------------------------------------------------------
from tika import parser
pdf_path = "./dataset/telegram_gate.pdf"
raw = parser.from_file(pdf_path)
pdf_content = raw['content']
#---------------------------------------------------------------------------------
pdf_content = pdf_content.strip("\n")
#---------------------------------------------------------------------------------
import re
# Remove "Telegram Web"
pdf_content = pdf_content.replace("Telegram Web", "")
# Remove the date "1/20/2019"
pdf_content = pdf_content.replace("1/20/2019", "")
# Remove the telegram URL which appears at the end of every page
# Create a regular expression to match different variations of the link which differ by extra empty spaces
regex = re.compile(r'https( )*:(\/|1)(\/|1)web( )*\.telegram( )*\.org\/#\/im\?p=s1209505337( )*_( )*15413785455230905639')
# Remove strings that match the regex
pdf_content = re.sub(regex, "", pdf_content)
#---------------------------------------------------------------------------------
# Create regex for matching timestamps
regex = re.compile(r'[0-9][0-9]?:[0-9][0-9]( )?:[0-9][0-9]( )?(A|P)M')
# Remove timestamps
pdf_content = re.sub(regex, "", pdf_content)
#---------------------------------------------------------------------------------
# Create a list of sentences from document
pdf_lines = pdf_content.split("\n")
# Remove empty string elements
regex = re.compile(r'^( )*$')
pdf_lines = [line for line in pdf_lines if not regex.match(line)]
#---------------------------------------------------------------------------------
# Get admin chat members by keeping unique lines which contain the word 'admin'
admin_chat_members = set(line.strip() for line in pdf_lines if ' admin ' in line)
#---------------------------------------------------------------------------------
# Clean the admin chat members list by removing ' admin' and any text after
admin_chat_members_cleaned = set()
for element in admin_chat_members:
index = element.find(' admin') # locate where in the line is the string ' admin'
admin_chat_members_cleaned.add(element[:index])
admin_chat_members = admin_chat_members_cleaned
#---------------------------------------------------------------------------------
# Remove the elements in admin_chat_members which contain the text 'gif', they are repeated
admin_chat_members = [member for member in admin_chat_members if not('gif' in member)]
#---------------------------------------------------------------------------------
# Two elements in the admin_chat_members list seem to be typos (Tika misread them), remove them
admin_chat_members.remove("R Russello") # assuming it's 'R Rosello' read incorrectly by Tika
admin_chat_members.remove("Fdo") # assuming it's 'F do' read incorrectly by Tika
#---------------------------------------------------------------------------------
# Replace typos: 'Fdo' with 'F do' and 'R Russello' with 'R Rosello'
pdf_lines_fixed = []
for line in pdf_lines:
new_line = line
if 'R Russello' in line:
new_line = line.replace('R Russello', 'R Rosello')
if 'Fdo' in line:
new_line = line.replace('Fdo', 'F do')
pdf_lines_fixed.append(new_line)
pdf_lines = pdf_lines_fixed
#---------------------------------------------------------------------------------
# Make a consolidated chat members list
nonadmin_chat_members = [
"Raul Maldonado",
"Anthony O. Maceira Zayas",
"Ricardo Llerandi",
"LuisG"
]
all_chat_members = admin_chat_members + nonadmin_chat_members
#---------------------------------------------------------------------------------
# Create admin member accronyms
user_acronyms = set()
for chat_member in all_chat_members:
names = chat_member.split(" ")
names = names[:2] # user accronyms in the PDF have a maximum of 2 letters
acronym = ""
for name in names:
acronym += name[0].upper()
user_acronyms.add(acronym)
#---------------------------------------------------------------------------------
# Build regular expression for identifying text containing only an accronym and spaces
regular_exp = ""
for acronym in user_acronyms:
regular_exp += acronym + "|"
regular_exp = regular_exp[:len(regular_exp)-1]
regex = re.compile(r'^( )*({regular_exp})( )*$'.format(regular_exp=regular_exp))
# Remove accronyms from pdf_lines
pdf_lines = [line for line in pdf_lines if not regex.match(line)]
#---------------------------------------------------------------------------------
# Store the conversation in the list conversation, which will be
# a list of dictionaries where the dictionary will contain the keys
# 'chat_member' and 'message'
page_number_regex = re.compile(r'( )*[0-9][0-9]?[0-9]?\/889( )*')
# Build date regex
# date example: Friday, November 30, 2018
weekday = '(Moday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)'
month = '(January|February|March|April|May|June|July|August|September|October|November|December)'
day = '[0-9]?[0-9]'
year = '20[1-2][0-9]'
date_regex = re.compile(r'{weekday}, {month} {day}, {year}'.format(weekday=weekday,
month=month,
day=day,
year=year))
page_number = 1
date = None
conversation = []
current_chat_member = None # which chat member is the current author
new = False # is the detected chat member new (different from previous)?
for line in pdf_lines:
if page_number_regex.match(line):
page_number += 1
continue
if date_regex.match(line):
date = line.strip()
continue
for chat_member in all_chat_members:
if chat_member in line:
# don't add chat member element to conversation
current_chat_member = chat_member
new = True
break
if new:
new = False
continue # skip to next iteration
if (current_chat_member != None) and not(current_chat_member in line):
conversation.append({
"chat_member": current_chat_member,
"message": line,
"page_number": page_number,
"date": date
})
#---------------------------------------------------------------------------------
# Create abridged Telegramgate
#---------------------------------------------------------------------------------
# Randomly generate colors per chat member for bar chart
import random
def random_color(): # returns a random color in hexadecimal
color = "%06x" % random.randint(0, 0xFFFFFF)
return color
# randomly generate colors per user
chat_member_colors = {member:random_color() for member in all_chat_members}
#---------------------------------------------------------------------------------
# Get messages per user
messages_per_user = {user:0 for user in all_chat_members}
for message in conversation:
messages_per_user[message['chat_member']] += 1
#---------------------------------------------------------------------------------
# Draw bar chart which represents messages per user, and save to '"barchart.png"
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
users = list(messages_per_user.keys())
y_pos = np.arange(len(users))
number_of_lines = list(messages_per_user.values())
fig, ax = plt.subplots()
barlist = ax.barh(y_pos, number_of_lines, align='center', alpha=0.5)
# color the bars
for i,user_color in enumerate(chat_member_colors.items()):
user = user_color[0]
color = user_color[1]
barlist[i].set_color('#'+color)
plt.yticks(y_pos, users)
plt.xlabel('Number of Lines per Chat Member')
plt.title('Messaging Frequency Per User')
for i, v in enumerate(number_of_lines):
ax.text(v + 4, i, " "+str(v), color='grey', fontweight='bold',va='center')
fig.savefig("barchart.png", bbox_inches = "tight")
#---------------------------------------------------------------------------------
# Create abridged Telegramgate PDF from created HTML
import pdfkit
html_content = "<html><body><h1>Telegramgate: Abridged</h1>"
page = 1
html_content += '<p>page {page} </br></p>'.format(page=page)
for msg in conversation:
user = msg['chat_member']
message = msg['message']
if msg["page_number"] > page:
page += 1
html_content += '<p></br>page {page}</p>'.format(page=page)
color = chat_member_colors[user]
html_content += '<p><font color="{color}"><b>{user}</b></font>: {message}</p>'.format(color=color,user=user,message=message)
html_content += "</body></html>"
filename = "telegramgate_abridged"
html_filename = filename + '.html'
f = open(html_filename,"w")
f.write(html_content)
f.close()
pdf_filename = filename + '.pdf'
pdfkit.from_file(html_filename, pdf_filename)