questcast 4.1.2__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.
- questcast/__init__.py +37 -0
- questcast/author_profile.example.md +132 -0
- questcast/author_profile.py +128 -0
- questcast/cli.py +398 -0
- questcast/config.py +284 -0
- questcast/dedup.py +24 -0
- questcast/feeds.py +143 -0
- questcast/fields.py +81 -0
- questcast/net.py +75 -0
- questcast/progress.py +89 -0
- questcast/prompt.py +179 -0
- questcast/providers.py +576 -0
- questcast/search.py +170 -0
- questcast/storage.py +143 -0
- questcast-4.1.2.dist-info/METADATA +629 -0
- questcast-4.1.2.dist-info/RECORD +19 -0
- questcast-4.1.2.dist-info/WHEEL +4 -0
- questcast-4.1.2.dist-info/entry_points.txt +3 -0
- questcast-4.1.2.dist-info/licenses/LICENSE +21 -0
questcast/config.py
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
"""Configuration: constants, and every environment variable the tool reads.
|
|
2
|
+
|
|
3
|
+
Environment variables are read at call time, never at import, so tests can
|
|
4
|
+
set them per test and the env file can be loaded first.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import re
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
MODEL = "claude-sonnet-4-6"
|
|
13
|
+
|
|
14
|
+
CONSOLE_BILLING = "https://console.anthropic.com/settings/billing"
|
|
15
|
+
CONSOLE_KEYS = "https://console.anthropic.com/settings/keys"
|
|
16
|
+
|
|
17
|
+
PROVIDERS = ("anthropic", "groq", "openai-compat")
|
|
18
|
+
DEFAULT_PROVIDER = "groq"
|
|
19
|
+
|
|
20
|
+
GROQ_BASE_URL = "https://api.groq.com/openai/v1"
|
|
21
|
+
GROQ_DEFAULT_MODEL = "openai/gpt-oss-120b" # groq/compound was shut down 21 Sep 2026
|
|
22
|
+
GROQ_KEYS = "https://console.groq.com/keys"
|
|
23
|
+
|
|
24
|
+
# Server-side search can take a minute or more, so provider calls get a long
|
|
25
|
+
# timeout. Applies to groq and openai-compat; the anthropic SDK keeps its own.
|
|
26
|
+
DEFAULT_PROVIDER_TIMEOUT = 120.0 # seconds, override with QC_POST_PROVIDER_TIMEOUT
|
|
27
|
+
|
|
28
|
+
# R51: on a 429, wait the provider's suggested time plus a margin and retry
|
|
29
|
+
# once, if the suggestion is at most QC_POST_RATE_LIMIT_WAIT (0 turns it off).
|
|
30
|
+
DEFAULT_RATE_LIMIT_WAIT = 60 # seconds
|
|
31
|
+
RATE_LIMIT_MARGIN = 1.0 # seconds added to the provider's suggestion
|
|
32
|
+
|
|
33
|
+
HTTP_USER_AGENT = "QuestCast/4 (+https://github.com/BearingQuest/questcast)"
|
|
34
|
+
MAX_RESPONSE_BYTES = 2_000_000 # cap on any one provider response we read
|
|
35
|
+
MAX_FEED_BYTES = 10_000_000 # feeds get their own cap; some run past 2 MB (R23)
|
|
36
|
+
|
|
37
|
+
# Where the item comes from: the provider's own server-side search, or RSS
|
|
38
|
+
# feeds listed in the profile's '## Feeds' section.
|
|
39
|
+
SEARCH_SOURCES = ("native", "rss")
|
|
40
|
+
NATIVE_SEARCH_PROVIDERS = ("anthropic", "groq") # default to native; others to rss
|
|
41
|
+
FEED_TIMEOUT = 15.0 # seconds per feed request (R20)
|
|
42
|
+
DEFAULT_RSS_PER_FEED = 3 # newest entries per feed, override with QC_POST_RSS_PER_FEED
|
|
43
|
+
# Total candidates sent, best topic match first, override with
|
|
44
|
+
# QC_POST_RSS_MAX_ENTRIES. Keeps one call under Groq's free 8,000 TPM (R22).
|
|
45
|
+
DEFAULT_RSS_MAX_ENTRIES = 20
|
|
46
|
+
# R53: with --search rss, the lowest-ranked candidates are dropped until the
|
|
47
|
+
# whole prompt's estimated size is within QC_POST_TOKEN_BUDGET. 7,000 leaves
|
|
48
|
+
# 1,000 of Groq's free 8,000 tokens per minute for the chat template and for
|
|
49
|
+
# text that tokenizes denser than the estimate. The arithmetic is in
|
|
50
|
+
# docs/decisions.md.
|
|
51
|
+
DEFAULT_TOKEN_BUDGET = 7000
|
|
52
|
+
# UTF-8 bytes per token for the estimate. English prose runs nearer 4.2 with
|
|
53
|
+
# GPT-style tokenizers; on the 3 Nov rss request, bytes / 4 came to 8,811
|
|
54
|
+
# against Groq's reported 8,344.
|
|
55
|
+
BYTES_PER_TOKEN = 4
|
|
56
|
+
# The prompt lists only the newest used URLs and titles. Each history entry
|
|
57
|
+
# adds about 43 estimated tokens to every prompt, so at 60 an rss prompt
|
|
58
|
+
# would pass the budget on its own after about 24 more runs. Dedup is not
|
|
59
|
+
# weakened: is_used checks a pick against the whole history, and rss
|
|
60
|
+
# candidates are filtered against it before they are sent (R53).
|
|
61
|
+
PROMPT_USED_LIMIT = 20
|
|
62
|
+
|
|
63
|
+
MAX_TWEET_TEXT = 255 # 280 minus ~24 chars X reserves for a t.co link
|
|
64
|
+
MAX_LINKEDIN_TEXT = 1100 # hard ceiling; the prompt targets 750-950
|
|
65
|
+
|
|
66
|
+
# Shipped inside the package; qc init copies it to the data directory (R33).
|
|
67
|
+
EXAMPLE_PROFILE = "author_profile.example.md"
|
|
68
|
+
|
|
69
|
+
NOTHING_LOST = "Nothing was saved, so today's topic is still available when you re-run."
|
|
70
|
+
|
|
71
|
+
# The env file can't name its own location, so QC_POST_ENV_FILE comes only from
|
|
72
|
+
# the process environment. Everything else may be set in the file.
|
|
73
|
+
PROCESS_ONLY = ("QC_POST_ENV_FILE",)
|
|
74
|
+
|
|
75
|
+
# Settings renamed from AI_POST_<NAME> to QC_POST_<NAME>. The old names are
|
|
76
|
+
# never read; old_name_problems finds them so the run can stop.
|
|
77
|
+
NEW_PREFIX = "QC_POST_"
|
|
78
|
+
OLD_PREFIX = "AI_POST_"
|
|
79
|
+
SETTING_NAMES = (
|
|
80
|
+
"PROVIDER",
|
|
81
|
+
"SEARCH",
|
|
82
|
+
"PROVIDER_TIMEOUT",
|
|
83
|
+
"RATE_LIMIT_WAIT",
|
|
84
|
+
"RSS_PER_FEED",
|
|
85
|
+
"RSS_MAX_ENTRIES",
|
|
86
|
+
"TOKEN_BUDGET",
|
|
87
|
+
"DATA_DIR",
|
|
88
|
+
"ENV_FILE",
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
CONTROL_CHARS = re.compile(r"[\x00-\x1f\x7f-\x9f\u2028\u2029]+")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def setting(name: str) -> str | None:
|
|
95
|
+
"""QC_POST_<name> if set (even to an empty value), else None."""
|
|
96
|
+
return os.environ.get(NEW_PREFIX + name)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def shown(path: Path) -> str:
|
|
100
|
+
"""A path fit for one line of output: the home directory as ~, and no
|
|
101
|
+
control characters."""
|
|
102
|
+
text = str(path)
|
|
103
|
+
home = str(Path.home())
|
|
104
|
+
if text == home or text.startswith(home + os.sep):
|
|
105
|
+
text = "~" + text[len(home) :]
|
|
106
|
+
return CONTROL_CHARS.sub(" ", text)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
# ---------------------------------------------------------------------------
|
|
110
|
+
# Paths
|
|
111
|
+
# ---------------------------------------------------------------------------
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _override(name: str) -> Path | None:
|
|
115
|
+
value = setting(name)
|
|
116
|
+
return None if value is None else Path(value)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def env_file() -> Path:
|
|
120
|
+
"""QC_POST_ENV_FILE, else ~/.qc_post_env."""
|
|
121
|
+
override = _override("ENV_FILE")
|
|
122
|
+
return Path.home() / ".qc_post_env" if override is None else override
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def data_dir() -> Path:
|
|
126
|
+
"""QC_POST_DATA_DIR, else ~/QuestCast. Nothing is created, moved or deleted."""
|
|
127
|
+
override = _override("DATA_DIR")
|
|
128
|
+
return Path.home() / "QuestCast" if override is None else override
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def old_name_problems() -> list[str]:
|
|
132
|
+
"""One line per old name found: names and paths only, never values.
|
|
133
|
+
|
|
134
|
+
Old names are never read, so a run that finds one stops (cli.refuse_old_names)
|
|
135
|
+
rather than carry on without a key, a provider choice or the history. Call it
|
|
136
|
+
after the env file is loaded, so AI_POST_* lines in the file are seen too.
|
|
137
|
+
Only exists() is called on the old paths: they are never opened, moved or
|
|
138
|
+
deleted. When the new path exists too, the old one is ignored quietly.
|
|
139
|
+
"""
|
|
140
|
+
problems = []
|
|
141
|
+
for name in SETTING_NAMES:
|
|
142
|
+
if OLD_PREFIX + name in os.environ:
|
|
143
|
+
problems.append(
|
|
144
|
+
f"{OLD_PREFIX}{name} is no longer read; rename it to {NEW_PREFIX}{name}"
|
|
145
|
+
)
|
|
146
|
+
for name, old, new, verb in (
|
|
147
|
+
("DATA_DIR", "XPosts", "QuestCast", "move"),
|
|
148
|
+
("ENV_FILE", ".ai_post_env", ".qc_post_env", "rename"),
|
|
149
|
+
):
|
|
150
|
+
if setting(name) is not None:
|
|
151
|
+
continue # a variable chose the path, so the default files don't matter
|
|
152
|
+
old_path, new_path = Path.home() / old, Path.home() / new
|
|
153
|
+
if old_path.exists() and not new_path.exists():
|
|
154
|
+
problems.append(
|
|
155
|
+
f"{shown(old_path)} is no longer read; {verb} it with: "
|
|
156
|
+
f"mv {shown(old_path)} {shown(new_path)} (or set {NEW_PREFIX}{name})"
|
|
157
|
+
)
|
|
158
|
+
return problems
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def profile_file() -> Path:
|
|
162
|
+
return data_dir() / "author_profile.md" # your voice — never in the repo
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def history_file() -> Path:
|
|
166
|
+
return data_dir() / "history.json" # URLs already used (dedup)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def drafts_file() -> Path:
|
|
170
|
+
return data_dir() / "drafts.md" # running log of drafts
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def log_file() -> Path:
|
|
174
|
+
return data_dir() / "run.log" # one line per run
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def load_env_file(path: Path | None = None) -> None:
|
|
178
|
+
"""Load KEY=value lines (with or without a leading 'export ') into
|
|
179
|
+
os.environ. Variables already set in the environment win. The env file's
|
|
180
|
+
path is read at call time, so tests can point it at a throwaway file."""
|
|
181
|
+
path = env_file() if path is None else path
|
|
182
|
+
if not path.exists():
|
|
183
|
+
return
|
|
184
|
+
for line in path.read_text().splitlines():
|
|
185
|
+
line = line.strip()
|
|
186
|
+
if not line or line.startswith("#"):
|
|
187
|
+
continue
|
|
188
|
+
if line.startswith("export "):
|
|
189
|
+
line = line[len("export ") :]
|
|
190
|
+
key, sep, value = line.partition("=")
|
|
191
|
+
key = key.strip()
|
|
192
|
+
if sep and key and key not in os.environ and key not in PROCESS_ONLY:
|
|
193
|
+
os.environ[key] = value.strip().strip("'\"")
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
# ---------------------------------------------------------------------------
|
|
197
|
+
# Provider and search selection
|
|
198
|
+
# ---------------------------------------------------------------------------
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def provider_setting() -> str:
|
|
202
|
+
return setting("PROVIDER") or ""
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def search_setting() -> str:
|
|
206
|
+
return setting("SEARCH") or ""
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def provider_timeout() -> float:
|
|
210
|
+
"""Seconds to wait for a groq or openai-compat response (R20)."""
|
|
211
|
+
raw = (setting("PROVIDER_TIMEOUT") or "").strip()
|
|
212
|
+
if not raw:
|
|
213
|
+
return DEFAULT_PROVIDER_TIMEOUT
|
|
214
|
+
try:
|
|
215
|
+
value = float(raw)
|
|
216
|
+
except ValueError:
|
|
217
|
+
value = -1.0
|
|
218
|
+
if not math.isfinite(value) or value <= 0:
|
|
219
|
+
raise SystemExit(
|
|
220
|
+
f"\nQC_POST_PROVIDER_TIMEOUT must be a positive number of seconds; got {raw!r}.\n"
|
|
221
|
+
f" Remove it to use the default of {DEFAULT_PROVIDER_TIMEOUT:g} seconds.\n"
|
|
222
|
+
)
|
|
223
|
+
return value
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def rate_limit_wait() -> int:
|
|
227
|
+
"""Longest suggested wait, in seconds, that a 429 is retried after (R51)."""
|
|
228
|
+
raw = (setting("RATE_LIMIT_WAIT") or "").strip()
|
|
229
|
+
if not raw:
|
|
230
|
+
return DEFAULT_RATE_LIMIT_WAIT
|
|
231
|
+
if not (raw.isascii() and raw.isdigit()):
|
|
232
|
+
raise SystemExit(
|
|
233
|
+
"\nQC_POST_RATE_LIMIT_WAIT must be a whole number of seconds, 0 or more\n"
|
|
234
|
+
f" (0 turns the retry off); got {raw!r}.\n"
|
|
235
|
+
)
|
|
236
|
+
return int(raw)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def env_whole_number(name: str, default: int) -> int:
|
|
240
|
+
var = NEW_PREFIX + name
|
|
241
|
+
raw = (setting(name) or "").strip()
|
|
242
|
+
if not raw:
|
|
243
|
+
return default
|
|
244
|
+
if not raw.isdigit() or int(raw) < 1:
|
|
245
|
+
raise SystemExit(f"\n{var} must be a whole number of 1 or more; got {raw!r}.\n")
|
|
246
|
+
return int(raw)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def rss_per_feed() -> int:
|
|
250
|
+
return env_whole_number("RSS_PER_FEED", DEFAULT_RSS_PER_FEED)
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def rss_max_entries() -> int:
|
|
254
|
+
return env_whole_number("RSS_MAX_ENTRIES", DEFAULT_RSS_MAX_ENTRIES)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def token_budget() -> int:
|
|
258
|
+
return env_whole_number("TOKEN_BUDGET", DEFAULT_TOKEN_BUDGET)
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
# ---------------------------------------------------------------------------
|
|
262
|
+
# Provider settings and credentials
|
|
263
|
+
# ---------------------------------------------------------------------------
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def anthropic_api_key() -> str | None:
|
|
267
|
+
return os.environ.get("ANTHROPIC_API_KEY")
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def groq_model() -> str:
|
|
271
|
+
return os.environ.get("GROQ_MODEL", "").strip()
|
|
272
|
+
|
|
273
|
+
|
|
274
|
+
def openai_compat_base_url() -> str:
|
|
275
|
+
return os.environ.get("OPENAI_COMPAT_BASE_URL", "").strip().rstrip("/")
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def openai_compat_model() -> str:
|
|
279
|
+
return os.environ.get("OPENAI_COMPAT_MODEL", "").strip()
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def api_key(var: str) -> str:
|
|
283
|
+
"""GROQ_API_KEY or OPENAI_COMPAT_API_KEY, whichever the provider names."""
|
|
284
|
+
return os.environ.get(var, "").strip()
|
questcast/dedup.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""What has already been used, by URL or by title (R17). No I/O."""
|
|
2
|
+
|
|
3
|
+
from typing import Any
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def normalize_title(title: str | None) -> str:
|
|
7
|
+
"""Case-folded, whitespace collapsed (R17)."""
|
|
8
|
+
return " ".join((title or "").casefold().split())
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def used_from(history: list[dict[str, Any]]) -> tuple[list[str], list[str]]:
|
|
12
|
+
"""(used URLs, used titles) from history.json entries, oldest first."""
|
|
13
|
+
return (
|
|
14
|
+
[h["url"] for h in history if h.get("url")],
|
|
15
|
+
[h["title"] for h in history if h.get("title")],
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def is_used(url: str, title: str | None, used_urls: list[str], used_titles: list[str]) -> bool:
|
|
20
|
+
"""True if the URL, or the normalized title, has been used before (R17)."""
|
|
21
|
+
if url in used_urls:
|
|
22
|
+
return True
|
|
23
|
+
title = normalize_title(title)
|
|
24
|
+
return bool(title) and title in {normalize_title(t) for t in used_titles}
|
questcast/feeds.py
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"""Feed parsing, cleaning and ranking for --search rss. No I/O."""
|
|
2
|
+
|
|
3
|
+
import html
|
|
4
|
+
import pyexpat
|
|
5
|
+
import re
|
|
6
|
+
import xml.etree.ElementTree as ET
|
|
7
|
+
from datetime import UTC, datetime
|
|
8
|
+
from email.utils import parsedate_to_datetime
|
|
9
|
+
from typing import NotRequired, TypedDict
|
|
10
|
+
|
|
11
|
+
STOP_WORDS = frozenset(
|
|
12
|
+
{"and", "the", "for", "with", "from", "into", "about", "that", "this", "are", "its", "how"}
|
|
13
|
+
)
|
|
14
|
+
RSS_SUMMARY_CHARS = 300
|
|
15
|
+
# Expat below 2.7.2 may be open to billion-laughs, quadratic-blowup and
|
|
16
|
+
# large-token attacks (https://docs.python.org/3/library/xml.html#xml-security).
|
|
17
|
+
MIN_EXPAT = (2, 7, 2)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class FeedEntry(TypedDict):
|
|
21
|
+
"""One feed entry. A plain dict at runtime; the type is for mypy only."""
|
|
22
|
+
|
|
23
|
+
title: str | None
|
|
24
|
+
link: str
|
|
25
|
+
date: datetime | None
|
|
26
|
+
summary: str | None
|
|
27
|
+
feed: NotRequired[str] # the feed's host name, added by RssSearch
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def require_expat() -> None:
|
|
31
|
+
"""Refuse to parse untrusted XML with an Expat that lacks entity-expansion
|
|
32
|
+
protection (R21)."""
|
|
33
|
+
if pyexpat.version_info < MIN_EXPAT:
|
|
34
|
+
need = ".".join(map(str, MIN_EXPAT))
|
|
35
|
+
have = ".".join(map(str, pyexpat.version_info))
|
|
36
|
+
raise SystemExit(
|
|
37
|
+
f"\n--search rss needs Expat {need} or newer, which protects against\n"
|
|
38
|
+
f" entity-expansion attacks in feed XML. This Python has Expat {have}\n"
|
|
39
|
+
f" ({pyexpat.EXPAT_VERSION}). Use a newer Python, or --search native.\n"
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def clean_text(text: str | None, limit: int = RSS_SUMMARY_CHARS) -> str:
|
|
44
|
+
"""Feed text as plain prose: no markup, no delimiters, bounded length."""
|
|
45
|
+
text = html.unescape(text or "")
|
|
46
|
+
text = re.sub(r"<[^>]*>", " ", text)
|
|
47
|
+
text = text.replace("<", " ").replace(">", " ").replace("===", "=")
|
|
48
|
+
text = re.sub(r"\s+", " ", text).strip()
|
|
49
|
+
return text if len(text) <= limit else text[:limit].rstrip() + "…"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def parse_date(text: str | None) -> datetime | None:
|
|
53
|
+
if not text:
|
|
54
|
+
return None
|
|
55
|
+
text = text.strip()
|
|
56
|
+
try:
|
|
57
|
+
parsed = parsedate_to_datetime(text) # RSS: RFC 822
|
|
58
|
+
except (TypeError, ValueError):
|
|
59
|
+
try:
|
|
60
|
+
parsed = datetime.fromisoformat(text) # Atom: RFC 3339
|
|
61
|
+
except ValueError:
|
|
62
|
+
return None
|
|
63
|
+
return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
ATOM = "{http://www.w3.org/2005/Atom}"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def parse_feed(data: bytes) -> list[FeedEntry]:
|
|
70
|
+
"""Entries from RSS 2.0 or Atom XML: dicts of title, link, date, summary.
|
|
71
|
+
|
|
72
|
+
The caller has already checked the Expat version (require_expat).
|
|
73
|
+
"""
|
|
74
|
+
root = ET.fromstring(data) # noqa: S314 - Expat >= 2.7.2 enforced by require_expat
|
|
75
|
+
entries: list[FeedEntry] = []
|
|
76
|
+
if root.tag == "rss":
|
|
77
|
+
for item in root.iterfind("./channel/item"):
|
|
78
|
+
entries.append(
|
|
79
|
+
{
|
|
80
|
+
"title": item.findtext("title"),
|
|
81
|
+
"link": (item.findtext("link") or "").strip(),
|
|
82
|
+
"date": parse_date(item.findtext("pubDate")),
|
|
83
|
+
"summary": item.findtext("description"),
|
|
84
|
+
}
|
|
85
|
+
)
|
|
86
|
+
elif root.tag == f"{ATOM}feed":
|
|
87
|
+
for entry in root.iterfind(f"{ATOM}entry"):
|
|
88
|
+
link = ""
|
|
89
|
+
for el in entry.iterfind(f"{ATOM}link"):
|
|
90
|
+
if el.get("rel", "alternate") == "alternate":
|
|
91
|
+
link = (el.get("href") or "").strip()
|
|
92
|
+
break
|
|
93
|
+
entries.append(
|
|
94
|
+
{
|
|
95
|
+
"title": entry.findtext(f"{ATOM}title"),
|
|
96
|
+
"link": link,
|
|
97
|
+
"date": parse_date(
|
|
98
|
+
entry.findtext(f"{ATOM}published") or entry.findtext(f"{ATOM}updated")
|
|
99
|
+
),
|
|
100
|
+
"summary": entry.findtext(f"{ATOM}summary") or entry.findtext(f"{ATOM}content"),
|
|
101
|
+
}
|
|
102
|
+
)
|
|
103
|
+
else:
|
|
104
|
+
raise ValueError(f"not an RSS 2.0 or Atom feed (root element {root.tag!r})")
|
|
105
|
+
return [e for e in entries if e["link"] and clean_text(e["title"])]
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def newest(entries: list[FeedEntry], limit: int) -> list[FeedEntry]:
|
|
109
|
+
"""Newest first; undated entries keep feed order after dated ones (R19)."""
|
|
110
|
+
floor = datetime.min.replace(tzinfo=UTC)
|
|
111
|
+
return sorted(entries, key=lambda e: e["date"] or floor, reverse=True)[:limit]
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def words(text: str) -> set[str]:
|
|
115
|
+
"""Lower-cased words of 3+ characters, stop words removed (R22)."""
|
|
116
|
+
return {w for w in re.findall(r"[a-z0-9]+", text.lower()) if len(w) >= 3} - STOP_WORDS
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def ranked(entries: list[FeedEntry], topic: str, limit: int) -> list[FeedEntry]:
|
|
120
|
+
"""Most topic words in title or summary first, then newest first; undated
|
|
121
|
+
entries go last within a score, in feed order (R22)."""
|
|
122
|
+
wanted = words(topic)
|
|
123
|
+
floor = datetime.min.replace(tzinfo=UTC)
|
|
124
|
+
|
|
125
|
+
def key(e: FeedEntry) -> tuple[int, datetime]:
|
|
126
|
+
found = words(f"{clean_text(e['title'])} {clean_text(e['summary'])}")
|
|
127
|
+
return len(wanted & found), e["date"] or floor
|
|
128
|
+
|
|
129
|
+
return sorted(entries, key=key, reverse=True)[:limit]
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def format_candidates(entries: list[FeedEntry]) -> str:
|
|
133
|
+
blocks = []
|
|
134
|
+
for n, e in enumerate(entries, 1):
|
|
135
|
+
when = e["date"].date().isoformat() if e["date"] else "unknown"
|
|
136
|
+
blocks.append(
|
|
137
|
+
f"[{n}] Title: {clean_text(e['title'], 200)}\n"
|
|
138
|
+
f" Link: {clean_text(e['link'], 500)}\n"
|
|
139
|
+
f" Date: {when}\n"
|
|
140
|
+
f" Feed: {e['feed']}\n"
|
|
141
|
+
f" Summary: {clean_text(e['summary'])}"
|
|
142
|
+
)
|
|
143
|
+
return "\n".join(blocks)
|
questcast/fields.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""The model's delimited response, and the posts made from it. No I/O."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from urllib.parse import quote
|
|
5
|
+
|
|
6
|
+
FIELD_PATTERN = re.compile(r"^===([A-Z]+)===\s*$", re.MULTILINE)
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def parse_fields(text: str) -> dict[str, str]:
|
|
10
|
+
"""Parse the delimited model response into a dict.
|
|
11
|
+
|
|
12
|
+
Delimiters rather than JSON: post text routinely contains quotes,
|
|
13
|
+
apostrophes, and line breaks, all of which need escaping inside a JSON
|
|
14
|
+
string and break the parse whenever the model gets that wrong.
|
|
15
|
+
"""
|
|
16
|
+
parts = FIELD_PATTERN.split(text)
|
|
17
|
+
if len(parts) < 3:
|
|
18
|
+
raise ValueError(f"Model output was not in the expected format:\n{text[:500]}")
|
|
19
|
+
fields = {}
|
|
20
|
+
for name, body in zip(parts[1::2], parts[2::2], strict=False):
|
|
21
|
+
if name != "END":
|
|
22
|
+
fields[name.lower()] = body.strip()
|
|
23
|
+
return fields
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def trim(text: str, limit: int) -> str:
|
|
27
|
+
"""Trim at a sentence boundary where possible so drafts never end
|
|
28
|
+
mid-word."""
|
|
29
|
+
text = text.strip()
|
|
30
|
+
if len(text) <= limit:
|
|
31
|
+
return text
|
|
32
|
+
cut = text[:limit]
|
|
33
|
+
for boundary in (". ", ".\n", "! ", "? "):
|
|
34
|
+
idx = cut.rfind(boundary)
|
|
35
|
+
if idx > limit * 0.6:
|
|
36
|
+
return cut[: idx + 1].strip()
|
|
37
|
+
return cut[: cut.rfind(" ")].strip() + "…"
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
URL_PATTERN = re.compile(r"(https?://\S+)")
|
|
41
|
+
# Paired emphasis markers: text just inside both markers, none just outside
|
|
42
|
+
# (so "2*3*4", "a**b**c" and "snake__case__name" stay as they are).
|
|
43
|
+
EMPHASIS_PATTERNS = (
|
|
44
|
+
re.compile(r"(?<![\w*])\*\*(?=[^\s*])([^\n]*?[^\s*])\*\*(?![\w*])"),
|
|
45
|
+
re.compile(r"(?<!\w)__(?=[^\s_])([^\n]*?[^\s_])__(?!\w)"),
|
|
46
|
+
re.compile(r"(?<![\w*])\*(?=[^\s*])([^*\n]*[^\s*])\*(?![\w*])"),
|
|
47
|
+
)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def strip_emphasis(text: str) -> str:
|
|
51
|
+
"""Remove paired Markdown emphasis (**text**, __text__, *text*), which X and
|
|
52
|
+
LinkedIn show literally. URLs, a lone "*", bullets and hashtags are left alone."""
|
|
53
|
+
parts = URL_PATTERN.split(text)
|
|
54
|
+
for i in range(0, len(parts), 2): # odd parts are the URLs
|
|
55
|
+
for pattern in EMPHASIS_PATTERNS:
|
|
56
|
+
parts[i] = pattern.sub(r"\1", parts[i])
|
|
57
|
+
return "".join(parts)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def compose_posts(item: dict[str, str]) -> tuple[str, str]:
|
|
61
|
+
return f"{item['tweet']}\n{item['url']}", f"{item['linkedin']}\n\n{item['url']}"
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def x_compose_link(draft: str) -> str:
|
|
65
|
+
"""X's web intent link: opens the compose box with the draft filled in.
|
|
66
|
+
|
|
67
|
+
Everything outside the unreserved set is percent-encoded (safe=""), so the
|
|
68
|
+
link holds only URL-safe characters whatever the draft contains.
|
|
69
|
+
"""
|
|
70
|
+
return f"https://x.com/intent/tweet?text={quote(draft, safe='')}"
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def linkedin_compose_link(draft: str) -> str:
|
|
74
|
+
"""LinkedIn's post-box link: opens the post box with the draft filled in.
|
|
75
|
+
|
|
76
|
+
The link is undocumented (LinkedIn's documented share plugin takes a URL
|
|
77
|
+
only), so LinkedIn could change it. Everything outside the unreserved set
|
|
78
|
+
is percent-encoded (safe=""), so the link holds only URL-safe characters
|
|
79
|
+
whatever the draft contains.
|
|
80
|
+
"""
|
|
81
|
+
return f"https://www.linkedin.com/feed/?shareActive=true&text={quote(draft, safe='')}"
|
questcast/net.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""HTTP plumbing shared by the providers, the feed reader and LinkedIn."""
|
|
2
|
+
|
|
3
|
+
import urllib.error
|
|
4
|
+
import urllib.parse
|
|
5
|
+
import urllib.request
|
|
6
|
+
|
|
7
|
+
from questcast.config import MAX_RESPONSE_BYTES
|
|
8
|
+
|
|
9
|
+
DEFAULT_PORTS = {"http": 80, "https": 443}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class InsecureRedirectError(urllib.error.URLError):
|
|
13
|
+
"""An HTTPS request was redirected to a non-HTTPS URL."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def origin(url: str) -> tuple[str, str, int | None] | None:
|
|
17
|
+
"""Scheme, lower-cased host and port, with default ports filled in.
|
|
18
|
+
|
|
19
|
+
None if the port can't be parsed; same_origin treats that as another origin.
|
|
20
|
+
"""
|
|
21
|
+
parts = urllib.parse.urlsplit(url)
|
|
22
|
+
scheme = parts.scheme.lower()
|
|
23
|
+
try:
|
|
24
|
+
port = parts.port or DEFAULT_PORTS.get(scheme)
|
|
25
|
+
except ValueError:
|
|
26
|
+
return None
|
|
27
|
+
return scheme, parts.hostname or "", port
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def same_origin(a: str, b: str) -> bool:
|
|
31
|
+
origin_a = origin(a)
|
|
32
|
+
return origin_a is not None and origin_a == origin(b)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class NoDowngradeRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
36
|
+
"""Follow redirects, except from HTTPS to anything that is not HTTPS (R18).
|
|
37
|
+
|
|
38
|
+
A downgraded feed can be altered in transit. urllib copies every request
|
|
39
|
+
header except Content-Length and Content-Type to the redirect target,
|
|
40
|
+
whatever its host, so credentials are removed when the origin changes
|
|
41
|
+
(R55), as the requests library does.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
45
|
+
if req.full_url.lower().startswith("https://") and not newurl.lower().startswith(
|
|
46
|
+
"https://"
|
|
47
|
+
):
|
|
48
|
+
raise InsecureRedirectError(f"refused redirect from HTTPS to {newurl}")
|
|
49
|
+
new = super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
50
|
+
if new is not None and not same_origin(req.full_url, newurl):
|
|
51
|
+
# Request.add_header stores names capitalize()d, in new.headers.
|
|
52
|
+
# ProxyHandler re-adds Proxy-authorization when the target is
|
|
53
|
+
# proxied, so this only drops it for a target that bypasses the proxy.
|
|
54
|
+
new.remove_header("Authorization")
|
|
55
|
+
new.remove_header("Proxy-authorization")
|
|
56
|
+
return new
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
HTTP_OPENER = urllib.request.build_opener(NoDowngradeRedirectHandler)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def read_capped(response, limit: int = MAX_RESPONSE_BYTES) -> bytes:
|
|
63
|
+
"""Read at most `limit` bytes; anything larger is refused, not truncated."""
|
|
64
|
+
body = response.read(limit + 1)
|
|
65
|
+
if len(body) > limit:
|
|
66
|
+
raise ValueError(f"response is larger than {limit:,} bytes")
|
|
67
|
+
return body
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def redact(text: str, *secrets: str) -> str:
|
|
71
|
+
"""Remove secret values from text that is about to be shown or logged."""
|
|
72
|
+
for secret in secrets:
|
|
73
|
+
if secret and len(secret) >= 8:
|
|
74
|
+
text = text.replace(secret, "[redacted]")
|
|
75
|
+
return text
|