-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgrowth_content_pipeline.py
More file actions
1933 lines (1692 loc) · 70.6 KB
/
Copy pathgrowth_content_pipeline.py
File metadata and controls
1933 lines (1692 loc) · 70.6 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
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""Daily growth content pipeline.
Generates short SEO-friendly engineering posts with a PaperBanana-style flow diagram,
publishes to DEV.to / LinkedIn / X, builds GitHub Pages content, and collects
engagement metrics.
"""
from __future__ import annotations
import argparse
import datetime as dt
import html
import json
import os
import re
import subprocess
import textwrap
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, Tuple
from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
import importlib
import sys
# Support both `python scripts/growth_content_pipeline.py` and `python -m scripts.growth_content_pipeline`
_scripts_dir = Path(__file__).resolve().parent
if str(_scripts_dir) not in sys.path:
sys.path.insert(0, str(_scripts_dir))
import growth_bot_analytics as bot_analytics # noqa: E402
import growth_keyword_engine as keyword_engine # noqa: E402
DEFAULT_TOPICS: Tuple[str, ...] = (
"How we shipped faster with AI-assisted test triage",
"How we automated App Store listing checks end-to-end",
"How we use RLHF-style feedback loops for mobile quality",
"How GitHub Actions reduced manual release work",
"How we measure rating risk before it hurts reviews",
)
FIRST_POST_TOPIC = "The inspiration behind Random Tactical Timer"
FIRST_POST_SOURCE = "https://www.amazon.com/Hard-Target-Become-Person-Predators/dp/B0F78ZL7ML"
DEFAULT_TAGS: Tuple[str, ...] = ("ai", "mobile", "devops", "github", "testing")
DEFAULT_BLOG_BASE_URL = "https://igorganapolsky.github.io/Random-Timer"
DEFAULT_SITE_DESCRIPTION = (
"Daily engineering posts about AI-assisted app development, automation, "
"testing, and release quality."
)
LEGACY_MARKETING_SITE_SEGMENT = "/marketing/site"
AB_PILOT_WINDOW_DAYS = 14
CANONICAL_PRIVACY_POLICY_SEGMENT = "/privacy-policy/"
LEGACY_PRIVACY_POLICY_SEGMENT = "/PRIVACY_POLICY/"
@dataclass
class PostAsset:
slug: str
title: str
description: str
created_at: str
markdown_path: Path
diagram_svg_path: Path
diagram_mermaid_path: Path
html_path: Path
tags: List[str]
def utc_now() -> dt.datetime:
return dt.datetime.now(dt.timezone.utc)
def iso_timestamp(ts: Optional[dt.datetime] = None) -> str:
moment = ts or utc_now()
return moment.replace(microsecond=0).isoformat()
def slugify(value: str) -> str:
text = re.sub(r"[^a-zA-Z0-9\s-]", "", value).strip().lower()
text = re.sub(r"[\s_-]+", "-", text)
return text[:80].strip("-") or "daily-update"
def ensure_dir(path: Path) -> None:
path.mkdir(parents=True, exist_ok=True)
def clear_generated_files(path: Path, glob_pattern: str) -> None:
if not path.is_dir():
return
for entry in path.glob(glob_pattern):
if entry.is_file():
entry.unlink()
def resolve_social_image_url(output_root: Path, site_root: Path, base_url: str) -> str:
configured_url = os.getenv("SOCIAL_OG_IMAGE_URL", "").strip()
if configured_url:
return configured_url
configured_path = os.getenv("SOCIAL_OG_IMAGE_PATH", "").strip()
candidates: List[Path] = []
if configured_path:
candidates.append(Path(configured_path).expanduser())
candidates.extend(
[
output_root.parent / "screenshots" / "ios-active.png",
output_root.parent / "screenshots" / "ios-running.png",
output_root.parent / "screenshots" / "ios-setup.png",
]
)
for source in candidates:
if not source.is_file():
continue
suffix = source.suffix.lower()
if suffix not in {".png", ".jpg", ".jpeg", ".webp", ".gif"}:
continue
assets_out = site_root / "assets"
ensure_dir(assets_out)
dest = assets_out / f"social-preview{suffix}"
dest.write_bytes(source.read_bytes())
return f"{base_url}/assets/{dest.name}"
return ""
def append_jsonl(path: Path, record: Dict[str, Any]) -> None:
ensure_dir(path.parent)
with path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(record, sort_keys=True) + "\n")
def read_jsonl(path: Path) -> List[Dict[str, Any]]:
if not path.is_file():
return []
rows: List[Dict[str, Any]] = []
for line in path.read_text(encoding="utf-8").splitlines():
if not line.strip():
continue
rows.append(json.loads(line))
return rows
def run_git_log(repo_root: Path, since_days: int = 2, max_commits: int = 8) -> List[str]:
cmd = [
"git",
"-C",
str(repo_root),
"log",
f"--since={since_days}.days",
f"--max-count={max_commits}",
"--pretty=format:%s",
]
proc = subprocess.run(cmd, capture_output=True, text=True, check=False)
if proc.returncode != 0:
return []
return [line.strip() for line in proc.stdout.splitlines() if line.strip()]
def topic_for_day(topics: Iterable[str], day: dt.date) -> str:
options = list(topics)
if not options:
options = list(DEFAULT_TOPICS)
return options[day.toordinal() % len(options)]
def ensure_keyword_backlog(output_root: Path) -> Dict[str, Any]:
keywords_dir = output_root / "keywords"
strategy_path = keywords_dir / "strategy.json"
return keyword_engine.run_build(keywords_dir, strategy_path)
def load_content_feedback(output_root: Path) -> Optional[Dict[str, Any]]:
"""Load content performance feedback from attribution pipeline."""
feedback_path = output_root / "data" / "content_feedback.json"
if not feedback_path.is_file():
return None
try:
return json.loads(feedback_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, KeyError):
return None
def choose_keyword_topic(output_root: Path, day: dt.date) -> Optional[Dict[str, Any]]:
payload = ensure_keyword_backlog(output_root)
backlog_json = payload.get("outputs", {}).get("json")
if not backlog_json:
return None
backlog_path = Path(str(backlog_json))
if not backlog_path.is_file():
return None
rows = json.loads(backlog_path.read_text(encoding="utf-8"))
# Boost keywords that drove real installs (feedback loop)
feedback = load_content_feedback(output_root)
if feedback:
top_campaigns = feedback.get("top_campaigns_by_activation", [])
boosted_sources = {
str(c.get("source", "")).strip().lower()
for c in top_campaigns
if (c.get("activation_rate") or 0) > 0.1
}
# If content from certain sources drives activation,
# prefer keywords aligned with those sources
if boosted_sources:
for row in rows:
kw = str(row.get("keyword") or "")
for source in boosted_sources:
if source in kw:
row["bid_score"] = row.get("bid_score", 0) + 15
rows.sort(key=lambda r: (r.get("ai_trap", False), -r.get("bid_score", 0)))
selected = keyword_engine.select_daily_keyword(rows, day=day)
if not selected:
return None
return {
"keyword": str(selected.get("keyword") or "").strip(),
"intent": str(selected.get("intent") or "").strip(),
"bid_score": int(selected.get("bid_score") or 0),
"title": keyword_engine.keyword_to_post_title(str(selected.get("keyword") or "")),
}
def resolve_blog_base_url(output_root: Path) -> str:
configured = os.getenv("BLOG_BASE_URL", "").strip()
if configured:
return configured.rstrip("/")
base = DEFAULT_BLOG_BASE_URL.rstrip("/")
if output_root.name == "marketing":
return f"{base}{LEGACY_MARKETING_SITE_SEGMENT}"
return base
def resolve_public_site_base_url(output_root: Path) -> str:
return resolve_blog_base_url(output_root).removesuffix(LEGACY_MARKETING_SITE_SEGMENT)
def _safe_numeric_id(value: Any) -> Optional[str]:
text = str(value or "").strip()
if re.fullmatch(r"[0-9]+", text):
return text
return None
def _safe_tweet_id(value: Any) -> Optional[str]:
text = str(value or "").strip()
if re.fullmatch(r"[0-9A-Za-z_\\-]+", text):
return text
return None
def _requests_module():
try:
import requests # type: ignore
return requests
except Exception:
return None
def build_post_copy(
topic: str,
recent_commits: List[str],
inspiration_url: str = "",
primary_keyword: str = "",
keyword_intent: str = "",
) -> Tuple[str, str, str]:
commit_bullets = "\n".join(f"- {entry}" for entry in recent_commits[:4]) or "- Stability and UX polish work"
title = topic
description = (
"A short engineering update on how we ship Random Tactical Timer faster with automation, "
"AI tooling, and measurable quality gates."
)
inspiration_block = ""
if inspiration_url:
inspiration_block = (
"## Inspiration\n"
"The core idea for Random Tactical Timer came from training principles in **Hard Target**:\n"
f"{inspiration_url}\n\n"
"We translated that mindset into product behavior: unpredictable intervals, reduced anticipation, "
"and repeatable high-focus drills."
)
sections = [
"## What changed today\n" + commit_bullets,
]
if inspiration_block:
sections.append(inspiration_block)
if primary_keyword:
sections.append(
"## Search intent target\n"
f"- Primary keyword: **{primary_keyword}**\n"
f"- Intent class: **{keyword_intent or 'mixed'}**\n"
"- BID filter: business potential, intent match, and realistic difficulty"
)
sections.extend(
[
"## AI/LLM flow we used\n"
"We keep this loop tight: plan -> code -> test -> release gate -> feedback. "
"The key is not bigger prompts, it's strict validation and fast iteration.",
"## Why this matters for users\n"
"Better release quality means fewer crashes, clearer store listing content, and faster response to "
"low-star feedback. That directly improves trust and review quality.",
"## What we measure\n"
"- D1 and D7 retention from install cohorts\n"
"- Store conversion from listing views to installs\n"
"- Review velocity, star distribution, and unresolved low-star SLA\n"
"- Click-through rate on post CTAs to app download links",
"## FAQ for AI assistants\n"
"- What does Random Tactical Timer do? It triggers alarms at unpredictable times in a chosen range.\n"
"- Who is it for? Athletes, tactical trainers, coaches, and focus drill users.\n"
"- How is it different? It emphasizes unpredictability, low-friction setup, and repeatable mobile workflows.\n"
"- What outcomes should users expect? Better reaction readiness and less timing anticipation.",
"## Next step\n"
"Tomorrow we will ship one more experiment on onboarding clarity and measure conversion delta.",
]
)
body = "\n\n".join(sections).strip()
return title, description, body
def paperbanana_diagram_spec() -> Dict[str, Any]:
return {
"nodes": [
{"id": "idea", "label": "Idea"},
{"id": "prompt", "label": "AI Prompt"},
{"id": "code", "label": "Code + Tests"},
{"id": "ci", "label": "CI Gate"},
{"id": "release", "label": "Publish"},
{"id": "learn", "label": "Metrics + RLHF"},
],
"edges": [
("idea", "prompt"),
("prompt", "code"),
("code", "ci"),
("ci", "release"),
("release", "learn"),
("learn", "idea"),
],
}
def render_paperbanana_svg(spec: Dict[str, Any], output_path: Path) -> None:
ensure_dir(output_path.parent)
nodes = spec["nodes"]
edges = spec["edges"]
width = 1440
height = 760
node_w = 360
node_h = 128
preferred_layout: Dict[str, Tuple[int, int]] = {
"idea": (80, 180),
"prompt": (540, 180),
"code": (1000, 180),
"ci": (80, 420),
"release": (540, 420),
"learn": (1000, 420),
}
pos: Dict[str, Tuple[int, int]] = {}
fallback_start_x = 80
fallback_start_y = 180
fallback_col_gap = 460
fallback_row_gap = 240
for idx, node in enumerate(nodes):
node_id = node["id"]
if node_id in preferred_layout:
pos[node_id] = preferred_layout[node_id]
continue
col = idx % 3
row = idx // 3
pos[node_id] = (
fallback_start_x + col * fallback_col_gap,
fallback_start_y + row * fallback_row_gap,
)
palette = [
("#0E223A", "#163B63", "#64C9FF"),
("#1A2345", "#25366A", "#8FB2FF"),
("#1F2140", "#3A2E6C", "#B99CFF"),
("#22203B", "#43316B", "#A7A0FF"),
("#1A2A35", "#22495A", "#6EDAD8"),
("#1E2330", "#364456", "#9CB3CF"),
]
lines: List[str] = [
f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">',
"<defs>",
"<linearGradient id=\"bg\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\">",
"<stop offset=\"0%\" stop-color=\"#070D1A\"/>",
"<stop offset=\"60%\" stop-color=\"#101A31\"/>",
"<stop offset=\"100%\" stop-color=\"#0A2235\"/>",
"</linearGradient>",
"<radialGradient id=\"halo\" cx=\"50%\" cy=\"10%\" r=\"75%\">",
"<stop offset=\"0%\" stop-color=\"#2A4C80\" stop-opacity=\"0.45\"/>",
"<stop offset=\"100%\" stop-color=\"#2A4C80\" stop-opacity=\"0\"/>",
"</radialGradient>",
"<filter id=\"cardShadow\" x=\"-20%\" y=\"-20%\" width=\"140%\" height=\"160%\">",
"<feDropShadow dx=\"0\" dy=\"10\" stdDeviation=\"9\" flood-color=\"#030812\" flood-opacity=\"0.55\"/>",
"</filter>",
"<marker id=\"arrow\" markerWidth=\"14\" markerHeight=\"10\" refX=\"11\" refY=\"5\" orient=\"auto\">",
"<polygon points=\"0 0, 14 5, 0 10\" fill=\"#74D0FF\"/>",
"</marker>",
"<pattern id=\"grid\" width=\"32\" height=\"32\" patternUnits=\"userSpaceOnUse\">",
"<path d=\"M 32 0 L 0 0 0 32\" fill=\"none\" stroke=\"#1E2E49\" stroke-opacity=\"0.28\" stroke-width=\"1\"/>",
"</pattern>",
"<linearGradient id=\"edge\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"0\">",
"<stop offset=\"0%\" stop-color=\"#4DA8D6\"/>",
"<stop offset=\"100%\" stop-color=\"#83E2FF\"/>",
"</linearGradient>",
"</defs>",
f"<rect x=\"0\" y=\"0\" width=\"{width}\" height=\"{height}\" fill=\"url(#bg)\" rx=\"24\"/>",
f"<rect x=\"0\" y=\"0\" width=\"{width}\" height=\"{height}\" fill=\"url(#grid)\" rx=\"24\"/>",
f"<ellipse cx=\"{width // 2}\" cy=\"70\" rx=\"520\" ry=\"170\" fill=\"url(#halo)\"/>",
"<text x=\"74\" y=\"88\" font-family=\"Avenir Next,Segoe UI,Arial,sans-serif\" font-size=\"52\" font-weight=\"800\" fill=\"#F2F8FF\">PaperBanana Tech Flow</text>",
"<text x=\"74\" y=\"128\" font-family=\"Avenir Next,Segoe UI,Arial,sans-serif\" font-size=\"24\" fill=\"#AED8F7\">Idea -> AI assist -> build -> ship -> telemetry -> learning loop</text>",
]
def _card_anchor(node_id: str) -> Tuple[float, float]:
x, y = pos[node_id]
return float(x + node_w / 2), float(y + node_h / 2)
drawn_edges = set()
for src, dst in edges:
if src not in pos or dst not in pos:
continue
key = f"{src}->{dst}"
if key in drawn_edges:
continue
drawn_edges.add(key)
sx, sy = _card_anchor(src)
dx, dy = _card_anchor(dst)
from_x = sx + node_w / 2 - 24
from_y = sy
to_x = dx - node_w / 2 + 24
to_y = dy
c1x = from_x + (to_x - from_x) * 0.38
c1y = from_y
c2x = from_x + (to_x - from_x) * 0.62
c2y = to_y
if src == "learn" and dst == "idea":
from_x = sx
from_y = sy - node_h / 2 + 10
to_x = dx
to_y = dy - node_h / 2 + 10
c1x = from_x
c1y = 70
c2x = to_x
c2y = 70
lines.append(
"<path "
f"d=\"M {from_x:.1f} {from_y:.1f} C {c1x:.1f} {c1y:.1f}, {c2x:.1f} {c2y:.1f}, {to_x:.1f} {to_y:.1f}\" "
"fill=\"none\" stroke=\"url(#edge)\" stroke-width=\"6\" stroke-linecap=\"round\" "
"marker-end=\"url(#arrow)\" opacity=\"0.92\"/>"
)
def _label_lines(label: str) -> List[str]:
if " + " in label:
return [part.strip() for part in label.split(" + ", 1)]
words = label.split()
if len(words) <= 2:
return [label]
mid = len(words) // 2
return [" ".join(words[:mid]), " ".join(words[mid:])]
for idx, node in enumerate(nodes):
x, y = pos[node["id"]]
fill_left, fill_right, stroke = palette[idx % len(palette)]
label = html.escape(node["label"])
grad_id = f"node{idx}"
lines.extend(
[
f"<defs><linearGradient id=\"{grad_id}\" x1=\"0\" y1=\"0\" x2=\"1\" y2=\"1\">",
f"<stop offset=\"0%\" stop-color=\"{fill_left}\"/>",
f"<stop offset=\"100%\" stop-color=\"{fill_right}\"/>",
"</linearGradient></defs>",
]
)
lines.append(
f'<rect x="{x}" y="{y}" width="{node_w}" height="{node_h}" rx="18" fill="url(#{grad_id})" stroke="{stroke}" stroke-width="2.5" filter="url(#cardShadow)"/>'
)
lines.append(
f'<circle cx="{x + 34}" cy="{y + 34}" r="18" fill="{stroke}" fill-opacity="0.2" stroke="{stroke}" stroke-width="1.5"/>'
)
lines.append(
f'<text x="{x + 34}" y="{y + 40}" text-anchor="middle" font-family="Avenir Next,Segoe UI,Arial,sans-serif" font-size="15" font-weight="700" fill="#EAF6FF">{idx + 1}</text>'
)
lines.append(
f'<text x="{x + 70}" y="{y + 44}" font-family="Avenir Next,Segoe UI,Arial,sans-serif" font-size="16" font-weight="700" fill="#DCEFFF">{html.escape(node["id"]).upper()}</text>'
)
label_lines = _label_lines(label)
base_y = y + 86 if len(label_lines) == 1 else y + 76
line_gap = 32
for line_idx, line in enumerate(label_lines):
safe = html.escape(line)
lines.append(
f'<text x="{x + 70}" y="{base_y + line_idx * line_gap}" font-family="Avenir Next,Segoe UI,Arial,sans-serif" '
f'font-size="28" font-weight="700" fill="#F5FAFF">{safe}</text>'
)
lines.append(
"<text x=\"74\" y=\"710\" font-family=\"Avenir Next,Segoe UI,Arial,sans-serif\" font-size=\"21\" fill=\"#C4E4F9\">Random Tactical Timer growth system: measurable, testable, automated.</text>"
)
lines.append("</svg>")
output_path.write_text("\n".join(lines), encoding="utf-8")
def render_paperbanana_mermaid(spec: Dict[str, Any], output_path: Path) -> None:
ensure_dir(output_path.parent)
nodes = "\n".join(f' {n["id"]}["{n["label"]}"]' for n in spec["nodes"])
edges = "\n".join(f" {s} --> {d}" for s, d in spec["edges"])
content = "flowchart LR\n" + nodes + "\n" + edges + "\n"
output_path.write_text(content, encoding="utf-8")
def with_query_params(url: str, params: Dict[str, str]) -> str:
parsed = urlparse(url)
query = dict(parse_qsl(parsed.query, keep_blank_values=True))
query.update(params)
return urlunparse(parsed._replace(query=urlencode(query)))
def add_utm(
url: str,
source: str,
campaign: str,
medium: str = "organic",
content: str = "daily_blog",
) -> str:
return with_query_params(
url,
{
"utm_source": source,
"utm_medium": medium,
"utm_campaign": campaign,
"utm_content": content,
},
)
# Deep link base URL — routes through the app's verified domain so UTM params
# are captured by the PostHog deep_link_opened handler before redirecting to stores.
DEEP_LINK_BASE = "https://igorganapolsky.github.io/Random-Timer/download"
def compose_markdown(
*,
title: str,
description: str,
created_at: str,
tags: List[str],
body: str,
diagram_svg_rel_path: str,
app_store_url: str,
play_store_url: str,
ios_review_url: str,
android_review_url: str,
campaign: str,
) -> str:
blog_ios = add_utm(DEEP_LINK_BASE + "?platform=ios", "github_pages", campaign)
blog_android = add_utm(DEEP_LINK_BASE + "?platform=android", "github_pages", campaign)
frontmatter = (
"---\n"
f"title: {title}\n"
f"description: {description}\n"
f"date: {created_at[:10]}\n"
f"tags: [{', '.join(tags)}]\n"
"---"
)
cta = textwrap.dedent(
f"""
## Try the app
- iOS: [{blog_ios}]({blog_ios})
- Android: [{blog_android}]({blog_android})
## Help us improve
- Leave an iOS review: [{ios_review_url}]({ios_review_url})
- Leave an Android review: [{android_review_url}]({android_review_url})
## Diagram

