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/output.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Write results: back into the calendar, or out to a CSV for sharing."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import csv
|
|
6
|
+
import shutil
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from .plan import Calendar
|
|
10
|
+
from .reconcile import CellUpdate, Report
|
|
11
|
+
from .tabular import column_index, read_csv, read_sheets
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _column_numbers(header: list, names: set[str]) -> dict[str, int]:
|
|
15
|
+
"""1-based column number for each header text."""
|
|
16
|
+
found = {}
|
|
17
|
+
for name in names:
|
|
18
|
+
i = column_index(header, [name])
|
|
19
|
+
if i is None:
|
|
20
|
+
raise ValueError(f"Column {name!r} not found in calendar header")
|
|
21
|
+
found[name] = i + 1
|
|
22
|
+
return found
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def write_gsheet(worksheet, updates: list[CellUpdate], calendar: Calendar) -> int:
|
|
26
|
+
"""Fill the cells in a live Google Sheet. Returns the number written."""
|
|
27
|
+
from gspread.utils import rowcol_to_a1
|
|
28
|
+
|
|
29
|
+
if not updates:
|
|
30
|
+
return 0
|
|
31
|
+
cols = _column_numbers(worksheet.row_values(calendar.header_row), {u.column for u in updates})
|
|
32
|
+
worksheet.batch_update(
|
|
33
|
+
[{"range": rowcol_to_a1(u.row, cols[u.column]), "values": [[u.value]]} for u in updates],
|
|
34
|
+
value_input_option="USER_ENTERED",
|
|
35
|
+
)
|
|
36
|
+
return len(updates)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def write_file(source: str | Path, target: str | Path, updates: list[CellUpdate], calendar: Calendar,
|
|
40
|
+
worksheet: str | None = None) -> int:
|
|
41
|
+
"""Save a filled copy of a .csv or .xlsx calendar. The original is never touched."""
|
|
42
|
+
source, target = Path(source), Path(target)
|
|
43
|
+
if target.suffix.lower() == ".csv": # also works for an .xlsx calendar: saves that sheet as CSV
|
|
44
|
+
if source.suffix.lower() == ".csv":
|
|
45
|
+
rows = read_csv(source)
|
|
46
|
+
else:
|
|
47
|
+
sheets = read_sheets(source)
|
|
48
|
+
name = worksheet or calendar.sheet or next(iter(sheets))
|
|
49
|
+
rows = [["" if c is None else c for c in r] for r in sheets[name]]
|
|
50
|
+
cols = _column_numbers(rows[calendar.header_row - 1], {u.column for u in updates}) if updates else {}
|
|
51
|
+
for u in updates:
|
|
52
|
+
row = rows[u.row - 1]
|
|
53
|
+
row.extend([""] * (cols[u.column] - len(row)))
|
|
54
|
+
row[cols[u.column] - 1] = u.value
|
|
55
|
+
with open(target, "w", newline="", encoding="utf-8-sig") as f:
|
|
56
|
+
csv.writer(f).writerows(rows)
|
|
57
|
+
return len(updates)
|
|
58
|
+
|
|
59
|
+
if source.suffix.lower() not in (".xlsx", ".xlsm"):
|
|
60
|
+
raise ValueError("Save the filled copy as .csv, or as .xlsx when the calendar is .xlsx.")
|
|
61
|
+
from openpyxl import load_workbook
|
|
62
|
+
|
|
63
|
+
shutil.copyfile(source, target)
|
|
64
|
+
book = load_workbook(target, keep_vba=target.suffix.lower() == ".xlsm") # else saving drops the macros
|
|
65
|
+
sheet = book[worksheet] if worksheet else _find_sheet(book, calendar)
|
|
66
|
+
header = [c.value for c in sheet[calendar.header_row]]
|
|
67
|
+
cols = _column_numbers(header, {u.column for u in updates}) if updates else {}
|
|
68
|
+
for u in updates:
|
|
69
|
+
sheet.cell(row=u.row, column=cols[u.column], value=u.value)
|
|
70
|
+
book.save(target)
|
|
71
|
+
return len(updates)
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _find_sheet(book, calendar: Calendar):
|
|
75
|
+
"""The sheet whose header row holds the calendar's columns."""
|
|
76
|
+
wanted = set(calendar.columns.values())
|
|
77
|
+
for sheet in book.worksheets:
|
|
78
|
+
header = {str(c.value) for c in sheet[calendar.header_row] if c.value is not None}
|
|
79
|
+
if wanted <= header:
|
|
80
|
+
return sheet
|
|
81
|
+
return book.worksheets[0]
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def write_report_csv(report: Report, path: str | Path) -> None:
|
|
85
|
+
"""One line per calendar row, with what each platform shows. Opens in Excel and Sheets."""
|
|
86
|
+
platforms = sorted(report.matches)
|
|
87
|
+
by_row = {(m.planned.row, p): m for p, ms in report.matches.items() for m in ms}
|
|
88
|
+
stale = {p.row for p, _ in report.stale_status}
|
|
89
|
+
overdue = {p.row for p in report.overdue}
|
|
90
|
+
review = {(m.planned.row, m.post.platform) for m in report.needs_review}
|
|
91
|
+
|
|
92
|
+
fields = ["row", "planned_date", "team", "topic", "status"]
|
|
93
|
+
for p in platforms:
|
|
94
|
+
fields += [f"{p}_published", f"{p}_days_late", f"{p}_reactions", f"{p}_comments",
|
|
95
|
+
f"{p}_shares", f"{p}_views", f"{p}_url", f"{p}_match"]
|
|
96
|
+
fields += ["flags"]
|
|
97
|
+
|
|
98
|
+
with open(path, "w", newline="", encoding="utf-8-sig") as f: # BOM: Excel reads Chinese correctly
|
|
99
|
+
writer = csv.DictWriter(f, fieldnames=fields)
|
|
100
|
+
writer.writeheader()
|
|
101
|
+
for row in report.planned:
|
|
102
|
+
line = {"row": row.row, "planned_date": row.planned_date.isoformat(),
|
|
103
|
+
"team": row.team, "topic": row.topic, "status": row.status}
|
|
104
|
+
for p in platforms:
|
|
105
|
+
m = by_row.get((row.row, p))
|
|
106
|
+
if m:
|
|
107
|
+
line.update({
|
|
108
|
+
f"{p}_published": m.post.timestamp(), f"{p}_days_late": m.days_late,
|
|
109
|
+
f"{p}_reactions": m.post.reactions, f"{p}_comments": m.post.comments,
|
|
110
|
+
f"{p}_shares": m.post.shares, f"{p}_views": m.post.views, f"{p}_url": m.post.url,
|
|
111
|
+
f"{p}_match": "guess" if m.guess else ("check" if (row.row, p) in review else "ok"),
|
|
112
|
+
})
|
|
113
|
+
flags = []
|
|
114
|
+
if row.row in stale:
|
|
115
|
+
flags.append("status not updated")
|
|
116
|
+
if row.row in overdue:
|
|
117
|
+
flags.append("overdue")
|
|
118
|
+
line["flags"] = "; ".join(flags)
|
|
119
|
+
writer.writerow(line)
|
postloop/plan.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
"""Read a post calendar: any table with a date and a title.
|
|
2
|
+
|
|
3
|
+
Only two columns are required. Everything else is optional and found by name:
|
|
4
|
+
|
|
5
|
+
date 預計發布日 / 發布日 / 日期 / Date / Planned date ...
|
|
6
|
+
title 發文主題 / 主題 / 標題 / Title / Topic / Post ...
|
|
7
|
+
platforms either checkbox columns (FB, IG, LinkedIn ...) or one column
|
|
8
|
+
with names separated by commas ("FB, IG")
|
|
9
|
+
status, team, published at, URL
|
|
10
|
+
|
|
11
|
+
Column names can also be given explicitly in the config or on the command line.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import re
|
|
17
|
+
from collections.abc import Sequence
|
|
18
|
+
from dataclasses import dataclass, field
|
|
19
|
+
from datetime import date, datetime, timedelta
|
|
20
|
+
from pathlib import Path
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from .config import Config
|
|
24
|
+
from .models import ANY_PLATFORM, PlannedPost
|
|
25
|
+
from .tabular import column_index, find_header, normalize, read_sheets
|
|
26
|
+
|
|
27
|
+
ALIASES: dict[str, tuple[str, ...]] = {
|
|
28
|
+
"date": ("預計發布日", "預計發佈日", "發布日期", "發佈日期", "發布日", "日期",
|
|
29
|
+
"date", "planned date", "publish date", "post date", "scheduled date"),
|
|
30
|
+
"title": ("發文主題", "貼文主題", "主題", "標題", "title", "topic", "post", "subject", "headline"),
|
|
31
|
+
"status": ("狀態", "status"),
|
|
32
|
+
"team": ("委託組別", "組別", "team", "requested by", "owner"),
|
|
33
|
+
"actual_time": ("實際發佈日期與時間", "實際發布日期與時間", "實際發布時間", "實際發佈時間",
|
|
34
|
+
"published at", "published_at", "actual time", "posted at"),
|
|
35
|
+
"url": ("網址(n8n用)", "網址", "貼文網址", "url", "link", "post url", "permalink"),
|
|
36
|
+
"platforms": ("平台", "管道", "platforms", "platform", "channels", "channel"),
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
# Checkbox column names, and words in a "platforms" cell, mapped to platform names.
|
|
40
|
+
PLATFORM_WORDS: dict[str, str] = {
|
|
41
|
+
"fb": "facebook", "facebook": "facebook", "臉書": "facebook",
|
|
42
|
+
"ig": "instagram", "instagram": "instagram",
|
|
43
|
+
"linkedin": "linkedin", "li": "linkedin",
|
|
44
|
+
"x": "twitter", "twitter": "twitter", "x、bluesky": "twitter",
|
|
45
|
+
"threads": "threads", "thread": "threads",
|
|
46
|
+
"bluesky": "bluesky", "mastodon": "mastodon", "discord": "discord",
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
_SERIAL_EPOCH = date(1899, 12, 30) # Google Sheets and Excel count days from here
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclass
|
|
53
|
+
class Calendar:
|
|
54
|
+
planned: list[PlannedPost]
|
|
55
|
+
columns: dict[str, str] = field(default_factory=dict) # field -> header text in the sheet
|
|
56
|
+
header_row: int = 1 # 1-based
|
|
57
|
+
sheet: str | None = None # which sheet of a workbook it came from
|
|
58
|
+
|
|
59
|
+
def column(self, name: str) -> str | None:
|
|
60
|
+
return self.columns.get(name)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def parse_date(value: Any, default_year: int | None = None) -> date | None:
|
|
64
|
+
"""Accept datetimes, sheet serial numbers and common text formats."""
|
|
65
|
+
if value in (None, ""):
|
|
66
|
+
return None
|
|
67
|
+
if isinstance(value, datetime):
|
|
68
|
+
return value.date()
|
|
69
|
+
if isinstance(value, date):
|
|
70
|
+
return value
|
|
71
|
+
if isinstance(value, bool):
|
|
72
|
+
return None
|
|
73
|
+
if isinstance(value, (int, float)):
|
|
74
|
+
return _SERIAL_EPOCH + timedelta(days=int(value))
|
|
75
|
+
text = str(value).strip()
|
|
76
|
+
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%Y-%m-%d %H:%M:%S", "%Y/%m/%d %H:%M", "%d.%m.%Y"):
|
|
77
|
+
try:
|
|
78
|
+
return datetime.strptime(text, fmt).date()
|
|
79
|
+
except ValueError:
|
|
80
|
+
pass
|
|
81
|
+
year = default_year or date.today().year
|
|
82
|
+
for fmt in ("%m/%d", "%m-%d", "%m/%d/%Y"): # "03/31" as a sheet displays it
|
|
83
|
+
try:
|
|
84
|
+
parsed = datetime.strptime(text, fmt)
|
|
85
|
+
return parsed.date() if "%Y" in fmt else parsed.replace(year=year).date()
|
|
86
|
+
except ValueError:
|
|
87
|
+
pass
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _ticked(value: Any) -> bool:
|
|
92
|
+
return value is True or str(value).strip().upper() in {"TRUE", "1", "V", "Y", "YES", "✓", "✔"}
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _platform_columns(header: Sequence[Any], config: Config) -> dict[int, str]:
|
|
96
|
+
"""Checkbox columns: from the config if given, otherwise recognized by name."""
|
|
97
|
+
if config.platforms:
|
|
98
|
+
found = {column_index(header, [name]): platform for name, platform in config.platforms.items()}
|
|
99
|
+
return {i: p for i, p in found.items() if i is not None}
|
|
100
|
+
return {
|
|
101
|
+
i: PLATFORM_WORDS[normalize(cell)]
|
|
102
|
+
for i, cell in enumerate(header)
|
|
103
|
+
if normalize(cell) in PLATFORM_WORDS
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _platforms_from_text(text: str) -> set[str]:
|
|
108
|
+
words = re.split(r"[,,、//;;+\s]+", text.lower())
|
|
109
|
+
return {PLATFORM_WORDS[w] for w in words if w in PLATFORM_WORDS}
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def rows_to_calendar(rows: Sequence[Sequence[Any]], config: Config) -> Calendar:
|
|
113
|
+
aliases = {name: list(values) for name, values in ALIASES.items()}
|
|
114
|
+
for name, header_text in config.columns.items(): # explicit names win
|
|
115
|
+
if header_text:
|
|
116
|
+
aliases[name] = [header_text]
|
|
117
|
+
|
|
118
|
+
if config.header_row:
|
|
119
|
+
header_index = config.header_row - 1
|
|
120
|
+
else:
|
|
121
|
+
header_index = find_header(rows, [aliases["date"], aliases["title"]])
|
|
122
|
+
if header_index is None:
|
|
123
|
+
raise ValueError(
|
|
124
|
+
"Could not find the calendar's header row: no row has both a date column "
|
|
125
|
+
f"({', '.join(aliases['date'][:4])}...) and a title column ({', '.join(aliases['title'][:4])}...). "
|
|
126
|
+
"Name them with --date-col and --title-col."
|
|
127
|
+
)
|
|
128
|
+
header = list(rows[header_index])
|
|
129
|
+
idx = {name: column_index(header, names) for name, names in aliases.items()}
|
|
130
|
+
if idx["date"] is None or idx["title"] is None:
|
|
131
|
+
raise ValueError(f"Calendar needs a date and a title column. Header found: {header}")
|
|
132
|
+
|
|
133
|
+
checkbox_cols = {} if idx["platforms"] is not None else _platform_columns(header, config)
|
|
134
|
+
columns = {name: str(header[i]) for name, i in idx.items() if i is not None}
|
|
135
|
+
|
|
136
|
+
def cell(row: Sequence[Any], name: str) -> Any:
|
|
137
|
+
i = idx[name]
|
|
138
|
+
return row[i] if i is not None and i < len(row) and row[i] is not None else ""
|
|
139
|
+
|
|
140
|
+
planned = []
|
|
141
|
+
for number, row in enumerate(rows[header_index + 1:], start=header_index + 2):
|
|
142
|
+
topic = str(cell(row, "title")).strip()
|
|
143
|
+
planned_date = parse_date(cell(row, "date"))
|
|
144
|
+
if not topic or planned_date is None:
|
|
145
|
+
continue
|
|
146
|
+
if idx["platforms"] is not None:
|
|
147
|
+
platforms = _platforms_from_text(str(cell(row, "platforms"))) or {ANY_PLATFORM}
|
|
148
|
+
elif checkbox_cols:
|
|
149
|
+
platforms = {p for i, p in checkbox_cols.items() if i < len(row) and _ticked(row[i])}
|
|
150
|
+
else:
|
|
151
|
+
platforms = {ANY_PLATFORM}
|
|
152
|
+
planned.append(PlannedPost(
|
|
153
|
+
row=number,
|
|
154
|
+
planned_date=planned_date,
|
|
155
|
+
topic=topic,
|
|
156
|
+
team=str(cell(row, "team")).strip(),
|
|
157
|
+
status=str(cell(row, "status")).strip(),
|
|
158
|
+
platforms=platforms,
|
|
159
|
+
actual_time=str(cell(row, "actual_time")).strip(),
|
|
160
|
+
url=str(cell(row, "url")).strip(),
|
|
161
|
+
))
|
|
162
|
+
return Calendar(planned, columns, header_index + 1)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def load_calendar(path: str | Path, config: Config) -> Calendar:
|
|
166
|
+
"""From a .csv, .xlsx or .xls file: the configured sheet, else the one with the most posts."""
|
|
167
|
+
sheets = read_sheets(path)
|
|
168
|
+
if config.worksheet:
|
|
169
|
+
if config.worksheet not in sheets:
|
|
170
|
+
raise ValueError(f"No sheet named {config.worksheet!r}. Sheets: {list(sheets)}")
|
|
171
|
+
calendar = rows_to_calendar(sheets[config.worksheet], config)
|
|
172
|
+
calendar.sheet = config.worksheet
|
|
173
|
+
return calendar
|
|
174
|
+
# Workbooks often keep old copies ("v1", "v3") next to the real calendar:
|
|
175
|
+
# use the sheet with the most planned posts.
|
|
176
|
+
found, errors = [], []
|
|
177
|
+
for name, rows in sheets.items():
|
|
178
|
+
try:
|
|
179
|
+
cal = rows_to_calendar(rows, config)
|
|
180
|
+
found.append((len(cal.planned), name, cal))
|
|
181
|
+
except ValueError as e:
|
|
182
|
+
errors.append(f"{name}: {e}")
|
|
183
|
+
if not found:
|
|
184
|
+
raise ValueError("No sheet looks like a post calendar.\n" + "\n".join(errors))
|
|
185
|
+
_, name, calendar = max(found, key=lambda f: f[0])
|
|
186
|
+
calendar.sheet = name
|
|
187
|
+
return calendar
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def open_worksheet(sheet_id: str, config: Config, credentials_json: str | None = None):
|
|
191
|
+
"""Open a live Google Sheet. Credentials: a service account's JSON key (string)."""
|
|
192
|
+
import json
|
|
193
|
+
import os
|
|
194
|
+
|
|
195
|
+
try:
|
|
196
|
+
import gspread
|
|
197
|
+
except ImportError as e: # pragma: no cover
|
|
198
|
+
raise ImportError("Google Sheets support needs gspread: pip install 'postloop[sheets]'") from e
|
|
199
|
+
credentials_json = credentials_json or os.environ.get("GOOGLE_CREDENTIALS")
|
|
200
|
+
if not credentials_json:
|
|
201
|
+
raise ValueError("--sheet-id needs GOOGLE_CREDENTIALS: a service account's JSON key")
|
|
202
|
+
client = gspread.service_account_from_dict(json.loads(credentials_json))
|
|
203
|
+
book = client.open_by_key(sheet_id)
|
|
204
|
+
return book.worksheet(config.worksheet) if config.worksheet else book.sheet1
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def load_calendar_gsheet(worksheet, config: Config) -> Calendar:
|
|
208
|
+
# Unformatted values give real booleans and date serials instead of "TRUE" and "03/31".
|
|
209
|
+
return rows_to_calendar(worksheet.get_all_values(value_render_option="UNFORMATTED_VALUE"), config)
|
postloop/reconcile.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
"""Compare the plan with what actually happened, and list what needs attention.
|
|
2
|
+
|
|
3
|
+
postloop fills in facts (when a post went out, its link) but leaves decisions
|
|
4
|
+
to people: a status that looks out of date is reported, never changed.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass, field
|
|
10
|
+
from datetime import date, timedelta
|
|
11
|
+
|
|
12
|
+
from .config import Config
|
|
13
|
+
from .matching import LATEST_DAYS, match_posts
|
|
14
|
+
from .models import Match, PlannedPost, PublishedPost
|
|
15
|
+
from .plan import Calendar
|
|
16
|
+
|
|
17
|
+
REVIEW_SCORE = 0.3 # matches below this are listed for a human to check
|
|
18
|
+
DUPLICATE_WINDOW = timedelta(hours=3)
|
|
19
|
+
PLATFORM_PREFERENCE = ("facebook", "instagram", "linkedin", "twitter", "threads")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class CellUpdate:
|
|
24
|
+
row: int
|
|
25
|
+
column: str # header text of the column in the sheet
|
|
26
|
+
value: str
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass
|
|
30
|
+
class Report:
|
|
31
|
+
planned: list[PlannedPost]
|
|
32
|
+
matches: dict[str, list[Match]] # platform -> matches
|
|
33
|
+
primary_platform: str | None = None
|
|
34
|
+
updates: list[CellUpdate] = field(default_factory=list)
|
|
35
|
+
stale_status: list[tuple[PlannedPost, Match]] = field(default_factory=list)
|
|
36
|
+
overdue: list[PlannedPost] = field(default_factory=list)
|
|
37
|
+
needs_review: list[Match] = field(default_factory=list)
|
|
38
|
+
unplanned: list[PublishedPost] = field(default_factory=list)
|
|
39
|
+
duplicates: list[tuple[PublishedPost, PublishedPost]] = field(default_factory=list)
|
|
40
|
+
missing_columns: list[str] = field(default_factory=list) # columns we could have filled
|
|
41
|
+
|
|
42
|
+
def matches_for(self, row: int) -> list[Match]:
|
|
43
|
+
return [m for ms in self.matches.values() for m in ms if m.planned.row == row]
|
|
44
|
+
|
|
45
|
+
def best_match(self, row: int) -> Match | None:
|
|
46
|
+
"""The primary platform's match for a row, else the earliest one."""
|
|
47
|
+
found = self.matches_for(row)
|
|
48
|
+
if not found:
|
|
49
|
+
return None
|
|
50
|
+
primary = [m for m in found if m.post.platform == self.primary_platform]
|
|
51
|
+
return primary[0] if primary else min(found, key=lambda m: m.post.published_at)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def choose_primary(posts: list[PublishedPost], preferred: str | None) -> str | None:
|
|
55
|
+
available = {p.platform for p in posts}
|
|
56
|
+
if preferred:
|
|
57
|
+
return preferred
|
|
58
|
+
for platform in PLATFORM_PREFERENCE:
|
|
59
|
+
if platform in available:
|
|
60
|
+
return platform
|
|
61
|
+
return min(available) if available else None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def reconcile(calendar: Calendar, posts: list[PublishedPost], config: Config, today: date | None = None) -> Report:
|
|
65
|
+
today = today or date.today()
|
|
66
|
+
planned = calendar.planned
|
|
67
|
+
platforms = sorted({p.platform for p in posts})
|
|
68
|
+
report = Report(
|
|
69
|
+
planned=planned,
|
|
70
|
+
matches={p: match_posts(planned, posts, p, config.synonyms) for p in platforms},
|
|
71
|
+
primary_platform=choose_primary(posts, config.primary_platform),
|
|
72
|
+
)
|
|
73
|
+
time_col, url_col = calendar.column("actual_time"), calendar.column("url")
|
|
74
|
+
uses_status = any(p.status for p in planned) # an all-empty status column is not in use
|
|
75
|
+
|
|
76
|
+
for row in planned:
|
|
77
|
+
best = report.best_match(row.row)
|
|
78
|
+
if best is None:
|
|
79
|
+
# Only overdue if we have data for at least one platform this row is meant for.
|
|
80
|
+
covered = any(row.wants(p) for p in platforms)
|
|
81
|
+
if row.planned_date < today and row.platforms and covered and not config.is_done(row.status):
|
|
82
|
+
report.overdue.append(row)
|
|
83
|
+
continue
|
|
84
|
+
if best.guess or best.score < REVIEW_SCORE:
|
|
85
|
+
report.needs_review.append(best)
|
|
86
|
+
if uses_status and not config.is_done(row.status):
|
|
87
|
+
report.stale_status.append((row, best))
|
|
88
|
+
if best.guess:
|
|
89
|
+
continue # do not write facts we are not sure about
|
|
90
|
+
if time_col and not row.actual_time:
|
|
91
|
+
report.updates.append(CellUpdate(row.row, time_col, best.post.timestamp()))
|
|
92
|
+
if url_col and not row.url and best.post.url:
|
|
93
|
+
report.updates.append(CellUpdate(row.row, url_col, best.post.url))
|
|
94
|
+
|
|
95
|
+
if not time_col:
|
|
96
|
+
report.missing_columns.append("published at")
|
|
97
|
+
if not url_col:
|
|
98
|
+
report.missing_columns.append("URL")
|
|
99
|
+
primary = [report.primary_platform] if report.primary_platform else []
|
|
100
|
+
report.unplanned = _unplanned(planned, posts, report, primary)
|
|
101
|
+
report.duplicates = _duplicates(posts)
|
|
102
|
+
return report
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _unplanned(planned, posts, report: Report, platforms) -> list[PublishedPost]:
|
|
106
|
+
"""Posts inside the calendar's time span that no calendar row explains."""
|
|
107
|
+
if not planned:
|
|
108
|
+
return []
|
|
109
|
+
start = min(p.planned_date for p in planned) - timedelta(days=1)
|
|
110
|
+
end = max(p.planned_date for p in planned) + timedelta(days=LATEST_DAYS)
|
|
111
|
+
used = {(m.post.platform, m.post.post_id) for ms in report.matches.values() for m in ms}
|
|
112
|
+
return sorted(
|
|
113
|
+
(
|
|
114
|
+
p for p in posts
|
|
115
|
+
if p.platform in platforms and (p.platform, p.post_id) not in used
|
|
116
|
+
and p.has_text and start <= p.published_at.date() <= end
|
|
117
|
+
),
|
|
118
|
+
key=lambda p: p.published_at,
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _duplicates(posts: list[PublishedPost]) -> list[tuple[PublishedPost, PublishedPost]]:
|
|
123
|
+
"""Same text on the same platform within a few hours: probably posted twice."""
|
|
124
|
+
pairs = []
|
|
125
|
+
ordered = sorted(posts, key=lambda p: (p.platform, p.published_at))
|
|
126
|
+
for a, b in zip(ordered, ordered[1:]):
|
|
127
|
+
if (
|
|
128
|
+
a.platform == b.platform and a.has_time and b.has_time and a.has_text
|
|
129
|
+
and a.message[:80] == b.message[:80]
|
|
130
|
+
and b.published_at - a.published_at <= DUPLICATE_WINDOW
|
|
131
|
+
):
|
|
132
|
+
pairs.append((a, b))
|
|
133
|
+
return pairs
|
postloop/tabular.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Read tables from the files organizers actually have: CSV, .xlsx and .xls.
|
|
2
|
+
|
|
3
|
+
Platform exports are messier than they look. Meta's CSVs can be UTF-16 with an
|
|
4
|
+
Excel `sep=,` hint on the first line; LinkedIn's export is a legacy .xls with a
|
|
5
|
+
note above the header. This module hides all of that and returns plain rows.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import csv
|
|
11
|
+
import io
|
|
12
|
+
from collections.abc import Iterable, Sequence
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
Rows = list[list[Any]]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def normalize(name: object) -> str:
|
|
20
|
+
"""Compare headers without case, spaces or line breaks ("預計\\n發布日" == "預計發布日")."""
|
|
21
|
+
return "".join(str(name or "").split()).lower()
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def decode(raw: bytes) -> str:
|
|
25
|
+
if raw.startswith((b"\xff\xfe", b"\xfe\xff")):
|
|
26
|
+
return raw.decode("utf-16")
|
|
27
|
+
for encoding in ("utf-8-sig", "cp950", "latin-1"): # cp950: Big5 files saved by Excel in Taiwan
|
|
28
|
+
try:
|
|
29
|
+
return raw.decode(encoding)
|
|
30
|
+
except UnicodeDecodeError:
|
|
31
|
+
continue
|
|
32
|
+
raise ValueError("Could not decode file") # latin-1 never fails; kept for type checkers
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def read_csv(path: str | Path) -> Rows:
|
|
36
|
+
text = decode(Path(path).read_bytes())
|
|
37
|
+
lines = text.splitlines(keepends=True)
|
|
38
|
+
delimiter = ","
|
|
39
|
+
if lines and lines[0].strip().lower().startswith("sep="): # Excel hint, e.g. "sep=,"
|
|
40
|
+
delimiter = lines[0].strip()[4:] or ","
|
|
41
|
+
text = "".join(lines[1:])
|
|
42
|
+
return [row for row in csv.reader(io.StringIO(text), delimiter=delimiter)]
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def read_xlsx(path: str | Path) -> dict[str, Rows]:
|
|
46
|
+
try:
|
|
47
|
+
from openpyxl import load_workbook
|
|
48
|
+
except ImportError as e: # pragma: no cover
|
|
49
|
+
raise ImportError("Reading .xlsx needs openpyxl: pip install 'postloop[xlsx]'") from e
|
|
50
|
+
book = load_workbook(path, read_only=True, data_only=True)
|
|
51
|
+
return {sheet.title: [list(r) for r in sheet.iter_rows(values_only=True)] for sheet in book.worksheets}
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def read_xls(path: str | Path) -> dict[str, Rows]:
|
|
55
|
+
try:
|
|
56
|
+
import xlrd
|
|
57
|
+
except ImportError as e:
|
|
58
|
+
raise ImportError(
|
|
59
|
+
f"{Path(path).name} is a legacy .xls file. Install support with "
|
|
60
|
+
"pip install 'postloop[xls]', or open it and save it as .xlsx."
|
|
61
|
+
) from e
|
|
62
|
+
book = xlrd.open_workbook(path)
|
|
63
|
+
return {
|
|
64
|
+
sheet.name: [sheet.row_values(i) for i in range(sheet.nrows)]
|
|
65
|
+
for sheet in book.sheets()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def read_sheets(path: str | Path) -> dict[str, Rows]:
|
|
70
|
+
"""Every sheet in a file, as {sheet name: rows}. A CSV is one sheet named after the file."""
|
|
71
|
+
path = Path(path)
|
|
72
|
+
suffix = path.suffix.lower()
|
|
73
|
+
if suffix in (".xlsx", ".xlsm"):
|
|
74
|
+
return read_xlsx(path)
|
|
75
|
+
if suffix == ".xls":
|
|
76
|
+
return read_xls(path)
|
|
77
|
+
return {path.stem: read_csv(path)}
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def find_header(rows: Sequence[Sequence[Any]], required: Iterable[Iterable[str]], scan: int = 10) -> int | None:
|
|
81
|
+
"""Index of the first row that contains one alias of every required column.
|
|
82
|
+
|
|
83
|
+
Exports often put a title or a note above the real header, so the header
|
|
84
|
+
is found by content instead of assuming it is row 1.
|
|
85
|
+
"""
|
|
86
|
+
groups = [{normalize(a) for a in aliases} for aliases in required]
|
|
87
|
+
for i, row in enumerate(rows[:scan]):
|
|
88
|
+
cells = {normalize(c) for c in row}
|
|
89
|
+
if all(group & cells for group in groups):
|
|
90
|
+
return i
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def column_index(header: Sequence[Any], aliases: Iterable[str]) -> int | None:
|
|
95
|
+
"""Position of the first alias found in the header."""
|
|
96
|
+
cells = [normalize(c) for c in header]
|
|
97
|
+
for alias in aliases:
|
|
98
|
+
key = normalize(alias)
|
|
99
|
+
if key in cells:
|
|
100
|
+
return cells.index(key)
|
|
101
|
+
return None
|