paperbrief 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.
- paperbrief/__init__.py +3 -0
- paperbrief/__main__.py +3 -0
- paperbrief/cli.py +536 -0
- paperbrief/config/__init__.py +0 -0
- paperbrief/config/loader.py +181 -0
- paperbrief/config/schema.py +208 -0
- paperbrief/config/template.yaml.j2 +116 -0
- paperbrief/data/env.example +22 -0
- paperbrief/deliver/__init__.py +207 -0
- paperbrief/llm/__init__.py +0 -0
- paperbrief/llm/core.py +158 -0
- paperbrief/llm/engines.py +216 -0
- paperbrief/llm/presets.py +97 -0
- paperbrief/models.py +56 -0
- paperbrief/net.py +85 -0
- paperbrief/packs/biomed.yaml +19 -0
- paperbrief/packs/cancer.yaml +11 -0
- paperbrief/packs/chemistry.yaml +8 -0
- paperbrief/packs/comp-path.yaml +11 -0
- paperbrief/packs/cs.yaml +6 -0
- paperbrief/packs/earth.yaml +8 -0
- paperbrief/packs/economics.yaml +7 -0
- paperbrief/packs/ml.yaml +7 -0
- paperbrief/packs/neuroscience.yaml +8 -0
- paperbrief/packs/physics.yaml +8 -0
- paperbrief/packs/psychology.yaml +6 -0
- paperbrief/packs/social-science.yaml +6 -0
- paperbrief/pipeline/__init__.py +0 -0
- paperbrief/pipeline/ai.py +311 -0
- paperbrief/pipeline/fulltext.py +105 -0
- paperbrief/pipeline/run.py +155 -0
- paperbrief/pipeline/select.py +64 -0
- paperbrief/prompts/brief.md +21 -0
- paperbrief/prompts/edit.md +22 -0
- paperbrief/prompts/overview.md +13 -0
- paperbrief/prompts/profile_draft.md +8 -0
- paperbrief/prompts/rank.md +18 -0
- paperbrief/render/__init__.py +128 -0
- paperbrief/render/templates/digest.md.j2 +63 -0
- paperbrief/render/templates/email.html.j2 +114 -0
- paperbrief/render/templates/feed.xml.j2 +17 -0
- paperbrief/schedule/__init__.py +205 -0
- paperbrief/secrets.py +41 -0
- paperbrief/sources/__init__.py +44 -0
- paperbrief/sources/apis.py +183 -0
- paperbrief/sources/common.py +41 -0
- paperbrief/sources/feeds.py +92 -0
- paperbrief/sources/resolve.py +76 -0
- paperbrief/store.py +57 -0
- paperbrief-0.1.0.dist-info/METADATA +285 -0
- paperbrief-0.1.0.dist-info/RECORD +54 -0
- paperbrief-0.1.0.dist-info/WHEEL +4 -0
- paperbrief-0.1.0.dist-info/entry_points.txt +2 -0
- paperbrief-0.1.0.dist-info/licenses/LICENSE +202 -0
paperbrief/__init__.py
ADDED
paperbrief/__main__.py
ADDED
paperbrief/cli.py
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
1
|
+
"""Command line: paperbrief <command>. Run `paperbrief --help` for the list."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import getpass
|
|
7
|
+
import json
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import sys
|
|
11
|
+
from datetime import date
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
import yaml
|
|
16
|
+
from jinja2 import Environment, FileSystemLoader
|
|
17
|
+
|
|
18
|
+
from paperbrief import __version__, net
|
|
19
|
+
from paperbrief import schedule as sched
|
|
20
|
+
from paperbrief.config import loader
|
|
21
|
+
from paperbrief.config.loader import ConfigError, Settings
|
|
22
|
+
from paperbrief.llm.core import AuthError, Ledger, ask
|
|
23
|
+
from paperbrief.llm.presets import PRESET_NOTES, PRESETS, SET_ME
|
|
24
|
+
|
|
25
|
+
DAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _settings(args) -> Settings:
|
|
29
|
+
st = loader.load(getattr(args, "config", None))
|
|
30
|
+
for w in st.warnings:
|
|
31
|
+
print(f"warning: {w}", file=sys.stderr)
|
|
32
|
+
return st
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
# ---------------------------------------------------------------- init
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _ask(question: str, default: str = "") -> str:
|
|
39
|
+
hint = f" [{default}]" if default else ""
|
|
40
|
+
answer = input(f"{question}{hint}: ").strip()
|
|
41
|
+
return answer or default
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _choose(question: str, options: list[str], default: str) -> str:
|
|
45
|
+
print(question)
|
|
46
|
+
for i, o in enumerate(options, 1):
|
|
47
|
+
print(f" {i}. {o}{' (default)' if o == default else ''}")
|
|
48
|
+
raw = input("> ").strip()
|
|
49
|
+
if raw.isdigit() and 1 <= int(raw) <= len(options):
|
|
50
|
+
return options[int(raw) - 1]
|
|
51
|
+
return raw if raw in options else default
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _write_config(target: Path, values: dict, profile: str, force: bool) -> None:
|
|
55
|
+
cfg_path = target / "paperbrief.yaml"
|
|
56
|
+
if cfg_path.exists() and not force:
|
|
57
|
+
raise SystemExit(f"{cfg_path} exists. Use --force to overwrite, or edit it by hand.")
|
|
58
|
+
target.mkdir(parents=True, exist_ok=True)
|
|
59
|
+
env = Environment(loader=FileSystemLoader(Path(loader.__file__).parent), trim_blocks=True, lstrip_blocks=True)
|
|
60
|
+
cfg_path.write_text(env.get_template("template.yaml.j2").render(**values))
|
|
61
|
+
if not (target / "profile.md").exists() or force:
|
|
62
|
+
(target / "profile.md").write_text(profile.strip() + "\n")
|
|
63
|
+
env_file = target / ".env"
|
|
64
|
+
if not env_file.exists():
|
|
65
|
+
example = Path(__file__).resolve().parent / "data" / "env.example"
|
|
66
|
+
env_file.write_text(
|
|
67
|
+
example.read_text() if example.exists() else "# Put secrets here (never commit this file)\n"
|
|
68
|
+
)
|
|
69
|
+
env_file.chmod(0o600)
|
|
70
|
+
gi = target / ".gitignore"
|
|
71
|
+
if not gi.exists():
|
|
72
|
+
gi.write_text(".env\npaperbrief-data/\n")
|
|
73
|
+
print(f"\nWrote {cfg_path}, profile.md, .env and .gitignore in {target}")
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def cmd_init(args) -> int:
|
|
77
|
+
packs = loader.list_packs()
|
|
78
|
+
target = Path(args.dir).expanduser().resolve()
|
|
79
|
+
values: dict[str, Any] = {
|
|
80
|
+
"reader_level": "researcher",
|
|
81
|
+
"language": "English",
|
|
82
|
+
"keywords": {},
|
|
83
|
+
"authors": [],
|
|
84
|
+
"packs": [],
|
|
85
|
+
"preset": args.preset or "subscription-cli",
|
|
86
|
+
"stage_overrides": "",
|
|
87
|
+
"days": DAYS[:5],
|
|
88
|
+
"times": ["07:00"],
|
|
89
|
+
"frequency": "daily",
|
|
90
|
+
"email_enabled": "false",
|
|
91
|
+
"smtp_preset": "gmail",
|
|
92
|
+
"sender": "",
|
|
93
|
+
"to": [],
|
|
94
|
+
}
|
|
95
|
+
profile = "Describe your research here in plain words: topics, methods, questions, and what you do not need.\n"
|
|
96
|
+
if args.packs:
|
|
97
|
+
values["packs"] = [p.strip() for p in args.packs.split(",") if p.strip()]
|
|
98
|
+
if not args.non_interactive:
|
|
99
|
+
print(
|
|
100
|
+
"PaperBrief setup. Press Enter to accept a default. You can change everything later in paperbrief.yaml.\n"
|
|
101
|
+
)
|
|
102
|
+
print("Source packs:")
|
|
103
|
+
for name, pack in packs.items():
|
|
104
|
+
print(f" {name:16} {pack.get('description', '')}")
|
|
105
|
+
chosen = _ask("Packs to use (comma-separated)", ",".join(values["packs"]) or "ml")
|
|
106
|
+
values["packs"] = [p.strip() for p in chosen.split(",") if p.strip() in packs]
|
|
107
|
+
print("\nModel presets:")
|
|
108
|
+
for name, note in PRESET_NOTES.items():
|
|
109
|
+
print(f" {name:17} {note}")
|
|
110
|
+
values["preset"] = _choose("Preset?", list(PRESETS), values["preset"])
|
|
111
|
+
if values["preset"] in ("gemini", "free-local"):
|
|
112
|
+
model = _ask("Model ID for every stage (see `paperbrief models`)", "")
|
|
113
|
+
if model:
|
|
114
|
+
prefix = "gemini/" if values["preset"] == "gemini" else "ollama/"
|
|
115
|
+
m = model if model.startswith(prefix) else prefix + model
|
|
116
|
+
values["stage_overrides"] = "\n".join(f' {s}: {{model: "{m}"}}' for s in ("rank", "brief", "overview"))
|
|
117
|
+
values["reader_level"] = _choose(
|
|
118
|
+
"Reader level?", ["student", "researcher", "clinician", "general"], "researcher"
|
|
119
|
+
)
|
|
120
|
+
values["language"] = _ask("Language of the briefs", "English")
|
|
121
|
+
desc = _ask("Describe your research in one or two sentences (used for your profile)", "")
|
|
122
|
+
if desc:
|
|
123
|
+
profile = desc
|
|
124
|
+
days = _ask("Days to run (daily, weekdays, or e.g. mon,wed,fri)", "weekdays")
|
|
125
|
+
values["days"] = (
|
|
126
|
+
DAYS
|
|
127
|
+
if days == "daily"
|
|
128
|
+
else DAYS[:5]
|
|
129
|
+
if days == "weekdays"
|
|
130
|
+
else [d for d in days.split(",") if d in DAYS] or DAYS[:5]
|
|
131
|
+
)
|
|
132
|
+
values["times"] = [_ask("Time (HH:MM, 24-hour, this computer's time)", "07:00")]
|
|
133
|
+
if _ask("Send by email? (y/n)", "n").lower().startswith("y"):
|
|
134
|
+
values["email_enabled"] = "true"
|
|
135
|
+
values["smtp_preset"] = _choose("Email provider?", ["gmail", "outlook", "custom"], "gmail")
|
|
136
|
+
values["sender"] = _ask("Sender address (the account that sends)", "")
|
|
137
|
+
values["to"] = [
|
|
138
|
+
a.strip() for a in _ask("Send to (comma-separated)", values["sender"]).split(",") if a.strip()
|
|
139
|
+
]
|
|
140
|
+
if _ask("Store the email app password in the OS keyring now? (y/n)", "y").lower().startswith("y"):
|
|
141
|
+
from paperbrief import secrets
|
|
142
|
+
|
|
143
|
+
pw = getpass.getpass("App password (input hidden): ")
|
|
144
|
+
if pw and not secrets.put("PAPERBRIEF_SMTP_PASSWORD", pw):
|
|
145
|
+
print("Keyring not available (pip install 'paperbrief[keyring]'); put it in .env instead.")
|
|
146
|
+
if args.ai:
|
|
147
|
+
values, profile = _ai_profile(args, values, profile, packs)
|
|
148
|
+
_write_config(target, values, profile, args.force)
|
|
149
|
+
print(
|
|
150
|
+
"\nNext steps:\n 1. Edit profile.md (who you are, what you need).\n 2. paperbrief doctor\n"
|
|
151
|
+
" 3. paperbrief preview\n 4. paperbrief schedule install"
|
|
152
|
+
)
|
|
153
|
+
return 0
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _ai_profile(args, values: dict, profile: str, packs: dict) -> tuple[dict, str]:
|
|
157
|
+
from paperbrief.config.schema import Config, Models
|
|
158
|
+
from paperbrief.pipeline.ai import draft_profile
|
|
159
|
+
from paperbrief.sources.resolve import resolve
|
|
160
|
+
|
|
161
|
+
cfg = Config(models=Models(preset=values["preset"]))
|
|
162
|
+
st = Settings(
|
|
163
|
+
cfg, Path(args.dir).resolve() / "paperbrief.yaml", Path(args.dir).resolve(), "", loader._stages(cfg), []
|
|
164
|
+
)
|
|
165
|
+
seeds = []
|
|
166
|
+
with net.client() as http:
|
|
167
|
+
for ident in args.seeds or []:
|
|
168
|
+
try:
|
|
169
|
+
seeds.append(resolve(ident, http))
|
|
170
|
+
except Exception as exc:
|
|
171
|
+
print(f"could not look up {ident}: {exc}")
|
|
172
|
+
print(f"Asking the AI to draft your profile from your description and {len(seeds)} papers...")
|
|
173
|
+
draft = draft_profile(st, Ledger(), args.ai, seeds, list(packs))
|
|
174
|
+
values["keywords"] = {k["name"].replace(" ", "_").lower(): k["terms"] for k in draft.get("keywords", [])}
|
|
175
|
+
values["authors"] = draft.get("authors", [])
|
|
176
|
+
values["packs"] = sorted(set(values["packs"]) | set(draft.get("packs", [])))
|
|
177
|
+
return values, draft.get("description", profile)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
# ---------------------------------------------------------------- checks
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def cmd_doctor(args) -> int:
|
|
184
|
+
from paperbrief import secrets
|
|
185
|
+
from paperbrief.sources import fetch_one
|
|
186
|
+
|
|
187
|
+
ok = True
|
|
188
|
+
try:
|
|
189
|
+
st = _settings(args)
|
|
190
|
+
except ConfigError as e:
|
|
191
|
+
print(f"config: FAIL\n{e}")
|
|
192
|
+
return 1
|
|
193
|
+
print(f"config: ok ({st.path})\n data dir: {st.data_dir}\n sources: {len(st.feeds)} feeds")
|
|
194
|
+
for name, s in st.stages.items():
|
|
195
|
+
print(
|
|
196
|
+
f" {name:9} {s.provider:11} {s.model} (effort {s.effort})"
|
|
197
|
+
if s.enabled and s.provider != "none"
|
|
198
|
+
else f" {name:9} off"
|
|
199
|
+
)
|
|
200
|
+
d = st.config.delivery
|
|
201
|
+
needed = []
|
|
202
|
+
if d.email.enabled:
|
|
203
|
+
needed.append(d.email.resend_key_env if d.email.method == "resend" else d.email.password_env)
|
|
204
|
+
needed += [w.url_env for w in (d.slack, d.discord) if w.enabled]
|
|
205
|
+
if d.telegram.enabled:
|
|
206
|
+
needed += [d.telegram.token_env, d.telegram.chat_id_env]
|
|
207
|
+
for n in needed:
|
|
208
|
+
found = bool(secrets.get(n))
|
|
209
|
+
ok &= found
|
|
210
|
+
print(f"secret {n}: {'ok' if found else 'MISSING (add it to .env or `paperbrief secret set ' + n + '`)'}")
|
|
211
|
+
if not args.no_ai:
|
|
212
|
+
tried = set()
|
|
213
|
+
for s in st.stages.values():
|
|
214
|
+
if not s.enabled or s.provider == "none" or (s.provider, s.model) in tried:
|
|
215
|
+
continue
|
|
216
|
+
tried.add((s.provider, s.model))
|
|
217
|
+
try:
|
|
218
|
+
ask(
|
|
219
|
+
s.model_copy(update={"timeout": 180}),
|
|
220
|
+
Ledger(),
|
|
221
|
+
"Reply with JSON.",
|
|
222
|
+
'Return {"ok": "yes"}',
|
|
223
|
+
{"type": "object", "properties": {"ok": {"type": "string"}}, "required": ["ok"]},
|
|
224
|
+
"doctor",
|
|
225
|
+
)
|
|
226
|
+
print(f"ai {s.provider}/{s.model}: ok")
|
|
227
|
+
except Exception as exc:
|
|
228
|
+
ok = False
|
|
229
|
+
print(f"ai {s.provider}/{s.model}: FAIL ({exc})")
|
|
230
|
+
if args.feeds:
|
|
231
|
+
with net.client(30) as http:
|
|
232
|
+
for f in st.feeds:
|
|
233
|
+
try:
|
|
234
|
+
count = len(fetch_one(f, http, date.today()))
|
|
235
|
+
print(f"feed {f.name}: ok ({count} items)")
|
|
236
|
+
except Exception as exc:
|
|
237
|
+
ok = False
|
|
238
|
+
print(f"feed {f.name}: FAIL ({type(exc).__name__}: {exc})")
|
|
239
|
+
for w in sched.warnings(st):
|
|
240
|
+
print(f"note: {w}")
|
|
241
|
+
print("\nAll checks passed." if ok else "\nSome checks failed (see above).")
|
|
242
|
+
return 0 if ok else 1
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def cmd_sources(args) -> int:
|
|
246
|
+
from paperbrief.sources import fetch_one
|
|
247
|
+
|
|
248
|
+
packs = loader.list_packs()
|
|
249
|
+
names = [args.pack] if args.pack else list(packs)
|
|
250
|
+
bad = 0
|
|
251
|
+
with net.client(30) as http:
|
|
252
|
+
for name in names:
|
|
253
|
+
print(f"[{name}] {packs[name].get('description', '')}")
|
|
254
|
+
for raw in packs[name].get("feeds", []):
|
|
255
|
+
from paperbrief.config.schema import Feed
|
|
256
|
+
|
|
257
|
+
f = Feed(**raw)
|
|
258
|
+
if args.action == "list":
|
|
259
|
+
print(f" {f.type:11} {f.name}")
|
|
260
|
+
continue
|
|
261
|
+
try:
|
|
262
|
+
n = len(fetch_one(f, http, date.today()))
|
|
263
|
+
print(f" ok {n:4d} {f.name}")
|
|
264
|
+
except Exception as exc:
|
|
265
|
+
bad += 1
|
|
266
|
+
print(f" FAIL {f.name}: {type(exc).__name__}: {str(exc)[:120]}")
|
|
267
|
+
if args.action == "check":
|
|
268
|
+
print(f"\n{bad} failing feed(s)")
|
|
269
|
+
return 1 if bad else 0
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def cmd_packs(args) -> int:
|
|
273
|
+
for name, pack in loader.list_packs().items():
|
|
274
|
+
print(f"{name:16} {len(pack.get('feeds', [])):3d} feeds {pack.get('description', '')}")
|
|
275
|
+
return 0
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def cmd_models(args) -> int:
|
|
279
|
+
if not args.provider:
|
|
280
|
+
for name, stages in PRESETS.items():
|
|
281
|
+
print(f"{name}: {PRESET_NOTES.get(name, '')}")
|
|
282
|
+
for s, v in stages.items():
|
|
283
|
+
print(f" {s:9} {v.get('provider')} {v.get('model')} effort={v.get('effort', '-')}")
|
|
284
|
+
print("\nList models for one provider: paperbrief models <openai|anthropic|gemini|ollama|openrouter>")
|
|
285
|
+
return 0
|
|
286
|
+
if args.provider == "ollama":
|
|
287
|
+
if not shutil.which("ollama"):
|
|
288
|
+
print("Ollama is not installed: https://ollama.com/download")
|
|
289
|
+
return 1
|
|
290
|
+
print(subprocess.run(["ollama", "list"], capture_output=True, text=True).stdout)
|
|
291
|
+
print("Use as model: ollama/<name>, e.g. ollama/<name from the list>")
|
|
292
|
+
return 0
|
|
293
|
+
try:
|
|
294
|
+
import litellm
|
|
295
|
+
except ImportError:
|
|
296
|
+
print("Install API support first: pip install 'paperbrief[api]'")
|
|
297
|
+
return 1
|
|
298
|
+
names = sorted(
|
|
299
|
+
k
|
|
300
|
+
for k, v in litellm.model_cost.items()
|
|
301
|
+
if v.get("litellm_provider", "").startswith(args.provider) and v.get("mode") == "chat"
|
|
302
|
+
)
|
|
303
|
+
for n in names:
|
|
304
|
+
print(n if "/" in n else f"{args.provider}/{n}")
|
|
305
|
+
print(
|
|
306
|
+
f"\n{len(names)} chat models known to LiteLLM {getattr(litellm, '__version__', '')}. Check the provider's docs for the newest IDs."
|
|
307
|
+
)
|
|
308
|
+
return 0
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def cmd_cost(args) -> int:
|
|
312
|
+
st = _settings(args)
|
|
313
|
+
it, sel = st.config.interests, st.config.selection
|
|
314
|
+
candidates = it.max_candidates
|
|
315
|
+
selected = sel.max_papers or max(5, candidates // 12)
|
|
316
|
+
rows = []
|
|
317
|
+
for name, s in st.stages.items():
|
|
318
|
+
if not s.enabled or s.provider == "none":
|
|
319
|
+
continue
|
|
320
|
+
calls = {
|
|
321
|
+
"rank": -(-candidates // s.batch_size),
|
|
322
|
+
"brief": selected,
|
|
323
|
+
"edit": -(-selected // s.batch_size),
|
|
324
|
+
"overview": 1,
|
|
325
|
+
}[name]
|
|
326
|
+
per = {
|
|
327
|
+
"rank": 25_000,
|
|
328
|
+
"brief": 15_000 if st.config.brief.full_text else 3_000,
|
|
329
|
+
"edit": 12_000,
|
|
330
|
+
"overview": 3_000,
|
|
331
|
+
}[name]
|
|
332
|
+
rows.append((name, s.provider, s.model, calls, calls * per))
|
|
333
|
+
print(f"Rough estimate for one run (up to {candidates} candidates, about {selected} selected):")
|
|
334
|
+
for r in rows:
|
|
335
|
+
print(f" {r[0]:9} {r[1]:11} {r[2]:32} ~{r[3]:4d} calls ~{r[4]:,} tokens")
|
|
336
|
+
print(f" total ~{sum(r[4] for r in rows):,} tokens. Real numbers appear in every digest footer and log.")
|
|
337
|
+
return 0
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
# ---------------------------------------------------------------- runs
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def cmd_run(args, dry_run: bool = False) -> int:
|
|
344
|
+
from paperbrief.pipeline import run as runner
|
|
345
|
+
|
|
346
|
+
st = _settings(args)
|
|
347
|
+
runner.setup_logging(st, args.verbose)
|
|
348
|
+
since = date.fromisoformat(args.since) if getattr(args, "since", None) else None
|
|
349
|
+
return runner.run(st, dry_run=dry_run or args.dry_run, force=args.force or dry_run, since=since)
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def cmd_preview(args) -> int:
|
|
353
|
+
args.dry_run, args.force = True, True
|
|
354
|
+
code = cmd_run(args, dry_run=True)
|
|
355
|
+
if code == 0:
|
|
356
|
+
print("\nPreview written (nothing sent): see paperbrief-data/out/ for today's HTML.")
|
|
357
|
+
return code
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def cmd_add(args) -> int:
|
|
361
|
+
from paperbrief import deliver, render
|
|
362
|
+
from paperbrief.pipeline import ai
|
|
363
|
+
from paperbrief.pipeline import run as runner
|
|
364
|
+
from paperbrief.sources.resolve import resolve
|
|
365
|
+
from paperbrief.store import Store
|
|
366
|
+
|
|
367
|
+
st = _settings(args)
|
|
368
|
+
runner.setup_logging(st, args.verbose)
|
|
369
|
+
ids = list(args.ids)
|
|
370
|
+
if args.file:
|
|
371
|
+
ids += [
|
|
372
|
+
ln.split("#", 1)[0].strip()
|
|
373
|
+
for ln in Path(args.file).read_text().splitlines()
|
|
374
|
+
if ln.split("#", 1)[0].strip()
|
|
375
|
+
]
|
|
376
|
+
papers, failed = [], []
|
|
377
|
+
with net.client() as http:
|
|
378
|
+
for i in ids:
|
|
379
|
+
try:
|
|
380
|
+
papers.append(resolve(i, http))
|
|
381
|
+
except Exception as exc:
|
|
382
|
+
failed.append(i)
|
|
383
|
+
print(f"could not look up {i}: {exc}")
|
|
384
|
+
if not papers:
|
|
385
|
+
return 1
|
|
386
|
+
ledger = runner.ledger_for(st)
|
|
387
|
+
try:
|
|
388
|
+
ranked = ai.rank(papers, st, ledger, floor=0)
|
|
389
|
+
glance, notes = runner.analyse(st, ledger, ranked)
|
|
390
|
+
except AuthError as exc:
|
|
391
|
+
print(exc)
|
|
392
|
+
return 2
|
|
393
|
+
ctx = render.context(
|
|
394
|
+
ranked,
|
|
395
|
+
"PaperBrief (added papers)",
|
|
396
|
+
{"fetched": len(ids), "candidates": len(papers), "selected": len(ranked)},
|
|
397
|
+
[f"not found: {f}" for f in failed] + notes + ([f"AI usage: {ledger.line()}"] if ledger.line() else []),
|
|
398
|
+
st.config.selection.top_picks,
|
|
399
|
+
glance,
|
|
400
|
+
)
|
|
401
|
+
done, errs = deliver.deliver(st, ctx, args.dry_run)
|
|
402
|
+
print("delivered:", ", ".join(done), *(["errors: " + "; ".join(errs)] if errs else []))
|
|
403
|
+
if not args.dry_run:
|
|
404
|
+
Store(st.dir("state") / "seen.sqlite").mark_seen(ranked)
|
|
405
|
+
return 1 if errs else 0
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def cmd_schedule(args) -> int:
|
|
409
|
+
st = _settings(args)
|
|
410
|
+
if args.action == "show":
|
|
411
|
+
b = sched.backend(st)
|
|
412
|
+
if b == "launchd":
|
|
413
|
+
print(sched.launchd_plist(st).decode())
|
|
414
|
+
elif b == "systemd":
|
|
415
|
+
print("\n\n".join(sched.systemd_units(st)))
|
|
416
|
+
elif b == "cron":
|
|
417
|
+
print("\n".join(sched.cron_lines(st)))
|
|
418
|
+
elif b == "windows":
|
|
419
|
+
print("\n".join(" ".join(c) for c in sched.windows_commands(st)))
|
|
420
|
+
else:
|
|
421
|
+
print(sched.install(st))
|
|
422
|
+
return 0
|
|
423
|
+
print({"install": sched.install, "remove": sched.remove, "status": sched.status}[args.action](st))
|
|
424
|
+
if args.action == "install":
|
|
425
|
+
for w in sched.warnings(st):
|
|
426
|
+
print(f"note: {w}")
|
|
427
|
+
return 0
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
def cmd_secret(args) -> int:
|
|
431
|
+
from paperbrief import secrets
|
|
432
|
+
|
|
433
|
+
if args.action == "set":
|
|
434
|
+
value = getpass.getpass(f"Value for {args.name} (input hidden): ")
|
|
435
|
+
if secrets.put(args.name, value):
|
|
436
|
+
print(f"Stored {args.name} in the OS keyring.")
|
|
437
|
+
return 0
|
|
438
|
+
print("Keyring not available. Install it (pip install 'paperbrief[keyring]') or put the value in .env.")
|
|
439
|
+
return 1
|
|
440
|
+
print(f"{args.name}: {'set' if secrets.get(args.name) else 'not set'}")
|
|
441
|
+
return 0
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
def cmd_config(args) -> int:
|
|
445
|
+
st = _settings(args)
|
|
446
|
+
data = st.config.model_dump(exclude_defaults=False)
|
|
447
|
+
data["models"] = {k: v.model_dump() for k, v in st.stages.items()}
|
|
448
|
+
print(yaml.safe_dump(json.loads(json.dumps(data)), sort_keys=False))
|
|
449
|
+
return 0
|
|
450
|
+
|
|
451
|
+
|
|
452
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
453
|
+
ap = argparse.ArgumentParser(
|
|
454
|
+
prog="paperbrief", description="Daily AI briefs of new research papers, for any field."
|
|
455
|
+
)
|
|
456
|
+
ap.add_argument("--version", action="version", version=f"paperbrief {__version__}")
|
|
457
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
458
|
+
|
|
459
|
+
def with_config(p):
|
|
460
|
+
p.add_argument("--config", help="path to paperbrief.yaml (default: ./paperbrief.yaml or ~/.config/paperbrief/)")
|
|
461
|
+
return p
|
|
462
|
+
|
|
463
|
+
p = sub.add_parser("init", help="create paperbrief.yaml (interactive, or --non-interactive)")
|
|
464
|
+
p.add_argument("--dir", default=".", help="folder to write the config into (default: current folder)")
|
|
465
|
+
p.add_argument("--preset", choices=list(PRESETS), help="model preset")
|
|
466
|
+
p.add_argument("--packs", help="comma-separated source packs, e.g. biomed,ml")
|
|
467
|
+
p.add_argument(
|
|
468
|
+
"--ai", metavar="DESCRIPTION", help="let the AI draft your profile, keywords and packs from this description"
|
|
469
|
+
)
|
|
470
|
+
p.add_argument("--seeds", nargs="*", help="DOIs or arXiv IDs of papers you like (used with --ai)")
|
|
471
|
+
p.add_argument("--non-interactive", action="store_true")
|
|
472
|
+
p.add_argument("--force", action="store_true", help="overwrite an existing config")
|
|
473
|
+
p.set_defaults(func=cmd_init)
|
|
474
|
+
|
|
475
|
+
p = with_config(sub.add_parser("doctor", help="check config, secrets, AI logins and (with --feeds) every feed"))
|
|
476
|
+
p.add_argument("--no-ai", action="store_true", help="skip the tiny test call to each AI model")
|
|
477
|
+
p.add_argument("--feeds", action="store_true", help="also fetch every configured feed once")
|
|
478
|
+
p.set_defaults(func=cmd_doctor)
|
|
479
|
+
|
|
480
|
+
for name, helptext in (("run", "fetch, score, brief and deliver (what the scheduler runs)"),):
|
|
481
|
+
p = with_config(sub.add_parser(name, help=helptext))
|
|
482
|
+
p.add_argument("--dry-run", action="store_true", help="write files but send nothing and remember nothing")
|
|
483
|
+
p.add_argument("--force", action="store_true", help="run even if today is not a scheduled day")
|
|
484
|
+
p.add_argument("--since", help="start date YYYY-MM-DD for API sources (default: last successful run)")
|
|
485
|
+
p.add_argument("-v", "--verbose", action="store_true")
|
|
486
|
+
p.set_defaults(func=cmd_run)
|
|
487
|
+
|
|
488
|
+
p = with_config(sub.add_parser("preview", help="a full run that sends nothing; writes the HTML preview"))
|
|
489
|
+
p.add_argument("--since")
|
|
490
|
+
p.add_argument("-v", "--verbose", action="store_true")
|
|
491
|
+
p.set_defaults(func=cmd_preview)
|
|
492
|
+
|
|
493
|
+
p = with_config(sub.add_parser("add", help="brief specific papers: DOI, arXiv ID or title:<words>"))
|
|
494
|
+
p.add_argument("ids", nargs="*")
|
|
495
|
+
p.add_argument("--file", help="text file with one ID per line (# starts a comment)")
|
|
496
|
+
p.add_argument("--dry-run", action="store_true")
|
|
497
|
+
p.add_argument("-v", "--verbose", action="store_true")
|
|
498
|
+
p.set_defaults(func=cmd_add)
|
|
499
|
+
|
|
500
|
+
p = sub.add_parser("sources", help="list or check the feeds in the built-in packs")
|
|
501
|
+
p.add_argument("action", choices=["list", "check"])
|
|
502
|
+
p.add_argument("--pack")
|
|
503
|
+
p.set_defaults(func=cmd_sources)
|
|
504
|
+
|
|
505
|
+
sub.add_parser("packs", help="list the source packs").set_defaults(func=cmd_packs)
|
|
506
|
+
|
|
507
|
+
p = sub.add_parser("models", help="list presets, or the models a provider offers")
|
|
508
|
+
p.add_argument("provider", nargs="?")
|
|
509
|
+
p.set_defaults(func=cmd_models)
|
|
510
|
+
|
|
511
|
+
with_config(sub.add_parser("cost", help="estimate AI usage for one run")).set_defaults(func=cmd_cost)
|
|
512
|
+
with_config(sub.add_parser("config", help="print the full resolved config")).set_defaults(func=cmd_config)
|
|
513
|
+
|
|
514
|
+
p = with_config(sub.add_parser("schedule", help="install, remove, show or check the OS schedule"))
|
|
515
|
+
p.add_argument("action", choices=["install", "remove", "status", "show"])
|
|
516
|
+
p.set_defaults(func=cmd_schedule)
|
|
517
|
+
|
|
518
|
+
p = sub.add_parser("secret", help="store or check a secret in the OS keyring")
|
|
519
|
+
p.add_argument("action", choices=["set", "check"])
|
|
520
|
+
p.add_argument("name", help="e.g. PAPERBRIEF_SMTP_PASSWORD, OPENAI_API_KEY")
|
|
521
|
+
p.set_defaults(func=cmd_secret)
|
|
522
|
+
return ap
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
def main(argv: list[str] | None = None) -> None:
|
|
526
|
+
args = build_parser().parse_args(argv)
|
|
527
|
+
try:
|
|
528
|
+
sys.exit(args.func(args))
|
|
529
|
+
except ConfigError as e:
|
|
530
|
+
print(e, file=sys.stderr)
|
|
531
|
+
sys.exit(1)
|
|
532
|
+
except KeyboardInterrupt:
|
|
533
|
+
sys.exit(130)
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
__all__ = ["main", "build_parser", "SET_ME"]
|
|
File without changes
|