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 ADDED
@@ -0,0 +1,38 @@
1
+ """postloop: plan, check and learn from your community's social media posts."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ from .adapters import load_many, load_posts
6
+ from .bootstrap import draft_calendar
7
+ from .config import Config, load_config
8
+ from .insights import analyze
9
+ from .matching import match_posts
10
+ from .models import Match, PlannedPost, PublishedPost
11
+ from .notify import format_summary, send_discord
12
+ from .plan import Calendar, load_calendar, rows_to_calendar
13
+ from .reconcile import Report, reconcile
14
+
15
+ try:
16
+ __version__ = version("postloop") # the one version number lives in pyproject.toml
17
+ except PackageNotFoundError: # running from a source checkout that was never installed
18
+ __version__ = "0.0.0"
19
+
20
+ __all__ = [
21
+ "Calendar",
22
+ "Config",
23
+ "Match",
24
+ "PlannedPost",
25
+ "PublishedPost",
26
+ "Report",
27
+ "analyze",
28
+ "draft_calendar",
29
+ "format_summary",
30
+ "load_calendar",
31
+ "load_config",
32
+ "load_many",
33
+ "load_posts",
34
+ "match_posts",
35
+ "reconcile",
36
+ "rows_to_calendar",
37
+ "send_discord",
38
+ ]
postloop/adapters.py ADDED
@@ -0,0 +1,250 @@
1
+ """Read published posts straight from the files each platform lets you download.
2
+
3
+ No ETL pipeline or API keys needed: export your posts from the platform's
4
+ dashboard and pass the file to postloop. The format is detected from the header.
5
+
6
+ Supported:
7
+ * Meta Business Suite, Facebook content export (lifetime or daily rows)
8
+ * Meta Business Suite, Instagram content export
9
+ * LinkedIn page analytics, content export (.xls/.xlsx)
10
+ * a generic CSV: platform, created_at, message, reactions, comments, shares[, post_id, url]
11
+
12
+ Headers are recognized in Traditional Chinese (verified on real exports) and
13
+ English. Exports in other languages can be added to the alias lists below.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from collections.abc import Callable, Sequence
19
+ from dataclasses import dataclass
20
+ from datetime import datetime, timedelta, timezone, tzinfo
21
+ from pathlib import Path
22
+ from typing import Any
23
+ from .config import zone
24
+ from .models import PublishedPost
25
+ from .tabular import column_index, find_header, read_sheets
26
+
27
+ # Meta writes "發佈時間 / Publish time" in US Pacific time, not the page's timezone:
28
+ # a post published 10:10 in Taipei shows up as 19:10 the evening before.
29
+ META_EXPORT_TZ = "America/Los_Angeles"
30
+
31
+
32
+ @dataclass(frozen=True)
33
+ class Format:
34
+ name: str
35
+ platform: str
36
+ signature: tuple[tuple[str, ...], ...] # aliases that must all be present to recognize it
37
+ fields: dict[str, tuple[str, ...]] # our field -> header aliases
38
+ time_formats: tuple[str, ...]
39
+ source_tz: str | None # timezone the export's times are written in
40
+ has_time: bool = True
41
+ lifetime_marker: tuple[str, ...] = () # value in the "date" column of lifetime rows
42
+
43
+
44
+ META_TIME = ("%m/%d/%Y %H:%M", "%Y-%m-%d %H:%M", "%Y-%m-%dT%H:%M:%S")
45
+
46
+ FACEBOOK = Format(
47
+ name="Meta Business Suite (Facebook)",
48
+ platform="facebook",
49
+ signature=(("粉絲專頁編號", "Page ID"), ("發佈時間", "Publish time"), ("貼文編號", "Post ID")),
50
+ fields={
51
+ "id": ("貼文編號", "Post ID"),
52
+ "title": ("標題", "Title"),
53
+ "text": ("說明", "Description"),
54
+ "time": ("發佈時間", "Publish time"),
55
+ "url": ("永久連結", "Permalink"),
56
+ "reactions": ("心情數", "Reactions"),
57
+ "comments": ("留言", "Comments"),
58
+ "shares": ("分享", "Shares"),
59
+ "views": ("觀看次數", "瀏覽次數", "Views"),
60
+ "views_boosted": ("來自加強推廣的貼文的觀看次數", "Views from boosted posts"),
61
+ "reach": ("觸及人數", "Reach"),
62
+ "type": ("貼文類型", "Post type"),
63
+ "date": ("日期", "Date"),
64
+ },
65
+ time_formats=META_TIME,
66
+ source_tz=META_EXPORT_TZ,
67
+ lifetime_marker=("總期間", "Lifetime"),
68
+ )
69
+
70
+ INSTAGRAM = Format(
71
+ name="Meta Business Suite (Instagram)",
72
+ platform="instagram",
73
+ signature=(("帳號用戶名稱", "Account username"), ("發佈時間", "Publish time"), ("貼文編號", "Post ID")),
74
+ fields={
75
+ "id": ("貼文編號", "Post ID"),
76
+ "text": ("說明", "Description"),
77
+ "time": ("發佈時間", "Publish time"),
78
+ "url": ("永久連結", "Permalink"),
79
+ "reactions": ("按讚數", "Likes"),
80
+ "comments": ("留言數", "Comments"),
81
+ "shares": ("分享", "Shares"),
82
+ "views": ("瀏覽次數", "Views"),
83
+ "reach": ("觸及人數", "Reach"),
84
+ "type": ("貼文類型", "Post type"),
85
+ "date": ("日期", "Date"),
86
+ },
87
+ time_formats=META_TIME,
88
+ source_tz=META_EXPORT_TZ,
89
+ lifetime_marker=("總期間", "Lifetime"),
90
+ )
91
+
92
+ LINKEDIN = Format(
93
+ name="LinkedIn content export",
94
+ platform="linkedin",
95
+ signature=(("貼文連結", "Post link"), ("建立日期", "Created date")),
96
+ fields={
97
+ "text": ("貼文標題", "Post title"),
98
+ "time": ("建立日期", "Created date"),
99
+ "url": ("貼文連結", "Post link"),
100
+ "reactions": ("讚", "Likes", "Reactions"),
101
+ "comments": ("回應", "Comments"),
102
+ "shares": ("轉發", "Reposts", "Shares"),
103
+ "views": ("曝光次數", "Impressions"),
104
+ },
105
+ time_formats=("%m/%d/%Y", "%Y-%m-%d"),
106
+ source_tz="UTC", # stated in the export: "所有日期和時間皆為 UTC 時區"
107
+ has_time=False,
108
+ )
109
+
110
+ GENERIC = Format(
111
+ name="generic CSV",
112
+ platform="", # read from the "platform" column
113
+ signature=(("platform",), ("created_at", "published_at"), ("message", "text")),
114
+ fields={
115
+ "platform": ("platform",),
116
+ "id": ("post_id", "id"),
117
+ "text": ("message", "text"),
118
+ "time": ("created_at", "published_at"),
119
+ "url": ("url", "permalink"),
120
+ "reactions": ("reactions", "likes"),
121
+ "comments": ("comments",),
122
+ "shares": ("share", "shares"),
123
+ "views": ("views", "impressions"),
124
+ },
125
+ time_formats=(), # ISO 8601
126
+ source_tz=None, # naive times are taken as local; "Z" or offsets are respected
127
+ )
128
+
129
+ FORMATS = (FACEBOOK, INSTAGRAM, LINKEDIN, GENERIC)
130
+
131
+
132
+ def detect(rows: Sequence[Sequence[Any]]) -> tuple[Format, int] | None:
133
+ """Which export this is, and where its header row is."""
134
+ for fmt in FORMATS:
135
+ header = find_header(rows, fmt.signature)
136
+ if header is not None:
137
+ return fmt, header
138
+ return None
139
+
140
+
141
+ def _number(value: Any) -> int:
142
+ try:
143
+ return int(float(str(value).replace(",", "")))
144
+ except (TypeError, ValueError):
145
+ return 0
146
+
147
+
148
+ def _parse_time(value: Any, fmt: Format, local: tzinfo, source_tz: str | None) -> datetime:
149
+ if isinstance(value, datetime):
150
+ moment = value
151
+ elif isinstance(value, (int, float)): # spreadsheet serial date
152
+ moment = datetime(1899, 12, 30) + timedelta(days=float(value))
153
+ else:
154
+ text = str(value).strip()
155
+ moment = None
156
+ for pattern in fmt.time_formats:
157
+ try:
158
+ moment = datetime.strptime(text, pattern)
159
+ break
160
+ except ValueError:
161
+ continue
162
+ if moment is None:
163
+ moment = datetime.fromisoformat(text.replace("Z", "+00:00").replace(" UTC", "+00:00"))
164
+ if moment.tzinfo is None:
165
+ name = source_tz or fmt.source_tz
166
+ moment = moment.replace(tzinfo=zone(name) if name else local)
167
+ return moment.astimezone(local)
168
+
169
+
170
+ def parse(rows: Sequence[Sequence[Any]], fmt: Format, header_index: int, local: tzinfo,
171
+ source_tz: str | None = None) -> list[PublishedPost]:
172
+ header = rows[header_index]
173
+ col = {name: column_index(header, aliases) for name, aliases in fmt.fields.items()}
174
+
175
+ def get(row: Sequence[Any], name: str) -> Any:
176
+ i = col.get(name)
177
+ return row[i] if i is not None and i < len(row) and row[i] is not None else ""
178
+
179
+ posts: dict[str, PublishedPost] = {}
180
+ for n, row in enumerate(rows[header_index + 1:]):
181
+ if not any(str(c).strip() for c in row if c is not None) or not str(get(row, "time")).strip():
182
+ continue
183
+ title, text = str(get(row, "title")), str(get(row, "text"))
184
+ message = max(title, text, key=len) # Facebook puts the text in either column
185
+ post_id = str(get(row, "id")).strip() or str(get(row, "url")).strip() or f"row-{n}"
186
+ is_daily = bool(fmt.lifetime_marker) and str(get(row, "date")).strip() not in fmt.lifetime_marker
187
+
188
+ if post_id in posts:
189
+ # Daily exports repeat each post once per day: add the days up.
190
+ if is_daily:
191
+ p = posts[post_id]
192
+ p.reactions += _number(get(row, "reactions"))
193
+ p.comments += _number(get(row, "comments"))
194
+ p.shares += _number(get(row, "shares"))
195
+ p.views += _number(get(row, "views"))
196
+ p.views_boosted += _number(get(row, "views_boosted"))
197
+ continue
198
+
199
+ posts[post_id] = PublishedPost(
200
+ post_id=post_id,
201
+ platform=(str(get(row, "platform")).strip().lower() if not fmt.platform else fmt.platform),
202
+ published_at=_parse_time(get(row, "time"), fmt, local, source_tz),
203
+ message=message,
204
+ reactions=_number(get(row, "reactions")),
205
+ comments=_number(get(row, "comments")),
206
+ shares=_number(get(row, "shares")),
207
+ views=_number(get(row, "views")),
208
+ url=str(get(row, "url")).strip(),
209
+ has_time=fmt.has_time,
210
+ views_boosted=_number(get(row, "views_boosted")),
211
+ reach=_number(get(row, "reach")),
212
+ type=str(get(row, "type")).strip(),
213
+ )
214
+ return list(posts.values())
215
+
216
+
217
+ @dataclass
218
+ class LoadedFile:
219
+ path: Path
220
+ format: Format
221
+ sheet: str
222
+ posts: list[PublishedPost]
223
+
224
+
225
+ def load_posts(path: str | Path, local: tzinfo | None = None, source_tz: str | None = None) -> LoadedFile:
226
+ """Read one export file, whatever platform it came from."""
227
+ local = local or datetime.now().astimezone().tzinfo or timezone.utc
228
+ for sheet, rows in read_sheets(path).items():
229
+ found = detect(rows)
230
+ if found:
231
+ fmt, header = found
232
+ return LoadedFile(Path(path), fmt, sheet, parse(rows, fmt, header, local, source_tz))
233
+ raise ValueError(
234
+ f"{Path(path).name}: not a recognized export. Supported: "
235
+ + ", ".join(f.name for f in FORMATS)
236
+ + ". For anything else, make a CSV with columns platform, created_at, message, reactions."
237
+ )
238
+
239
+
240
+ def load_many(paths: Sequence[str | Path], local: tzinfo | None = None, source_tz: str | None = None,
241
+ on_file: Callable[[LoadedFile], None] | None = None) -> list[PublishedPost]:
242
+ """Read several exports. A post exported twice (overlapping date ranges) is kept once."""
243
+ seen: dict[tuple[str, str], PublishedPost] = {}
244
+ for path in paths:
245
+ loaded = load_posts(path, local, source_tz)
246
+ if on_file:
247
+ on_file(loaded)
248
+ for post in loaded.posts:
249
+ seen.setdefault((post.platform, post.post_id), post)
250
+ return list(seen.values())
postloop/bootstrap.py ADDED
@@ -0,0 +1,135 @@
1
+ """`postloop bootstrap`: turn last year's posts into a draft calendar for the next event.
2
+
3
+ A community that runs a yearly event posts much the same things each year: the
4
+ call for proposals, the speakers, the tickets, the countdown. This takes every
5
+ post from around last year's event, works out how many days before (or after)
6
+ the event it went out, and places it the same number of days before the next
7
+ event, on the same weekday. The result is a starting point to edit, not a plan.
8
+
9
+ Only the event date is used as an anchor. If a deadline moves (early bird ends a
10
+ week later this year), move those rows by hand.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import csv
16
+ import re
17
+ from dataclasses import dataclass, field
18
+ from datetime import date, timedelta
19
+ from pathlib import Path
20
+
21
+ from .models import PublishedPost
22
+
23
+
24
+ @dataclass
25
+ class DraftPost:
26
+ planned_date: date
27
+ days_to_event: int # negative = before the event
28
+ topic: str
29
+ last_year: PublishedPost # the best-performing copy, when it went out on several platforms
30
+ platforms: list[str] = field(default_factory=list)
31
+ top_performer: bool = False
32
+
33
+
34
+ def _normalize(text: str) -> str:
35
+ """Text for comparing headlines: letters and digits only, lower case."""
36
+ return re.sub(r"[\W_]+", "", text).lower()
37
+
38
+
39
+ def _same_weekday(target: date, weekday: int, max_shift: int = 3) -> date:
40
+ """The day nearest ``target`` (within max_shift days) that falls on ``weekday``."""
41
+ for shift in sorted(range(-max_shift, max_shift + 1), key=abs):
42
+ d = target + timedelta(days=shift)
43
+ if d.weekday() == weekday:
44
+ return d
45
+ return target
46
+
47
+
48
+ def _bump_year(text: str, old: int, new: int) -> str:
49
+ """Change last year's year to next year's: "PyCon TW 2026" and "TW26" alike."""
50
+ text = re.sub(rf"(?<!\d){old}(?!\d)", str(new), text)
51
+ return re.sub(rf"(?<=[A-Za-z]){old % 100:02d}(?!\d)", f"{new % 100:02d}", text)
52
+
53
+
54
+ def _group_copies(posts: list[PublishedPost], days: int = 2) -> list[tuple[PublishedPost, list[str]]]:
55
+ """One entry per post, even if it went out on several platforms or twice within a few days.
56
+
57
+ The copy with the most organic views stands for the group.
58
+ """
59
+ groups: list[tuple[PublishedPost, list[str]]] = []
60
+ for p in sorted(posts, key=lambda p: p.views_organic, reverse=True):
61
+ key = _normalize(p.headline)
62
+ for best, platforms in groups:
63
+ if _normalize(best.headline) == key and abs((best.published_at - p.published_at).days) <= days:
64
+ if p.platform not in platforms:
65
+ platforms.append(p.platform)
66
+ break
67
+ else:
68
+ groups.append((p, [p.platform]))
69
+ return sorted(groups, key=lambda g: g[0].published_at)
70
+
71
+
72
+ def draft_calendar(posts: list[PublishedPost], last_event: date, next_event: date,
73
+ days_before: int = 240, days_after: int = 14, keep_weekday: bool = True) -> list[DraftPost]:
74
+ window = [p for p in posts
75
+ if p.has_text and -days_before <= (p.published_at.date() - last_event).days <= days_after]
76
+ groups = _group_copies(window)
77
+ if not groups:
78
+ return []
79
+
80
+ # The top quarter by organic views is worth a look first.
81
+ ranked = sorted(best.views_organic for best, _ in groups)
82
+ cutoff = ranked[int(len(ranked) * 0.75)] if len(ranked) >= 4 else ranked[-1]
83
+
84
+ drafts = []
85
+ for best, platforms in groups:
86
+ offset = (best.published_at.date() - last_event).days
87
+ planned = next_event + timedelta(days=offset)
88
+ if keep_weekday:
89
+ planned = _same_weekday(planned, best.published_at.weekday())
90
+ drafts.append(DraftPost(
91
+ planned_date=planned,
92
+ days_to_event=(planned - next_event).days,
93
+ topic=_bump_year(best.headline, last_event.year, next_event.year),
94
+ last_year=best,
95
+ platforms=sorted(platforms),
96
+ top_performer=best.views_organic >= cutoff and best.views_organic > 0,
97
+ ))
98
+ return sorted(drafts, key=lambda d: d.planned_date)
99
+
100
+
101
+ def write_draft_csv(drafts: list[DraftPost], path: str | Path) -> None:
102
+ """A calendar to paste into a sheet. UTF-8 with BOM so Excel shows Chinese correctly."""
103
+ with open(path, "w", encoding="utf-8-sig", newline="") as f:
104
+ w = csv.writer(f)
105
+ w.writerow(["Date", "Weekday", "Days to event", "Title", "Platforms", "Repeat?",
106
+ "Last year", "Last year organic views", "Last year boosted", "Last year link"])
107
+ for d in drafts:
108
+ p = d.last_year
109
+ w.writerow([d.planned_date.isoformat(), d.planned_date.strftime("%a"), d.days_to_event, d.topic,
110
+ ", ".join(d.platforms), "★ top performer" if d.top_performer else "",
111
+ p.published_at.strftime("%Y-%m-%d"), p.views_organic, "yes" if p.boosted else "", p.url])
112
+
113
+
114
+ def summary(drafts: list[DraftPost], next_event: date, language: str = "en") -> str:
115
+ if not drafts:
116
+ return "去年活動前後沒有找到貼文。" if language == "zh-TW" else "No posts found around last year's event."
117
+ months: dict[str, int] = {}
118
+ for d in drafts:
119
+ key = d.planned_date.strftime("%Y-%m")
120
+ months[key] = months.get(key, 0) + 1
121
+ first = drafts[0]
122
+ stars = [d for d in drafts if d.top_performer]
123
+ bars = [f" {m} {'█' * n} {n}" for m, n in months.items()]
124
+ starred = [f" {d.planned_date} {d.topic}" for d in stars]
125
+ if language == "zh-TW":
126
+ return "\n".join([f"{next_event} 活動的日曆草稿:{len(drafts)} 篇貼文",
127
+ f"第一篇在活動前 {-first.days_to_event} 天({first.planned_date}):{first.topic}", "",
128
+ "每月篇數:", *bars, "",
129
+ f"去年自然觀看最高的 {len(stars)} 篇(規劃時可優先參考):", *starred, "",
130
+ "截止日(早鳥、投稿)如果跟去年不同,請手動調整那幾篇。"])
131
+ return "\n".join([f"Draft calendar for {next_event}: {len(drafts)} posts",
132
+ f"First post {-first.days_to_event} days before the event ({first.planned_date}): {first.topic}",
133
+ "", "Posts per month:", *bars, "",
134
+ f"The {len(stars)} posts with the most organic views last year (worth a look first):", *starred,
135
+ "", "If a deadline (early bird, proposals) moved this year, move those rows by hand."])
postloop/cli.py ADDED
@@ -0,0 +1,143 @@
1
+ """Command line.
2
+
3
+ postloop --plan calendar.csv --posts facebook.csv instagram.csv linkedin.xlsx check the calendar
4
+ postloop report --posts facebook.csv what worked
5
+ postloop bootstrap --posts facebook.csv --event-date ... --next-event ... draft next year's calendar
6
+
7
+ Nothing is written anywhere unless you ask: --write saves a filled copy of the
8
+ calendar (or fills the live Google Sheet), --discord sends the summary.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import os
15
+ import sys
16
+ from datetime import date
17
+ from pathlib import Path
18
+
19
+ from . import __version__
20
+ from .commands import bootstrap, report
21
+ from .adapters import LoadedFile, load_many
22
+ from .config import load_config
23
+ from .notify import format_summary, send_discord
24
+ from .output import write_file, write_gsheet, write_report_csv
25
+ from .plan import load_calendar, load_calendar_gsheet, open_worksheet
26
+ from .reconcile import reconcile
27
+
28
+
29
+ def build_parser() -> argparse.ArgumentParser:
30
+ p = argparse.ArgumentParser(
31
+ prog="postloop",
32
+ description="Check a post calendar against what was actually posted. "
33
+ "No calendar yet? Try `postloop report` or `postloop bootstrap`.",
34
+ epilog="Other commands:\n"
35
+ " postloop report --posts ... what worked, from platform exports alone\n"
36
+ " postloop bootstrap --posts ... draft next year's calendar from last year's posts\n"
37
+ "Run `postloop report -h` or `postloop bootstrap -h` for their options.\n\n"
38
+ "Exports: Meta Business Suite > Insights > Content > Export data (Facebook and Instagram "
39
+ "separately); LinkedIn page > Analytics > Content > Export.",
40
+ formatter_class=argparse.RawDescriptionHelpFormatter,
41
+ )
42
+ p.add_argument("--version", action="version", version=f"postloop {__version__}")
43
+
44
+ cal = p.add_mutually_exclusive_group(required=True)
45
+ cal.add_argument("--plan", metavar="FILE", help="post calendar: .csv, .xlsx or .xls")
46
+ cal.add_argument("--sheet-id", help="Google Sheet ID of a live calendar (needs GOOGLE_CREDENTIALS)")
47
+ p.add_argument("--posts", metavar="FILE", nargs="+", required=True,
48
+ help="platform exports (Facebook, Instagram, LinkedIn) or a generic CSV; as many as you like")
49
+
50
+ p.add_argument("--config", help="TOML settings file (optional)")
51
+ p.add_argument("--worksheet", help="sheet/tab name in the calendar (default: found automatically)")
52
+ p.add_argument("--date-col", help="calendar column with the planned date")
53
+ p.add_argument("--title-col", help="calendar column with the post title")
54
+ p.add_argument("--timezone", help='your timezone, e.g. "Asia/Taipei" (default: this computer\'s)')
55
+ p.add_argument("--lang", choices=["en", "zh-TW"], help="summary language")
56
+ p.add_argument("--today", type=date.fromisoformat, help="pretend today is YYYY-MM-DD")
57
+
58
+ p.add_argument("--report", metavar="CSV", help="save the row-by-row result as CSV")
59
+ p.add_argument("--write", action="store_true", help="fill the empty published-at/URL cells")
60
+ p.add_argument("--out", help="with --plan --write: where to save the filled copy (.xlsx or .csv)")
61
+ p.add_argument("--discord", action="store_true", help="send the summary to $DISCORD_WEBHOOK")
62
+ p.add_argument("-q", "--quiet", action="store_true", help="only print the summary")
63
+ return p
64
+
65
+
66
+ def main(argv: list[str] | None = None) -> int:
67
+ argv = sys.argv[1:] if argv is None else list(argv)
68
+ if argv and argv[0] in SUBCOMMANDS:
69
+ return SUBCOMMANDS[argv[0]](argv[1:])
70
+ return check(argv)
71
+
72
+
73
+ def check(argv: list[str]) -> int:
74
+ args = build_parser().parse_args(argv)
75
+ say = (lambda *a: None) if args.quiet else (lambda *a: print(*a, file=sys.stderr))
76
+
77
+ try:
78
+ config = load_config(args.config)
79
+ for name, value in (("date", args.date_col), ("title", args.title_col)):
80
+ if value:
81
+ config.columns[name] = value
82
+ if args.worksheet:
83
+ config.worksheet = args.worksheet
84
+ if args.timezone:
85
+ config.timezone = args.timezone
86
+ if args.lang:
87
+ config.language = args.lang
88
+
89
+ worksheet = None
90
+ if args.sheet_id:
91
+ worksheet = open_worksheet(args.sheet_id, config)
92
+ calendar = load_calendar_gsheet(worksheet, config)
93
+ else:
94
+ calendar = load_calendar(args.plan, config)
95
+ where = f" in sheet {calendar.sheet!r}" if calendar.sheet and args.plan and not args.plan.endswith(".csv") else ""
96
+ say(f"Calendar: {len(calendar.planned)} planned posts{where} "
97
+ f"(date: {calendar.column('date')!r}, title: {calendar.column('title')!r})")
98
+
99
+ def describe(loaded: LoadedFile) -> None:
100
+ say(f"Posts: {loaded.path.name} → {loaded.format.name}, {len(loaded.posts)} posts")
101
+
102
+ posts = load_many(args.posts, config.tz, config.export_timezone, on_file=describe)
103
+ except (ValueError, ImportError, FileNotFoundError) as e:
104
+ print(f"postloop: {e}", file=sys.stderr)
105
+ return 2
106
+
107
+ report = reconcile(calendar, posts, config, today=args.today)
108
+ summary = format_summary(report, config.language)
109
+ say("")
110
+ print(summary)
111
+
112
+ if args.report:
113
+ write_report_csv(report, args.report)
114
+ say(f"\nReport saved to {args.report}")
115
+
116
+ if args.write:
117
+ if worksheet is not None:
118
+ n = write_gsheet(worksheet, report.updates, calendar)
119
+ say(f"\nFilled {n} cells in the Google Sheet")
120
+ else:
121
+ source = Path(args.plan)
122
+ target = Path(args.out) if args.out else source.with_name(f"{source.stem}_filled{source.suffix}")
123
+ if target.resolve() == source.resolve():
124
+ print("postloop: --out must not be the calendar itself", file=sys.stderr)
125
+ return 2
126
+ n = write_file(source, target, report.updates, calendar, config.worksheet)
127
+ say(f"\nFilled {n} cells, saved to {target}")
128
+
129
+ if args.discord:
130
+ webhook = os.environ.get("DISCORD_WEBHOOK")
131
+ if not webhook:
132
+ print("postloop: DISCORD_WEBHOOK is not set; summary not sent", file=sys.stderr)
133
+ return 1
134
+ send_discord(webhook, summary)
135
+ say("\nSummary sent to Discord")
136
+ return 0
137
+
138
+
139
+ SUBCOMMANDS = {"check": check, "report": report, "bootstrap": bootstrap}
140
+
141
+
142
+ if __name__ == "__main__":
143
+ raise SystemExit(main())
postloop/commands.py ADDED
@@ -0,0 +1,84 @@
1
+ """`postloop report` and `postloop bootstrap`: work from platform exports alone, no calendar needed.
2
+
3
+ postloop report --posts facebook.csv instagram.csv
4
+ postloop bootstrap --posts facebook.csv --event-date 2026-10-17 --next-event 2027-10-16
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import sys
11
+ from datetime import date
12
+ from pathlib import Path
13
+
14
+ from .adapters import load_many
15
+ from .bootstrap import draft_calendar, summary, write_draft_csv
16
+ from .config import Config, load_config
17
+ from .insights import analyze, to_markdown, write_posts_table
18
+
19
+
20
+ def _common(p: argparse.ArgumentParser) -> None:
21
+ p.add_argument("--posts", metavar="FILE", nargs="+", required=True,
22
+ help="platform exports (Facebook, Instagram, LinkedIn) or a generic CSV")
23
+ p.add_argument("--config", help="TOML settings file (optional)")
24
+ p.add_argument("--timezone", help='your timezone, e.g. "Asia/Seoul" (default: this computer\'s)')
25
+ p.add_argument("--lang", choices=["en", "zh-TW"], help="summary language")
26
+
27
+
28
+ def _setup(args) -> tuple[Config, list]:
29
+ config = load_config(args.config)
30
+ if args.timezone:
31
+ config.timezone = args.timezone
32
+ if args.lang:
33
+ config.language = args.lang
34
+ posts = load_many(args.posts, config.tz, config.export_timezone)
35
+ return config, posts
36
+
37
+
38
+ def report(argv: list[str]) -> int:
39
+ p = argparse.ArgumentParser(prog="postloop report",
40
+ description="What worked, from platform exports alone. No calendar needed.")
41
+ _common(p)
42
+ p.add_argument("--top", type=int, default=5, help="how many top posts to list per platform")
43
+ p.add_argument("--gap-days", type=int, default=14, help="report stretches with no posts longer than this")
44
+ p.add_argument("--out", default="post_report", help="output path without extension (.md and .csv are written)")
45
+ args = p.parse_args(argv)
46
+ try:
47
+ config, posts = _setup(args)
48
+ results = analyze(posts, top_n=args.top, gap_days=args.gap_days)
49
+ except (ValueError, ImportError, FileNotFoundError) as e:
50
+ print(f"postloop: {e}", file=sys.stderr)
51
+ return 2
52
+ text = to_markdown(results, config.language, args.gap_days)
53
+ print(text)
54
+ out = Path(args.out)
55
+ out.with_suffix(".md").write_text(text, encoding="utf-8")
56
+ write_posts_table(results, out.with_suffix(".csv"))
57
+ print(f"Saved {out.with_suffix('.md')} and {out.with_suffix('.csv')}", file=sys.stderr)
58
+ return 0
59
+
60
+
61
+ def bootstrap(argv: list[str]) -> int:
62
+ p = argparse.ArgumentParser(prog="postloop bootstrap",
63
+ description="Turn last year's posts into a draft calendar for the next event.")
64
+ _common(p)
65
+ p.add_argument("--event-date", required=True, type=date.fromisoformat, help="last event's first day, YYYY-MM-DD")
66
+ p.add_argument("--next-event", required=True, type=date.fromisoformat, help="next event's first day, YYYY-MM-DD")
67
+ p.add_argument("--days-before", type=int, default=240, help="include posts up to this many days before the event")
68
+ p.add_argument("--days-after", type=int, default=14, help="and up to this many days after it")
69
+ p.add_argument("--exact-days", action="store_true",
70
+ help="keep the exact number of days to the event instead of moving to the same weekday")
71
+ p.add_argument("--out", default="draft_calendar.csv", help="where to save the draft calendar")
72
+ args = p.parse_args(argv)
73
+ try:
74
+ config, posts = _setup(args)
75
+ except (ValueError, ImportError, FileNotFoundError) as e:
76
+ print(f"postloop: {e}", file=sys.stderr)
77
+ return 2
78
+ drafts = draft_calendar(posts, args.event_date, args.next_event, args.days_before, args.days_after,
79
+ keep_weekday=not args.exact_days)
80
+ print(summary(drafts, args.next_event, config.language))
81
+ if drafts:
82
+ write_draft_csv(drafts, args.out)
83
+ print(f"\nSaved {args.out}", file=sys.stderr)
84
+ return 0