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/__init__.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""
|
|
2
|
+
QuestCast
|
|
3
|
+
|
|
4
|
+
Picks a technology topic, finds one noteworthy recent item on it, and drafts
|
|
5
|
+
two posts from that same source:
|
|
6
|
+
|
|
7
|
+
* X/Twitter — short, link-forward, hashtagged.
|
|
8
|
+
* LinkedIn — longer, first-person point of view on why the item matters.
|
|
9
|
+
|
|
10
|
+
The topic is chosen at run time: pass --topic, or answer the numbered menu.
|
|
11
|
+
The menu comes from the '## Topics' section of your author profile if you
|
|
12
|
+
have one, otherwise from TOPIC_CATALOG below.
|
|
13
|
+
|
|
14
|
+
What makes the posts sound like YOU is an author profile file kept outside
|
|
15
|
+
this repo (default: ~/QuestCast/author_profile.md). `qc init` copies the
|
|
16
|
+
scaffold, author_profile.example.md in this package, there to fill in.
|
|
17
|
+
|
|
18
|
+
Default behavior is draft-only: both posts are printed and appended to
|
|
19
|
+
drafts.md for you to review and post yourself. Each run also prints a link that
|
|
20
|
+
opens X's compose box with the X draft filled in; --post opens it for you, and
|
|
21
|
+
nothing is posted until you click Post. --post-linkedin can publish to LinkedIn.
|
|
22
|
+
|
|
23
|
+
The model comes from one of three providers (--provider, default groq):
|
|
24
|
+
|
|
25
|
+
* groq — free tier; the standard library is enough.
|
|
26
|
+
* openai-compat — any OpenAI-compatible endpoint (Gemini, Cerebras, Ollama).
|
|
27
|
+
* anthropic — paid; needs the anthropic package.
|
|
28
|
+
|
|
29
|
+
Requirements:
|
|
30
|
+
Python standard library only for groq and openai-compat.
|
|
31
|
+
The 'anthropic' extra (only for --provider anthropic)
|
|
32
|
+
Installed qc, from the clone: uv tool install --reinstall '.[anthropic]'
|
|
33
|
+
The clone's venv: ~/.qc_post_venv/bin/pip install -e '.[anthropic]'
|
|
34
|
+
The pinned version is in pyproject.toml.
|
|
35
|
+
|
|
36
|
+
Credentials are read from ~/.qc_post_env — see README.md.
|
|
37
|
+
"""
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
# Author Profile — scaffold
|
|
2
|
+
|
|
3
|
+
Copy this file to your data directory (default `~/QuestCast/author_profile.md`)
|
|
4
|
+
and rewrite it in your own words. It never belongs in the repo: it is your
|
|
5
|
+
voice, and for most people it contains details they would not publish as a
|
|
6
|
+
config file.
|
|
7
|
+
|
|
8
|
+
The script parses `##` headings. **Beat** and **Voice** are required; the rest
|
|
9
|
+
are optional but each one measurably improves the output. Headings the script
|
|
10
|
+
does not recognize are ignored, so you can keep notes to yourself in here.
|
|
11
|
+
|
|
12
|
+
Write in plain prose and short bullets. You are briefing a sharp new
|
|
13
|
+
ghostwriter who has never met you — not filling in a form.
|
|
14
|
+
|
|
15
|
+
Delete everything above this line once you have read it.
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Topics
|
|
20
|
+
|
|
21
|
+
*The menu you pick from at run time. Optional — omit this section and the
|
|
22
|
+
script falls back to its built-in catalog of common IT areas.*
|
|
23
|
+
|
|
24
|
+
One topic per line. Bullets and numbering are stripped, so any of these work.
|
|
25
|
+
Make them specific enough to steer a web search: "Kubernetes and container
|
|
26
|
+
platforms" searches better than "infrastructure".
|
|
27
|
+
|
|
28
|
+
- (topic)
|
|
29
|
+
- (topic)
|
|
30
|
+
- (topic)
|
|
31
|
+
|
|
32
|
+
## Beat
|
|
33
|
+
|
|
34
|
+
*Not the subject — the subject is chosen per run from Topics above. This is
|
|
35
|
+
what makes an item worth posting about, whatever the topic is.*
|
|
36
|
+
|
|
37
|
+
- Good finds look like:
|
|
38
|
+
- Exclude:
|
|
39
|
+
- Audience:
|
|
40
|
+
- Recency: prefer items from roughly the last 7 days
|
|
41
|
+
- The lens you read everything through:
|
|
42
|
+
|
|
43
|
+
## Voice
|
|
44
|
+
|
|
45
|
+
*How do you think, and what do you sound like?*
|
|
46
|
+
|
|
47
|
+
The single highest-leverage section. Positions and priors matter more than
|
|
48
|
+
adjectives — "believes X" gives the model something to argue from, "smart and
|
|
49
|
+
approachable" does not.
|
|
50
|
+
|
|
51
|
+
What I believe about this space:
|
|
52
|
+
|
|
53
|
+
- (2-4 real positions, including anything where you disagree with the
|
|
54
|
+
mainstream)
|
|
55
|
+
|
|
56
|
+
What I care about enough to argue in public:
|
|
57
|
+
|
|
58
|
+
- (the things that actually get you going — this is the passion layer, and its
|
|
59
|
+
absence is what makes generated posts feel like nobody wrote them)
|
|
60
|
+
|
|
61
|
+
How I actually write:
|
|
62
|
+
|
|
63
|
+
- (cadence, sentence length, habits, words to avoid)
|
|
64
|
+
|
|
65
|
+
Sentences I have actually written, for cadence — do not reuse them verbatim:
|
|
66
|
+
|
|
67
|
+
- (paste 4-6 real sentences of your own from emails, docs, posts, anything)
|
|
68
|
+
|
|
69
|
+
This last list is worth more than everything above it. A description of your
|
|
70
|
+
tone produces competent generic prose; actual samples give the model something
|
|
71
|
+
to imitate. Strip anything from them you would not want repeated — employer
|
|
72
|
+
names, figures you keep private.
|
|
73
|
+
|
|
74
|
+
## Experience
|
|
75
|
+
|
|
76
|
+
*What can it legitimately claim you have done?*
|
|
77
|
+
|
|
78
|
+
This is what separates your post from a summary anyone could write. It is also
|
|
79
|
+
the riskiest section: a model asked to sound like an expert will invent
|
|
80
|
+
credentials unless you fence it in. List only things you have actually done,
|
|
81
|
+
phrased the way you would be willing to see them in public, then keep the
|
|
82
|
+
guardrail below.
|
|
83
|
+
|
|
84
|
+
- (achievement, with a real number if you have one)
|
|
85
|
+
- (achievement)
|
|
86
|
+
- (achievement)
|
|
87
|
+
|
|
88
|
+
Guardrail — keep this, it does real work:
|
|
89
|
+
|
|
90
|
+
- BEFORE writing, check this list for a genuine connection to the item. If one
|
|
91
|
+
exists, use it. If nothing genuinely connects, write the post without one.
|
|
92
|
+
Do not force it.
|
|
93
|
+
- Use AT MOST ONE per post, worked in as evidence for a claim, not as a
|
|
94
|
+
credential.
|
|
95
|
+
- NEVER invent experience, metrics, employers, clients, tools, or anecdotes
|
|
96
|
+
beyond this list.
|
|
97
|
+
|
|
98
|
+
## Never
|
|
99
|
+
|
|
100
|
+
*Hard rules. What would embarrass you or misrepresent you?*
|
|
101
|
+
|
|
102
|
+
Anything here is worth being explicit about, because the model will otherwise
|
|
103
|
+
guess. Common entries:
|
|
104
|
+
|
|
105
|
+
- Never name my employer or clients.
|
|
106
|
+
- Never state or imply years of experience, career length, or "back when".
|
|
107
|
+
- Never claim hands-on depth with tools I have not used — opinions are fine,
|
|
108
|
+
implied operational history is not.
|
|
109
|
+
- Never inflate my title, level, or scope.
|
|
110
|
+
- If today's topic is one where my depth is thin, write from principle rather
|
|
111
|
+
than manufacturing a war story to fill the gap.
|
|
112
|
+
- Never disparage a named company; critique the pattern instead.
|
|
113
|
+
|
|
114
|
+
## Hashtags
|
|
115
|
+
|
|
116
|
+
*A pool to draw from, not a fixed set. Cover every topic you listed.*
|
|
117
|
+
|
|
118
|
+
#YourTag #YourTag #YourTag
|
|
119
|
+
|
|
120
|
+
## Feeds
|
|
121
|
+
|
|
122
|
+
*Optional, and used only with `--search rss`: the RSS or Atom feeds to pick
|
|
123
|
+
today's item from, instead of a web search.*
|
|
124
|
+
|
|
125
|
+
One feed URL per line; bullets are stripped. Only `https://` feeds are read,
|
|
126
|
+
and a feed that redirects to plain `http://` is skipped. The newest 3 entries
|
|
127
|
+
of each feed are offered (set `QC_POST_RSS_PER_FEED` to change that), so
|
|
128
|
+
high-volume feeds don't crowd out the rest. Prefer original vendor and project
|
|
129
|
+
blogs over aggregators.
|
|
130
|
+
|
|
131
|
+
- https://blog.example.com/feed.xml
|
|
132
|
+
- https://news.example.org/atom.xml
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""The author profile: its sections, and the topic menu it defines. No I/O."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
# Fallback topic menu. Override it with a '## Topics' section in your profile —
|
|
7
|
+
# one topic per line, optionally "Label — extra scoping detail".
|
|
8
|
+
TOPIC_CATALOG = [
|
|
9
|
+
"AI and machine learning in the enterprise",
|
|
10
|
+
"Cybersecurity and threat defense",
|
|
11
|
+
"Cloud infrastructure and architecture",
|
|
12
|
+
"Platform engineering and developer experience",
|
|
13
|
+
"Site reliability, observability, and incident response",
|
|
14
|
+
"DevOps, CI/CD, and release engineering",
|
|
15
|
+
"Kubernetes and container platforms",
|
|
16
|
+
"Identity and access management",
|
|
17
|
+
"Data engineering and analytics platforms",
|
|
18
|
+
"FinOps and cloud cost management",
|
|
19
|
+
"Governance, risk, and compliance automation",
|
|
20
|
+
"Agentic AI and workflow automation",
|
|
21
|
+
"Networking, edge, and content delivery",
|
|
22
|
+
"Engineering leadership and team practices",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
# Profile sections. "required" ones must be present and non-empty.
|
|
26
|
+
PROFILE_SECTIONS = {
|
|
27
|
+
"beat": True, # audience, exclusions, what counts as a good find
|
|
28
|
+
"voice": True, # how the author thinks and sounds
|
|
29
|
+
"topics": False, # menu of technology areas to choose from
|
|
30
|
+
"experience": False, # verified things the author may reference
|
|
31
|
+
"never": False, # hard rules
|
|
32
|
+
"hashtags": False, # preferred tag pool
|
|
33
|
+
"feeds": False, # RSS/Atom feed URLs, used only with --search rss
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def parse_profile(text: str, path: Path) -> dict[str, str]:
|
|
38
|
+
"""Parse the author profile into {section_name: body}.
|
|
39
|
+
|
|
40
|
+
Sections are '## Heading' blocks. Heading names are matched
|
|
41
|
+
case-insensitively against PROFILE_SECTIONS; unknown sections are ignored,
|
|
42
|
+
so you can keep notes to yourself in the file. `path` is only named in
|
|
43
|
+
the error message.
|
|
44
|
+
"""
|
|
45
|
+
sections: dict[str, list[str]] = {}
|
|
46
|
+
current: str | None = None
|
|
47
|
+
for line in text.splitlines():
|
|
48
|
+
heading = re.match(r"^##\s+(.+?)\s*$", line)
|
|
49
|
+
if heading:
|
|
50
|
+
current = heading.group(1).strip().lower()
|
|
51
|
+
sections[current] = []
|
|
52
|
+
elif current:
|
|
53
|
+
sections[current].append(line)
|
|
54
|
+
|
|
55
|
+
parsed = {k: "\n".join(v).strip() for k, v in sections.items()}
|
|
56
|
+
missing = [
|
|
57
|
+
name for name, required in PROFILE_SECTIONS.items() if required and not parsed.get(name)
|
|
58
|
+
]
|
|
59
|
+
if missing:
|
|
60
|
+
raise SystemExit(
|
|
61
|
+
f"{path} is missing required section(s): "
|
|
62
|
+
+ ", ".join(f"## {m.title()}" for m in missing)
|
|
63
|
+
)
|
|
64
|
+
return parsed
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# Sections whose text (or, for topics, the chosen topic) goes to the provider.
|
|
68
|
+
# "never" is left out of the unedited check: the example's rules are real rules,
|
|
69
|
+
# so keeping them as they are is a legitimate profile.
|
|
70
|
+
CHECKED_SECTIONS = ("topics", "beat", "voice", "experience", "hashtags")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _bullet_text(line: str) -> str:
|
|
74
|
+
return re.sub(r"^\s*(?:[-*]|\d+[.)])\s*", "", line).strip()
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _placeholder_lines(example: dict[str, str]) -> set[str]:
|
|
78
|
+
"""The example's own placeholder lines, whole and stripped: its bullets that
|
|
79
|
+
start with '(' and its '#Tag' lines. Taken from the shipped file, so they
|
|
80
|
+
can't drift from it."""
|
|
81
|
+
lines = set()
|
|
82
|
+
for name in CHECKED_SECTIONS:
|
|
83
|
+
for line in example.get(name, "").splitlines():
|
|
84
|
+
if _bullet_text(line).startswith(("(", "#")):
|
|
85
|
+
lines.add(line.strip())
|
|
86
|
+
return lines
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def unfilled_sections(profile: dict[str, str], example: dict[str, str]) -> list[str]:
|
|
90
|
+
"""Names of the sections still holding the example profile's text: the body
|
|
91
|
+
equals the example's, or it keeps one of the example's placeholder lines
|
|
92
|
+
exactly. A real line that merely starts with '(' is not a placeholder."""
|
|
93
|
+
placeholders = _placeholder_lines(example)
|
|
94
|
+
unfilled = []
|
|
95
|
+
for name in CHECKED_SECTIONS:
|
|
96
|
+
body = profile.get(name, "")
|
|
97
|
+
if not body:
|
|
98
|
+
continue
|
|
99
|
+
lines = {line.strip() for line in body.splitlines()}
|
|
100
|
+
if body == example.get(name) or lines & placeholders:
|
|
101
|
+
unfilled.append(name)
|
|
102
|
+
return unfilled
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def topic_menu(profile: dict[str, str]) -> list[str]:
|
|
106
|
+
"""Topics from the profile's '## Topics' section, else the built-in
|
|
107
|
+
catalog. One topic per line; '-' and '*' bullets and numbering are
|
|
108
|
+
stripped."""
|
|
109
|
+
raw = profile.get("topics", "")
|
|
110
|
+
topics = []
|
|
111
|
+
for line in raw.splitlines():
|
|
112
|
+
line = re.sub(r"^\s*(?:[-*]|\d+[.)])\s*", "", line).strip()
|
|
113
|
+
if line and not line.startswith("#"):
|
|
114
|
+
topics.append(line)
|
|
115
|
+
return topics or list(TOPIC_CATALOG)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def match_topic(topics: list[str], requested: str) -> str:
|
|
119
|
+
"""--topic as a menu number, a case-insensitive substring of a menu
|
|
120
|
+
entry, or free text that is not in the menu at all."""
|
|
121
|
+
if requested.isdigit() and 1 <= int(requested) <= len(topics):
|
|
122
|
+
return topics[int(requested) - 1]
|
|
123
|
+
matches = [t for t in topics if requested.lower() in t.lower()]
|
|
124
|
+
if len(matches) == 1:
|
|
125
|
+
return matches[0]
|
|
126
|
+
if len(matches) > 1:
|
|
127
|
+
raise SystemExit("Ambiguous --topic. Matches:\n " + "\n ".join(matches))
|
|
128
|
+
return requested # free-text topic, not in the menu
|
questcast/cli.py
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
1
|
+
"""Command-line interface: the flags, one run, and the entry point."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import random
|
|
5
|
+
import sys
|
|
6
|
+
import webbrowser
|
|
7
|
+
from datetime import date
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from questcast import config, storage
|
|
11
|
+
from questcast.author_profile import match_topic, topic_menu, unfilled_sections
|
|
12
|
+
from questcast.config import (
|
|
13
|
+
DEFAULT_PROVIDER,
|
|
14
|
+
MAX_LINKEDIN_TEXT,
|
|
15
|
+
MAX_TWEET_TEXT,
|
|
16
|
+
NOTHING_LOST,
|
|
17
|
+
PROVIDERS,
|
|
18
|
+
SEARCH_SOURCES,
|
|
19
|
+
)
|
|
20
|
+
from questcast.dedup import is_used, used_from
|
|
21
|
+
from questcast.fields import (
|
|
22
|
+
compose_posts,
|
|
23
|
+
linkedin_compose_link,
|
|
24
|
+
parse_fields,
|
|
25
|
+
strip_emphasis,
|
|
26
|
+
trim,
|
|
27
|
+
x_compose_link,
|
|
28
|
+
)
|
|
29
|
+
from questcast.prompt import build_prompt, estimate_tokens
|
|
30
|
+
from questcast.providers import make_provider, select_provider
|
|
31
|
+
from questcast.search import make_search, select_search
|
|
32
|
+
from questcast.storage import load_history, load_profile, log_drafts, log_run, save_history
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def choose_topic(topics: list, requested: str | None = None, pick_random: bool = False) -> str:
|
|
36
|
+
"""Resolve the topic from --topic, --random-topic, or an interactive menu.
|
|
37
|
+
|
|
38
|
+
--topic accepts a menu number, a case-insensitive substring of a menu
|
|
39
|
+
entry, or free text that is not in the menu at all.
|
|
40
|
+
"""
|
|
41
|
+
if pick_random:
|
|
42
|
+
return random.choice(topics) # noqa: S311 - random topic choice, not security
|
|
43
|
+
|
|
44
|
+
if requested:
|
|
45
|
+
return match_topic(topics, requested)
|
|
46
|
+
|
|
47
|
+
if not sys.stdin.isatty():
|
|
48
|
+
raise SystemExit(
|
|
49
|
+
'No topic given and no terminal to ask on. Use --topic "..." or --random-topic.'
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
print("\nPick a topic for today:\n")
|
|
53
|
+
for i, topic in enumerate(topics, 1):
|
|
54
|
+
print(f" {i:>2}. {topic}")
|
|
55
|
+
print("\n r. Random")
|
|
56
|
+
print(" Or type any topic of your own.\n")
|
|
57
|
+
|
|
58
|
+
answer = input("Topic: ").strip()
|
|
59
|
+
if not answer:
|
|
60
|
+
raise SystemExit("No topic chosen.")
|
|
61
|
+
if answer.lower() == "r":
|
|
62
|
+
return random.choice(topics) # noqa: S311 - random topic choice, not security
|
|
63
|
+
if answer.isdigit() and 1 <= int(answer) <= len(topics):
|
|
64
|
+
return topics[int(answer) - 1]
|
|
65
|
+
return answer
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def generate_item(
|
|
69
|
+
provider, search, profile: dict, topic: str, used_urls: list, used_titles: list
|
|
70
|
+
) -> dict:
|
|
71
|
+
candidates = search.candidates(used_urls, used_titles, topic)
|
|
72
|
+
if candidates is not None:
|
|
73
|
+
candidates = search.fit_budget(
|
|
74
|
+
lambda block: build_prompt(profile, topic, used_urls, used_titles, block)
|
|
75
|
+
)
|
|
76
|
+
if len(search.sent) < len(search.picked):
|
|
77
|
+
print(
|
|
78
|
+
f"Sending {len(search.sent)} of {len(search.picked)} feed entries "
|
|
79
|
+
"to fit the token budget",
|
|
80
|
+
file=sys.stderr,
|
|
81
|
+
)
|
|
82
|
+
prompt = build_prompt(profile, topic, used_urls, used_titles, candidates)
|
|
83
|
+
try:
|
|
84
|
+
text = provider.generate(prompt, native_search=candidates is None)
|
|
85
|
+
finally:
|
|
86
|
+
# Set even when generate fails, so the FAILED line gets the counts.
|
|
87
|
+
# In native mode the estimate is of the prompt before search (R59).
|
|
88
|
+
storage.RUN_TOKENS = storage.token_note(provider.usage, estimate_tokens(prompt))
|
|
89
|
+
|
|
90
|
+
try:
|
|
91
|
+
item = parse_fields(text)
|
|
92
|
+
except ValueError as exc:
|
|
93
|
+
raise SystemExit(
|
|
94
|
+
f"\nThe model's response could not be parsed.\n\n {exc}\n\n"
|
|
95
|
+
f" This is usually a one-off. Re-run and it will normally\n"
|
|
96
|
+
f" succeed.\n\n {NOTHING_LOST}\n"
|
|
97
|
+
) from None
|
|
98
|
+
|
|
99
|
+
missing = [k for k in ("url", "title", "tweet", "linkedin") if not item.get(k)]
|
|
100
|
+
if missing:
|
|
101
|
+
raise SystemExit(
|
|
102
|
+
f"\nThe model's response was missing: {', '.join(missing)}.\n\n"
|
|
103
|
+
f" Re-run — this is usually a one-off.\n\n {NOTHING_LOST}\n"
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
if is_used(item["url"], item["title"], used_urls, used_titles):
|
|
107
|
+
raise SystemExit(
|
|
108
|
+
f"\nThe model picked an item already covered:\n {item['title']}\n {item['url']}\n\n"
|
|
109
|
+
" Re-run, or try a different topic — this one may be quiet this\n"
|
|
110
|
+
f" week.\n\n {NOTHING_LOST}\n"
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
if candidates is not None and item["url"] not in search.links:
|
|
114
|
+
print(
|
|
115
|
+
f"WARNING: the picked URL is not one of the feed entries — check it "
|
|
116
|
+
f"before posting:\n {item['url']}",
|
|
117
|
+
file=sys.stderr,
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
# X gets hard-trimmed (the platform enforces the limit anyway). LinkedIn is
|
|
121
|
+
# only flagged — trimming from the end would eat the closing question and
|
|
122
|
+
# hashtags, which is worse than a draft you shorten by hand.
|
|
123
|
+
# R75: X and LinkedIn show Markdown literally.
|
|
124
|
+
item["tweet"] = trim(strip_emphasis(item["tweet"]), MAX_TWEET_TEXT)
|
|
125
|
+
item["linkedin"] = strip_emphasis(item["linkedin"]).strip()
|
|
126
|
+
if len(item["linkedin"]) > MAX_LINKEDIN_TEXT:
|
|
127
|
+
print(
|
|
128
|
+
f"WARNING: LinkedIn draft is {len(item['linkedin'])} characters "
|
|
129
|
+
f"(ceiling {MAX_LINKEDIN_TEXT}) — shorten it before posting.",
|
|
130
|
+
file=sys.stderr,
|
|
131
|
+
)
|
|
132
|
+
return item
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
136
|
+
"""The command-line parser; abbreviated flags are rejected, not guessed."""
|
|
137
|
+
parser = argparse.ArgumentParser(
|
|
138
|
+
allow_abbrev=False,
|
|
139
|
+
description="Daily X and LinkedIn draft generator, driven by an "
|
|
140
|
+
"author profile file and a topic you pick at run time.",
|
|
141
|
+
)
|
|
142
|
+
parser.add_argument(
|
|
143
|
+
"--topic",
|
|
144
|
+
help="menu number, part of a menu entry, or free text; skips the interactive menu",
|
|
145
|
+
)
|
|
146
|
+
parser.add_argument(
|
|
147
|
+
"--random-topic", action="store_true", help="pick a topic from the menu at random"
|
|
148
|
+
)
|
|
149
|
+
parser.add_argument("--list-topics", action="store_true", help="show the topic menu and exit")
|
|
150
|
+
parser.add_argument(
|
|
151
|
+
"--profile",
|
|
152
|
+
type=Path,
|
|
153
|
+
default=config.profile_file(),
|
|
154
|
+
help=f"author profile path (default: {config.profile_file()})",
|
|
155
|
+
)
|
|
156
|
+
parser.add_argument(
|
|
157
|
+
"--provider",
|
|
158
|
+
choices=PROVIDERS,
|
|
159
|
+
help=f"LLM provider (default: QC_POST_PROVIDER, else {DEFAULT_PROVIDER})",
|
|
160
|
+
)
|
|
161
|
+
parser.add_argument(
|
|
162
|
+
"--search",
|
|
163
|
+
choices=SEARCH_SOURCES,
|
|
164
|
+
help="where the item comes from (default: QC_POST_SEARCH, else native for "
|
|
165
|
+
"anthropic and groq, rss for openai-compat)",
|
|
166
|
+
)
|
|
167
|
+
parser.add_argument(
|
|
168
|
+
"--post",
|
|
169
|
+
action="store_true",
|
|
170
|
+
help="open X's compose box with the X draft filled in; nothing is posted "
|
|
171
|
+
"until you click Post",
|
|
172
|
+
)
|
|
173
|
+
parser.add_argument(
|
|
174
|
+
"--post-linkedin",
|
|
175
|
+
action="store_true",
|
|
176
|
+
help="open LinkedIn's post box with the LinkedIn draft filled in; nothing is "
|
|
177
|
+
"posted until you click Post",
|
|
178
|
+
)
|
|
179
|
+
parser.add_argument(
|
|
180
|
+
"--post-all",
|
|
181
|
+
action="store_true",
|
|
182
|
+
help="open both compose boxes, X first, then LinkedIn; the same as --post --post-linkedin",
|
|
183
|
+
)
|
|
184
|
+
parser.add_argument(
|
|
185
|
+
"--history", action="store_true", help="show the last 10 items used, then exit"
|
|
186
|
+
)
|
|
187
|
+
commands = parser.add_subparsers(dest="command", title="commands", metavar="COMMAND")
|
|
188
|
+
commands.add_parser(
|
|
189
|
+
"init",
|
|
190
|
+
help="create the data directory and an author profile to fill in, then exit",
|
|
191
|
+
allow_abbrev=False,
|
|
192
|
+
)
|
|
193
|
+
return parser
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def refuse_old_names() -> None:
|
|
197
|
+
"""Stop, before anything is read or written, if an old name is in use.
|
|
198
|
+
|
|
199
|
+
Exits with the int code 1 (not a message): main() logs a string exit to
|
|
200
|
+
run.log, which would create the data folder this check exists to protect.
|
|
201
|
+
"""
|
|
202
|
+
problems = config.old_name_problems()
|
|
203
|
+
if not problems:
|
|
204
|
+
return
|
|
205
|
+
print("questcast: old names found, and QuestCast 4 no longer reads them:", file=sys.stderr)
|
|
206
|
+
for problem in problems:
|
|
207
|
+
print(f" - {problem}", file=sys.stderr)
|
|
208
|
+
print(
|
|
209
|
+
'See "Upgrading to 4.0" in the README. Nothing was run or written.',
|
|
210
|
+
file=sys.stderr,
|
|
211
|
+
)
|
|
212
|
+
raise SystemExit(1)
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def run() -> None:
|
|
216
|
+
"""One run: parse the flags, then draft (and optionally publish)."""
|
|
217
|
+
# Loaded first, so QC_POST_DATA_DIR set in the env file applies to the
|
|
218
|
+
# --profile default as well as to the history, drafts and run log.
|
|
219
|
+
config.load_env_file()
|
|
220
|
+
|
|
221
|
+
args = build_parser().parse_args()
|
|
222
|
+
refuse_old_names()
|
|
223
|
+
|
|
224
|
+
if args.command == "init":
|
|
225
|
+
init()
|
|
226
|
+
return
|
|
227
|
+
|
|
228
|
+
if args.history:
|
|
229
|
+
for h in load_history()[-10:]:
|
|
230
|
+
topic = f" [{h['topic']}]" if h.get("topic") else ""
|
|
231
|
+
print(f"{h['date']} {h['title'][:70]}{topic}\n {h['url']}")
|
|
232
|
+
return
|
|
233
|
+
|
|
234
|
+
profile = load_profile(args.profile)
|
|
235
|
+
topics = topic_menu(profile)
|
|
236
|
+
|
|
237
|
+
if args.list_topics:
|
|
238
|
+
for i, topic in enumerate(topics, 1):
|
|
239
|
+
print(f"{i:>2}. {topic}")
|
|
240
|
+
return
|
|
241
|
+
|
|
242
|
+
unfilled = unfilled_sections(profile, storage.example_profile())
|
|
243
|
+
if unfilled:
|
|
244
|
+
raise SystemExit(
|
|
245
|
+
f"{args.profile} still has the example text in: "
|
|
246
|
+
+ ", ".join(f"## {name.title()}" for name in unfilled)
|
|
247
|
+
+ ".\nFill those sections in (see the README), then run again. "
|
|
248
|
+
"Nothing was sent to a provider."
|
|
249
|
+
)
|
|
250
|
+
|
|
251
|
+
provider = make_provider(select_provider(args.provider))
|
|
252
|
+
search_name = select_search(args.search, provider.name)
|
|
253
|
+
storage.RUN_VIA = f"{provider.name}/{provider.model or 'unset'}, search {search_name}"
|
|
254
|
+
provider.require_credentials()
|
|
255
|
+
search = make_search(search_name, profile)
|
|
256
|
+
|
|
257
|
+
topic = choose_topic(topics, args.topic, args.random_topic)
|
|
258
|
+
storage.ensure_data_dir()
|
|
259
|
+
|
|
260
|
+
history = load_history()
|
|
261
|
+
used_urls, used_titles = used_from(history)
|
|
262
|
+
|
|
263
|
+
if search.name == "rss":
|
|
264
|
+
print(f"\nReading {len(search.feeds)} feed(s) for: {topic}\n")
|
|
265
|
+
else:
|
|
266
|
+
print(f"\nSearching: {topic}\n")
|
|
267
|
+
item = generate_item(provider, search, profile, topic, used_urls, used_titles)
|
|
268
|
+
x_post, li_post = compose_posts(item)
|
|
269
|
+
|
|
270
|
+
x_link = x_compose_link(x_post)
|
|
271
|
+
li_link = linkedin_compose_link(li_post)
|
|
272
|
+
|
|
273
|
+
history.append(
|
|
274
|
+
{
|
|
275
|
+
"date": date.today().isoformat(),
|
|
276
|
+
"topic": topic,
|
|
277
|
+
"url": item["url"],
|
|
278
|
+
"title": item["title"],
|
|
279
|
+
"posted_x": False, # the user posts from X's compose box; we can't know
|
|
280
|
+
"posted_linkedin": False, # same: the user posts from LinkedIn's post box
|
|
281
|
+
"tweet_id": "",
|
|
282
|
+
"provider": provider.name,
|
|
283
|
+
"model": provider.model,
|
|
284
|
+
"search": search.name,
|
|
285
|
+
}
|
|
286
|
+
)
|
|
287
|
+
save_history(history)
|
|
288
|
+
log_drafts(item, topic, x_post, li_post, x_link, li_link, storage.RUN_VIA)
|
|
289
|
+
# R53, R59: to check the token estimate against real figures
|
|
290
|
+
log_run(f"OK — [{topic}] {item['title']} ({item['url']}){storage.RUN_TOKENS}")
|
|
291
|
+
|
|
292
|
+
rule = "=" * 70
|
|
293
|
+
print(rule)
|
|
294
|
+
print("X — draft")
|
|
295
|
+
print(rule)
|
|
296
|
+
print(x_post)
|
|
297
|
+
print(f"\n{rule}")
|
|
298
|
+
print("LINKEDIN — draft")
|
|
299
|
+
print(f"{rule}")
|
|
300
|
+
print(li_post)
|
|
301
|
+
print(f"\n[{len(item['linkedin'])} characters] Saved to {config.drafts_file()}")
|
|
302
|
+
|
|
303
|
+
open_x = args.post or args.post_all
|
|
304
|
+
open_linkedin = args.post_linkedin or args.post_all
|
|
305
|
+
if not (open_x or open_linkedin):
|
|
306
|
+
print(
|
|
307
|
+
"Compose links for X and LinkedIn are in drafts.md; --post, --post-linkedin "
|
|
308
|
+
"or --post-all opens them."
|
|
309
|
+
)
|
|
310
|
+
if open_x:
|
|
311
|
+
open_compose_box(x_link, "X", "X's compose box")
|
|
312
|
+
if open_linkedin:
|
|
313
|
+
if open_x and platform_name() == "ios" and not ios_wait_for_return():
|
|
314
|
+
print_link_fallback(li_link, "LinkedIn")
|
|
315
|
+
else:
|
|
316
|
+
open_compose_box(li_link, "LinkedIn", "LinkedIn's post box")
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def platform_name() -> str:
|
|
320
|
+
"""sys.platform, read here so tests can patch it alone."""
|
|
321
|
+
return sys.platform
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def ios_wait_for_return() -> bool:
|
|
325
|
+
"""R73: on iOS, opening X sends a-Shell to the background and iOS drops a
|
|
326
|
+
second open, so LinkedIn opens only after a Return. False means skip it:
|
|
327
|
+
no terminal to ask on, end of input, or Ctrl-C."""
|
|
328
|
+
if not sys.stdin.isatty():
|
|
329
|
+
return False
|
|
330
|
+
print("Press Return to open LinkedIn's post box (Ctrl-C to skip).")
|
|
331
|
+
try:
|
|
332
|
+
input()
|
|
333
|
+
except (EOFError, KeyboardInterrupt):
|
|
334
|
+
return False
|
|
335
|
+
return True
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def open_compose_box(link: str, site: str, box: str) -> None:
|
|
339
|
+
"""--post, --post-linkedin: open one site's compose box. Never raises.
|
|
340
|
+
|
|
341
|
+
The link is printed only when no browser opens, on its own line so it can be copied.
|
|
342
|
+
"""
|
|
343
|
+
try:
|
|
344
|
+
opened = webbrowser.open(link)
|
|
345
|
+
except webbrowser.Error:
|
|
346
|
+
opened = False
|
|
347
|
+
if opened:
|
|
348
|
+
print(f"Opened {box}.")
|
|
349
|
+
else:
|
|
350
|
+
print_link_fallback(link, site)
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
def print_link_fallback(link: str, site: str) -> None:
|
|
354
|
+
"""The link on its own line, so it can be copied."""
|
|
355
|
+
print(f"No browser opened; to post on {site}, open this link:")
|
|
356
|
+
print(link)
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def init() -> None:
|
|
360
|
+
"""qc init: create the data directory and an author profile to fill in.
|
|
361
|
+
|
|
362
|
+
An existing profile is never touched, and nothing is written to run.log,
|
|
363
|
+
so a refused init changes nothing in the data directory.
|
|
364
|
+
"""
|
|
365
|
+
try:
|
|
366
|
+
path = storage.create_profile()
|
|
367
|
+
except FileExistsError:
|
|
368
|
+
print(
|
|
369
|
+
f"An author profile already exists at {config.profile_file()}; "
|
|
370
|
+
"qc init left it unchanged.",
|
|
371
|
+
file=sys.stderr,
|
|
372
|
+
)
|
|
373
|
+
raise SystemExit(1) from None
|
|
374
|
+
print(
|
|
375
|
+
f"Created {path} from the example profile (mode 600).\n"
|
|
376
|
+
"Fill in at least ## Beat and ## Voice, then add GROQ_API_KEY to "
|
|
377
|
+
f"{config.shown(config.env_file())} (see the README)."
|
|
378
|
+
)
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def main() -> None:
|
|
382
|
+
"""Entry point for qc and daily_post.py."""
|
|
383
|
+
try:
|
|
384
|
+
run()
|
|
385
|
+
except KeyboardInterrupt:
|
|
386
|
+
print("\nCancelled.")
|
|
387
|
+
sys.exit(1)
|
|
388
|
+
except SystemExit as exc:
|
|
389
|
+
# Expected, explained failures: log the first line, print the message
|
|
390
|
+
# as written, and exit without a traceback.
|
|
391
|
+
if exc.code and isinstance(exc.code, str):
|
|
392
|
+
log_run(f"FAILED — {exc.code.strip().splitlines()[0]}{storage.RUN_TOKENS}")
|
|
393
|
+
raise
|
|
394
|
+
except Exception as exc:
|
|
395
|
+
# Genuinely unexpected: log it and let the traceback through, since
|
|
396
|
+
# that is the useful artifact for an unknown bug.
|
|
397
|
+
log_run(f"FAILED — {type(exc).__name__}: {exc}{storage.RUN_TOKENS}")
|
|
398
|
+
raise
|