Repository navigation
Expand file tree
/
Copy pathprocessor.py
More file actions
808 lines (683 loc) · 27.1 KB
/
Copy pathprocessor.py
File metadata and controls
808 lines (683 loc) · 27.1 KB
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
"""
WhatsApp Export Processor
Core processing logic for extracting, transcribing, and reconstructing WhatsApp exports.
This module provides the backend for the web UI.
"""
import json
import os
import random
import re
import shutil
import subprocess
import zipfile
from dataclasses import dataclass, field
from pathlib import Path
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
@dataclass
class Message:
"""Represents a single chat message."""
timestamp: str
sender: str
content: str
is_attachment: bool = False
attachment_name: str | None = None
attachment_type: str | None = None # 'voice', 'image', 'video', 'other'
transcription: str | None = None
@dataclass
class ChatExport:
"""Represents a parsed WhatsApp chat export."""
messages: list[Message] = field(default_factory=list)
participants: set[str] = field(default_factory=set)
voice_messages: list[str] = field(default_factory=list)
images: list[str] = field(default_factory=list)
videos: list[str] = field(default_factory=list)
other_files: list[str] = field(default_factory=list)
transcriptions: dict[str, str] = field(default_factory=dict)
video_transcriptions: dict[str, str] = field(default_factory=dict)
extracted_dir: Path | None = None
chat_name: str = "WhatsApp Chat"
# Alias pools for anonymization
ALIAS_POOLS = {
'human': ['Alice', 'Bob', 'Carol', 'David', 'Eve', 'Frank',
'Grace', 'Henry', 'Ivy', 'Jack', 'Kate', 'Leo',
'Maria', 'Nathan', 'Olivia', 'Paul', 'Quinn', 'Rachel',
'Sam', 'Tina', 'Uma', 'Victor', 'Wendy', 'Xavier'],
'generic': [f'Participant {chr(65 + i)}' for i in range(26)],
'codename': ['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo',
'Foxtrot', 'Golf', 'Hotel', 'India', 'Juliet',
'Kilo', 'Lima', 'Mike', 'November', 'Oscar',
'Papa', 'Quebec', 'Romeo', 'Sierra', 'Tango']
}
# Regex patterns - support both DD/MM/YYYY and MM/DD/YYYY formats
MESSAGE_PATTERN = re.compile(
r"^(\d{1,2}/\d{1,2}/\d{2,4}, \d{1,2}:\d{2}(?::\d{2})?(?: [AP]M)?) - ([^:]+): (.+)$"
)
SYSTEM_PATTERN = re.compile(
r"^(\d{1,2}/\d{1,2}/\d{2,4}, \d{1,2}:\d{2}(?::\d{2})?(?: [AP]M)?) - (.+)$"
)
ATTACHMENT_PATTERN = re.compile(r"^(.+) \(file attached\)$")
CONTINUATION_PATTERN = re.compile(r"^\d{1,2}/\d{1,2}/\d{2,4}, \d{1,2}:\d{2}")
def get_attachment_type(filename: str) -> str:
"""Determine the type of attachment from filename."""
lower = filename.lower()
if lower.startswith("ptt-") or lower.endswith(".opus"):
return "voice"
elif lower.endswith((".jpg", ".jpeg", ".png", ".gif", ".webp")):
return "image"
elif lower.endswith((".mp4", ".mov", ".avi", ".mkv", ".webm")):
return "video"
return "other"
def parse_chat_text(text: str) -> ChatExport:
"""Parse WhatsApp chat text and extract messages and participants."""
export = ChatExport()
lines = text.strip().split("\n")
current_message = None
for line in lines:
if CONTINUATION_PATTERN.match(line):
match = MESSAGE_PATTERN.match(line)
if match:
if current_message:
export.messages.append(current_message)
export.participants.add(current_message.sender)
timestamp, sender, content = match.groups()
attach_match = ATTACHMENT_PATTERN.match(content)
if attach_match:
filename = attach_match.group(1)
att_type = get_attachment_type(filename)
current_message = Message(
timestamp=timestamp,
sender=sender,
content=content,
is_attachment=True,
attachment_name=filename,
attachment_type=att_type,
)
else:
current_message = Message(
timestamp=timestamp,
sender=sender,
content=content,
)
elif current_message:
current_message.content += "\n" + line
elif current_message and line:
current_message.content += "\n" + line
if current_message:
export.messages.append(current_message)
export.participants.add(current_message.sender)
return export
def categorize_files(export: ChatExport, filenames: list[str]) -> None:
"""Categorize extracted files by type."""
for filename in filenames:
lower = filename.lower()
if lower.endswith(".txt"):
continue
elif lower.startswith("ptt-") or lower.endswith(".opus"):
export.voice_messages.append(filename)
elif lower.endswith((".jpg", ".jpeg", ".png", ".gif", ".webp")):
export.images.append(filename)
elif lower.endswith((".mp4", ".mov", ".avi", ".mkv", ".webm")):
export.videos.append(filename)
else:
export.other_files.append(filename)
def convert_opus_to_ogg(opus_path: Path) -> Path | None:
"""Convert opus file to ogg format for Whisper API compatibility."""
ogg_path = opus_path.with_suffix(".ogg")
try:
result = subprocess.run(
["ffmpeg", "-y", "-i", str(opus_path), "-c:a", "libopus", str(ogg_path)],
capture_output=True,
text=True
)
if result.returncode == 0 and ogg_path.exists():
return ogg_path
return None
except FileNotFoundError:
return None
def extract_audio_from_video(video_path: Path) -> Path | None:
"""Extract audio from video file for transcription."""
audio_path = video_path.with_suffix(".audio.ogg")
try:
result = subprocess.run(
["ffmpeg", "-y", "-i", str(video_path), "-vn", "-c:a", "libopus", str(audio_path)],
capture_output=True,
text=True
)
if result.returncode == 0 and audio_path.exists():
return audio_path
return None
except FileNotFoundError:
return None
def transcribe_audio(audio_path: Path, client: OpenAI) -> str:
"""Transcribe an audio file using OpenAI Whisper API."""
try:
with open(audio_path, "rb") as audio_file:
transcription = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file,
response_format="text"
)
return transcription.strip()
except Exception as e:
return f"[Transcription failed: {e}]"
def transcribe_voice_message(audio_path: Path, client: OpenAI) -> str:
"""Transcribe a voice message using OpenAI Whisper API."""
file_to_transcribe = audio_path
converted = False
if audio_path.suffix.lower() == ".opus":
converted_path = convert_opus_to_ogg(audio_path)
if converted_path:
file_to_transcribe = converted_path
converted = True
else:
return "[Transcription failed: Could not convert opus file. Ensure ffmpeg is installed.]"
try:
result = transcribe_audio(file_to_transcribe, client)
return result
finally:
if converted and file_to_transcribe.exists():
file_to_transcribe.unlink()
def transcribe_video(video_path: Path, client: OpenAI) -> str:
"""Extract audio from video and transcribe it."""
audio_path = extract_audio_from_video(video_path)
if not audio_path:
return "[Transcription failed: Could not extract audio from video. Ensure ffmpeg is installed.]"
try:
result = transcribe_audio(audio_path, client)
return result
finally:
if audio_path.exists():
audio_path.unlink()
def transcribe_all_voice_messages(export: ChatExport, client: OpenAI, progress_callback=None) -> None:
"""Transcribe all voice messages in the export."""
if not export.extracted_dir:
return
total = len(export.voice_messages)
for i, voice_file in enumerate(export.voice_messages, 1):
audio_path = export.extracted_dir / voice_file
if audio_path.exists():
if progress_callback:
progress_callback(f"Transcribing voice message {i}/{total}: {voice_file}")
transcription = transcribe_voice_message(audio_path, client)
export.transcriptions[voice_file] = transcription
for msg in export.messages:
if msg.attachment_name == voice_file:
msg.transcription = transcription
def transcribe_all_videos(export: ChatExport, client: OpenAI, progress_callback=None) -> None:
"""Transcribe all videos in the export."""
if not export.extracted_dir:
return
total = len(export.videos)
for i, video_file in enumerate(export.videos, 1):
video_path = export.extracted_dir / video_file
if video_path.exists():
if progress_callback:
progress_callback(f"Transcribing video {i}/{total}: {video_file}")
transcription = transcribe_video(video_path, client)
export.video_transcriptions[video_file] = transcription
for msg in export.messages:
if msg.attachment_name == video_file:
msg.transcription = transcription
def generate_random_alias(style: str, used: set[str]) -> str:
"""Generate a random alias from the specified style pool."""
pool = ALIAS_POOLS.get(style, ALIAS_POOLS['human'])
available = [name for name in pool if name not in used]
if available:
return random.choice(available)
# If pool exhausted, generate numbered alias
base = pool[0] if pool else 'User'
counter = 1
while f"{base}{counter}" in used:
counter += 1
return f"{base}{counter}"
def apply_anonymization(export: ChatExport, mapping: dict[str, str]) -> None:
"""Apply anonymization mapping to all messages."""
# Update participants set
new_participants = set()
for p in export.participants:
new_participants.add(mapping.get(p, p))
export.participants = new_participants
# Update messages
for msg in export.messages:
if msg.sender in mapping:
msg.sender = mapping[msg.sender]
def extract_whatsapp_export(zip_path: Path, output_dir: Path | None = None) -> ChatExport:
"""Extract and process a WhatsApp export ZIP file."""
if not zip_path.exists():
raise FileNotFoundError(f"ZIP file not found: {zip_path}")
if output_dir is None:
output_dir = zip_path.parent / zip_path.stem
output_dir.mkdir(parents=True, exist_ok=True)
chat_text = None
extracted_files = []
with zipfile.ZipFile(zip_path, "r") as zf:
for member in zf.namelist():
zf.extract(member, output_dir)
extracted_files.append(member)
if member.lower().endswith(".txt"):
with zf.open(member) as f:
chat_text = f.read().decode("utf-8")
if chat_text is None:
raise ValueError("No chat text file found in ZIP")
export = parse_chat_text(chat_text)
export.extracted_dir = output_dir
export.chat_name = zip_path.stem
categorize_files(export, extracted_files)
return export
def get_chat_statistics(export: ChatExport) -> dict:
"""Calculate statistics about the chat export."""
stats = {
"total_messages": len(export.messages),
"participants": sorted(list(export.participants)),
"participant_count": len(export.participants),
"voice_messages": len(export.voice_messages),
"images": len(export.images),
"videos": len(export.videos),
"other_files": len(export.other_files),
"first_message": None,
"last_message": None,
"message_counts": {},
}
if export.messages:
stats["first_message"] = export.messages[0].timestamp
stats["last_message"] = export.messages[-1].timestamp
for participant in export.participants:
stats["message_counts"][participant] = sum(
1 for m in export.messages if m.sender == participant
)
return stats
def generate_participants_json(export: ChatExport, output_path: Path) -> None:
"""Generate participants.json analysis file."""
stats = get_chat_statistics(export)
participants_data = {
"participants": stats["participants"],
"message_counts": stats["message_counts"],
"voice_message_counts": {},
"total_messages": stats["total_messages"],
"date_range": {
"first": stats["first_message"],
"last": stats["last_message"],
},
"media_counts": {
"voice": stats["voice_messages"],
"images": stats["images"],
"videos": stats["videos"],
"other": stats["other_files"],
},
}
for participant in export.participants:
participants_data["voice_message_counts"][participant] = sum(
1 for m in export.messages
if m.sender == participant and m.attachment_type == "voice"
)
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, "w", encoding="utf-8") as f:
json.dump(participants_data, f, indent=2, ensure_ascii=False)
def generate_audio_index(export: ChatExport, output_path: Path) -> None:
"""Generate audio-index.json with metadata for all audio files."""
audio_entries = []
for msg in export.messages:
if msg.attachment_type == "voice" and msg.attachment_name:
entry = {
"filename": msg.attachment_name,
"sender": msg.sender,
"timestamp": msg.timestamp,
"transcription": msg.transcription,
"type": "voice",
}
audio_entries.append(entry)
elif msg.attachment_type == "video" and msg.attachment_name:
# Include videos with audio transcriptions
entry = {
"filename": msg.attachment_name,
"sender": msg.sender,
"timestamp": msg.timestamp,
"transcription": msg.transcription,
"type": "video",
}
audio_entries.append(entry)
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, "w", encoding="utf-8") as f:
json.dump(audio_entries, f, indent=2, ensure_ascii=False)
def generate_transcriptions_json(export: ChatExport, output_path: Path) -> None:
"""Generate transcriptions.json with all transcriptions and metadata."""
transcriptions = []
for msg in export.messages:
if msg.transcription:
entry = {
"filename": msg.attachment_name,
"sender": msg.sender,
"timestamp": msg.timestamp,
"transcription": msg.transcription,
"type": msg.attachment_type,
}
transcriptions.append(entry)
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, "w", encoding="utf-8") as f:
json.dump(transcriptions, f, indent=2, ensure_ascii=False)
def generate_constructed_chat(export: ChatExport, output_path: Path) -> None:
"""Generate constructed chat with transcriptions inline."""
lines = []
lines.append(f"# {export.chat_name}")
lines.append(f"# Participants: {', '.join(sorted(export.participants))}")
lines.append("")
for msg in export.messages:
if msg.is_attachment:
if msg.attachment_type == "voice" and msg.transcription:
lines.append(f"[{msg.timestamp}] {msg.sender} (voice message):")
lines.append(f' "{msg.transcription}"')
elif msg.attachment_type == "video":
if msg.transcription:
lines.append(f"[{msg.timestamp}] {msg.sender} (video):")
lines.append(f' "{msg.transcription}"')
else:
lines.append(f"[{msg.timestamp}] {msg.sender}: [Video: {msg.attachment_name}]")
elif msg.attachment_type == "image":
lines.append(f"[{msg.timestamp}] {msg.sender}: [Image: {msg.attachment_name}]")
else:
lines.append(f"[{msg.timestamp}] {msg.sender}: [Attachment: {msg.attachment_name}]")
else:
lines.append(f"[{msg.timestamp}] {msg.sender}: {msg.content}")
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
def generate_typst_file(export: ChatExport, output_path: Path) -> None:
"""Generate Typst source file for PDF generation."""
lines = [
'#set page(margin: 2cm)',
'#set text(font: "Liberation Sans", size: 11pt)',
'',
f'#align(center)[#text(size: 18pt, weight: "bold")[{export.chat_name}]]',
'',
f'#align(center)[Participants: {", ".join(sorted(export.participants))}]',
'',
'#line(length: 100%)',
'',
]
for msg in export.messages:
def escape(s):
return s.replace("\\", "\\\\").replace("#", "\\#").replace("$", "\\$").replace("@", "\\@")
sender = escape(msg.sender)
timestamp = escape(msg.timestamp)
if msg.is_attachment:
if msg.attachment_type == "voice" and msg.transcription:
transcription = escape(msg.transcription)
lines.append(f'#text(size: 9pt, fill: gray)[{timestamp}]')
lines.append(f'#text(weight: "bold")[{sender}] #text(fill: blue)[(voice message)]')
lines.append(f'#block(inset: (left: 1em))[_{transcription}_]')
lines.append('')
elif msg.attachment_type == "video":
lines.append(f'#text(size: 9pt, fill: gray)[{timestamp}]')
lines.append(f'#text(weight: "bold")[{sender}]: #text(fill: purple)[\\[Video\\]]')
if msg.transcription:
transcription = escape(msg.transcription)
lines.append(f'#block(inset: (left: 1em))[_{transcription}_]')
lines.append('')
elif msg.attachment_type == "image":
lines.append(f'#text(size: 9pt, fill: gray)[{timestamp}]')
lines.append(f'#text(weight: "bold")[{sender}]: #text(fill: green)[\\[Image\\]]')
lines.append('')
else:
lines.append(f'#text(size: 9pt, fill: gray)[{timestamp}]')
lines.append(f'#text(weight: "bold")[{sender}]: #text(fill: orange)[\\[Attachment\\]]')
lines.append('')
else:
content = escape(msg.content)
lines.append(f'#text(size: 9pt, fill: gray)[{timestamp}]')
lines.append(f'#text(weight: "bold")[{sender}]: {content}')
lines.append('')
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, "w", encoding="utf-8") as f:
f.write("\n".join(lines))
def generate_pdf(typst_path: Path, pdf_path: Path) -> bool:
"""Compile Typst file to PDF."""
try:
result = subprocess.run(
["typst", "compile", str(typst_path), str(pdf_path)],
capture_output=True,
text=True
)
if result.returncode != 0:
return False
return True
except FileNotFoundError:
return False
def generate_html_chat(export: ChatExport, output_path: Path, media_dir: Path) -> None:
"""Generate interactive HTML chat viewer."""
colors = ["#DCF8C6", "#E3F2FD", "#FFF3E0", "#F3E5F5", "#E8F5E9", "#FFEBEE"]
participant_colors = {}
for i, p in enumerate(sorted(export.participants)):
participant_colors[p] = colors[i % len(colors)]
media_rel = os.path.relpath(media_dir, output_path.parent)
messages_html = []
for msg in export.messages:
color = participant_colors.get(msg.sender, "#FFFFFF")
sender_class = "sent" if msg.sender == sorted(export.participants)[0] else "received"
if msg.is_attachment:
if msg.attachment_type == "voice":
transcription_html = ""
if msg.transcription:
transcription_html = f'<div class="transcription">"{msg.transcription}"</div>'
content_html = f'''
<div class="voice-message">
<audio controls>
<source src="{media_rel}/{msg.attachment_name}" type="audio/ogg">
Your browser does not support audio.
</audio>
{transcription_html}
</div>
'''
elif msg.attachment_type == "image":
content_html = f'''
<div class="image-message">
<img src="{media_rel}/{msg.attachment_name}" alt="Image" loading="lazy">
</div>
'''
elif msg.attachment_type == "video":
transcription_html = ""
if msg.transcription:
transcription_html = f'<div class="transcription">"{msg.transcription}"</div>'
content_html = f'''
<div class="video-message">
<video controls>
<source src="{media_rel}/{msg.attachment_name}" type="video/mp4">
Your browser does not support video.
</video>
{transcription_html}
</div>
'''
else:
content_html = f'<div class="attachment">[Attachment: {msg.attachment_name}]</div>'
else:
import html
content_html = f'<div class="text">{html.escape(msg.content)}</div>'
messages_html.append(f'''
<div class="message {sender_class}" style="background-color: {color};">
<div class="sender">{msg.sender}</div>
{content_html}
<div class="timestamp">{msg.timestamp}</div>
</div>
''')
html_content = f'''<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{export.chat_name}</title>
<style>
* {{
box-sizing: border-box;
margin: 0;
padding: 0;
}}
body {{
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
background-color: #E5DDD5;
background-image: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23d4cdc4' fill-opacity='0.4'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
}}
.container {{
max-width: 800px;
margin: 0 auto;
padding: 20px;
}}
.header {{
background: #075E54;
color: white;
padding: 15px 20px;
border-radius: 10px 10px 0 0;
margin-bottom: 0;
}}
.header h1 {{
font-size: 1.2em;
font-weight: 500;
}}
.header .participants {{
font-size: 0.85em;
opacity: 0.9;
margin-top: 5px;
}}
.chat-container {{
background: #E5DDD5;
padding: 20px;
border-radius: 0 0 10px 10px;
min-height: 400px;
}}
.message {{
max-width: 75%;
padding: 8px 12px;
margin-bottom: 10px;
border-radius: 8px;
position: relative;
box-shadow: 0 1px 1px rgba(0,0,0,0.1);
clear: both;
}}
.message.sent {{
margin-left: auto;
margin-right: 0;
float: right;
clear: both;
}}
.message.received {{
margin-left: 0;
margin-right: auto;
float: left;
clear: both;
}}
.message::after {{
content: "";
display: table;
clear: both;
}}
.sender {{
font-weight: 600;
font-size: 0.85em;
color: #075E54;
margin-bottom: 4px;
}}
.text {{
word-wrap: break-word;
line-height: 1.4;
white-space: pre-wrap;
}}
.timestamp {{
font-size: 0.7em;
color: #667781;
text-align: right;
margin-top: 4px;
}}
.voice-message audio {{
width: 100%;
max-width: 300px;
height: 40px;
}}
.transcription {{
font-style: italic;
color: #555;
margin-top: 8px;
padding: 8px;
background: rgba(255,255,255,0.5);
border-radius: 4px;
font-size: 0.9em;
}}
.image-message img {{
max-width: 100%;
max-height: 300px;
border-radius: 8px;
cursor: pointer;
}}
.video-message video {{
max-width: 100%;
max-height: 300px;
border-radius: 8px;
}}
.attachment {{
color: #667781;
font-style: italic;
}}
.clearfix::after {{
content: "";
display: table;
clear: both;
}}
.modal {{
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.9);
}}
.modal img {{
max-width: 90%;
max-height: 90%;
margin: auto;
display: block;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}}
.modal .close {{
position: absolute;
top: 20px;
right: 30px;
color: white;
font-size: 40px;
cursor: pointer;
}}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>{export.chat_name}</h1>
<div class="participants">{', '.join(sorted(export.participants))}</div>
</div>
<div class="chat-container clearfix">
{''.join(messages_html)}
</div>
</div>
<div id="imageModal" class="modal" onclick="this.style.display='none'">
<span class="close">×</span>
<img id="modalImg">
</div>
<script>
document.querySelectorAll('.image-message img').forEach(img => {{
img.onclick = function() {{
const modal = document.getElementById('imageModal');
const modalImg = document.getElementById('modalImg');
modal.style.display = 'block';
modalImg.src = this.src;
}};
}});
</script>
</body>
</html>
'''
output_path.parent.mkdir(parents=True, exist_ok=True)
with open(output_path, "w", encoding="utf-8") as f:
f.write(html_content)