-
Notifications
You must be signed in to change notification settings - Fork 55
/
chatparsers.py
371 lines (301 loc) · 12.5 KB
/
chatparsers.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
300
301
302
303
304
305
306
307
308
309
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
import datetime as dt
import json
import logging
import re
import unicodedata
from abc import ABC, abstractmethod
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any, Dict, List, Optional
import polars as pl
from dateutil import parser as datetimeparser
from tqdm import tqdm
from tqdm.contrib.logging import logging_redirect_tqdm
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)-8s %(message)s",
datefmt="%d.%m.%Y %H:%M:%S",
)
@dataclass(frozen=True)
class ParsedMessage:
timestamp: dt.datetime
author: str
message: str
class ParsedMessageCollection:
def __init__(self):
self._parsed_messages: List[ParsedMessage] = []
def append(self, mess: ParsedMessage):
self._parsed_messages.append(mess)
def get_df(self, as_pandas=False):
messages_as_dict = [asdict(mess) for mess in self._parsed_messages]
df = pl.DataFrame(messages_as_dict)
return df.to_pandas() if as_pandas else df
def write_to_json(self, file: str):
def serialize_message(mess: ParsedMessage):
return {
"timestamp": mess.timestamp.isoformat(),
"author": mess.author,
"message": mess.message,
}
with open(file, "w") as json_file:
json.dump(
[serialize_message(mess) for mess in self._parsed_messages],
json_file,
indent=4,
)
def read_from_json(self, file: str):
def deserialize_message(mess: dict):
timestamp = dt.datetime.fromisoformat(mess["timestamp"])
author = mess["author"]
message = mess["message"]
return ParsedMessage(timestamp=timestamp, author=author, message=message)
with open(file, "r") as json_file:
self._parsed_messages = [
deserialize_message(mess) for mess in json.load(json_file)
]
def __eq__(self, other):
return self._parsed_messages == other._parsed_messages
class Parser(ABC):
def __init__(self, filepath: str):
self._file = Path(filepath)
assert self._file.is_file()
self._raw_messages: List[Dict[str, Any]] | List[str] = []
self.parsed_messages = ParsedMessageCollection()
self._logger = logging.getLogger(__name__)
self._logger.info(
"""
Depending on the platform, the message format in chat logs might not be
standardized across devices/versions/localization and might change over
time. Please report issues including your message format via GitHub.
"""
)
self._logger.info("Initialized parser.")
def parse_file(self):
self._logger.info("Starting reading raw messages...")
self._read_raw_messages_from_file()
self._logger.info("Finished reading %i raw messages.", len(self._raw_messages))
self._logger.info("Starting parsing raw messages...")
self._parse_raw_messages()
self._logger.info("Finished parsing raw messages.")
@abstractmethod
def _read_raw_messages_from_file(self): ...
def _parse_raw_messages(self):
with logging_redirect_tqdm():
for raw_mess in tqdm(self._raw_messages):
parsed_mess = self._parse_message(raw_mess)
if parsed_mess:
self.parsed_messages.append(parsed_mess)
@abstractmethod
def _parse_message(self, mess: Any) -> Optional[ParsedMessage]: ...
class SignalParser(Parser):
def _read_raw_messages_from_file(self):
def _is_new_message(line: str):
regex = r"^\[\d{4}-\d{2}-\d{2}, \d{2}:\d{2}\]"
return re.match(regex, line)
with self._file.open(encoding="utf-8") as f:
lines = reversed(list(f))
self._raw_messages: List[str]
buffer: List[str] = []
for line in lines:
if not line:
continue
if _is_new_message(line):
if buffer:
buffer.append(line)
buffer.reverse()
joined_buffer = " ".join(buffer)
self._raw_messages.append("".join(joined_buffer.splitlines()))
buffer.clear()
else:
self._raw_messages.append(line)
else:
buffer.append(line)
def _parse_message(self, mess: str):
datetime_raw, mess = mess.split("]", 1)
time = datetimeparser.parse(datetime_raw[1:])
author, body = mess.split(":", 1)
author = author.strip()
body = body.strip()
return ParsedMessage(time, author, body)
class WhatsAppParser(Parser):
def __init__(self, filepath: str):
super().__init__(filepath)
self._datefmt = WhatsAppDateFormat(self._logger)
def _read_raw_messages_from_file(self):
def _is_new_message(line: str):
regex = r"^[\u200e]?\[?(\d{1,4})([./,-])\d{1,2}\2\d{2,4}([, ])"
return re.match(regex, line)
with self._file.open(encoding="utf-8") as f:
lines = reversed(list(f))
self._raw_messages: List[str]
buffer: List[str] = []
for line in lines:
if not line:
continue
if _is_new_message(line):
line = line.replace("\u200e", "")
line = unicodedata.normalize("NFKC", line.strip())
if buffer:
buffer.append(line)
buffer.reverse()
joined_buffer = " ".join(buffer)
self._raw_messages.append("".join(joined_buffer.splitlines()))
buffer.clear()
else:
self._raw_messages.append(line)
else:
buffer.append(line)
self._datefmt.infer_format(self._raw_messages)
def _parse_message(self, mess: str):
datestr, author_and_body = mess.split(self._datefmt.date_author_sep, 1)
time = datetimeparser.parse(
datestr, dayfirst=self._datefmt.is_dayfirst, fuzzy=True
)
if ": " in author_and_body:
author, body = [x.strip() for x in author_and_body.split(": ", 1)]
return ParsedMessage(time, author, body)
elif ":." in author_and_body:
self._logger.info(f"Ignoring self-destroying message on {time}.")
else:
body = author_and_body.strip()
self._logger.info(f"Ignoring sytem message on {time}: {body}.")
class FacebookMessengerParser(Parser):
def _read_raw_messages_from_file(self):
with self._file.open(encoding="utf-8") as f:
self._raw_messages: List[Dict[str, Any]] = json.load(f)["messages"]
def _parse_message(self, mess: Dict[str, Any]):
if "content" not in mess:
return None
body = mess["content"]
time = dt.datetime.utcfromtimestamp(mess["timestamp_ms"] / 1000)
author = mess["sender_name"].encode("latin-1").decode("utf-8")
body = body.encode("latin-1").decode("utf-8")
return ParsedMessage(time, author, body)
class InstagramJsonParser(Parser):
def _read_raw_messages_from_file(self):
with self._file.open(encoding="utf-8") as f:
self._raw_messages: List[Dict[str, Any]] = json.load(f)["messages"]
def _parse_message(self, mess: Dict[str, Any]):
if "content" not in mess:
return None
system_messages = [
"to your message",
"in the poll.",
"created a poll: ",
"liked a message",
"This poll is no longer available.",
"'s poll has multiple updates.",
]
if any(flag in mess["content"] for flag in system_messages):
return None
body = mess["content"]
time = dt.datetime.utcfromtimestamp(mess["timestamp_ms"] / 1000)
author = mess["sender_name"].encode("latin-1").decode("utf-8")
body = body.encode("latin-1").decode("utf-8")
return ParsedMessage(time, author, body)
class TelegramJsonParser(Parser):
def __init__(self, filepath: str, chat_name: Optional[str] = None):
super().__init__(filepath)
self.chat_name: Optional[str] = chat_name
def _read_raw_messages_from_file(self):
with self._file.open(encoding="utf-8") as f:
json_objects = json.load(f)
if "messages" in json_objects:
self._logger.info("Detected single chat export.")
self._raw_messages = json_objects["messages"]
else:
self._logger.info("Detected batch export.")
if self.chat_name:
for chat in json_objects["chats"]["list"]:
if "name" in chat and chat["name"] == self.chat_name:
self._raw_messages = chat["messages"]
break
else:
raise ValueError(f"{self.chat_name} not found in {self._file}")
def _parse_message(self, mess: Dict[str, Any]):
if "from" not in mess or "text" not in mess:
return None
if isinstance(mess["text"], str):
body = mess["text"]
elif isinstance(mess["text"], list):
text_elements = [
m["text"] if isinstance(m, dict) else m for m in mess["text"]
]
body = " ".join(text_elements)
time = dt.datetime.utcfromtimestamp(int(mess["date_unixtime"]))
author = mess["from"]
return ParsedMessage(time, author, body)
class WhatsAppDateFormat:
def __init__(self, logger: logging.Logger):
self.is_dayfirst = None
self.is_yearfirst = None
self.has_brackets = None
self.date_sep = None
self.date_author_sep = None
self._logger = logger
def infer_format(self, raw_messages: List[str]):
self.has_brackets = self._infer_brackets(raw_messages[0])
self.date_author_sep = self._infer_date_author_sep()
self.date_sep = self._infer_date_sep(raw_messages[0])
self.is_yearfirst = self._infer_yearfirst(raw_messages[0])
self.is_dayfirst = self._infer_dayfirst(raw_messages)
self._log_resulting_format()
@staticmethod
def _infer_brackets(mess: str):
return mess[0] == "["
def _infer_date_author_sep(self):
return "]" if self.has_brackets else " - "
def _infer_date_sep(self, mess: str):
datestr = mess.split(self.date_author_sep, 1)[0]
if self.has_brackets:
datestr = datestr.lstrip("[").rstrip("]")
for c in datestr:
if not c.isdigit():
return c
raise ValueError("No non-numeric character in datestring.")
def _infer_yearfirst(self, mess: str):
datestr = mess.split(self.date_author_sep, 1)[0]
if self.has_brackets:
datestr = datestr.lstrip("[").rstrip("]")
return int(datestr.split(self.date_sep)[0]) >= 100
def _infer_dayfirst(self, raw_messages: List[str]):
max_first = 0
max_second = 0
for mess in raw_messages:
datestr = mess.split(self.date_author_sep, 1)[0]
if self.has_brackets:
datestr = datestr.lstrip("[").rstrip("]")
if self.is_yearfirst:
datepart = datestr.split(",")[0]
day_and_month = [int(num) for num in datepart.split(self.date_sep)[1:3]]
else:
day_and_month = [int(num) for num in datestr.split(self.date_sep)[:2]]
max_first = max(max_first, day_and_month[0])
max_second = max(max_second, day_and_month[1])
if max_first > 12 or max_second > 12:
break
if max_first > 12 >= max_second:
return True
if max_first <= 12 < max_second:
return False
self._logger.warning(
"Can't infer date format: No day > 12. Falling back on day first."
)
return True
def _log_resulting_format(self):
start = "[" if self.has_brackets else ""
end = "]" if self.has_brackets else ""
if self.is_yearfirst:
date1 = "year"
date2 = "month"
date3 = "day"
elif self.is_dayfirst:
date1 = "day"
date2 = "month"
date3 = "year"
else:
date1 = "month"
date2 = "day"
date3 = "year"
composition = f"{start}{date1}{self.date_sep}{date2}{self.date_sep}{date3}{end}"
self._logger.info("Inferred date format: %s", composition)