postloop 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- postloop/__init__.py +38 -0
- postloop/adapters.py +250 -0
- postloop/bootstrap.py +135 -0
- postloop/cli.py +143 -0
- postloop/commands.py +84 -0
- postloop/config.py +63 -0
- postloop/insights.py +167 -0
- postloop/matching.py +185 -0
- postloop/models.py +89 -0
- postloop/notify.py +101 -0
- postloop/output.py +119 -0
- postloop/plan.py +209 -0
- postloop/reconcile.py +133 -0
- postloop/tabular.py +101 -0
- postloop-0.1.0.dist-info/METADATA +197 -0
- postloop-0.1.0.dist-info/RECORD +20 -0
- postloop-0.1.0.dist-info/WHEEL +5 -0
- postloop-0.1.0.dist-info/entry_points.txt +2 -0
- postloop-0.1.0.dist-info/licenses/LICENSE +21 -0
- postloop-0.1.0.dist-info/top_level.txt +1 -0
postloop/config.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"""Optional settings, loaded from a TOML file.
|
|
2
|
+
|
|
3
|
+
postloop works without a config file: columns are found by name and platform
|
|
4
|
+
exports are detected automatically. A config is for when your sheet uses
|
|
5
|
+
column names postloop does not know, or to teach it your community's words.
|
|
6
|
+
See examples/pycontw/postloop.toml for a full example.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import tomllib
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
from datetime import datetime, timezone, tzinfo
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
|
|
16
|
+
|
|
17
|
+
DEFAULT_DONE = ("已發布", "已發佈", "published", "posted", "done", "完成")
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def zone(name: str) -> ZoneInfo:
|
|
21
|
+
"""A timezone by IANA name, with a readable error for a typo like "Asia/Taipe"."""
|
|
22
|
+
try:
|
|
23
|
+
return ZoneInfo(name)
|
|
24
|
+
except (ZoneInfoNotFoundError, ValueError) as e:
|
|
25
|
+
raise ValueError(f"Unknown timezone {name!r}. Use an IANA name such as \"Asia/Taipei\".") from e
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass
|
|
29
|
+
class Config:
|
|
30
|
+
timezone: str | None = None # IANA name, e.g. "Asia/Taipei". None: this computer's timezone
|
|
31
|
+
worksheet: str | None = None # None: the first sheet that looks like a calendar
|
|
32
|
+
header_row: int | None = None # 1-based. None: found automatically
|
|
33
|
+
# Calendar column names: date, title, status, team, actual_time, url, platforms.
|
|
34
|
+
# Leave out any that postloop finds by itself.
|
|
35
|
+
columns: dict[str, str] = field(default_factory=dict)
|
|
36
|
+
# Checkbox column -> platform. Empty: recognized by name (FB, IG, LinkedIn, X, Threads ...).
|
|
37
|
+
platforms: dict[str, str] = field(default_factory=dict)
|
|
38
|
+
done_statuses: list[str] = field(default_factory=lambda: list(DEFAULT_DONE))
|
|
39
|
+
primary_platform: str | None = None # whose time and link are written back. None: first available
|
|
40
|
+
language: str = "en" # summary language: "en" or "zh-TW"
|
|
41
|
+
export_timezone: str | None = None # override the timezone platform exports are written in
|
|
42
|
+
# Word in the calendar -> phrase likely to appear in the post, e.g. shorts = "interview".
|
|
43
|
+
synonyms: dict[str, str] = field(default_factory=dict)
|
|
44
|
+
|
|
45
|
+
@property
|
|
46
|
+
def tz(self) -> tzinfo:
|
|
47
|
+
if self.timezone:
|
|
48
|
+
return zone(self.timezone)
|
|
49
|
+
return datetime.now().astimezone().tzinfo or timezone.utc
|
|
50
|
+
|
|
51
|
+
def is_done(self, status: str) -> bool:
|
|
52
|
+
return status.strip().lower() in {s.lower() for s in self.done_statuses}
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def load_config(path: str | Path | None) -> Config:
|
|
56
|
+
if path is None:
|
|
57
|
+
return Config()
|
|
58
|
+
data = tomllib.loads(Path(path).read_text(encoding="utf-8"))
|
|
59
|
+
known = set(Config.__dataclass_fields__)
|
|
60
|
+
unknown = set(data) - known
|
|
61
|
+
if unknown:
|
|
62
|
+
raise ValueError(f"Unknown settings in {path}: {sorted(unknown)}")
|
|
63
|
+
return Config(**data)
|
postloop/insights.py
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
"""`postloop report`: what worked, from the platform exports alone. No calendar needed.
|
|
2
|
+
|
|
3
|
+
For a community that has never kept a post calendar, this is the first step:
|
|
4
|
+
look at what was actually posted and what people responded to.
|
|
5
|
+
|
|
6
|
+
Numbers are described, not tested: a community posts tens of times a year, too
|
|
7
|
+
few to say that one weekday or hour is better. Medians are used because one viral
|
|
8
|
+
or boosted post can be larger than all the others together.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import csv
|
|
14
|
+
from collections import defaultdict
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from datetime import date
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from statistics import median
|
|
19
|
+
|
|
20
|
+
from .models import PublishedPost
|
|
21
|
+
|
|
22
|
+
PLATFORM_NAMES = {"facebook": "Facebook", "instagram": "Instagram", "linkedin": "LinkedIn"}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def engagement(p: PublishedPost) -> int:
|
|
26
|
+
return p.reactions + p.comments + p.shares
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Gap:
|
|
31
|
+
start: date # day of the last post before the gap
|
|
32
|
+
end: date # day of the first post after it
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def days(self) -> int:
|
|
36
|
+
return (self.end - self.start).days
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@dataclass
|
|
40
|
+
class PlatformInsights:
|
|
41
|
+
platform: str
|
|
42
|
+
posts: list[PublishedPost]
|
|
43
|
+
median_views_organic: float
|
|
44
|
+
median_engagement: float
|
|
45
|
+
top: list[PublishedPost] # by organic views
|
|
46
|
+
boosted: list[PublishedPost]
|
|
47
|
+
by_type: dict[str, tuple[int, float]] # type -> (posts, median organic views)
|
|
48
|
+
per_month: dict[str, int] # "2026-08" -> posts
|
|
49
|
+
gaps: list[Gap] # long stretches with no posts
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def analyze_platform(platform: str, posts: list[PublishedPost], top_n: int = 5,
|
|
53
|
+
gap_days: int = 14) -> PlatformInsights:
|
|
54
|
+
posts = sorted(posts, key=lambda p: p.published_at)
|
|
55
|
+
types: dict[str, list[int]] = defaultdict(list)
|
|
56
|
+
months: dict[str, int] = defaultdict(int)
|
|
57
|
+
for p in posts:
|
|
58
|
+
types[p.type or "?"].append(p.views_organic)
|
|
59
|
+
months[p.published_at.strftime("%Y-%m")] += 1
|
|
60
|
+
days = sorted({p.published_at.date() for p in posts})
|
|
61
|
+
gaps = [Gap(a, b) for a, b in zip(days, days[1:]) if (b - a).days > gap_days]
|
|
62
|
+
return PlatformInsights(
|
|
63
|
+
platform=platform,
|
|
64
|
+
posts=posts,
|
|
65
|
+
median_views_organic=median(p.views_organic for p in posts),
|
|
66
|
+
median_engagement=median(engagement(p) for p in posts),
|
|
67
|
+
top=sorted(posts, key=lambda p: p.views_organic, reverse=True)[:top_n],
|
|
68
|
+
boosted=[p for p in posts if p.boosted],
|
|
69
|
+
by_type={t: (len(v), median(v)) for t, v in sorted(types.items(), key=lambda kv: -len(kv[1]))},
|
|
70
|
+
per_month=dict(sorted(months.items())),
|
|
71
|
+
gaps=sorted(gaps, key=lambda g: g.days, reverse=True),
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def analyze(posts: list[PublishedPost], top_n: int = 5, gap_days: int = 14) -> list[PlatformInsights]:
|
|
76
|
+
"""One summary per platform. Posts with no views (a cover photo change) are left out."""
|
|
77
|
+
by_platform: dict[str, list[PublishedPost]] = defaultdict(list)
|
|
78
|
+
for p in posts:
|
|
79
|
+
if p.views > 0:
|
|
80
|
+
by_platform[p.platform].append(p)
|
|
81
|
+
if not by_platform:
|
|
82
|
+
raise ValueError("no posts with views to analyze")
|
|
83
|
+
return [analyze_platform(name, items, top_n, gap_days)
|
|
84
|
+
for name, items in sorted(by_platform.items(), key=lambda kv: -len(kv[1]))]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
TEXT = {
|
|
88
|
+
"en": {
|
|
89
|
+
"title": "Post report",
|
|
90
|
+
"period": "{n} posts from {first} to {last}",
|
|
91
|
+
"median": "Typical post (median): {views:,} organic views, {eng:,} reactions, comments and shares",
|
|
92
|
+
"top": "Top posts by organic views",
|
|
93
|
+
"times": "{x:.1f}× typical",
|
|
94
|
+
"boosted": "Boosted posts (views from the ad)",
|
|
95
|
+
"boosted_line": "{share:.0%} of {views:,} views were paid",
|
|
96
|
+
"types": "By post type",
|
|
97
|
+
"types_line": "{n} posts, median {views:,} organic views",
|
|
98
|
+
"months": "Posts per month",
|
|
99
|
+
"gaps": "Longest stretches with no posts",
|
|
100
|
+
"gap_line": "{days} days, {start} → {end}",
|
|
101
|
+
"no_gaps": "No gaps longer than {d} days.",
|
|
102
|
+
"note": "With this few posts, read these as descriptions, not proof.",
|
|
103
|
+
},
|
|
104
|
+
"zh-TW": {
|
|
105
|
+
"title": "貼文成效報告",
|
|
106
|
+
"period": "共 {n} 篇貼文,{first} 至 {last}",
|
|
107
|
+
"median": "一般貼文(中位數):自然觀看 {views:,} 次,心情、留言和分享 {eng:,} 次",
|
|
108
|
+
"top": "自然觀看最多的貼文",
|
|
109
|
+
"times": "一般貼文的 {x:.1f} 倍",
|
|
110
|
+
"boosted": "加強推廣的貼文(廣告帶來的觀看)",
|
|
111
|
+
"boosted_line": "{views:,} 次觀看中有 {share:.0%} 來自廣告",
|
|
112
|
+
"types": "依貼文類型",
|
|
113
|
+
"types_line": "{n} 篇,自然觀看中位數 {views:,}",
|
|
114
|
+
"months": "每月貼文數",
|
|
115
|
+
"gaps": "最長的空窗期",
|
|
116
|
+
"gap_line": "{days} 天,{start} → {end}",
|
|
117
|
+
"no_gaps": "沒有超過 {d} 天的空窗期。",
|
|
118
|
+
"note": "貼文數量不多,以上是描述,不是統計上的結論。",
|
|
119
|
+
},
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def to_markdown(results: list[PlatformInsights], language: str = "en", gap_days: int = 14) -> str:
|
|
124
|
+
t = TEXT.get(language, TEXT["en"])
|
|
125
|
+
out = [f"# {t['title']}", ""]
|
|
126
|
+
for r in results:
|
|
127
|
+
base = r.median_views_organic or 1
|
|
128
|
+
first, last = r.posts[0].published_at.date(), r.posts[-1].published_at.date()
|
|
129
|
+
out += [f"## {PLATFORM_NAMES.get(r.platform, r.platform)}", "",
|
|
130
|
+
t["period"].format(n=len(r.posts), first=first, last=last), "",
|
|
131
|
+
t["median"].format(views=round(r.median_views_organic), eng=round(r.median_engagement)), "",
|
|
132
|
+
f"### {t['top']}", ""]
|
|
133
|
+
for p in r.top:
|
|
134
|
+
link = f"[{p.headline}]({p.url})" if p.url else p.headline
|
|
135
|
+
out.append(f"- {p.published_at:%Y-%m-%d} · {p.views_organic:,} · "
|
|
136
|
+
f"{t['times'].format(x=p.views_organic / base)} · {link}")
|
|
137
|
+
if r.boosted:
|
|
138
|
+
out += ["", f"### {t['boosted']}", ""]
|
|
139
|
+
for p in r.boosted:
|
|
140
|
+
share = p.views_boosted / p.views if p.views else 0
|
|
141
|
+
out.append(f"- {p.published_at:%Y-%m-%d} · "
|
|
142
|
+
f"{t['boosted_line'].format(share=share, views=p.views)} · {p.headline}")
|
|
143
|
+
if any(k != "?" for k in r.by_type):
|
|
144
|
+
out += ["", f"### {t['types']}", ""]
|
|
145
|
+
out += [f"- {k}: {t['types_line'].format(n=n, views=round(v))}" for k, (n, v) in r.by_type.items()]
|
|
146
|
+
out += ["", f"### {t['months']}", ""]
|
|
147
|
+
out += [f"- {m}: {'█' * n} {n}" for m, n in r.per_month.items()]
|
|
148
|
+
out += ["", f"### {t['gaps']}", ""]
|
|
149
|
+
out += ([f"- {t['gap_line'].format(days=g.days, start=g.start, end=g.end)}" for g in r.gaps[:5]]
|
|
150
|
+
or [t["no_gaps"].format(d=gap_days)])
|
|
151
|
+
out.append("")
|
|
152
|
+
out += [f"_{t['note']}_", ""]
|
|
153
|
+
return "\n".join(out)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def write_posts_table(results: list[PlatformInsights], path: str | Path) -> None:
|
|
157
|
+
"""Every post with its numbers, for a spreadsheet. UTF-8 with BOM so Excel shows Chinese correctly."""
|
|
158
|
+
with open(path, "w", encoding="utf-8-sig", newline="") as f:
|
|
159
|
+
w = csv.writer(f)
|
|
160
|
+
w.writerow(["published", "weekday", "platform", "type", "headline", "views", "views_organic",
|
|
161
|
+
"views_boosted", "vs_typical", "reach", "engagement", "comments", "shares", "url"])
|
|
162
|
+
for r in results:
|
|
163
|
+
base = r.median_views_organic or 1
|
|
164
|
+
for p in r.posts:
|
|
165
|
+
w.writerow([p.timestamp(), p.published_at.strftime("%a"), p.platform, p.type, p.headline,
|
|
166
|
+
p.views, p.views_organic, p.views_boosted, round(p.views_organic / base, 1),
|
|
167
|
+
p.reach, engagement(p), p.comments, p.shares, p.url])
|
postloop/matching.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
"""Match planned posts (the calendar) to published posts (the platforms).
|
|
2
|
+
|
|
3
|
+
Dates alone are not enough: posts often go out a day or two late, and
|
|
4
|
+
several posts can share a date. So each candidate pair gets a score:
|
|
5
|
+
|
|
6
|
+
score = text similarity + number bonus - lateness penalty
|
|
7
|
+
|
|
8
|
+
and pairs are assigned greedily, best score first, so a published post is
|
|
9
|
+
never claimed by two calendar rows.
|
|
10
|
+
|
|
11
|
+
Text similarity weighs each character pair by how rare it is among the posts
|
|
12
|
+
(like TF-IDF): "PyCon" and "Python" appear in every post of a Python
|
|
13
|
+
community, so sharing them says little; sharing "高見龍" or "Sprints" says a lot.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import math
|
|
19
|
+
import re
|
|
20
|
+
from collections import Counter
|
|
21
|
+
from collections.abc import Iterable, Mapping
|
|
22
|
+
|
|
23
|
+
from .models import Match, PlannedPost, PublishedPost
|
|
24
|
+
|
|
25
|
+
# How far from the planned date a post may land and still be considered.
|
|
26
|
+
EARLIEST_DAYS = -1
|
|
27
|
+
LATEST_DAYS = 7
|
|
28
|
+
MIN_SCORE = 0.25
|
|
29
|
+
LATENESS_PENALTY = 0.02 # per day
|
|
30
|
+
FALLBACK_DAYS = 1
|
|
31
|
+
MIN_POSTS_FOR_WEIGHTS = 10 # too few posts to tell common words from rare ones
|
|
32
|
+
|
|
33
|
+
_PARENS = re.compile(r"\(.*?\)|(.*?)")
|
|
34
|
+
_PART = re.compile(r"part\s*(\d+)", re.IGNORECASE)
|
|
35
|
+
_ORDINAL = re.compile(
|
|
36
|
+
r"(?:#|\bpart\b|\bday\b)\s*(\d+)|第\s*([一二三四五六七八九十\d]+)\s*[天日週次波篇]",
|
|
37
|
+
re.IGNORECASE,
|
|
38
|
+
)
|
|
39
|
+
_CHINESE_DIGITS = {c: i for i, c in enumerate("一二三四五六七八九十", start=1)}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def clean_topic(topic: str) -> str:
|
|
43
|
+
"""Drop notes like "(圖: 行銷組, 文: 議程組)"; read "Part 2" as "#2" too."""
|
|
44
|
+
text = _PARENS.sub(" ", topic)
|
|
45
|
+
text = _PART.sub(lambda m: f"part {m.group(1)} #{m.group(1)}", text)
|
|
46
|
+
return text.strip()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def topic_variants(topic: str, synonyms: Mapping[str, str] | None = None) -> list[str]:
|
|
50
|
+
"""The topic itself, plus any synonym phrases it triggers.
|
|
51
|
+
|
|
52
|
+
Synonyms bridge the words people use in the calendar and the words that
|
|
53
|
+
end up in the post, e.g. a calendar row saying "shorts" is posted as "專訪".
|
|
54
|
+
Each variant is scored on its own, so a synonym never dilutes the topic.
|
|
55
|
+
"""
|
|
56
|
+
cleaned = clean_topic(topic)
|
|
57
|
+
variants = [cleaned]
|
|
58
|
+
for word, phrase in (synonyms or {}).items():
|
|
59
|
+
if word.lower() in cleaned.lower():
|
|
60
|
+
variants.append(phrase)
|
|
61
|
+
return variants
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def bigrams(text: str) -> set[str]:
|
|
65
|
+
"""Character bigrams: works for Chinese and English without a tokenizer."""
|
|
66
|
+
text = re.sub(r"\s+", "", text.lower())
|
|
67
|
+
return {text[i : i + 2] for i in range(len(text) - 1)}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
HEAD_CHARS = 200 # the start of a post says what it is about; the rest is details
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def bigram_weights(messages: Iterable[str]) -> dict[str, float]:
|
|
74
|
+
"""Rarer character pairs weigh more (square root of the IDF, so no pair dominates)."""
|
|
75
|
+
docs = [bigrams(m[:HEAD_CHARS]) for m in messages]
|
|
76
|
+
counts = Counter(b for d in docs for b in d)
|
|
77
|
+
n = len(docs)
|
|
78
|
+
return {b: math.sqrt(math.log(1 + n / c)) for b, c in counts.items()}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def text_similarity(topic: str, message: str, weights: Mapping[str, float] | None = None) -> float:
|
|
82
|
+
"""Weighted share of the topic's bigrams found in the start of the post.
|
|
83
|
+
|
|
84
|
+
A topic word that appears in no post at all gets the highest weight: it is
|
|
85
|
+
as rare as a word can be, and a post that misses it is probably not this one.
|
|
86
|
+
"""
|
|
87
|
+
wanted = bigrams(topic)
|
|
88
|
+
if not wanted:
|
|
89
|
+
return 0.0
|
|
90
|
+
found = wanted & bigrams(message[:HEAD_CHARS])
|
|
91
|
+
if weights:
|
|
92
|
+
rarest = max(weights.values())
|
|
93
|
+
weigh = lambda b: weights.get(b, rarest) # noqa: E731
|
|
94
|
+
else:
|
|
95
|
+
weigh = lambda b: 1.0 # noqa: E731
|
|
96
|
+
return sum(map(weigh, found)) / sum(map(weigh, wanted))
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def ordinals(text: str) -> set[int]:
|
|
100
|
+
"""Sequence numbers in a text: "#2", "Part 2", "Day 2" and "第二天" all give 2."""
|
|
101
|
+
found = set()
|
|
102
|
+
for digits, chinese in _ORDINAL.findall(text):
|
|
103
|
+
value = digits or chinese
|
|
104
|
+
found.add(int(value) if value.isdigit() else _CHINESE_DIGITS.get(value, 0))
|
|
105
|
+
return found - {0}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def number_bonus(topic: str, message: str, head_chars: int = 120) -> float:
|
|
109
|
+
"""Reward "Part 2" meeting "#2"; punish "#3" or "第三天" when the topic says 2.
|
|
110
|
+
|
|
111
|
+
Series posts (議程宣傳 Part 1..5, Day 1/Day 2) share almost all their words,
|
|
112
|
+
so the sequence number is what tells them apart.
|
|
113
|
+
"""
|
|
114
|
+
wanted = ordinals(topic)
|
|
115
|
+
seen = ordinals(message[:head_chars])
|
|
116
|
+
if wanted and seen:
|
|
117
|
+
return 0.15 if wanted & seen else -0.3
|
|
118
|
+
return 0.0
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def score(
|
|
122
|
+
planned: PlannedPost,
|
|
123
|
+
post: PublishedPost,
|
|
124
|
+
synonyms: Mapping[str, str] | None = None,
|
|
125
|
+
weights: Mapping[str, float] | None = None,
|
|
126
|
+
) -> float | None:
|
|
127
|
+
"""Score one pair, or None when the dates are too far apart."""
|
|
128
|
+
days = (post.published_at.date() - planned.planned_date).days
|
|
129
|
+
if not EARLIEST_DAYS <= days <= LATEST_DAYS:
|
|
130
|
+
return None
|
|
131
|
+
variants = topic_variants(planned.topic, synonyms)
|
|
132
|
+
similarity = max(text_similarity(v, post.message, weights) for v in variants)
|
|
133
|
+
return similarity + number_bonus(variants[0], post.message) - LATENESS_PENALTY * abs(days)
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def match_posts(
|
|
137
|
+
planned: Iterable[PlannedPost],
|
|
138
|
+
published: Iterable[PublishedPost],
|
|
139
|
+
platform: str,
|
|
140
|
+
synonyms: Mapping[str, str] | None = None,
|
|
141
|
+
min_score: float = MIN_SCORE,
|
|
142
|
+
) -> list[Match]:
|
|
143
|
+
"""One-to-one matches for a single platform.
|
|
144
|
+
|
|
145
|
+
Calendar rows are considered when they tick this platform, or when the
|
|
146
|
+
calendar does not say where posts go. Rows that tick no platform at all
|
|
147
|
+
(e.g. stories) are skipped.
|
|
148
|
+
"""
|
|
149
|
+
rows = [p for p in planned if p.wants(platform)]
|
|
150
|
+
posts = [p for p in published if p.platform == platform and p.has_text]
|
|
151
|
+
weights = bigram_weights(p.message for p in posts) if len(posts) >= MIN_POSTS_FOR_WEIGHTS else None
|
|
152
|
+
|
|
153
|
+
candidates: list[tuple[float, PlannedPost, PublishedPost]] = []
|
|
154
|
+
for row in rows:
|
|
155
|
+
for post in posts:
|
|
156
|
+
s = score(row, post, synonyms, weights)
|
|
157
|
+
if s is not None and s >= min_score:
|
|
158
|
+
candidates.append((s, row, post))
|
|
159
|
+
|
|
160
|
+
candidates.sort(key=lambda c: c[0], reverse=True)
|
|
161
|
+
taken_rows: set[int] = set()
|
|
162
|
+
taken_posts: set[str] = set()
|
|
163
|
+
matches: list[Match] = []
|
|
164
|
+
for s, row, post in candidates:
|
|
165
|
+
if row.row in taken_rows or post.post_id in taken_posts:
|
|
166
|
+
continue
|
|
167
|
+
taken_rows.add(row.row)
|
|
168
|
+
taken_posts.add(post.post_id)
|
|
169
|
+
matches.append(Match(row, post, round(s, 3)))
|
|
170
|
+
|
|
171
|
+
# Fallback: the text says nothing in common, but exactly one leftover post
|
|
172
|
+
# went out on the planned day or the day after. Probably it, but a human
|
|
173
|
+
# should confirm, so it is marked as a guess.
|
|
174
|
+
for row in rows:
|
|
175
|
+
if row.row in taken_rows:
|
|
176
|
+
continue
|
|
177
|
+
nearby = [
|
|
178
|
+
p for p in posts
|
|
179
|
+
if p.post_id not in taken_posts and 0 <= (p.published_at.date() - row.planned_date).days <= FALLBACK_DAYS
|
|
180
|
+
]
|
|
181
|
+
if len(nearby) == 1:
|
|
182
|
+
taken_rows.add(row.row)
|
|
183
|
+
taken_posts.add(nearby[0].post_id)
|
|
184
|
+
matches.append(Match(row, nearby[0], 0.0, guess=True))
|
|
185
|
+
return sorted(matches, key=lambda m: m.planned.row)
|
postloop/models.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
"""Plain data types shared by every part of postloop."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from dataclasses import dataclass, field
|
|
6
|
+
from datetime import date, datetime
|
|
7
|
+
|
|
8
|
+
ANY_PLATFORM = "*" # a calendar row that does not say where it will be posted
|
|
9
|
+
|
|
10
|
+
# Texts platforms fill in by themselves; they say nothing about the post.
|
|
11
|
+
PLACEHOLDER_TEXTS = (
|
|
12
|
+
"no message found",
|
|
13
|
+
"你的 reel", "your reel",
|
|
14
|
+
"更新了封面相片", "updated their cover photo", "updated its cover photo",
|
|
15
|
+
"更新了大頭貼照", "updated their profile picture", "updated its profile picture",
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
@dataclass
|
|
20
|
+
class PlannedPost:
|
|
21
|
+
"""One row of the post calendar: a post somebody asked for."""
|
|
22
|
+
|
|
23
|
+
row: int # 1-based row in the sheet, used when writing results back
|
|
24
|
+
planned_date: date
|
|
25
|
+
topic: str
|
|
26
|
+
team: str = ""
|
|
27
|
+
status: str = ""
|
|
28
|
+
platforms: set[str] = field(default_factory=lambda: {ANY_PLATFORM})
|
|
29
|
+
actual_time: str = "" # what the sheet already says, if anything
|
|
30
|
+
url: str = ""
|
|
31
|
+
|
|
32
|
+
def wants(self, platform: str) -> bool:
|
|
33
|
+
return ANY_PLATFORM in self.platforms or platform in self.platforms
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class PublishedPost:
|
|
38
|
+
"""A post that actually went out, with its latest metrics."""
|
|
39
|
+
|
|
40
|
+
post_id: str
|
|
41
|
+
platform: str
|
|
42
|
+
published_at: datetime # timezone-aware, in the community's timezone
|
|
43
|
+
message: str
|
|
44
|
+
reactions: int = 0
|
|
45
|
+
comments: int = 0
|
|
46
|
+
shares: int = 0
|
|
47
|
+
views: int = 0
|
|
48
|
+
url: str = ""
|
|
49
|
+
has_time: bool = True # False when the source only gives a date (LinkedIn)
|
|
50
|
+
views_boosted: int = 0 # views that came from paid promotion (Meta exports only)
|
|
51
|
+
reach: int = 0
|
|
52
|
+
type: str = "" # photo, video, link ... as the platform names it
|
|
53
|
+
|
|
54
|
+
@property
|
|
55
|
+
def views_organic(self) -> int:
|
|
56
|
+
return max(self.views - self.views_boosted, 0)
|
|
57
|
+
|
|
58
|
+
@property
|
|
59
|
+
def boosted(self) -> bool:
|
|
60
|
+
return self.views_boosted > 0
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def headline(self) -> str:
|
|
64
|
+
"""First non-empty line of the post, trimmed for display."""
|
|
65
|
+
for line in self.message.splitlines():
|
|
66
|
+
if line.strip():
|
|
67
|
+
return line.strip()[:60]
|
|
68
|
+
return "(no text)"
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def has_text(self) -> bool:
|
|
72
|
+
text = self.message.strip().rstrip("。.!!").lower()
|
|
73
|
+
return bool(text) and not any(text == p or text.endswith(p) for p in PLACEHOLDER_TEXTS)
|
|
74
|
+
|
|
75
|
+
def timestamp(self) -> str:
|
|
76
|
+
fmt = "%Y-%m-%d %H:%M" if self.has_time else "%Y-%m-%d"
|
|
77
|
+
return self.published_at.strftime(fmt)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@dataclass
|
|
81
|
+
class Match:
|
|
82
|
+
planned: PlannedPost
|
|
83
|
+
post: PublishedPost
|
|
84
|
+
score: float
|
|
85
|
+
guess: bool = False # matched by date only; worth a human look
|
|
86
|
+
|
|
87
|
+
@property
|
|
88
|
+
def days_late(self) -> int:
|
|
89
|
+
return (self.post.published_at.date() - self.planned.planned_date).days
|
postloop/notify.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Turn a Report into a short message, and send it to Discord."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import urllib.request
|
|
7
|
+
|
|
8
|
+
from .reconcile import Report
|
|
9
|
+
|
|
10
|
+
LABELS = {
|
|
11
|
+
"zh-TW": {
|
|
12
|
+
"title": "📅 貼文日曆對帳結果",
|
|
13
|
+
"matched": "對到 {n} 篇已發布的貼文",
|
|
14
|
+
"updates": "✍️ 可自動補上的欄位:{n} 格",
|
|
15
|
+
"stale": "🟡 已經發了,但狀態還沒改",
|
|
16
|
+
"overdue": "🔴 日期已過,還沒找到貼文",
|
|
17
|
+
"review": "🔍 配對信心較低,請人工確認",
|
|
18
|
+
"unplanned": "❓ 不在日曆上的貼文",
|
|
19
|
+
"duplicates": "♊ 疑似重複發文",
|
|
20
|
+
"all_good": "✅ 一切正常,沒有需要處理的項目",
|
|
21
|
+
"more": "…還有 {n} 筆",
|
|
22
|
+
"empty": "空白",
|
|
23
|
+
"missing": "ℹ️ 日曆沒有「{cols}」欄位,所以沒有自動填寫",
|
|
24
|
+
},
|
|
25
|
+
"en": {
|
|
26
|
+
"title": "📅 Post calendar check",
|
|
27
|
+
"matched": "Matched {n} published posts",
|
|
28
|
+
"updates": "✍️ Cells that can be filled in: {n}",
|
|
29
|
+
"stale": "🟡 Posted, but status not updated",
|
|
30
|
+
"overdue": "🔴 Date passed, no post found",
|
|
31
|
+
"review": "🔍 Low-confidence matches, please check",
|
|
32
|
+
"unplanned": "❓ Posts missing from the calendar",
|
|
33
|
+
"duplicates": "♊ Possibly posted twice",
|
|
34
|
+
"all_good": "✅ All good, nothing to do",
|
|
35
|
+
"more": "…and {n} more",
|
|
36
|
+
"empty": "empty",
|
|
37
|
+
"missing": "ℹ️ The calendar has no {cols} column, so nothing was filled in",
|
|
38
|
+
},
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
DISCORD_LIMIT = 2000
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _section(title: str, lines: list[str], more: str, limit: int = 8) -> list[str]:
|
|
45
|
+
if not lines:
|
|
46
|
+
return []
|
|
47
|
+
shown = [f"• {line}" for line in lines[:limit]]
|
|
48
|
+
if len(lines) > limit:
|
|
49
|
+
shown.append(more.format(n=len(lines) - limit))
|
|
50
|
+
return ["", f"**{title}**", *shown]
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def format_summary(report: Report, language: str = "en") -> str:
|
|
54
|
+
t = LABELS.get(language, LABELS["en"])
|
|
55
|
+
rows = {m.planned.row for ms in report.matches.values() for m in ms}
|
|
56
|
+
out = [f"**{t['title']}**", t["matched"].format(n=len(rows))]
|
|
57
|
+
if report.updates:
|
|
58
|
+
out.append(t["updates"].format(n=len(report.updates)))
|
|
59
|
+
if report.missing_columns and rows:
|
|
60
|
+
out.append(t["missing"].format(cols=" / ".join(report.missing_columns)))
|
|
61
|
+
|
|
62
|
+
d = lambda day: day.strftime("%m/%d") # noqa: E731
|
|
63
|
+
out += _section(
|
|
64
|
+
t["stale"],
|
|
65
|
+
[f"{d(p.planned_date)} {p.topic} ({p.status or t['empty']} → {m.post.platform} {m.post.timestamp()[5:]})" for p, m in report.stale_status],
|
|
66
|
+
t["more"],
|
|
67
|
+
)
|
|
68
|
+
out += _section(t["overdue"], [f"{d(p.planned_date)} {p.topic}" for p in report.overdue], t["more"])
|
|
69
|
+
out += _section(
|
|
70
|
+
t["review"],
|
|
71
|
+
[f"{d(m.planned.planned_date)} {m.planned.topic} ↔ [{m.post.platform}] {m.post.headline[:30]}" for m in report.needs_review],
|
|
72
|
+
t["more"],
|
|
73
|
+
)
|
|
74
|
+
out += _section(
|
|
75
|
+
t["unplanned"],
|
|
76
|
+
[f"{p.published_at:%m/%d} [{p.platform}] {p.headline[:40]}" for p in report.unplanned],
|
|
77
|
+
t["more"],
|
|
78
|
+
)
|
|
79
|
+
out += _section(
|
|
80
|
+
t["duplicates"],
|
|
81
|
+
[f"{a.published_at:%m/%d %H:%M} [{a.platform}] {a.headline[:40]}" for a, _ in report.duplicates],
|
|
82
|
+
t["more"],
|
|
83
|
+
)
|
|
84
|
+
issues = (report.stale_status, report.overdue, report.needs_review, report.unplanned, report.duplicates)
|
|
85
|
+
if not any(issues):
|
|
86
|
+
out += ["", t["all_good"]]
|
|
87
|
+
|
|
88
|
+
text = "\n".join(out)
|
|
89
|
+
return text if len(text) <= DISCORD_LIMIT else text[: DISCORD_LIMIT - 1] + "…"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def send_discord(webhook_url: str, content: str) -> None:
|
|
93
|
+
"""Post a message through a Discord webhook (standard library only)."""
|
|
94
|
+
request = urllib.request.Request(
|
|
95
|
+
webhook_url,
|
|
96
|
+
data=json.dumps({"content": content}).encode("utf-8"),
|
|
97
|
+
headers={"Content-Type": "application/json", "User-Agent": "postloop"},
|
|
98
|
+
method="POST",
|
|
99
|
+
)
|
|
100
|
+
with urllib.request.urlopen(request, timeout=15) as response:
|
|
101
|
+
response.read()
|