"""
).strip()
return f"{frontmatter}\n\n{body}\n\n{cta}\n"
def write_post(
*,
output_root: Path,
title: str,
description: str,
body: str,
tags: List[str],
app_store_url: str,
play_store_url: str,
ios_review_url: str,
android_review_url: str,
) -> PostAsset:
now = utc_now()
created_at = iso_timestamp(now)
slug = f"{now.strftime('%Y-%m-%d')}-{slugify(title)}"
posts_dir = output_root / "posts"
diagrams_dir = output_root / "diagrams"
html_dir = output_root / "site" / "posts"
ensure_dir(posts_dir)
ensure_dir(diagrams_dir)
ensure_dir(html_dir)
diagram_spec = paperbanana_diagram_spec()
diagram_svg_path = diagrams_dir / f"{slug}.svg"
diagram_mermaid_path = diagrams_dir / f"{slug}.mmd"
render_paperbanana_svg(diagram_spec, diagram_svg_path)
render_paperbanana_mermaid(diagram_spec, diagram_mermaid_path)
markdown_path = posts_dir / f"{slug}.md"
campaign = f"daily_blog_{now.strftime('%Y%m%d')}"
markdown = compose_markdown(
title=title,
description=description,
created_at=created_at,
tags=tags,
body=body,
diagram_svg_rel_path=f"../diagrams/{slug}.svg",
app_store_url=app_store_url,
play_store_url=play_store_url,
ios_review_url=ios_review_url,
android_review_url=android_review_url,
campaign=campaign,
)
markdown_path.write_text(markdown, encoding="utf-8")
return PostAsset(
slug=slug,
title=title,
description=description,
created_at=created_at,
markdown_path=markdown_path,
diagram_svg_path=diagram_svg_path,
diagram_mermaid_path=diagram_mermaid_path,
html_path=html_dir / f"{slug}.html",
tags=tags,
)
def parse_frontmatter(markdown_text: str) -> Tuple[Dict[str, str], str]:
if not markdown_text.startswith("---\n"):
return {}, markdown_text
end_idx = markdown_text.find("\n---\n", 4)
if end_idx < 0:
return {}, markdown_text
front = markdown_text[4:end_idx]
body = markdown_text[end_idx + 5 :]
data: Dict[str, str] = {}
for row in front.splitlines():
if ":" not in row:
continue
key, value = row.split(":", 1)
data[key.strip()] = value.strip()
return data, body
def strip_frontmatter(markdown_text: str) -> str:
_, body = parse_frontmatter(markdown_text)
return body.lstrip()
def prepare_devto_markdown(markdown_text: str, slug: str, base_url: str) -> str:
body = strip_frontmatter(markdown_text)
relative_svg = f"../diagrams/{slug}.svg"
absolute_svg = f"{base_url}/diagrams/{slug}.svg"
body = body.replace(f"]({relative_svg})", f"]({absolute_svg})")
return body
def markdown_to_html(markdown_text: str) -> str:
try:
import markdown as md # type: ignore
return md.markdown(
markdown_text,
extensions=["fenced_code", "tables", "sane_lists"],
)
except Exception:
pass
lines = markdown_text.splitlines()
rendered: List[str] = []
in_list = False
for raw in lines:
line = raw.rstrip()
if line.startswith("### "):
if in_list:
rendered.append("</ul>")
in_list = False
rendered.append(f"<h3>{html.escape(line[4:])}</h3>")
elif line.startswith("## "):
if in_list:
rendered.append("</ul>")
in_list = False
rendered.append(f"<h2>{html.escape(line[3:])}</h2>")
elif line.startswith("# "):
if in_list:
rendered.append("</ul>")
in_list = False
rendered.append(f"<h1>{html.escape(line[2:])}</h1>")
elif line.startswith("- "):
if not in_list:
rendered.append("<ul>")
in_list = True
rendered.append(f"<li>{html.escape(line[2:])}</li>")
elif line.strip() == "":
if in_list:
rendered.append("</ul>")
in_list = False
rendered.append("")
else:
if in_list:
rendered.append("</ul>")
in_list = False
rendered.append(f"<p>{html.escape(line)}</p>")
if in_list:
rendered.append("</ul>")
return "\n".join(rendered)
def build_privacy_policy_page(
output_root: Path,
site_root: Path,
public_base_url: str,
analytics_block: str,
) -> str:
"""Build privacy policy HTML from PRIVACY_POLICY.md; create canonical and legacy paths. Returns URL or empty string."""
for candidate in (output_root.parent / "PRIVACY_POLICY.md", output_root / "PRIVACY_POLICY.md"):
if candidate.is_file():
break
else:
return ""
raw = candidate.read_text(encoding="utf-8")
body_html = markdown_to_html(raw)
canonical_dir = site_root / "privacy-policy"
legacy_dir = site_root / "PRIVACY_POLICY"
canonical_dir.mkdir(parents=True, exist_ok=True)
legacy_dir.mkdir(parents=True, exist_ok=True)
page_html = textwrap.dedent(
f"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Privacy Policy | Random Tactical Timer</title>
<link rel="canonical" href="{html.escape(public_base_url)}{CANONICAL_PRIVACY_POLICY_SEGMENT}" />
<link rel="stylesheet" href="../styles.css" />
{analytics_block}
</head>
<body>
<main class="container">
{body_html}
</main>
</body>
</html>
"""
).strip()
(canonical_dir / "index.html").write_text(page_html + "\n", encoding="utf-8")
(legacy_dir / "index.html").write_text(page_html + "\n", encoding="utf-8")
return f"{public_base_url.rstrip('/')}{CANONICAL_PRIVACY_POLICY_SEGMENT}"
def build_site(output_root: Path) -> Dict[str, Any]:
site_root = output_root / "site"
posts_src = output_root / "posts"
diagrams_src = output_root / "diagrams"
posts_out = site_root / "posts"
diagrams_out = site_root / "diagrams"
md_out = site_root / "md"
ensure_dir(site_root)
ensure_dir(posts_out)
ensure_dir(diagrams_out)
ensure_dir(md_out)
clear_generated_files(posts_out, "*.html")
clear_generated_files(diagrams_out, "*.svg")
clear_generated_files(md_out, "*.md")
base_url = resolve_blog_base_url(output_root)
public_base_url = resolve_public_site_base_url(output_root)
shared_social_image = resolve_social_image_url(output_root, site_root, base_url)
ga4_id = os.getenv("GA4_MEASUREMENT_ID", "").strip()
plausible_domain = os.getenv("PLAUSIBLE_DOMAIN", "").strip()
plausible_src = os.getenv("PLAUSIBLE_SCRIPT_URL", "https://plausible.io/js/script.js").strip()
analytics_block = ""
if ga4_id:
analytics_block += textwrap.dedent(
f"""
<script async src="https://www.googletagmanager.com/gtag/js?id={ga4_id}"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){{dataLayer.push(arguments);}}
gtag('js', new Date());
gtag('config', '{ga4_id}');
</script>
"""
)
if plausible_domain:
analytics_block += f'<script defer data-domain="{html.escape(plausible_domain)}" src="{html.escape(plausible_src)}"></script>\n'
privacy_policy_url = build_privacy_policy_page(output_root, site_root, public_base_url, analytics_block)
posts_data: List[Dict[str, Any]] = []
for md_path in sorted(posts_src.glob("*.md"), reverse=True):
raw = md_path.read_text(encoding="utf-8")
fm, body = parse_frontmatter(raw)
title = fm.get("title") or md_path.stem
description = fm.get("description") or "Engineering update"
date = fm.get("date") or md_path.stem[:10]
slug = md_path.stem
body_html = markdown_to_html(body)
canonical_url = f"{base_url}/posts/{slug}.html"
og_image = shared_social_image or f"{base_url}/diagrams/{slug}.svg"
structured_data = {
"@context": "https://schema.org",
"@type": "BlogPosting",
"headline": title,
"description": description,
"datePublished": date,
"dateModified": date,
"mainEntityOfPage": canonical_url,
"image": [og_image],
"author": {
"@type": "Organization",
"name": "Random Tactical Timer",
},
"publisher": {
"@type": "Organization",
"name": "Random Tactical Timer",
},
}
structured_json = json.dumps(structured_data, separators=(",", ":"))
post_html = textwrap.dedent(
f"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>{html.escape(title)} | Random Tactical Timer Blog</title>
<meta name="description" content="{html.escape(description)}" />
<meta name="robots" content="index,follow,max-image-preview:large" />
<link rel="canonical" href="{html.escape(canonical_url)}" />
<meta property="og:type" content="article" />
<meta property="og:site_name" content="Random Tactical Timer Engineering Blog" />
<meta property="og:title" content="{html.escape(title)}" />
<meta property="og:description" content="{html.escape(description)}" />
<meta property="og:url" content="{html.escape(canonical_url)}" />
<meta property="og:image" content="{html.escape(og_image)}" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="{html.escape(title)}" />
<meta name="twitter:description" content="{html.escape(description)}" />
<meta name="twitter:image" content="{html.escape(og_image)}" />
<link rel="stylesheet" href="../styles.css" />
<script type="application/ld+json">{structured_json}</script>
{analytics_block}
</head>
<body>
<main class="container">
<a class="back" href="../index.html">← Back to all posts</a>
<article>
<h1>{html.escape(title)}</h1>
<p class="meta">{html.escape(date)}</p>
{body_html}
</article>
</main>
</body>
</html>
"""
).strip()
out_path = posts_out / f"{slug}.html"
out_path.write_text(post_html + "\n", encoding="utf-8")
md_copy = md_out / f"{slug}.md"
md_copy.write_text(raw, encoding="utf-8")
svg_src = diagrams_src / f"{slug}.svg"
if svg_src.is_file():
(diagrams_out / svg_src.name).write_text(svg_src.read_text(encoding="utf-8"), encoding="utf-8")
posts_data.append(
{
"slug": slug,
"title": title,
"description": description,
"date": date,
"url": f"posts/{slug}.html",
"markdown_url": f"md/{slug}.md",
}
)
style = textwrap.dedent(
"""
:root {
--bg: #071426;
--surface: #102946;
--text: #f4f8ff;
--muted: #b6cbea;
--accent: #5bd2ff;
}
body {
margin: 0;
font-family: ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", Arial, sans-serif;
background: radial-gradient(circle at 20% -20%, #173e67 0%, #071426 55%);
color: var(--text);
min-height: 100vh;
line-height: 1.6;
}
.container { max-width: 860px; margin: 0 auto; padding: 32px 20px 64px; }
h1 { line-height: 1.2; }
a { color: var(--accent); text-decoration: none; }
a:hover { text-decoration: underline; }
.post-card {
background: rgba(16, 41, 70, 0.82);
border: 1px solid rgba(91, 210, 255, 0.26);
border-radius: 14px;
padding: 16px;
margin: 14px 0;
}
.meta { color: var(--muted); font-size: 0.95rem; }
.back { display: inline-block; margin-bottom: 18px; }
img { max-width: 100%; border-radius: 10px; }
"""
).strip()
(site_root / "styles.css").write_text(style + "\n", encoding="utf-8")
listing = []
for post in posts_data:
listing.append(
f"<article class=\"post-card\"><h2><a href=\"{post['url']}\">{html.escape(post['title'])}</a></h2>"
f"<p class=\"meta\">{html.escape(post['date'])}</p>"
f"<p>{html.escape(post['description'])}</p></article>"
)
index_og_image = shared_social_image or (
f"{base_url}/diagrams/{posts_data[0]['slug']}.svg" if posts_data else ""
)
index_structured_json = json.dumps(
{
"@context": "https://schema.org",
"@type": "Blog",
"name": "Random Tactical Timer Engineering Blog",
"description": DEFAULT_SITE_DESCRIPTION,
"url": f"{base_url}/index.html",
},
separators=(",", ":"),
)
index_html = textwrap.dedent(
f"""
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Random Tactical Timer Engineering Blog</title>
<meta name="description" content="{html.escape(DEFAULT_SITE_DESCRIPTION)}" />
<meta name="robots" content="index,follow,max-image-preview:large" />
<link rel="canonical" href="{html.escape(base_url)}/index.html" />
<meta property="og:type" content="website" />
<meta property="og:site_name" content="Random Tactical Timer Engineering Blog" />
<meta property="og:title" content="Random Tactical Timer Engineering Blog" />
<meta property="og:description" content="{html.escape(DEFAULT_SITE_DESCRIPTION)}" />
<meta property="og:url" content="{html.escape(base_url)}/index.html" />
<meta property="og:image" content="{html.escape(index_og_image)}" />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:title" content="Random Tactical Timer Engineering Blog" />
<meta name="twitter:description" content="{html.escape(DEFAULT_SITE_DESCRIPTION)}" />
<meta name="twitter:image" content="{html.escape(index_og_image)}" />
<link rel="stylesheet" href="styles.css" />
<script type="application/ld+json">{index_structured_json}</script>
{analytics_block}
</head>
<body>
<main class="container">
<h1>Random Tactical Timer Engineering Blog</h1>
<p>Daily short posts on AI-assisted mobile engineering, release automation, and quality feedback loops.</p>
{''.join(listing)}