-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy path_rewrite_posts.py
More file actions
587 lines (520 loc) · 19.8 KB
/
Copy path_rewrite_posts.py
File metadata and controls
587 lines (520 loc) · 19.8 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
#!/usr/bin/env python3
"""Rewrite each post HTML with the new site layout.
Reads existing post HTML, extracts the article body / title / tags / date,
then wraps them in the new layout (top nav + sidebar + footer).
"""
import json
import re
from collections import Counter
from html import escape
from html import unescape as _unescape
def unescape(s):
"""Unescape repeatedly until stable — handles previously double-escaped strings."""
if s is None:
return s
prev = None
while prev != s:
prev = s
s = _unescape(s)
return s
from pathlib import Path
ROOT = Path(__file__).parent
CAT_LABEL = {
"thought": "思考",
"chatbot": "Chatbot",
"presentation": "演讲",
"interview": "访谈",
"project": "项目",
"reading": "读书",
"saas": "SaaS",
"microsoft": "Microsoft",
"tech": "Tech",
}
POST_DIRS = ["chatbot", "interview", "microsoft", "presentation",
"project", "reading", "saas", "thought"]
SITE_URL = "https://rui.juzi.bot"
HEAD = """<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{title} · 李佳芮的博客</title>
<meta name="description" content="{desc}">
<meta name="author" content="李佳芮">
<meta name="keywords" content="{keywords}">
<link rel="canonical" href="{canonical}">
<meta property="og:title" content="{title}">
<meta property="og:description" content="{desc}">
<meta property="og:type" content="article">
<meta property="og:url" content="{canonical}">
<meta property="og:image" content="{og_image}">
<meta property="og:site_name" content="李佳芮的博客">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="李佳芮">
<meta property="article:published_time" content="{date_iso}">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="{title}">
<meta name="twitter:description" content="{desc}">
<meta name="twitter:image" content="{og_image}">
<link rel="stylesheet" href="/css/site.css?v=20260816">
<link rel="shortcut icon" href="/images/favicon.png?v=3">
<link rel="apple-touch-icon" href="/images/apple-touch-icon.png?v=3">
<link rel="alternate" type="application/rss+xml" title="李佳芮的博客 RSS" href="/feed.xml">
<script defer src="https://cloud.umami.is/script.js" data-website-id="ad8bf824-0bb3-4a1a-9cc6-800a038b222f"></script>
<script>
var _hmt = _hmt || [];
(function() {{
var hm = document.createElement("script");
hm.src = "https://hm.baidu.com/hm.js?5454a88502f6c286882f8de764e762bf";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
}})();
</script>
{ld_json}
</head>
<body>
"""
FOOT = """<footer class="site-foot"><div class="wrap">
<a href="https://github.com/lijiarui">GitHub</a>
<a href="https://juzibot.com">句子互动</a>
<a href="/claude/">Claude 永动机</a>
<a href="/blog/">博客</a>
<a href="/slides/">分享 PPT</a>
<a href="/yearly/">年度思考</a>
<a href="/feed.xml">RSS</a>
<a href="/about/">关于</a>
<div class="copyright">© Li Jiarui · 时间看得见</div>
</div></footer>
<script src="/js/search.js" defer></script>
</body></html>
"""
def topnav():
items = [
("home", "/", "首页"),
("claude", "/claude/", "Claude 永动机"),
("blog", "/blog/", "博客"),
("slides", "/slides/", "分享 PPT"),
("yearly", "/yearly/", "年度思考"),
("about", "/about/", "关于"),
]
links = "".join(f'<a href="{href}">{label}</a>' for _, href, label in items)
links += '<a href="https://github.com/lijiarui" target="_blank" rel="noopener" class="nav-ext" title="GitHub">GitHub ↗</a>'
return f"""<header class="topnav"><div class="wrap row">
<div class="brand"><a href="/">李佳芮</a><span class="tagline">时间看得见</span></div>
<nav>{links}</nav>
</div></header>
"""
def load_posts():
data = json.loads((ROOT / "content.json").read_text())
posts = data["posts"]
for p in posts:
cat = p["categories"][0]["name"] if p.get("categories") else "thought"
p["_cat"] = cat
p["_cat_label"] = CAT_LABEL.get(cat, cat.title())
d = p.get("date", "")
p["_date"] = d[:10]
p["_year"] = d[:4]
posts.sort(key=lambda p: p.get("date", ""), reverse=True)
return posts
def sidebar(posts, slide_posts):
"""Compact sidebar for article pages — fewer widgets, tighter."""
recent_html = "".join(
f'<li><a href="/{escape(p["path"])}">{escape(p["title"])}</a></li>'
for p in posts[:8]
)
cat_count = Counter(p["_cat"] for p in posts)
cat_html = "".join(
f'<li><a href="/blog/#{c}">{escape(CAT_LABEL.get(c, c))}</a>'
f'<span class="count">{n}</span></li>'
for c, n in cat_count.most_common()
)
year_count = Counter(p["_year"] for p in posts if p["_year"])
year_html = "".join(
f'<li><a href="/blog/#y{y}">{y}</a><span class="count">{n}</span></li>'
for y, n in sorted(year_count.items(), reverse=True)
)
return f"""<aside class="sidebar">
<div class="widget">
<h3>搜索</h3>
<div class="search-box">
<input type="search" id="search-input" placeholder="搜索文章关键词…" autocomplete="off">
<ul class="search-results" id="search-results"></ul>
</div>
</div>
<div class="widget">
<div class="about-box">
<img src="/images/avatar.jpg?v=2" alt="李佳芮" class="about-avatar" loading="lazy" decoding="async">
<p><strong>李佳芮</strong>,<a href="https://juzibot.com">句子互动</a> 创始人。</p>
<p>创业、产品、读书,断断续续写了十年。</p>
<p>十年前我是程序员,这个博客是自己写的。后来做公司,代码不写了,更新也停了。</p>
<p>最近又能写起来——这次没自己动手,AI 干的。</p>
</div>
</div>
<div class="widget">
<h3>微信</h3>
<div class="wechat-box">
<img src="/images/wechat-qr.jpg" alt="微信公众号" class="wechat-qr" loading="lazy" decoding="async">
<p class="wechat-cap">扫码关注公众号</p>
<p class="wechat-id">个人微信 · <code>jiaruijuzi</code></p>
</div>
</div>
<div class="widget">
<h3>近期文章</h3>
<ul>{recent_html}</ul>
</div>
<div class="widget">
<h3>分类</h3>
<ul>{cat_html}</ul>
</div>
<div class="widget">
<h3>归档</h3>
<ul>{year_html}</ul>
</div>
<div class="widget">
<h3>订阅</h3>
<ul>
<li><a href="/feed.xml" title="RSS Feed">RSS Feed <span class="rss-badge">📡</span></a></li>
</ul>
</div>
</aside>"""
def clean_feishu_html(html):
"""Convert Feishu custom tags in rendered HTML to standard HTML."""
# callout: <p><callout ...></p>TEXT</callout></p> → <div class="callout">TEXT</div>
html = re.sub(r'<p>\s*<callout[^>]*>\s*</p>', '<div class="callout">', html, flags=re.I)
html = re.sub(r'</callout>\s*</p>', '</div>', html, flags=re.I)
html = re.sub(r'<callout[^>]*>', '<div class="callout">', html, flags=re.I)
html = re.sub(r'</callout>', '</div>', html, flags=re.I)
# quote-container: strip wrapper only, keep inner content
html = re.sub(r'<p>\s*<quote-container[^>]*>\s*</p>', '', html, flags=re.I)
html = re.sub(r'</quote-container[^>]*>\s*</p>', '', html, flags=re.I)
html = re.sub(r'</?quote-container[^>]*>', '', html, flags=re.I)
# <text color="X"> → <span style="color:X">
def _text_to_span(m):
attrs = m.group(1)
color_m = re.search(r'color="([^"]+)"', attrs)
underline_m = re.search(r'underline="true"', attrs)
styles = []
if color_m:
styles.append(f'color:{color_m.group(1)}')
if underline_m:
styles.append('text-decoration:underline')
return f'<span style="{";".join(styles)}">' if styles else '<span>'
html = re.sub(r'<text\s+([^>]*)>', _text_to_span, html, flags=re.I)
html = re.sub(r'<text>', '<span>', html, flags=re.I)
html = re.sub(r'</text>', '</span>', html, flags=re.I)
# SEO + perf: lazy loading + async decode for all <img> tags missing them
def _img_hints(m):
tag = m.group(0)
lower = tag.lower()
extra = ''
if 'loading=' not in lower:
extra += ' loading="lazy"'
if 'decoding=' not in lower:
extra += ' decoding="async"'
if not extra:
return tag
if tag.endswith('/>'):
return tag[:-2].rstrip() + extra + '/>'
return tag[:-1] + extra + '>'
html = re.sub(r'<img\b[^>]*>', _img_hints, html, flags=re.I)
# 正文所有链接新标签页打开(页内锚点除外)
def _a_blank(m):
tag = m.group(0)
lower = tag.lower()
href_m = re.search(r'href="([^"]*)"', tag, flags=re.I)
if not href_m or href_m.group(1).startswith('#'):
return tag
if 'target=' not in lower:
tag = tag[:-1] + ' target="_blank"' + tag[-1]
if 'rel=' not in lower:
tag = tag[:-1] + ' rel="noopener"' + tag[-1]
return tag
html = re.sub(r'<a\b[^>]*>', _a_blank, html, flags=re.I)
return html
def extract_post(html):
"""Parse the body, title, date, tags from either legacy or new HTML."""
body = ""
# try patterns: legacy (post-tool follows), new (post-tags or post-wechat follow), fallback (article close)
for pat in (
r'<div class="post-content markdown-body">(.*?)</div>\s*<div class="post-tool">',
r'<div class="post-content markdown-body">(.*?)</div>\s*<div class="post-tags">',
r'<div class="post-content markdown-body">(.*?)</div>\s*<aside class="post-wechat">',
r'<div class="post-content markdown-body">(.*?)</div>\s*</article>',
):
m = re.search(pat, html, re.S)
if m:
body = clean_feishu_html(m.group(1).strip())
break
# Title: legacy h2, or new h1 — unescape entities so we don't double-escape later
title_m = re.search(r'<h2 class="post-title">(.*?)</h2>', html, re.S)
if not title_m:
title_m = re.search(r'<h1 class="post-title-h1">(.*?)</h1>', html, re.S)
title = unescape(title_m.group(1).strip()) if title_m else ""
# Date: legacy span, or new <time>
date_m = re.search(r'<span title="最后编辑于[^"]*">([^<]+)</span>', html)
if not date_m:
date_m = re.search(r'<div class="post-byline">\s*<time>([^<]+)</time>', html)
date = unescape(date_m.group(1).strip()) if date_m else ""
# Tags: legacy /tags/ links, or new .post-tag spans
tags = re.findall(r'<a href="/tags/[^"]*/?">([^<]+)</a>', html)
if not tags:
tags = [t.lstrip("#") for t in re.findall(r'<span class="post-tag">([^<]+)</span>', html)]
tags = [unescape(t) for t in tags]
# Word count: legacy "本文共计N个字", or new "全文 N 字"
word_m = re.search(r'本文共计(\d+)个字', html)
if not word_m:
word_m = re.search(r'全文\s*(\d+)\s*字', html)
word_count = word_m.group(1) if word_m else None
return {
"title": title,
"date": date,
"tags": tags,
"word_count": word_count,
"body": body,
}
def neighbors(posts, current_path):
paths = [p["path"] for p in posts]
try:
i = paths.index(current_path)
except ValueError:
return None, None
# posts sorted desc by date — index 0 is newest
newer = posts[i - 1] if i > 0 else None
older = posts[i + 1] if i < len(posts) - 1 else None
return newer, older
def find_related(post, posts, n=3):
"""Find n posts with highest tag overlap; ties broken by date (newer wins)."""
post_tags = set(t["name"] for t in post.get("tags", []))
if not post_tags:
return []
scored = []
for p in posts:
if p["path"] == post["path"]:
continue
p_tags = set(t["name"] for t in p.get("tags", []))
overlap = len(post_tags & p_tags)
if overlap > 0:
scored.append((overlap, p.get("date", ""), p))
# sort: higher overlap first, then more recent
scored.sort(key=lambda x: (x[0], x[1]), reverse=True)
return [p for _, _, p in scored[:n]]
def build_post_page(post_meta, parsed, side_html, newer, older, related=None):
title = parsed["title"] or post_meta["title"]
date = parsed["date"] or post_meta["_date"]
cat = post_meta["_cat_label"]
body = parsed["body"]
tags_html = ""
if parsed["tags"]:
tags_html = '<div class="post-tags">' + "".join(
f'<span class="post-tag">#{escape(t)}</span>' for t in parsed["tags"]
) + '</div>'
related_html = ""
if related:
items = "".join(
f'<li><a href="/{escape(p["path"])}">{escape(p["title"])}</a>'
f'<span class="post-related-date">{escape(p.get("date","")[:10])}</span></li>'
for p in related
)
related_html = (
f'<aside class="post-related">'
f'<h3>相关阅读</h3><ul>{items}</ul>'
f'</aside>'
)
wechat_block = """<aside class="post-wechat">
<img src="/images/wechat-qr.jpg" alt="李佳芮的公众号" class="post-wechat-qr" loading="lazy" decoding="async">
<div class="post-wechat-text">
<h4>欢迎扫码关注</h4>
<p>不定期更新 · 创业、产品、读书</p>
<p class="post-wechat-id">个人微信 · <code>jiaruijuzi</code></p>
</div>
</aside>"""
# 2026-09-07: LiveRe 评论插件带广告,Grace 要求全站去掉;评论区留空
comments_block = ""
word_html = ""
if parsed["word_count"]:
word_html = f' · 全文 {parsed["word_count"]} 字'
nav_html = ""
if newer or older:
n_html = (
f'<a class="prev" href="/{escape(newer["path"])}">← {escape(newer["title"])}</a>'
if newer else '<span class="prev"></span>'
)
o_html = (
f'<a class="next" href="/{escape(older["path"])}">{escape(older["title"])} →</a>'
if older else '<span class="next"></span>'
)
nav_html = f'<nav class="post-nav">{n_html}{o_html}</nav>'
body_html = f"""{topnav()}
<div class="wrap">
<div class="cols">
<main class="post-main">
<article class="post-article">
<header class="post-head">
<div class="post-cat-line">
<a href="/blog/#{post_meta['_cat']}" class="post-cat">{escape(cat)}</a>
</div>
<h1 class="post-title-h1">{escape(title)}</h1>
<div class="post-byline">
<time>{escape(date)}</time>{word_html}
</div>
</header>
<div class="post-content markdown-body">
{body}
</div>
{tags_html}
{related_html}
{wechat_block}
</article>
{comments_block}
{nav_html}
</main>
{side_html}
</div>
</div>
{FOOT}"""
# SEO description: prefer explicit description from content.json (set via posts/*.md frontmatter)
desc = post_meta.get("description") or ""
if not desc:
desc = re.sub(r"<[^>]+>", "", body)[:150].replace("\n", " ").strip()
desc = unescape(desc)
_path = post_meta["path"]
if _path.endswith("/index.html"):
_path = _path[: -len("index.html")]
canonical = f"{SITE_URL}/{_path}"
keywords = ", ".join([t["name"] for t in post_meta.get("tags", [])][:8])
# OG image: first <img> in body, else avatar
og_image_match = re.search(r'<img[^>]+src="([^"]+)"', body)
og_image = og_image_match.group(1) if og_image_match else "/images/avatar.jpg"
if og_image.startswith("/"):
og_image = SITE_URL + og_image
# JSON-LD structured data
import json as _json
ld_data = {
"@context": "https://schema.org",
"@type": "BlogPosting",
"headline": title,
"description": desc,
"image": og_image,
"url": canonical,
"datePublished": post_meta.get("date", "")[:10],
"dateModified": post_meta.get("updated", post_meta.get("date", ""))[:10],
"author": {"@type": "Person", "name": "李佳芮", "url": SITE_URL},
"publisher": {
"@type": "Person",
"name": "李佳芮",
"logo": {"@type": "ImageObject", "url": f"{SITE_URL}/images/avatar.jpg"},
},
"mainEntityOfPage": canonical,
"keywords": keywords,
}
breadcrumb_data = {
"@context": "https://schema.org",
"@type": "BreadcrumbList",
"itemListElement": [
{"@type": "ListItem", "position": 1, "name": "首页", "item": SITE_URL + "/"},
{"@type": "ListItem", "position": 2, "name": "博客", "item": SITE_URL + "/blog/"},
{"@type": "ListItem", "position": 3, "name": title, "item": canonical},
],
}
ld_json = (
f'<script type="application/ld+json">{_json.dumps(ld_data, ensure_ascii=False)}</script>\n'
f'<script type="application/ld+json">{_json.dumps(breadcrumb_data, ensure_ascii=False)}</script>'
)
head = HEAD.format(
title=escape(title),
desc=escape(desc),
canonical=escape(canonical),
og_image=escape(og_image),
keywords=escape(keywords),
date_iso=escape(post_meta.get("date", "")[:10]),
ld_json=ld_json,
)
return head + body_html
def build_page(parsed, side_html, page_meta):
"""Build a static page (about, links, etc) — no comment form, no wechat block."""
title = parsed["title"] or page_meta.get("title", "")
body = parsed["body"]
body_html = f"""{topnav()}
<div class="wrap">
<div class="cols">
<main class="post-main">
<article class="post-article">
<header class="post-head">
<h1 class="post-title-h1">{escape(title)}</h1>
</header>
<div class="post-content markdown-body">
{body}
</div>
</article>
</main>
{side_html}
</div>
</div>
{FOOT}"""
desc = re.sub(r"<[^>]+>", "", body)[:120].replace("\n", " ").strip()
desc = unescape(desc)
path = page_meta.get("path", "")
_cpath = path[: -len("index.html")] if path.endswith("/index.html") else path
canonical = f"{SITE_URL}/{_cpath}" if _cpath else SITE_URL
head = HEAD.format(
title=escape(title),
desc=escape(desc),
canonical=escape(canonical),
og_image=escape(f"{SITE_URL}/images/avatar.jpg"),
keywords="",
date_iso="",
ld_json="",
)
return head + body_html
def main():
posts = load_posts()
blog_posts = [p for p in posts if p["_cat"] != "presentation"]
slide_posts = [p for p in posts if p["_cat"] == "presentation"]
side_html = sidebar(blog_posts, slide_posts)
rewritten = 0
skipped = 0
failed = []
for p in posts:
fp = ROOT / p["path"]
if not fp.exists():
skipped += 1
continue
original = fp.read_text(errors="ignore")
if 'class="post-content markdown-body"' not in original:
skipped += 1
continue
parsed = extract_post(original)
if not parsed["body"]:
failed.append(p["path"])
continue
newer, older = neighbors(posts, p["path"])
related = find_related(p, posts, n=3)
new_html = build_post_page(p, parsed, side_html, newer, older, related=related)
fp.write_text(new_html, encoding="utf-8")
rewritten += 1
# ---- Standalone pages (about, links, help) ----
data = json.loads((ROOT / "content.json").read_text())
for page in data.get("pages", []):
path = page.get("path", "")
if path not in ("about/index.html",): # only about for now
continue
fp = ROOT / path
if not fp.exists():
continue
original = fp.read_text(errors="ignore")
if 'class="post-content markdown-body"' not in original:
continue
parsed = extract_post(original)
if not parsed["body"]:
failed.append(path)
continue
new_html = build_page(parsed, side_html, page)
fp.write_text(new_html, encoding="utf-8")
print(f"rewrote page {path}")
print(f"rewrote {rewritten} posts, skipped {skipped}")
if failed:
print(f"failed ({len(failed)}):")
for f in failed[:10]:
print(f" {f}")
if __name__ == "__main__":
main()