Repository navigation
Expand file tree
/
Copy pathspecstream_lists.py
More file actions
187 lines (149 loc) · 8.47 KB
/
Copy pathspecstream_lists.py
File metadata and controls
187 lines (149 loc) · 8.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
"""SpecStream lists from Python, standard library only.
Every list has a page on https://specstream.ai/data, and its path is the list's name here.
describe("/data/funded-startups") no key: title, rows, columns, price, last update
sample("/data/funded-startups") no key: the 10 newest rows, free
find_lists("funded startups california") no key: the lists that match, with their row counts
rows("/data/funded-startups", max_cents=0) key: prices the rows waiting, charges nothing
rows("/data/funded-startups", max_cents=500, since="2026-11-01") key: rows up to $5
rows("/data/funded-startups", max_cents=500, new_only=True) key: only rows this key has not had
`rows` reads SPECSTREAM_API_KEY from the environment (Agents & API at https://specstream.ai/workspace) and never
spends more than max_cents. A row costs 5 cents the first time your account takes it; a row it had comes again free.
"""
from __future__ import annotations
import csv
import json
import os
import urllib.error
import urllib.parse
import urllib.request
API = "https://api.specstream.ai"
USER_AGENT = "specstream-lists-python/1.0"
class SpecStreamError(RuntimeError):
def __init__(self, status: int, message: str):
super().__init__(f"HTTP {status}: {message}")
self.status = status
def _call(path: str, params: dict | None = None, key: str | None = None, body: dict | None = None) -> dict:
query = urllib.parse.urlencode({k: v for k, v in (params or {}).items() if v is not None and v != "" and v is not False})
headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
if key:
headers["Authorization"] = f"Bearer {key}"
data = None
if body is not None:
data = json.dumps(body).encode()
headers["Content-Type"] = "application/json"
request = urllib.request.Request(f"{API}{path}{'?' + query if query else ''}", data=data, headers=headers)
try:
with urllib.request.urlopen(request, timeout=90) as reply:
return json.load(reply)
except urllib.error.HTTPError as error:
try:
detail = json.load(error)
message = (detail.get("error") or {}).get("message") if isinstance(detail.get("error"), dict) else detail.get("error")
except ValueError:
message = None
raise SpecStreamError(error.code, message or error.reason) from None
def _key() -> str:
key = os.environ.get("SPECSTREAM_API_KEY", "")
if not key:
raise SystemExit("Set SPECSTREAM_API_KEY. Create a key under Agents & API at https://specstream.ai/workspace")
return key
def _clean(reply: dict) -> list[dict]:
"""Rows as dicts with the list's own column names, without the internal _id and _date."""
columns = reply.get("columns") or []
out = []
for row in reply.get("rows") or []:
if isinstance(row, list):
row = dict(zip(columns, row))
out.append({k: v for k, v in row.items() if not k.startswith("_")})
return out
def describe(page: str) -> dict:
"""Title, rows, columns, period, price of the whole list and the day it was updated. Free."""
return _call("/v1/data/lists", {"page": page})
def sample(page: str) -> list[dict]:
"""The 10 newest rows of the list. Free, no key."""
return _clean(_call("/v1/data/lists/sample", {"page": page}))
def find_lists(q: str, family: str = "", limit: int = 10) -> list[dict]:
"""Lists whose title matches q, largest first: page, title, rows, price_usd. Free, no key."""
return _call("/v1/data/lists/search", {"q": q, "family": family, "limit": limit}).get("lists", [])
def rows(page: str, max_cents: int, since: str = "", new_only: bool = False, limit: int = 100) -> list[dict] | dict:
"""Rows dated on or after `since` (default: the last 7 days, or 90 with new_only), oldest first.
Follows the cursor until max_cents is spent or the list ends. With max_cents=0 nothing is charged and
the reply prices what waits instead (rows_waiting, new_rows_waiting, price_cents_all)."""
key = _key()
params = {"page": page, "since": since, "limit": limit, "new_only": "true" if new_only else ""}
if max_cents == 0:
return _call("/v1/data/lists/rows", {**params, "max_cents": 0}, key)
out, spent, cursor = [], 0, ""
while spent < max_cents:
try:
reply = _call("/v1/data/lists/rows", {**params, "max_cents": max_cents - spent, "cursor": cursor}, key)
except SpecStreamError as error:
if error.status == 402 and out: # the next page costs more than what is left of max_cents
break
raise
out.extend(_clean(reply))
spent += reply.get("price_cents") or 0
cursor = reply.get("next_cursor") or ""
if not cursor:
break
return out
def web_search(q: str, fast: bool = True) -> dict:
"""GET /v1/web-search: ranked sources and, for a question with one answer, the answer and its page.
$1 per 1,000 with fast=True, $5 per 1,000 otherwise."""
return _call("/v1/web-search", {"q": q, "speed": "fast" if fast else ""}, _key())["data"]
def extract(urls: list[str], query: str = "") -> list[dict]:
"""POST /v1/extract: the main text of 1 to 20 pages as Markdown, $0.80 per 1,000 pages."""
body = {"urls": urls[:20], "format": "markdown", **({"query": query} if query else {})}
return _call("/v1/extract", key=_key(), body=body)["data"]["results"]
def write_csv(records: list[dict], path: str) -> str:
columns = list(dict.fromkeys(k for r in records for k in r))
with open(path, "w", newline="", encoding="utf-8") as handle:
writer = csv.DictWriter(handle, fieldnames=columns)
writer.writeheader()
writer.writerows(records)
return path
def show(records: list[dict], columns: list[str], width: int = 40) -> None:
"""Print the chosen columns as a plain table, each cell cut at `width` characters."""
columns = [c for c in columns if any(c in r for r in records)]
sizes = {c: min(width, max([len(c)] + [len(str(r.get(c, ""))) for r in records])) for c in columns}
print(" ".join(c[: sizes[c]].ljust(sizes[c]) for c in columns))
for r in records:
print(" ".join(str(r.get(c, ""))[: sizes[c]].ljust(sizes[c]) for c in columns))
def recipe(page: str, columns: list[str], argv: list[str] | None = None) -> list[dict]:
"""The command line every recipe shares.
No flags: the list's live count and its 10 newest rows, free and without a key.
--rows: with SPECSTREAM_API_KEY, rows up to --max-cents (default 0, which only prices them), from --since,
or only the rows this key has not had with --new-only; --csv writes them to a file."""
import argparse
parser = argparse.ArgumentParser(description=f"Rows of https://specstream.ai{page}")
parser.add_argument("--list", default=page, help="another list path, such as one find_lists.py printed")
parser.add_argument("--rows", action="store_true", help="pull rows with your key instead of the free sample")
parser.add_argument("--max-cents", type=int, default=0, help="the most this run may cost; 0 only prices the rows")
parser.add_argument("--since", default="", help="rows dated on or after YYYY-MM-DD")
parser.add_argument("--new-only", action="store_true", help="only rows this key has not had from this list")
parser.add_argument("--csv", default="", help="write the rows to this CSV file")
args = parser.parse_args(argv)
try:
return _recipe(args.list, columns, args)
except SpecStreamError as error:
raise SystemExit(str(error)) from None
def _recipe(page: str, columns: list[str], args) -> list[dict]:
info = describe(page)
print(f"{info['title']}: {info['rows']:,} rows, {info.get('period') or ''}")
print(f"https://specstream.ai{page}\n")
if not args.rows:
records = sample(page)
show(records, columns)
print("\nThe 10 newest rows, free. Pull more with --rows and SPECSTREAM_API_KEY.")
else:
found = rows(page, args.max_cents, since=args.since, new_only=args.new_only)
if isinstance(found, dict):
print(f"{found.get('new_rows_waiting', 0):,} new rows waiting since {args.since or 'the default window'}, "
f"${found.get('price_cents_all', 0) / 100:,.2f} in all. Run again with --max-cents to take them.")
return []
records = found
show(records[:25], columns)
print(f"\n{len(records):,} rows.")
if args.csv and records:
print(f"Wrote {write_csv(records, args.csv)}")
return records