@octen.ai/cli 0.10.0 → 0.11.0
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.
- package/README.md +2 -4
- package/dist/api/constants.d.ts +0 -5
- package/dist/api/constants.js +0 -2
- package/dist/api/mediaSearch.d.ts +0 -4
- package/dist/api/mediaSearch.js +2 -10
- package/dist/commands/configureSkills.js +1 -1
- package/dist/commands/imageSearch.js +1 -7
- package/package.json +1 -1
- package/skills/manifest.json +1 -1
- package/skills/octen-image-search/SKILL.md +3 -18
- package/skills/octen-image-search/agents/openai.yaml +1 -1
- package/skills/octen-place-search/SKILL.md +196 -0
- package/skills/octen-place-search/agents/openai.yaml +4 -0
- package/skills/octen-search/SKILL.md +195 -4
- package/skills/octen-web-search/SKILL.md +10 -6
- package/skills/octen-design/SKILL.md +0 -241
- package/skills/octen-design/agents/openai.yaml +0 -4
- package/skills/octen-design/scripts/search.py +0 -559
- package/skills/octen-design/scripts/tests/test_search.py +0 -449
|
@@ -1,559 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env python3
|
|
2
|
-
"""
|
|
3
|
-
Query the octen.ai image-search API for UI reference designs.
|
|
4
|
-
|
|
5
|
-
Searches TWO topics and merges them into one set of references (octen_refs):
|
|
6
|
-
|
|
7
|
-
* topic=design — curated UI design corpus. Each hit carries a reference
|
|
8
|
-
screenshot plus structured `summary` (design tokens) and an `html_snippet`.
|
|
9
|
-
These are the primary refs for implementation.
|
|
10
|
-
* topic=general — broad general-web image search. Wider visual coverage, but
|
|
11
|
-
NO summary / html_snippet (and usually empty description). These are
|
|
12
|
-
supplementary visual inspiration / style references.
|
|
13
|
-
|
|
14
|
-
Reads the API key from the OCTEN_API_KEY environment variable. Downloads result
|
|
15
|
-
images locally, writes each design-style summary and reusable HTML/CSS snippet to
|
|
16
|
-
an output directory, then prints a concise report to stdout (design refs first,
|
|
17
|
-
general refs after) so the model can act on it. The merged manifest is written to
|
|
18
|
-
results.json as `octen_refs`, with `partial` / `topic_errors` recording any
|
|
19
|
-
topic-level failures.
|
|
20
|
-
|
|
21
|
-
Stdlib only — no pip install required.
|
|
22
|
-
"""
|
|
23
|
-
|
|
24
|
-
import argparse
|
|
25
|
-
import base64
|
|
26
|
-
import hashlib
|
|
27
|
-
import http.client
|
|
28
|
-
import json
|
|
29
|
-
import mimetypes
|
|
30
|
-
import os
|
|
31
|
-
import re
|
|
32
|
-
import sys
|
|
33
|
-
import time
|
|
34
|
-
import urllib.error
|
|
35
|
-
import urllib.parse
|
|
36
|
-
import urllib.request
|
|
37
|
-
from concurrent.futures import ThreadPoolExecutor
|
|
38
|
-
from pathlib import Path
|
|
39
|
-
|
|
40
|
-
# Image downloads run concurrently within a topic; one slow/blocked host (e.g. a
|
|
41
|
-
# proxy resetting a CDN) no longer serializes behind the others. Per-download
|
|
42
|
-
# timeout is unchanged — this only overlaps the waiting.
|
|
43
|
-
DOWNLOAD_WORKERS = 8
|
|
44
|
-
|
|
45
|
-
# Endpoint. Override with OCTEN_API_URL if the path/host changes.
|
|
46
|
-
# NOTE: the working path is `/image-search` (NOT `/v1/image-search`, which 404s).
|
|
47
|
-
API_URL = os.environ.get("OCTEN_API_URL", "https://api.octen.ai/image-search")
|
|
48
|
-
|
|
49
|
-
# Topics queried by default. `design` = curated UI corpus (rich metadata);
|
|
50
|
-
# `general` = broad web image search (visual inspiration only).
|
|
51
|
-
DEFAULT_TOPICS = ["design", "general"]
|
|
52
|
-
|
|
53
|
-
ERROR_HINTS = {
|
|
54
|
-
400: "Missing or malformed parameter.",
|
|
55
|
-
401: "Invalid API key. Check the OCTEN_API_KEY environment variable.",
|
|
56
|
-
403: "No beta access for this endpoint, or insufficient account balance "
|
|
57
|
-
"(the server message below says which).",
|
|
58
|
-
413: "Input too large (image > 5MB base64-encoded, or query too long).",
|
|
59
|
-
415: "Unsupported input media type.",
|
|
60
|
-
422: "Input unreadable, invalid, or unsupported topic.",
|
|
61
|
-
429: "Rate limit exceeded. Wait and retry.",
|
|
62
|
-
500: "Server error. Retry later.",
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
# Retry policy for transient failures: statuses retried, retries after the
|
|
66
|
-
# first attempt, base backoff.
|
|
67
|
-
RETRYABLE_STATUSES = {429, 500, 502, 503, 504}
|
|
68
|
-
MAX_RETRIES = 2
|
|
69
|
-
RETRY_BASE_DELAY = 1.0
|
|
70
|
-
|
|
71
|
-
# Cap on a single downloaded image (per download; up to DOWNLOAD_WORKERS may be
|
|
72
|
-
# in flight at once); guards memory against oversized files from arbitrary
|
|
73
|
-
# general-topic hosts.
|
|
74
|
-
MAX_DOWNLOAD_BYTES = 20 * 1024 * 1024 # 20 MB
|
|
75
|
-
|
|
76
|
-
# Cap on a local reference image sent inline. The OpenAPI contract sets the
|
|
77
|
-
# limit on the base64-ENCODED payload ("at most 5MB after encoding"), so the
|
|
78
|
-
# pre-check measures encoded size; failing locally avoids burning a request.
|
|
79
|
-
MAX_LOCAL_IMAGE_BYTES = 5 * 1024 * 1024
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
class APICallError(Exception):
|
|
83
|
-
"""One topic's API call failed definitively (retries exhausted, a
|
|
84
|
-
non-retryable error, or an envelope/contract mismatch); other topics may
|
|
85
|
-
still work."""
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
def image_input(ref):
|
|
89
|
-
"""Turn a local path or URL into an inputs[] image entry."""
|
|
90
|
-
try:
|
|
91
|
-
scheme = urllib.parse.urlsplit(ref).scheme.lower()
|
|
92
|
-
except ValueError:
|
|
93
|
-
scheme = "" # unparseable as a URL; treat as a local path below
|
|
94
|
-
if scheme in ("http", "https"):
|
|
95
|
-
return {"type": "image", "url": ref}
|
|
96
|
-
p = Path(ref)
|
|
97
|
-
if not p.is_file():
|
|
98
|
-
sys.exit(f"Image reference not found: {ref}")
|
|
99
|
-
size = p.stat().st_size
|
|
100
|
-
encoded_size = 4 * ((size + 2) // 3) # base64 output size for `size` raw bytes
|
|
101
|
-
if encoded_size > MAX_LOCAL_IMAGE_BYTES:
|
|
102
|
-
sys.exit(
|
|
103
|
-
f"Image {ref} is {size / 1048576:.1f}MB "
|
|
104
|
-
f"({encoded_size / 1048576:.1f}MB base64-encoded); the API accepts "
|
|
105
|
-
"at most 5MB after encoding — pass a public https URL instead."
|
|
106
|
-
)
|
|
107
|
-
data = base64.b64encode(p.read_bytes()).decode("ascii")
|
|
108
|
-
return {"type": "image", "data": data}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
def build_payload(args, topic):
|
|
112
|
-
# The API accepts exactly ONE input per request (OpenAPI: "either one text
|
|
113
|
-
# input or one image input"; two inputs are rejected with 400).
|
|
114
|
-
if args.image:
|
|
115
|
-
inputs = [image_input(args.image)]
|
|
116
|
-
else:
|
|
117
|
-
inputs = [{"type": "text", "data": args.query[:500]}]
|
|
118
|
-
payload = {
|
|
119
|
-
"inputs": inputs,
|
|
120
|
-
"topic": topic,
|
|
121
|
-
"count": args.count,
|
|
122
|
-
# Only honored for topic=design; harmless for general.
|
|
123
|
-
"html_snippet": {"enable": True, "max_tokens": args.max_snippet_tokens},
|
|
124
|
-
}
|
|
125
|
-
return payload
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
def call_api(payload, api_key):
|
|
129
|
-
"""POST to the API with retries on transient failures.
|
|
130
|
-
|
|
131
|
-
Raises APICallError on any definitive failure — HTTP error, exhausted
|
|
132
|
-
retries, network/read failure, or an unreadable response body — so the
|
|
133
|
-
caller can decide whether to continue with other topics (a 403 on one
|
|
134
|
-
topic must not discard results already fetched for another).
|
|
135
|
-
"""
|
|
136
|
-
body = json.dumps(payload).encode("utf-8")
|
|
137
|
-
last_error = None
|
|
138
|
-
for attempt in range(MAX_RETRIES + 1):
|
|
139
|
-
req = urllib.request.Request(
|
|
140
|
-
API_URL,
|
|
141
|
-
data=body,
|
|
142
|
-
headers={
|
|
143
|
-
"x-api-key": api_key,
|
|
144
|
-
"Content-Type": "application/json",
|
|
145
|
-
},
|
|
146
|
-
method="POST",
|
|
147
|
-
)
|
|
148
|
-
server_delay = None
|
|
149
|
-
try:
|
|
150
|
-
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
151
|
-
raw = resp.read()
|
|
152
|
-
try:
|
|
153
|
-
return json.loads(raw.decode("utf-8"))
|
|
154
|
-
except (json.JSONDecodeError, UnicodeDecodeError) as e:
|
|
155
|
-
last_error = (
|
|
156
|
-
f"Unreadable (non-JSON) response body from the image "
|
|
157
|
-
f"search API: {e}"
|
|
158
|
-
)
|
|
159
|
-
break
|
|
160
|
-
except urllib.error.HTTPError as e:
|
|
161
|
-
hint = ERROR_HINTS.get(e.code, "")
|
|
162
|
-
try:
|
|
163
|
-
detail = e.read().decode("utf-8", "replace").strip()
|
|
164
|
-
except Exception:
|
|
165
|
-
detail = ""
|
|
166
|
-
# Cap the server body: it is replayed on every retry warning and
|
|
167
|
-
# persisted into results.json.
|
|
168
|
-
if len(detail) > 500:
|
|
169
|
-
detail = detail[:500] + "…(truncated)"
|
|
170
|
-
last_error = f"API error {e.code}: {hint} {detail or '(no readable response body)'}".strip()
|
|
171
|
-
if e.code not in RETRYABLE_STATUSES:
|
|
172
|
-
break
|
|
173
|
-
retry_after = e.headers.get("Retry-After") if e.headers else None
|
|
174
|
-
if retry_after:
|
|
175
|
-
try:
|
|
176
|
-
server_delay = min(float(retry_after), 30.0)
|
|
177
|
-
except ValueError:
|
|
178
|
-
pass
|
|
179
|
-
except (urllib.error.URLError, http.client.HTTPException, OSError) as e:
|
|
180
|
-
# Read-phase failures (timeout, reset, truncated body) surface as
|
|
181
|
-
# raw OSError/HTTPException rather than URLError; all transient.
|
|
182
|
-
# Bare OSErrors stringify to "", so always include the class name.
|
|
183
|
-
last_error = (f"Network error reaching the image search API: "
|
|
184
|
-
f"{e.__class__.__name__}: {getattr(e, 'reason', e)}")
|
|
185
|
-
if attempt < MAX_RETRIES:
|
|
186
|
-
delay = max(RETRY_BASE_DELAY * (2 ** attempt), server_delay or 0)
|
|
187
|
-
print(
|
|
188
|
-
f"WARNING: image search API attempt {attempt + 1}/{MAX_RETRIES + 1} "
|
|
189
|
-
f"failed ({last_error}); retrying in {delay:.0f}s",
|
|
190
|
-
file=sys.stderr,
|
|
191
|
-
)
|
|
192
|
-
time.sleep(delay)
|
|
193
|
-
raise APICallError(last_error or "unknown error")
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
class _HttpOnlyRedirectHandler(urllib.request.HTTPRedirectHandler):
|
|
197
|
-
"""Refuse redirects to any non-http(s) scheme (urllib itself would follow
|
|
198
|
-
a redirect to ftp://)."""
|
|
199
|
-
|
|
200
|
-
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
201
|
-
if urllib.parse.urlsplit(newurl).scheme.lower() not in ("http", "https"):
|
|
202
|
-
# The stdlib drains/closes fp only after redirect_request returns;
|
|
203
|
-
# raising would otherwise leak the connection.
|
|
204
|
-
fp.read()
|
|
205
|
-
fp.close()
|
|
206
|
-
raise urllib.error.URLError(f"redirect to non-http(s) URL blocked: {newurl}")
|
|
207
|
-
return super().redirect_request(req, fp, code, msg, headers, newurl)
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
_DOWNLOAD_OPENER = urllib.request.build_opener(_HttpOnlyRedirectHandler)
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
def download_image(url, dest_stem):
|
|
214
|
-
"""Download an image URL to dest_stem.<ext>.
|
|
215
|
-
|
|
216
|
-
Returns (path, None) on success or (None, reason) on failure, so the
|
|
217
|
-
caller can record WHY an image is missing. Only http(s) URLs are fetched
|
|
218
|
-
— enforced across redirects too — and reads are capped at
|
|
219
|
-
MAX_DOWNLOAD_BYTES so an oversized file from an arbitrary host cannot
|
|
220
|
-
exhaust memory.
|
|
221
|
-
"""
|
|
222
|
-
if not url:
|
|
223
|
-
return None, "no image URL in the API response"
|
|
224
|
-
try:
|
|
225
|
-
scheme = urllib.parse.urlsplit(url).scheme.lower()
|
|
226
|
-
except ValueError as e:
|
|
227
|
-
return None, f"unparseable image URL: {e}"
|
|
228
|
-
if scheme not in ("http", "https"):
|
|
229
|
-
return None, f"blocked non-http(s) URL scheme: {scheme or '(none)'}"
|
|
230
|
-
try:
|
|
231
|
-
req = urllib.request.Request(url, headers={"User-Agent": "ui-design-search/1.0"})
|
|
232
|
-
with _DOWNLOAD_OPENER.open(req, timeout=60) as resp:
|
|
233
|
-
data = resp.read(MAX_DOWNLOAD_BYTES + 1)
|
|
234
|
-
if len(data) > MAX_DOWNLOAD_BYTES:
|
|
235
|
-
return None, "image exceeds the 20MB download cap"
|
|
236
|
-
ctype = resp.headers.get("Content-Type", "")
|
|
237
|
-
except Exception as e:
|
|
238
|
-
return None, f"download failed: {e.__class__.__name__}: {e}"
|
|
239
|
-
ext = mimetypes.guess_extension(ctype.split(";")[0].strip()) or ".jpg"
|
|
240
|
-
if ext == ".jpe":
|
|
241
|
-
ext = ".jpg"
|
|
242
|
-
path = dest_stem.with_suffix(ext)
|
|
243
|
-
try:
|
|
244
|
-
path.write_bytes(data)
|
|
245
|
-
except OSError as e:
|
|
246
|
-
return None, f"cannot write {path} locally: {e}"
|
|
247
|
-
return str(path), None
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
def safe_topic_slug(topic):
|
|
251
|
-
"""Filesystem-safe slug for a topic used in output filenames.
|
|
252
|
-
|
|
253
|
-
--topics is user input that gets interpolated into paths; strip anything
|
|
254
|
-
that could escape the output directory (e.g. "../evil"). Sanitized or
|
|
255
|
-
non-lowercase slugs get a short hash suffix so distinct topics cannot
|
|
256
|
-
collide on the same output files — whether by sanitizing to the same text
|
|
257
|
-
("a b" vs "a_b") or by case-folding on case-insensitive filesystems
|
|
258
|
-
("Design" vs "design" on APFS/NTFS).
|
|
259
|
-
"""
|
|
260
|
-
slug = re.sub(r"[^A-Za-z0-9_-]", "_", topic) or "topic"
|
|
261
|
-
if slug != topic or slug != slug.lower():
|
|
262
|
-
slug += "-" + hashlib.md5(topic.encode("utf-8"), usedforsecurity=False).hexdigest()[:6]
|
|
263
|
-
return slug
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
def collect_topic(topic, args, api_key):
|
|
267
|
-
"""Query one topic and return its raw image results (list of dicts)."""
|
|
268
|
-
resp = call_api(build_payload(args, topic), api_key)
|
|
269
|
-
# The beta envelope is loose (code/msg may be absent, data may be null on
|
|
270
|
-
# zero hits) — tolerate that, but a missing `data` key or wrong-typed
|
|
271
|
-
# data/results is a contract problem, NOT an empty result set.
|
|
272
|
-
if not isinstance(resp, dict) or "data" not in resp:
|
|
273
|
-
got = f"top-level keys {sorted(resp)}" if isinstance(resp, dict) else type(resp).__name__
|
|
274
|
-
raise APICallError(
|
|
275
|
-
f"Unexpected response envelope from the image search API (no 'data' key; got: {got})"
|
|
276
|
-
)
|
|
277
|
-
data = resp["data"] or {}
|
|
278
|
-
if not isinstance(data, dict):
|
|
279
|
-
raise APICallError(
|
|
280
|
-
"Unexpected response envelope from the image search API "
|
|
281
|
-
f"(data is {type(data).__name__}, expected an object)"
|
|
282
|
-
)
|
|
283
|
-
results = data.get("results") or []
|
|
284
|
-
if not isinstance(results, list):
|
|
285
|
-
raise APICallError(
|
|
286
|
-
"Unexpected response envelope from the image search API "
|
|
287
|
-
f"(results is {type(results).__name__}, expected an array)"
|
|
288
|
-
)
|
|
289
|
-
# The image-search endpoint returns image hits with no `type` field; keep
|
|
290
|
-
# any entry that has an image URL (do NOT filter on type == "image").
|
|
291
|
-
return [r for r in results if isinstance(r, dict) and r.get("url")]
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
def fetch_one_image(topic, i, r, out):
|
|
295
|
-
"""Download a single result's image (with thumbnail fallback). Thread-safe.
|
|
296
|
-
|
|
297
|
-
Returns (path, used_thumbnail, error); error is set only when no image
|
|
298
|
-
could be saved at all.
|
|
299
|
-
"""
|
|
300
|
-
# Primary image is `url` (full-res). For general, the foreign-host image
|
|
301
|
-
# may be huge or hotlink-blocked, so fall back to the octen-proxied
|
|
302
|
-
# `thumbnail` when the original download fails.
|
|
303
|
-
slug = safe_topic_slug(topic)
|
|
304
|
-
img_path, primary_error = download_image(r.get("url"), out / f"{slug}_{i}")
|
|
305
|
-
used_thumbnail = False
|
|
306
|
-
error = None
|
|
307
|
-
if img_path is None:
|
|
308
|
-
if r.get("thumbnail"):
|
|
309
|
-
img_path, thumb_error = download_image(r.get("thumbnail"), out / f"{slug}_{i}")
|
|
310
|
-
used_thumbnail = img_path is not None
|
|
311
|
-
if img_path is None:
|
|
312
|
-
error = f"original: {primary_error}; thumbnail: {thumb_error}"
|
|
313
|
-
else:
|
|
314
|
-
print(f"NOTE: [{topic}:{i}] full-res download failed "
|
|
315
|
-
f"({primary_error}); saved the thumbnail instead", file=sys.stderr)
|
|
316
|
-
else:
|
|
317
|
-
error = primary_error
|
|
318
|
-
if error:
|
|
319
|
-
print(f"WARNING: [{topic}:{i}] image not saved — {error}", file=sys.stderr)
|
|
320
|
-
return img_path, used_thumbnail, error
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
def process_topic(topic, results, args, out):
|
|
324
|
-
"""Download images/snippets for one topic; return that topic's octen_refs."""
|
|
325
|
-
# Fan out the image downloads concurrently; results keyed by index so the
|
|
326
|
-
# output order is preserved regardless of completion order.
|
|
327
|
-
images = {}
|
|
328
|
-
if results:
|
|
329
|
-
with ThreadPoolExecutor(max_workers=min(DOWNLOAD_WORKERS, len(results))) as ex:
|
|
330
|
-
futures = {
|
|
331
|
-
ex.submit(fetch_one_image, topic, i, r, out): i
|
|
332
|
-
for i, r in enumerate(results)
|
|
333
|
-
}
|
|
334
|
-
for fut in futures:
|
|
335
|
-
images[futures[fut]] = fut.result()
|
|
336
|
-
|
|
337
|
-
refs = []
|
|
338
|
-
for i, r in enumerate(results):
|
|
339
|
-
img_path, used_thumbnail, image_error = images.get(i, (None, False, None))
|
|
340
|
-
|
|
341
|
-
snippet = r.get("html_snippet")
|
|
342
|
-
snippet_path = None
|
|
343
|
-
snippet_error = None
|
|
344
|
-
if snippet:
|
|
345
|
-
if not isinstance(snippet, str):
|
|
346
|
-
snippet_error = f"unexpected html_snippet type: {type(snippet).__name__}"
|
|
347
|
-
else:
|
|
348
|
-
snippet_path = str(out / f"{safe_topic_slug(topic)}_snippet_{i}.html")
|
|
349
|
-
try:
|
|
350
|
-
# errors="replace": json.loads can hand us lone surrogates
|
|
351
|
-
# (\ud83d-style escapes) that utf-8 cannot encode; a lossy
|
|
352
|
-
# write beats losing the snippet (or the whole run).
|
|
353
|
-
Path(snippet_path).write_text(snippet, encoding="utf-8", errors="replace")
|
|
354
|
-
except (OSError, ValueError) as e:
|
|
355
|
-
snippet_path = None
|
|
356
|
-
snippet_error = f"cannot write snippet locally: {e}"
|
|
357
|
-
if snippet_error:
|
|
358
|
-
print(f"WARNING: [{topic}:{i}] {snippet_error}", file=sys.stderr)
|
|
359
|
-
|
|
360
|
-
refs.append({
|
|
361
|
-
"topic": topic,
|
|
362
|
-
"index": i,
|
|
363
|
-
"title": r.get("title"),
|
|
364
|
-
"source_page": r.get("source_page"),
|
|
365
|
-
"image_url": r.get("url"),
|
|
366
|
-
"thumbnail_url": r.get("thumbnail") or None,
|
|
367
|
-
"local_image": img_path,
|
|
368
|
-
"local_image_is_thumbnail": used_thumbnail,
|
|
369
|
-
"image_error": image_error,
|
|
370
|
-
"description": r.get("description"),
|
|
371
|
-
"summary": r.get("summary"),
|
|
372
|
-
"html_snippet_file": snippet_path,
|
|
373
|
-
"snippet_error": snippet_error,
|
|
374
|
-
"width": r.get("width"),
|
|
375
|
-
"height": r.get("height"),
|
|
376
|
-
})
|
|
377
|
-
return refs
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
def print_topic_report(topic, refs, heading, error=None):
|
|
381
|
-
print("=" * 64)
|
|
382
|
-
print(heading)
|
|
383
|
-
print("=" * 64)
|
|
384
|
-
if error:
|
|
385
|
-
print(f"(TOPIC FAILED: {error})")
|
|
386
|
-
return
|
|
387
|
-
if not refs:
|
|
388
|
-
print("(no results for this topic)")
|
|
389
|
-
return
|
|
390
|
-
for ref in refs:
|
|
391
|
-
i = ref["index"]
|
|
392
|
-
print(f"[{topic}:{i}] {ref.get('title') or '(untitled)'}")
|
|
393
|
-
print(f" source : {ref.get('source_page') or ref.get('image_url')}")
|
|
394
|
-
if ref.get("local_image"):
|
|
395
|
-
tag = " (thumbnail)" if ref.get("local_image_is_thumbnail") else ""
|
|
396
|
-
print(f" image : {ref['local_image']}{tag} <-- view this")
|
|
397
|
-
else:
|
|
398
|
-
print(f" image : (not saved: {ref.get('image_error')}) {ref.get('image_url')}")
|
|
399
|
-
if ref.get("description"):
|
|
400
|
-
print(f" desc : {ref['description']}")
|
|
401
|
-
if ref.get("summary"):
|
|
402
|
-
print(f" style : {ref['summary']}")
|
|
403
|
-
if ref.get("html_snippet_file"):
|
|
404
|
-
print(f" snippet: {ref['html_snippet_file']} <-- read it; use fully if detailed, else as structure only")
|
|
405
|
-
print("-" * 64)
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
def write_manifest(out, query, topics, octen_refs, topic_errors):
|
|
409
|
-
"""Write results.json atomically: a crash mid-write must not leave a
|
|
410
|
-
truncated manifest, and a run that reaches the API but fails must not
|
|
411
|
-
leave a stale one."""
|
|
412
|
-
manifest = {
|
|
413
|
-
"query": query,
|
|
414
|
-
"topics": topics,
|
|
415
|
-
"partial": bool(topic_errors),
|
|
416
|
-
"topic_errors": topic_errors,
|
|
417
|
-
"octen_refs": octen_refs,
|
|
418
|
-
}
|
|
419
|
-
tmp = out / "results.json.tmp"
|
|
420
|
-
try:
|
|
421
|
-
# errors="replace": API strings may contain lone surrogates.
|
|
422
|
-
tmp.write_text(json.dumps(manifest, ensure_ascii=False, indent=2),
|
|
423
|
-
encoding="utf-8", errors="replace")
|
|
424
|
-
os.replace(tmp, out / "results.json")
|
|
425
|
-
except OSError as e:
|
|
426
|
-
try:
|
|
427
|
-
tmp.unlink()
|
|
428
|
-
except OSError:
|
|
429
|
-
pass
|
|
430
|
-
sys.exit(f"Cannot write the results manifest: {e}")
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
def count_arg(value):
|
|
434
|
-
n = int(value)
|
|
435
|
-
if not 1 <= n <= 10:
|
|
436
|
-
raise argparse.ArgumentTypeError("must be between 1 and 10 (the API's documented range)")
|
|
437
|
-
return n
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
def main():
|
|
441
|
-
parser = argparse.ArgumentParser(
|
|
442
|
-
description="Search UI design references via the octen.ai image-search API (design + general topics)."
|
|
443
|
-
)
|
|
444
|
-
parser.add_argument(
|
|
445
|
-
"query", nargs="?", default="",
|
|
446
|
-
help="Text query (<=500 chars). Describe the component AND its style/theme.",
|
|
447
|
-
)
|
|
448
|
-
parser.add_argument(
|
|
449
|
-
"--image",
|
|
450
|
-
help="Reference image for image-based search: local path (sent as base64) "
|
|
451
|
-
"or public URL. Cannot be combined with a text query.",
|
|
452
|
-
)
|
|
453
|
-
parser.add_argument("--count", type=count_arg, default=5, help="Number of results PER TOPIC, 1-10 (default 5).")
|
|
454
|
-
parser.add_argument(
|
|
455
|
-
"--topics", nargs="+", default=DEFAULT_TOPICS,
|
|
456
|
-
help="Topics to query (default: design general). design = curated UI corpus; general = broad web images.",
|
|
457
|
-
)
|
|
458
|
-
parser.add_argument(
|
|
459
|
-
"--max-snippet-tokens", type=int, default=5000,
|
|
460
|
-
help="Max tokens per html_snippet (default 5000; raise for complex components).",
|
|
461
|
-
)
|
|
462
|
-
parser.add_argument(
|
|
463
|
-
"--out", default="./.ui-refs",
|
|
464
|
-
help="Output directory for downloaded images, snippets, and results.json.",
|
|
465
|
-
)
|
|
466
|
-
args = parser.parse_args()
|
|
467
|
-
|
|
468
|
-
if args.query and args.image:
|
|
469
|
-
sys.exit(
|
|
470
|
-
"The image-search API accepts a single input per request: pass a "
|
|
471
|
-
"text query OR --image, not both. Run the script twice to combine "
|
|
472
|
-
"text and image references."
|
|
473
|
-
)
|
|
474
|
-
if not args.query and not args.image:
|
|
475
|
-
sys.exit("Provide a text query or --image.")
|
|
476
|
-
|
|
477
|
-
api_key = os.environ.get("OCTEN_API_KEY")
|
|
478
|
-
if not api_key:
|
|
479
|
-
sys.exit(
|
|
480
|
-
"OCTEN_API_KEY is not set. Export it before running "
|
|
481
|
-
"(do NOT paste the key into the chat)."
|
|
482
|
-
)
|
|
483
|
-
|
|
484
|
-
out = Path(args.out)
|
|
485
|
-
out.mkdir(parents=True, exist_ok=True)
|
|
486
|
-
|
|
487
|
-
# Duplicate topics would query the same corpus twice and overwrite each
|
|
488
|
-
# other's files; keep the first occurrence of each.
|
|
489
|
-
topics = list(dict.fromkeys(args.topics))
|
|
490
|
-
if len(topics) < len(args.topics):
|
|
491
|
-
dropped = sorted({t for t in args.topics if args.topics.count(t) > 1})
|
|
492
|
-
print(f"WARNING: duplicate --topics values ignored: {', '.join(dropped)}",
|
|
493
|
-
file=sys.stderr)
|
|
494
|
-
|
|
495
|
-
print(f"Query : {args.query or '[image search]'}")
|
|
496
|
-
print(f"Topics : {', '.join(topics)}")
|
|
497
|
-
|
|
498
|
-
octen_refs = []
|
|
499
|
-
per_topic = {}
|
|
500
|
-
topic_errors = {}
|
|
501
|
-
for topic in topics:
|
|
502
|
-
try:
|
|
503
|
-
raw = collect_topic(topic, args, api_key)
|
|
504
|
-
except APICallError as e:
|
|
505
|
-
# One topic failing (e.g. 403 no beta access) must not discard
|
|
506
|
-
# results already fetched for other topics.
|
|
507
|
-
topic_errors[topic] = str(e)
|
|
508
|
-
print(f"WARNING: topic '{topic}' failed: {e}", file=sys.stderr)
|
|
509
|
-
per_topic[topic] = []
|
|
510
|
-
continue
|
|
511
|
-
refs = process_topic(topic, raw, args, out)
|
|
512
|
-
per_topic[topic] = refs
|
|
513
|
-
octen_refs.extend(refs)
|
|
514
|
-
|
|
515
|
-
if topic_errors and not octen_refs:
|
|
516
|
-
# Nothing was retrieved and at least one topic failed outright. Exit
|
|
517
|
-
# non-zero with the failure — NOT "no results": broadening the query
|
|
518
|
-
# is the wrong remedy for e.g. a 403.
|
|
519
|
-
write_manifest(out, args.query, topics, octen_refs, topic_errors)
|
|
520
|
-
details = "; ".join(f"{t}: {err}" for t, err in topic_errors.items())
|
|
521
|
-
sys.exit(f"No results — {len(topic_errors)} of {len(topics)} topic(s) failed. {details}")
|
|
522
|
-
|
|
523
|
-
status = ", ".join(
|
|
524
|
-
f"{t}=FAILED" if t in topic_errors else f"{t}={len(per_topic.get(t, []))}"
|
|
525
|
-
for t in topics
|
|
526
|
-
)
|
|
527
|
-
print(f"Results: {len(octen_refs)} total ({status})")
|
|
528
|
-
if topic_errors:
|
|
529
|
-
print(
|
|
530
|
-
f"NOTE: partial results — {len(topic_errors)} topic(s) failed: "
|
|
531
|
-
+ "; ".join(f"{t}: {err}" for t, err in topic_errors.items())
|
|
532
|
-
)
|
|
533
|
-
|
|
534
|
-
if not octen_refs:
|
|
535
|
-
print(
|
|
536
|
-
"NO RESULTS. Proceed using your own design judgment, tell the user no "
|
|
537
|
-
"reference was found, and consider broadening the query."
|
|
538
|
-
)
|
|
539
|
-
write_manifest(out, args.query, topics, octen_refs, topic_errors)
|
|
540
|
-
return
|
|
541
|
-
|
|
542
|
-
headings = {
|
|
543
|
-
"design": "DESIGN refs (primary — structured summary + html_snippet)",
|
|
544
|
-
"general": "GENERAL refs (supplementary — visual inspiration only)",
|
|
545
|
-
}
|
|
546
|
-
# design first (primary), then general (supplementary), then any other topics.
|
|
547
|
-
ordered = [t for t in ("design", "general") if t in per_topic]
|
|
548
|
-
ordered += [t for t in topics if t not in ordered]
|
|
549
|
-
for topic in ordered:
|
|
550
|
-
print_topic_report(topic, per_topic.get(topic, []),
|
|
551
|
-
headings.get(topic, f"{topic.upper()} refs"),
|
|
552
|
-
error=topic_errors.get(topic))
|
|
553
|
-
|
|
554
|
-
write_manifest(out, args.query, topics, octen_refs, topic_errors)
|
|
555
|
-
print(f"Manifest: {out / 'results.json'} (key: octen_refs)")
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
if __name__ == "__main__":
|
|
559
|
-
main()
|