-
Notifications
You must be signed in to change notification settings - Fork 15
/
whatsapp_archive.py
executable file
·327 lines (285 loc) · 10.4 KB
/
whatsapp_archive.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
#!/usr/bin/python3
"""Reads a WhatsApp conversation export file and writes a HTML file."""
import argparse
import collections
import dateutil.parser
import itertools
import jinja2
import logging
import mimetypes
import os.path
import re
from typing import Optional
from dataclasses import dataclass
# Format of the standard WhatsApp export line. This is likely to continue to
# change in the future and so this application will need to be updated.
# The biggest challenge is that every language seems to have its own set of
# rules for dates, and it's not trivial to match them all correctly.
TIME_RE = '(?P<time>[\d:]+( [AP]M)?)'
SEPARATOR_RE = '( - |: | )'
NAME_RE = '(?P<name>[^:]+)'
DTSEP_RE = ' ?[,à]? ?'
class Error(Exception):
"""Something bad happened."""
Matchers = collections.namedtuple(
'Matchers',
'date time datetime name firstline line')
def _MakeDatePattern():
patterns = []
d = '[\d]+'
separators = ['-', '\.', '/']
for sep in separators:
patterns.append(f'{d}{sep}{d}{sep}{d}')
return '(?P<date>' + '|'.join(patterns) + ')'
def _MakeDateTimePattern():
return '\[?' + _MakeDatePattern() + DTSEP_RE + TIME_RE + '\]?'
def _MakeLinePattern():
return (
_MakeDateTimePattern() +
SEPARATOR_RE +
NAME_RE +
': ' +
'(?P<body>.*$)')
def _MakeFirstLinePattern():
return (_MakeDateTimePattern() + SEPARATOR_RE + '(?P<body>.*$)')
def _MakeMatchers() -> Matchers:
return Matchers(
date = _MakeDatePattern(),
time = TIME_RE,
datetime = _MakeDateTimePattern(),
name = NAME_RE,
firstline = _MakeFirstLinePattern(),
line = _MakeLinePattern(),
)
def ParseLine(matchers: Matchers, line: str):
"""Parses a single line of WhatsApp export file."""
m = re.match(matchers.line, line)
if m:
d = dateutil.parser.parse("%s %s" % (m.group('date'),
m.group('time')), dayfirst=True)
return d, m.group('name'), m.group('body')
# Maybe it's the first line which doesn't contain a person's name.
m = re.match(matchers.firstline, line)
if m:
d = dateutil.parser.parse("%s %s" % (m.group('date'),
m.group('time')), dayfirst=True)
return d, 'nobody', m.group('body')
return None
FILE_RE = u'(?P<path>(AUD|PTT|STK|IMG|VID|DOC)-(\d){8}-WA\d+\.(m4a|jpg|mp4|pdf|webp|gif|opus|mp3|aac|wav|mpeg|3gp|avi|wmm|jpeg|png|tiff|ico))'
@dataclass
class Media:
path: str
mime: str
def MediaMessageToPath(msg_body: str) -> Optional[str]:
m = re.match(u'\u200e?' + FILE_RE, msg_body, re.U)
if m:
return m.group('path')
def AsMedia(msg_body: str) -> Optional[Media]:
"""Guesses whether the current message is a media message or not.
Since media files seem to be named consistently, we don't need to match the
text in the parentheses. We just match that there's something in
parentheses.
"""
m = re.match(u'\u200e?' + FILE_RE + ' \([a-z ]+\)', msg_body, re.U)
if m is not None:
path = MediaMessageToPath(msg_body)
mime_type, _ = mimetypes.guess_type(path)
return Media(path, mime_type)
return None
def IdentifyMessages(lines):
"""Input text can contain multi-line messages. If there's a line that
doesn't start with a date and a name, that's probably a continuation of the
previous message and should be appended to it.
"""
matchers = _MakeMatchers()
messages = []
msg_date = None
msg_user = None
msg_body = None
msg_media = None
for line in lines:
m = ParseLine(matchers, line)
if m is not None:
if msg_date is not None:
# We have a new message, so there will be no more lines for the
# one we've seen previously -- it's complete. Let's add it to
# the list.
msg_media = AsMedia(msg_body)
messages.append((msg_date, msg_user, msg_body, msg_media))
msg_date, msg_user, msg_body, msg_media = None, None, None, None
msg_date, msg_user, msg_body = m
else:
if msg_date is None:
raise Error("Can't parse the first line: " + repr(line) +
', regexes are first_line = ' + repr(matchers.firstline) +
' and line =' + repr(matchers.line))
msg_body += '\n' + line.strip()
msg_media = AsMedia(line.strip())
# The last message remains. Let's add it, if it exists.
if msg_date is not None:
msg_media = AsMedia(msg_body)
messages.append((msg_date, msg_user, msg_body, msg_media))
return messages
def TemplateData(messages, input_filename):
"""Create a struct suitable for procesing in a template.
Returns:
A dictionary of values.
"""
by_user = []
file_basename = os.path.basename(input_filename)
for user, msgs_of_user in itertools.groupby(messages, lambda x: x[1]):
msgs_as_list = list(msgs_of_user)
by_user.append((user, msgs_as_list[0][0].date(), msgs_as_list))
dates = []
prev_date = None
for _, first_msg_date, _ in by_user:
if first_msg_date != prev_date:
dates.append(first_msg_date)
prev_date = first_msg_date
by_month = []
# Item format:
# ((year, month), [(day_of_month, datetime_object)])
for month, days in itertools.groupby(dates, lambda x: (x.year, x.month)):
by_month.append((month, [(d.day, d) for d in days]))
return dict(by_user=by_user, dates=by_month, input_basename=file_basename,
input_full_path=input_filename)
def FormatHTML(data):
tmpl = """<!DOCTYPE html>
<html>
<head>
<title>WhatsApp archive {{ input_basename }}</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 10px;
background-color: rgb(255, 255, 255);
display: flex;
width: 100%;
flex-direction: column;
}
@media screen and (min-width: 600px) {
body, ol.users {
flex-direction: column;
width: 600px;
}
}
ol.users {
list-style-type: none;
list-style-position: inside;
margin: 1em;
padding: 0;
background-color: rgb(250, 240, 227);
border-radius: 7px;
}
ol.messages {
list-style-type: none;
list-style-position: inside;
margin: 1em;
padding-left: 1.5em;
}
ol.messages li.text-msg {
margin-left: 1em;
font-size: 12px;
background-color: rgb(220,248,200);
margin: 1em;
margin-left: 0em;
margin-bottom: 0em;
margin-top: 0.3em;
padding: 0.8em;
border-width:1px;
border-style: solid;
border-color:rgb(225, 245, 212);
border-radius: 7px;
background: #dcf8c8;
box-shadow: 5px 5px 5px #b0c6a0,
0px -0px 7px #fffff0;
}
span.username {
color: rgb(26, 26, 26);
font-size: 14px;
font-weight: bolder;
}
span.date {
color: rgb(20, 20, 20);
font-style: Oblique;
font-size: 10px;
}
ol.img {
display: block;
margin-left: auto;
margin-right: auto;
width: 50%;
border-width:1px;
border-style: solid;
border-color:rgb(225, 245, 212);
}
ol.date-index {
list-style: none;
}
</style>
</head>
<body>
<h1>{{ input_basename }}</h1>
<ol class="date-index">
{% for month, days in dates %}
<li> {{ month[0] }}-{{ month[1] }}
{% for day, date_ in days %}
<a href="#{{ date_ }}">{{ day }}</a>
{% endfor %}
</li>
{% endfor %}
</ol>
<ol class="users">
{% for user, first_msg_date, messages in by_user -%}
<li>
<a id="{{first_msg_date}}">
<span class="username">{{ user }}</span>
</a>
<span class="date">{{ messages[0][0] }}</span>
<ol class="messages">
{% for _, _, body, media in messages -%}
{% if media is not none -%}
<li class="media">
{% if media.mime.startswith("image/") %}
<a href='{{ media.path }}' target="_blank"><img src='{{ media.path }}' width="400"></img></a>
{% elif media.mime.startswith("audio/") %}
<audio controls>
<source src="{{ media.path }}" type="{{ media.mime }}">
</audio>
{% elif media.mime.startswith("video/") %}
<video controls>
<source src="{{ media.path }}" type="{{ media.mime }}"/>
</video>
{%- else -%}
unsupported media {{ media.path | e }}
{%- endif %}
</li>
{% else %}
<li class="text-msg">{{ body | e }}</li>
{% endif %}
{%- endfor %}
</ol>
</li>
{% endfor %}
</ol>
</body>
</html>
"""
return jinja2.Environment().from_string(tmpl).render(**data)
def main():
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(description='Produce a browsable history '
'of a WhatsApp conversation')
parser.add_argument('-i', dest='input_file', required=True)
parser.add_argument('-o', dest='output_file', required=True)
args = parser.parse_args()
with open(args.input_file, 'rt', encoding='utf-8-sig') as fd:
messages = IdentifyMessages(fd.readlines())
template_data = TemplateData(messages, args.input_file)
HTML = FormatHTML(template_data)
with open(args.output_file, 'w', encoding='utf-8') as fd:
fd.write(HTML)
if __name__ == '__main__':
main()