-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkindle_send.py
More file actions
369 lines (316 loc) · 13.5 KB
/
kindle_send.py
File metadata and controls
369 lines (316 loc) · 13.5 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
#!/usr/bin/env python3
"""
Kindle Scribe Document Sender
Send PDFs with checkboxes to Kindle Scribe for pen annotation.
Usage:
./kindle_send.py --html file.html Send HTML as PDF
./kindle_send.py --pdf file.pdf Send existing PDF
./kindle_send.py --checklist file.txt Convert checklist text to PDF
./kindle_send.py --subject "My Doc" Custom email subject (default: filename)
"""
import argparse
import base64
import json
import logging
import os
import sys
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from pathlib import Path
from google.auth.transport.requests import Request as GoogleRequest
from google.oauth2.credentials import Credentials as GoogleCredentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build as google_build
SCRIPT_DIR = Path(__file__).resolve().parent
CONFIG_FILE = SCRIPT_DIR / "config.json"
GOOGLE_GMAIL_SCOPES = [
"https://www.googleapis.com/auth/gmail.send",
]
logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(message)s", datefmt="%H:%M:%S")
log = logging.getLogger(__name__)
logging.getLogger("googleapiclient.discovery_cache").setLevel(logging.ERROR)
def load_config():
with open(CONFIG_FILE) as f:
return json.load(f)
def get_gmail_creds():
token_file = SCRIPT_DIR / ".google_token.json"
creds_path = SCRIPT_DIR / "google_credentials.json"
creds = None
if token_file.exists():
creds = GoogleCredentials.from_authorized_user_file(str(token_file), GOOGLE_GMAIL_SCOPES)
if creds and creds.expired and creds.refresh_token:
creds.refresh(GoogleRequest())
token_file.write_text(creds.to_json())
os.chmod(token_file, 0o600)
if creds and creds.valid:
return creds
if not creds_path.exists():
log.error(f"Gmail credentials not found at {creds_path}")
return None
flow = InstalledAppFlow.from_client_secrets_file(str(creds_path), GOOGLE_GMAIL_SCOPES)
creds = flow.run_local_server(port=0)
token_file.write_text(creds.to_json())
os.chmod(token_file, 0o600)
return creds
def html_to_pdf(html_content: str, output_path: Path):
from weasyprint import HTML as WeasyHTML
WeasyHTML(string=html_content).write_pdf(str(output_path))
def make_cover_image(title: str, subtitle: str = "", meta: str = "",
stats: str = "", width: int = 1240, height: int = 1754) -> str:
"""Generate a cover image and return base64 data URI. Size default = A4 at 150 DPI."""
from PIL import Image, ImageDraw, ImageFont
import io
img = Image.new("RGB", (width, height), "#eef2f7")
draw = ImageDraw.Draw(img)
# Border rectangle
margin = 80
draw.rectangle(
[margin, margin, width - margin, height - margin],
outline="#2c3e50", width=6
)
# Inner decorative lines
inner = margin + 30
draw.line([(inner, inner), (width - inner, inner)], fill="#2c3e50", width=2)
draw.line([(inner, height - inner), (width - inner, height - inner)], fill="#2c3e50", width=2)
# Try to load a nice font, fall back to default
def get_font(size):
for name in ["Georgia.ttf", "Georgia", "Times New Roman.ttf",
"/System/Library/Fonts/Supplemental/Georgia.ttf",
"/System/Library/Fonts/Times.ttc"]:
try:
return ImageFont.truetype(name, size)
except (OSError, IOError):
continue
return ImageFont.load_default()
font_title = get_font(72)
font_subtitle = get_font(36)
font_meta = get_font(28)
# Center title — handle multiline for long titles
cy = height // 2 - 120
words = title.split()
lines = []
current = ""
for w in words:
test = f"{current} {w}".strip()
bbox = draw.textbbox((0, 0), test, font=font_title)
if bbox[2] - bbox[0] > width - 2 * margin - 80:
if current:
lines.append(current)
current = w
else:
current = test
if current:
lines.append(current)
for i, line in enumerate(lines):
bbox = draw.textbbox((0, 0), line, font=font_title)
tw = bbox[2] - bbox[0]
x = (width - tw) // 2
draw.text((x, cy + i * 90), line, fill="#2c3e50", font=font_title)
# Decorative line under title
line_y = cy + len(lines) * 90 + 30
lw = width // 3
draw.line([(width // 2 - lw // 2, line_y), (width // 2 + lw // 2, line_y)],
fill="#2c3e50", width=3)
# Subtitle
if subtitle:
bbox = draw.textbbox((0, 0), subtitle, font=font_subtitle)
tw = bbox[2] - bbox[0]
draw.text(((width - tw) // 2, line_y + 40), subtitle, fill="#555555", font=font_subtitle)
# Stats
if stats:
bbox = draw.textbbox((0, 0), stats, font=font_meta)
tw = bbox[2] - bbox[0]
draw.text(((width - tw) // 2, height - margin - 160), stats, fill="#888888", font=font_meta)
# Meta (author/date) at bottom
if meta:
bbox = draw.textbbox((0, 0), meta, font=font_meta)
tw = bbox[2] - bbox[0]
draw.text(((width - tw) // 2, height - margin - 110), meta, fill="#777777", font=font_meta)
buf = io.BytesIO()
img.save(buf, format="PNG", optimize=True)
b64 = base64.b64encode(buf.getvalue()).decode()
return f"data:image/png;base64,{b64}"
def checklist_to_html(text: str, title: str = "Checklist", columns: int = 1,
author: str = "", description: str = "", cover: bool = True) -> str:
"""Convert structured text with headers and items into checkbox HTML.
Format: lines starting with ## are section headers.
Comma-separated items on a single line become individual checkboxes.
Lines starting with - or * are individual items.
"""
from datetime import datetime
lines = text.strip().splitlines()
col_width = {1: "100%", 2: "48%", 3: "31%"}[columns]
# Count items for cover stats
total_items = 0
total_sections = 0
for line in lines:
line = line.rstrip()
if not line:
continue
if line.startswith("## "):
total_sections += 1
continue
if line.startswith("# "):
continue
if "," in line:
total_items += len([i for i in line.split(",") if i.strip()])
else:
total_items += 1
date_str = datetime.now().strftime("%d.%m.%Y")
meta_author = f'<meta name="author" content="{author}">' if author else ''
meta_desc = f'<meta name="description" content="{description}">' if description else ''
parts = [
f'<!DOCTYPE html><html><head><title>{title}</title>',
meta_author,
meta_desc,
f'<meta name="dcterms.created" content="{datetime.now().strftime("%Y-%m-%d")}">',
'<style>',
'@page { size: A4; margin: 20mm; }',
'@page cover { margin: 0; }',
'body { font-family: Georgia, serif; font-size: 10pt; }',
'h1 { font-size: 14pt; margin-bottom: 4pt; margin-top: 0; }',
'h2 { font-size: 11pt; margin-top: 8pt; margin-bottom: 2pt; font-weight: bold; clear: both; border-bottom: 1px solid #999; padding-bottom: 2pt; }',
f'.col {{ float: left; width: {col_width}; }}' if columns > 1 else '',
'.item { margin: 1pt 0; padding-left: 8pt; font-size: 9.5pt; }',
'.clear { clear: both; }',
'.notes { border-bottom: 1px solid #ccc; margin: 6pt 0; }',
'.cover { page: cover; page-break-after: always; margin: 0; padding: 0; }',
'.cover img { width: 210mm; height: 297mm; display: block; }',
'</style></head><body>',
]
if cover:
stats_text = f"{total_sections} sections \u00b7 {total_items} items"
meta_line = date_str
if author:
meta_line = f"{author} \u00b7 {date_str}"
cover_uri = make_cover_image(title, subtitle=description, meta=meta_line, stats=stats_text)
parts.append(f'<div class="cover"><img src="{cover_uri}" /></div>')
parts.append('<div style="page-break-before: always;"></div>')
parts.append(f'<h1>{title}</h1>')
for line in lines:
line = line.rstrip()
if not line:
continue
if line.startswith("## "):
parts.append(f'<div class="clear"></div><h2>{line[3:]}</h2>')
continue
if line.startswith("# "):
parts.append(f'<div class="clear"></div><h1>{line[2:]}</h1>')
continue
# Split comma-separated items
if "," in line:
items = [i.strip() for i in line.split(",") if i.strip()]
elif line.startswith("- ") or line.startswith("* "):
items = [line[2:].strip()]
else:
items = [line.strip()]
if columns > 1:
for i, item in enumerate(items):
if i % columns == 0 and i > 0:
parts.append('<div class="clear"></div>')
parts.append(f'<div class="col"><p class="item">[ ] {item}</p></div>')
parts.append('<div class="clear"></div>')
else:
for item in items:
parts.append(f'<p class="item">[ ] {item}</p>')
# Blank lines for notes
parts.append('<div class="clear"></div>')
parts.append('<h2>Notes</h2>')
for _ in range(10):
parts.append('<p class="notes"> </p>')
parts.append('</body></html>')
return '\n'.join(parts)
def send_to_kindle(pdf_path: Path, subject: str = None):
"""Send PDF to Kindle Scribe via Gmail."""
cfg = load_config()
kindle_cfg = cfg.get("kindle", {})
to_email = kindle_cfg.get("to_email")
from_email = kindle_cfg.get("from_email")
if not to_email or not from_email:
log.error("Kindle not configured in config.json")
return False
creds = get_gmail_creds()
if not creds:
return False
service = google_build("gmail", "v1", credentials=creds)
subject = subject or pdf_path.stem
msg = MIMEMultipart("mixed")
msg["From"] = from_email
msg["To"] = to_email
msg["Subject"] = subject
msg.attach(MIMEText("Document attached.", "plain"))
part = MIMEBase("application", "pdf")
with open(pdf_path, "rb") as f:
part.set_payload(f.read())
encoders.encode_base64(part)
part.add_header("Content-Disposition", "attachment", filename=pdf_path.name)
msg.attach(part)
raw = base64.urlsafe_b64encode(msg.as_bytes()).decode()
service.users().messages().send(userId="me", body={"raw": raw}).execute()
log.info(f"Sent to Kindle: {pdf_path.name} ({pdf_path.stat().st_size // 1024}KB)")
return True
def main():
parser = argparse.ArgumentParser(description="Send documents to Kindle Scribe")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--html", help="HTML file to convert to PDF and send")
group.add_argument("--pdf", help="PDF file to send directly")
group.add_argument("--checklist", help="Text file with checklist items (lines become checkboxes)")
parser.add_argument("--subject", help="Email subject (default: filename)")
parser.add_argument("--title", help="Document title for checklist (default: filename)")
parser.add_argument("--author", help="Author/description shown on cover and in PDF metadata")
parser.add_argument("--description", help="Subtitle shown on cover page")
parser.add_argument("--columns", type=int, default=1, choices=[1, 2, 3], help="Number of columns for checklist layout (default: 1)")
parser.add_argument("--no-cover", action="store_true", help="Skip cover page")
parser.add_argument("--output", help="Save PDF to this path instead of temp")
parser.add_argument("--no-send", action="store_true", help="Generate PDF only, don't send to Kindle")
args = parser.parse_args()
pdf_dir = SCRIPT_DIR / "pdfs"
pdf_dir.mkdir(exist_ok=True)
if args.pdf:
pdf_path = Path(args.pdf)
if not pdf_path.exists():
print(f"File not found: {pdf_path}")
sys.exit(1)
elif args.html:
html_path = Path(args.html)
if not html_path.exists():
print(f"File not found: {html_path}")
sys.exit(1)
html_content = html_path.read_text()
pdf_path = Path(args.output) if args.output else pdf_dir / f"{html_path.stem}.pdf"
html_to_pdf(html_content, pdf_path)
log.info(f"PDF generated: {pdf_path}")
elif args.checklist:
checklist_path = Path(args.checklist)
if not checklist_path.exists():
print(f"File not found: {checklist_path}")
sys.exit(1)
from datetime import datetime
text = checklist_path.read_text()
title = args.title or checklist_path.stem.replace("_", " ").title()
html = checklist_to_html(
text, title,
columns=args.columns,
author=args.author or datetime.now().strftime("%d.%m.%Y %H:%M"),
description=args.description or "",
cover=not args.no_cover,
)
if args.output:
pdf_path = Path(args.output)
else:
date_tag = datetime.now().strftime("%d.%m.%Y")
filename = f"{title} — {date_tag}.pdf"
pdf_path = pdf_dir / filename
html_to_pdf(html, pdf_path)
log.info(f"PDF generated: {pdf_path}")
if args.no_send:
print(f"PDF saved: {pdf_path}")
elif send_to_kindle(pdf_path, args.subject or pdf_path.stem.replace("_", " ")):
print(f"Sent to Kindle: {pdf_path.name}")
else:
print("Failed to send")
sys.exit(1)
if __name__ == "__main__":
main()