@octen.ai/cli 0.1.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/LICENSE +21 -0
- package/README.md +184 -0
- package/dist/api/chat.d.ts +33 -0
- package/dist/api/chat.js +23 -0
- package/dist/api/client.d.ts +19 -0
- package/dist/api/client.js +111 -0
- package/dist/api/constants.d.ts +38 -0
- package/dist/api/constants.js +32 -0
- package/dist/api/embedding.d.ts +18 -0
- package/dist/api/embedding.js +27 -0
- package/dist/api/errors.d.ts +14 -0
- package/dist/api/errors.js +22 -0
- package/dist/api/extract.d.ts +34 -0
- package/dist/api/extract.js +26 -0
- package/dist/api/search.d.ts +33 -0
- package/dist/api/search.js +34 -0
- package/dist/api/sse.d.ts +6 -0
- package/dist/api/sse.js +53 -0
- package/dist/api/vlEmbedding.d.ts +39 -0
- package/dist/api/vlEmbedding.js +68 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +39 -0
- package/dist/commands/chat.d.ts +2 -0
- package/dist/commands/chat.js +122 -0
- package/dist/commands/configureMcp.d.ts +11 -0
- package/dist/commands/configureMcp.js +101 -0
- package/dist/commands/configureSkills.d.ts +11 -0
- package/dist/commands/configureSkills.js +118 -0
- package/dist/commands/embed.d.ts +2 -0
- package/dist/commands/embed.js +69 -0
- package/dist/commands/fetch.d.ts +2 -0
- package/dist/commands/fetch.js +26 -0
- package/dist/commands/reset.d.ts +11 -0
- package/dist/commands/reset.js +112 -0
- package/dist/commands/search.d.ts +2 -0
- package/dist/commands/search.js +31 -0
- package/dist/commands/utils.d.ts +10 -0
- package/dist/commands/utils.js +24 -0
- package/dist/commands/vlEmbed.d.ts +2 -0
- package/dist/commands/vlEmbed.js +98 -0
- package/dist/config/resolve.d.ts +2 -0
- package/dist/config/resolve.js +12 -0
- package/dist/mcp/clients.d.ts +9 -0
- package/dist/mcp/clients.js +58 -0
- package/dist/mcp/detect.d.ts +2 -0
- package/dist/mcp/detect.js +35 -0
- package/dist/mcp/install.d.ts +20 -0
- package/dist/mcp/install.js +56 -0
- package/dist/mcp/write.d.ts +3 -0
- package/dist/mcp/write.js +104 -0
- package/dist/output/pretty/chat.d.ts +2 -0
- package/dist/output/pretty/chat.js +9 -0
- package/dist/output/pretty/embedding.d.ts +11 -0
- package/dist/output/pretty/embedding.js +43 -0
- package/dist/output/pretty/extract.d.ts +2 -0
- package/dist/output/pretty/extract.js +41 -0
- package/dist/output/pretty/search.d.ts +2 -0
- package/dist/output/pretty/search.js +28 -0
- package/dist/output/pretty/vlEmbedding.d.ts +13 -0
- package/dist/output/pretty/vlEmbedding.js +47 -0
- package/dist/output/render.d.ts +6 -0
- package/dist/output/render.js +13 -0
- package/dist/skills/clients.d.ts +7 -0
- package/dist/skills/clients.js +47 -0
- package/dist/skills/install.d.ts +18 -0
- package/dist/skills/install.js +77 -0
- package/dist/skills/source.d.ts +12 -0
- package/dist/skills/source.js +56 -0
- package/dist/util/preflightColor.d.ts +1 -0
- package/dist/util/preflightColor.js +7 -0
- package/package.json +44 -0
- package/skills/manifest.json +8 -0
- package/skills/octen-design/SKILL.md +218 -0
- package/skills/octen-design/scripts/search.py +304 -0
- package/skills/octen-search/SKILL.md +199 -0
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: octen-design
|
|
3
|
+
description: >-
|
|
4
|
+
Pull real-world UI design references before building any frontend. Use this skill
|
|
5
|
+
whenever implementing, restyling, or improving any web UI in Claude Code — pages,
|
|
6
|
+
components, layouts, dashboards, forms, cards, navs, modals, marketing sections —
|
|
7
|
+
even when the user does not explicitly ask for a "design reference." Phrases like
|
|
8
|
+
"build me a settings page," "make a pricing card," "this looks plain, improve it,"
|
|
9
|
+
or "match the style of X" should all trigger it. It queries a multimodal design
|
|
10
|
+
search API for reference screenshots from top products, structured style
|
|
11
|
+
descriptions, and HTML/CSS snippets, so the implementation is
|
|
12
|
+
grounded in proven patterns instead of invented from scratch. Skip it only for
|
|
13
|
+
pure logic/back-end work with no visual surface.
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
# Octen Design
|
|
17
|
+
|
|
18
|
+
> **Invite-only beta.** Octen Design is currently in invite-only beta. To request
|
|
19
|
+
> access, contact Octen at support@octen.ai (or via https://octen.ai). Calls will
|
|
20
|
+
> fail without access — if so, tell the user it's invite-only and how to reach Octen.
|
|
21
|
+
|
|
22
|
+
Before writing frontend code, **search for real reference designs and build from
|
|
23
|
+
them.** Designing UI blind tends to produce generic, low-polish output; grounding
|
|
24
|
+
the work in screenshots, explicit style notes, and snippets from well-designed
|
|
25
|
+
products raises quality substantially. This skill wraps the octen.ai image-search
|
|
26
|
+
API and queries **two topics at once**, merging the hits into one set of
|
|
27
|
+
references (`octen_refs`) that drives the design content you then generate:
|
|
28
|
+
|
|
29
|
+
- **`topic=design` — primary.** A curated UI design corpus. Each hit carries a
|
|
30
|
+
reference screenshot, a structured `summary` of its style (colors, typography,
|
|
31
|
+
layout, spacing, animation — sometimes empty), and an `html_snippet` ranging
|
|
32
|
+
from a complete component to a bare skeleton. These are the refs you build the
|
|
33
|
+
implementation from.
|
|
34
|
+
- **`topic=general` — supplementary.** Broad general-web image search. Much wider
|
|
35
|
+
visual coverage, but **no `summary`, no `html_snippet`, and usually no
|
|
36
|
+
`description`** — just an image, title, and source page. Use these purely as
|
|
37
|
+
extra visual inspiration / style direction; never expect structured metadata or
|
|
38
|
+
buildable markup from them.
|
|
39
|
+
|
|
40
|
+
Both topics are queried automatically; the script downloads every image, writes
|
|
41
|
+
each design `html_snippet`/`summary`, and emits a merged `octen_refs` manifest
|
|
42
|
+
(`results.json`) with design refs first, general refs after.
|
|
43
|
+
|
|
44
|
+
## Prerequisite
|
|
45
|
+
|
|
46
|
+
The query script reads the API key from the `OCTEN_API_KEY` environment variable.
|
|
47
|
+
If it is not set, tell the user to export it themselves — never ask them to paste a
|
|
48
|
+
key into the chat:
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
export OCTEN_API_KEY="<their key>"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Workflow
|
|
55
|
+
|
|
56
|
+
Follow these steps for any UI build/restyle task.
|
|
57
|
+
|
|
58
|
+
1. **Build a tight, precise query — this drives result quality more than any other
|
|
59
|
+
step.** The search fuses your words into one vector, so every word must earn its
|
|
60
|
+
place: name the component's canonical type plus 2–4 concrete visual traits, and
|
|
61
|
+
little else. English, one line, ≤500 chars.
|
|
62
|
+
|
|
63
|
+
**Keep (high signal):** the standard component name in real UI vocabulary (hero
|
|
64
|
+
section, logo cloud, bento grid, testimonial carousel, sticky navbar); concrete
|
|
65
|
+
visual traits (dark theme, gradient, minimal, centered, card grid); and visually
|
|
66
|
+
distinctive interactions (auto-scrolling, animated).
|
|
67
|
+
|
|
68
|
+
**Drop (noise):** command verbs and filler ("build a", "make me", articles);
|
|
69
|
+
subjective fluff ("beautiful", "modern", "clean", "sleek"); engineering/behavior
|
|
70
|
+
terms ("responsive", "accessible", "SEO", framework names); the user's *own* brand
|
|
71
|
+
or content — "our AcmeCorp pricing page" searches for `pricing page`, not
|
|
72
|
+
"AcmeCorp" (their brand is filled in later); and **invented traits** — never add a
|
|
73
|
+
look the request never mentioned (e.g. "dark theme" when it was not asked for); let
|
|
74
|
+
the reference and the returned images reveal the real style.
|
|
75
|
+
|
|
76
|
+
**Reference brand → put the bare brand name at the front of the query text.** When
|
|
77
|
+
the user names a site or product to emulate ("like Octen"), **lead every query with
|
|
78
|
+
the brand name itself** — e.g. `"Octen, hero section, web search product"`. Use the
|
|
79
|
+
brand exactly as it appears in the index (its title / name); do **not** glue on
|
|
80
|
+
"style" or similar ("Octen style"), because the index stores the bare brand title,
|
|
81
|
+
so the plain name matches best. Same brand token, same front position, on every
|
|
82
|
+
query. Drop the brand only when there is no reference brand in the request at all.
|
|
83
|
+
|
|
84
|
+
**Multiple reference brands → one query per brand, never fused into one.** When the
|
|
85
|
+
request names several brands to compare, analyze, or blend ("Vercel, Linear and
|
|
86
|
+
Supabase heroes", "mix Stripe and Linear"), do **not** stuff them all into a single
|
|
87
|
+
query. The search fuses every word into one vector, so N brand names collapse into a
|
|
88
|
+
blended average that matches none of them strongly — in practice one or more brands
|
|
89
|
+
come back with **zero results** (e.g. a fused `Vercel Linear Supabase, hero section`
|
|
90
|
+
returns Vercel + Supabase hits but no Linear at all). Instead run **one query per
|
|
91
|
+
brand**, each led by that single brand name, holding the component type and trait
|
|
92
|
+
modifiers **identical** across all of them; then read/compare the per-brand refs and
|
|
93
|
+
merge. Use a separate `--out` dir per brand so the downloads don't overwrite each
|
|
94
|
+
other. This is the multi-brand counterpart to the single-brand "same modifiers on
|
|
95
|
+
every query" rule below — same modifiers, the brand token is the one thing that
|
|
96
|
+
varies, one brand per run:
|
|
97
|
+
- `"Vercel, hero section, developer tool, animated gradient" --out ./.ui-refs-vercel`
|
|
98
|
+
- `"Linear, hero section, developer tool, animated gradient" --out ./.ui-refs-linear`
|
|
99
|
+
- `"Supabase, hero section, developer tool, animated gradient" --out ./.ui-refs-supabase`
|
|
100
|
+
|
|
101
|
+
(If the request also spans multiple sections/pages, this multiplies with the
|
|
102
|
+
granularity rule below: run the per-section queries once **per brand**.)
|
|
103
|
+
|
|
104
|
+
**Translate intent into standard English UI terms** (轮播→carousel, 落地页→landing
|
|
105
|
+
page, 面包屑→breadcrumb) — the index is English-dominant and the canonical term
|
|
106
|
+
matches best.
|
|
107
|
+
|
|
108
|
+
**Match query granularity to the request — keep shared anchors identical.** The
|
|
109
|
+
index holds both whole-page assets and individual sections, and **granularity is
|
|
110
|
+
set by wording alone (there is no parameter)** — so the words must signal the
|
|
111
|
+
level: whole-page terms ("homepage", "landing page", "full page") for a page, and
|
|
112
|
+
"X section" for a section. Query at the level the request needs:
|
|
113
|
+
- **Single component / section** ("a pricing table", "improve this card") → one
|
|
114
|
+
section-level query. Done.
|
|
115
|
+
- **Full page or multi-section** ("a homepage like Octen") → go top-down in two
|
|
116
|
+
stages. **(a) Page first:** run one page-level query, e.g. `"web search product
|
|
117
|
+
homepage"` (count 1–2), to pull a whole-page reference; read the overall
|
|
118
|
+
composition from it — which sections appear, in what order, and the global
|
|
119
|
+
design system (color, type, spacing). Confirm from the image that you actually
|
|
120
|
+
got a full page, not a section crop. **(b) Then sections:** run one query per
|
|
121
|
+
section (hero, logo cloud, features, pricing, footer, CTA) for implementation
|
|
122
|
+
detail, looping steps 2–5 for each.
|
|
123
|
+
|
|
124
|
+
Decide the shared modifiers **once** — the brand token (kept at the front) and a
|
|
125
|
+
single product descriptor (e.g. "web search product") — and apply the *same* ones,
|
|
126
|
+
in the same order, to every query in both stages; do not let them drift or change
|
|
127
|
+
wording.
|
|
128
|
+
|
|
129
|
+
- Too vague: `"table"`
|
|
130
|
+
- Too loaded: `"a beautiful modern responsive pricing table with dark theme, subtle gradients and hover effects for a SaaS landing page"`
|
|
131
|
+
- On point: `"pricing comparison table, dark theme, SaaS"`
|
|
132
|
+
- Full page + reference: `"build a websearch api homepage like Octen"` — lead every
|
|
133
|
+
query with the bare brand **Octen**:
|
|
134
|
+
(a) page: `"Octen, web search product homepage"` (count 1–2);
|
|
135
|
+
(b) sections: `"Octen, hero section, web search product"`, `"Octen, logo cloud marquee, web search product"`,
|
|
136
|
+
`"Octen, features grid section, web search product"`, `"Octen, pricing cards section, web search product"`
|
|
137
|
+
|
|
138
|
+
2. **Run the search** (from the skill directory):
|
|
139
|
+
|
|
140
|
+
```bash
|
|
141
|
+
python scripts/search.py "pricing comparison table, dark theme, SaaS" \
|
|
142
|
+
--count 5 \
|
|
143
|
+
--out ./.ui-refs
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
The script runs the query against **both `design` and `general` topics**
|
|
147
|
+
(`--count` is per topic, so `--count 5` returns up to 5 + 5). It downloads each
|
|
148
|
+
reference image to `./.ui-refs/` (named `design_N.*` / `general_N.*`), writes
|
|
149
|
+
each design snippet to `design_snippet_N.html`, saves a merged `results.json`
|
|
150
|
+
(the `octen_refs` array, design refs first), and prints a per-result report
|
|
151
|
+
grouped by topic. To restrict to one topic, pass e.g. `--topics design`.
|
|
152
|
+
|
|
153
|
+
3. **View the reference images — this is the anchor.** Use the `view` tool on each
|
|
154
|
+
`design_N.*` and `general_N.*` path the script printed. The image is always
|
|
155
|
+
present and is the primary signal: read layout, spacing, hierarchy, color, and
|
|
156
|
+
typography directly from it. Lean on the `design_N` images for the structure and
|
|
157
|
+
tokens you implement; use the `general_N` images as a wider mood/style board —
|
|
158
|
+
they broaden the visual direction but carry no `summary` or `html_snippet`, so
|
|
159
|
+
read everything below (4–5) only from the design refs. Everything below only
|
|
160
|
+
supplements the images.
|
|
161
|
+
|
|
162
|
+
4. **Use `summary` when present — but expect it to sometimes be empty.** When
|
|
163
|
+
returned, `summary` is rich structured markdown with exact design tokens:
|
|
164
|
+
background/foreground colors, font families and sizes, per-tag typography,
|
|
165
|
+
spacing and padding, layout ratios, logo/image counts, and dynamic signals (e.g.
|
|
166
|
+
the duration/timing of a marquee animation for an auto-scrolling logo wall). Use
|
|
167
|
+
it to make the implementation precise. When it is empty or missing, do not
|
|
168
|
+
stall — derive the styling from the image plus the `description` instead.
|
|
169
|
+
|
|
170
|
+
5. **Use `html_snippet` based on how complete it is — read it first, then judge.**
|
|
171
|
+
- **If the snippet is detailed and usable** (real list/grid items are present, and
|
|
172
|
+
actual CSS or fully self-contained utility classes are included), lean on it:
|
|
173
|
+
build directly from the snippet, porting it into the project's stack and
|
|
174
|
+
reconciling its class names and values with the codebase's design tokens. A
|
|
175
|
+
complete snippet is the most concrete starting point — use as much of it as is
|
|
176
|
+
sound.
|
|
177
|
+
- **If the snippet is a bare skeleton** (empty `<ul>`/containers, or class names
|
|
178
|
+
with no accompanying CSS or keyframes), use it for DOM structure and semantics
|
|
179
|
+
only, and take the styling from the image plus `summary`.
|
|
180
|
+
|
|
181
|
+
Either way, target the project's actual stack (React, Vue, Tailwind, plain CSS,
|
|
182
|
+
whatever it uses) and its existing design tokens rather than pasting verbatim, so
|
|
183
|
+
the result stays consistent with the codebase.
|
|
184
|
+
|
|
185
|
+
6. **Handle no results.** If the script reports `NO RESULTS`, say so, then either
|
|
186
|
+
broaden the query and retry once, or proceed on your
|
|
187
|
+
own design judgment. Do not stall.
|
|
188
|
+
|
|
189
|
+
## Image-based search
|
|
190
|
+
|
|
191
|
+
When the user already has a mockup, screenshot, or inspiration image, search by it
|
|
192
|
+
to find similar real implementations and their snippets. Pass a local path (sent as
|
|
193
|
+
base64) or a public URL:
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
python scripts/search.py "dashboard sidebar" --image ./mockup.png --count 5
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
Text plus image together is allowed and usually sharpest. An image alone also works.
|
|
200
|
+
|
|
201
|
+
## Notes and constraints
|
|
202
|
+
|
|
203
|
+
- `--count` defaults to 5 and is **per topic**, so you get up to `2 × count`
|
|
204
|
+
images total (design + general). Keep it modest (≈3–5); each design result pulls
|
|
205
|
+
an image plus a snippet, so very large counts bloat context and cost.
|
|
206
|
+
- `html_snippet` is capped by `--max-snippet-tokens` (default 5000). For a complex
|
|
207
|
+
component that looks truncated, rerun with a higher value.
|
|
208
|
+
- Results come back ranked within each topic; the first results are the most
|
|
209
|
+
relevant. There is no numeric relevance score, so trust the order. In
|
|
210
|
+
`results.json` they are merged into one `octen_refs` array (each entry tagged
|
|
211
|
+
with its `topic`), design refs first.
|
|
212
|
+
- Only `topic=design` hits carry `summary` and `html_snippet` (the script requests
|
|
213
|
+
image output and enables snippets); `topic=general` hits are image-only — treat
|
|
214
|
+
them as visual inspiration, not as a source of tokens or buildable markup.
|
|
215
|
+
- The endpoint path is `/image-search` (override the full URL with `OCTEN_API_URL`
|
|
216
|
+
if it changes). `topic=general` images come from arbitrary sites; if an original
|
|
217
|
+
fails to download (hotlink-blocked / oversized), the script falls back to the
|
|
218
|
+
octen-proxied thumbnail and marks `local_image_is_thumbnail` in the manifest.
|
|
@@ -0,0 +1,304 @@
|
|
|
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`.
|
|
19
|
+
|
|
20
|
+
Stdlib only — no pip install required.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import argparse
|
|
24
|
+
import base64
|
|
25
|
+
import json
|
|
26
|
+
import mimetypes
|
|
27
|
+
import os
|
|
28
|
+
import sys
|
|
29
|
+
import urllib.error
|
|
30
|
+
import urllib.request
|
|
31
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
# Image downloads run concurrently within a topic; one slow/blocked host (e.g. a
|
|
35
|
+
# proxy resetting a CDN) no longer serializes behind the others. Per-download
|
|
36
|
+
# timeout is unchanged — this only overlaps the waiting.
|
|
37
|
+
DOWNLOAD_WORKERS = 8
|
|
38
|
+
|
|
39
|
+
# Endpoint. Override with OCTEN_API_URL if the path/host changes.
|
|
40
|
+
# NOTE: the working path is `/image-search` (NOT `/v1/image-search`, which 404s).
|
|
41
|
+
API_URL = os.environ.get("OCTEN_API_URL", "https://api.octen.ai/image-search")
|
|
42
|
+
|
|
43
|
+
# Topics queried by default. `design` = curated UI corpus (rich metadata);
|
|
44
|
+
# `general` = broad web image search (visual inspiration only).
|
|
45
|
+
DEFAULT_TOPICS = ["design", "general"]
|
|
46
|
+
|
|
47
|
+
ERROR_HINTS = {
|
|
48
|
+
400: "Missing or malformed parameter.",
|
|
49
|
+
401: "Invalid API key. Check the OCTEN_API_KEY environment variable.",
|
|
50
|
+
403: "Insufficient account balance.",
|
|
51
|
+
413: "Input too large (image > 5MB, or query too long).",
|
|
52
|
+
415: "Unsupported input media type.",
|
|
53
|
+
422: "Input unreadable, invalid, or unsupported topic.",
|
|
54
|
+
429: "Rate limit exceeded. Wait and retry.",
|
|
55
|
+
500: "Server error. Retry later.",
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def image_input(ref):
|
|
60
|
+
"""Turn a local path or URL into an inputs[] image entry."""
|
|
61
|
+
if ref.startswith("http://") or ref.startswith("https://"):
|
|
62
|
+
return {"type": "image", "url": ref}
|
|
63
|
+
p = Path(ref)
|
|
64
|
+
if not p.is_file():
|
|
65
|
+
sys.exit(f"Image reference not found: {ref}")
|
|
66
|
+
data = base64.b64encode(p.read_bytes()).decode("ascii")
|
|
67
|
+
return {"type": "image", "data": data}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def build_payload(args, topic):
|
|
71
|
+
inputs = []
|
|
72
|
+
if args.query:
|
|
73
|
+
inputs.append({"type": "text", "data": args.query[:500]})
|
|
74
|
+
if args.image:
|
|
75
|
+
inputs.append(image_input(args.image))
|
|
76
|
+
payload = {
|
|
77
|
+
"inputs": inputs,
|
|
78
|
+
"topic": topic,
|
|
79
|
+
"output_modalities": ["image"],
|
|
80
|
+
"count": args.count,
|
|
81
|
+
# Only honored for topic=design; harmless for general.
|
|
82
|
+
"html_snippet": {"enable": True, "max_tokens": args.max_snippet_tokens},
|
|
83
|
+
}
|
|
84
|
+
return payload
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def call_api(payload, api_key):
|
|
88
|
+
body = json.dumps(payload).encode("utf-8")
|
|
89
|
+
req = urllib.request.Request(
|
|
90
|
+
API_URL,
|
|
91
|
+
data=body,
|
|
92
|
+
headers={
|
|
93
|
+
"x-api-key": api_key,
|
|
94
|
+
"Content-Type": "application/json",
|
|
95
|
+
},
|
|
96
|
+
method="POST",
|
|
97
|
+
)
|
|
98
|
+
try:
|
|
99
|
+
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
100
|
+
return json.loads(resp.read().decode("utf-8"))
|
|
101
|
+
except urllib.error.HTTPError as e:
|
|
102
|
+
hint = ERROR_HINTS.get(e.code, "")
|
|
103
|
+
try:
|
|
104
|
+
detail = e.read().decode("utf-8")
|
|
105
|
+
except Exception:
|
|
106
|
+
detail = ""
|
|
107
|
+
sys.exit(f"API error {e.code}: {hint} {detail}".strip())
|
|
108
|
+
except urllib.error.URLError as e:
|
|
109
|
+
sys.exit(f"Network error reaching the image search API: {e.reason}")
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def download_image(url, dest_stem):
|
|
113
|
+
"""Download an image URL to dest_stem.<ext>. Returns the path or None."""
|
|
114
|
+
if not url:
|
|
115
|
+
return None
|
|
116
|
+
try:
|
|
117
|
+
req = urllib.request.Request(url, headers={"User-Agent": "ui-design-search/1.0"})
|
|
118
|
+
with urllib.request.urlopen(req, timeout=60) as resp:
|
|
119
|
+
data = resp.read()
|
|
120
|
+
ctype = resp.headers.get("Content-Type", "")
|
|
121
|
+
ext = mimetypes.guess_extension(ctype.split(";")[0].strip()) or ".jpg"
|
|
122
|
+
if ext == ".jpe":
|
|
123
|
+
ext = ".jpg"
|
|
124
|
+
path = dest_stem.with_suffix(ext)
|
|
125
|
+
path.write_bytes(data)
|
|
126
|
+
return str(path)
|
|
127
|
+
except Exception:
|
|
128
|
+
return None
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def collect_topic(topic, args, api_key):
|
|
132
|
+
"""Query one topic and return its raw image results (list of dicts)."""
|
|
133
|
+
resp = call_api(build_payload(args, topic), api_key)
|
|
134
|
+
results = (resp.get("data") or {}).get("results") or []
|
|
135
|
+
# The image-search endpoint returns image hits with no `type` field; keep
|
|
136
|
+
# any entry that has an image URL (do NOT filter on type == "image").
|
|
137
|
+
return [r for r in results if r.get("url")]
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def fetch_one_image(topic, i, r, out):
|
|
141
|
+
"""Download a single result's image (with thumbnail fallback). Thread-safe."""
|
|
142
|
+
# Primary image is `url` (full-res). For general, the foreign-host image
|
|
143
|
+
# may be huge or hotlink-blocked, so fall back to the octen-proxied
|
|
144
|
+
# `thumbnail` when the original download fails.
|
|
145
|
+
img_path = download_image(r.get("url"), out / f"{topic}_{i}")
|
|
146
|
+
used_thumbnail = False
|
|
147
|
+
if img_path is None and r.get("thumbnail"):
|
|
148
|
+
img_path = download_image(r.get("thumbnail"), out / f"{topic}_{i}")
|
|
149
|
+
used_thumbnail = img_path is not None
|
|
150
|
+
return img_path, used_thumbnail
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def process_topic(topic, results, args, out):
|
|
154
|
+
"""Download images/snippets for one topic; return that topic's octen_refs."""
|
|
155
|
+
# Fan out the image downloads concurrently; results keyed by index so the
|
|
156
|
+
# output order is preserved regardless of completion order.
|
|
157
|
+
images = {}
|
|
158
|
+
if results:
|
|
159
|
+
with ThreadPoolExecutor(max_workers=min(DOWNLOAD_WORKERS, len(results))) as ex:
|
|
160
|
+
futures = {
|
|
161
|
+
ex.submit(fetch_one_image, topic, i, r, out): i
|
|
162
|
+
for i, r in enumerate(results)
|
|
163
|
+
}
|
|
164
|
+
for fut in futures:
|
|
165
|
+
images[futures[fut]] = fut.result()
|
|
166
|
+
|
|
167
|
+
refs = []
|
|
168
|
+
for i, r in enumerate(results):
|
|
169
|
+
img_path, used_thumbnail = images.get(i, (None, False))
|
|
170
|
+
|
|
171
|
+
snippet = r.get("html_snippet")
|
|
172
|
+
snippet_path = None
|
|
173
|
+
if snippet:
|
|
174
|
+
snippet_path = str(out / f"{topic}_snippet_{i}.html")
|
|
175
|
+
Path(snippet_path).write_text(snippet, encoding="utf-8")
|
|
176
|
+
|
|
177
|
+
refs.append({
|
|
178
|
+
"topic": topic,
|
|
179
|
+
"index": i,
|
|
180
|
+
"title": r.get("title"),
|
|
181
|
+
"source_page": r.get("source_page"),
|
|
182
|
+
"image_url": r.get("url"),
|
|
183
|
+
"thumbnail_url": r.get("thumbnail") or None,
|
|
184
|
+
"local_image": img_path,
|
|
185
|
+
"local_image_is_thumbnail": used_thumbnail,
|
|
186
|
+
"description": r.get("description"),
|
|
187
|
+
"summary": r.get("summary"),
|
|
188
|
+
"html_snippet_file": snippet_path,
|
|
189
|
+
"width": r.get("width"),
|
|
190
|
+
"height": r.get("height"),
|
|
191
|
+
})
|
|
192
|
+
return refs
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def print_topic_report(topic, refs, heading):
|
|
196
|
+
print("=" * 64)
|
|
197
|
+
print(heading)
|
|
198
|
+
print("=" * 64)
|
|
199
|
+
if not refs:
|
|
200
|
+
print("(no results for this topic)")
|
|
201
|
+
return
|
|
202
|
+
for ref in refs:
|
|
203
|
+
i = ref["index"]
|
|
204
|
+
print(f"[{topic}:{i}] {ref.get('title') or '(untitled)'}")
|
|
205
|
+
print(f" source : {ref.get('source_page') or ref.get('image_url')}")
|
|
206
|
+
if ref.get("local_image"):
|
|
207
|
+
tag = " (thumbnail)" if ref.get("local_image_is_thumbnail") else ""
|
|
208
|
+
print(f" image : {ref['local_image']}{tag} <-- view this")
|
|
209
|
+
else:
|
|
210
|
+
print(f" image : (download failed) {ref.get('image_url')}")
|
|
211
|
+
if ref.get("description"):
|
|
212
|
+
print(f" desc : {ref['description']}")
|
|
213
|
+
if ref.get("summary"):
|
|
214
|
+
print(f" style : {ref['summary']}")
|
|
215
|
+
if ref.get("html_snippet_file"):
|
|
216
|
+
print(f" snippet: {ref['html_snippet_file']} <-- read it; use fully if detailed, else as structure only")
|
|
217
|
+
print("-" * 64)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def main():
|
|
221
|
+
parser = argparse.ArgumentParser(
|
|
222
|
+
description="Search UI design references via the octen.ai image-search API (design + general topics)."
|
|
223
|
+
)
|
|
224
|
+
parser.add_argument(
|
|
225
|
+
"query", nargs="?", default="",
|
|
226
|
+
help="Text query (<=500 chars). Describe the component AND its style/theme.",
|
|
227
|
+
)
|
|
228
|
+
parser.add_argument(
|
|
229
|
+
"--image",
|
|
230
|
+
help="Reference image for image-based search: local path (sent as base64) or public URL.",
|
|
231
|
+
)
|
|
232
|
+
parser.add_argument("--count", type=int, default=5, help="Number of results PER TOPIC, 1-100 (default 5).")
|
|
233
|
+
parser.add_argument(
|
|
234
|
+
"--topics", nargs="+", default=DEFAULT_TOPICS,
|
|
235
|
+
help="Topics to query (default: design general). design = curated UI corpus; general = broad web images.",
|
|
236
|
+
)
|
|
237
|
+
parser.add_argument(
|
|
238
|
+
"--max-snippet-tokens", type=int, default=5000,
|
|
239
|
+
help="Max tokens per html_snippet (default 5000; raise for complex components).",
|
|
240
|
+
)
|
|
241
|
+
parser.add_argument(
|
|
242
|
+
"--out", default="./.ui-refs",
|
|
243
|
+
help="Output directory for downloaded images, snippets, and results.json.",
|
|
244
|
+
)
|
|
245
|
+
args = parser.parse_args()
|
|
246
|
+
|
|
247
|
+
if not args.query and not args.image:
|
|
248
|
+
sys.exit("Provide a text query and/or --image.")
|
|
249
|
+
|
|
250
|
+
api_key = os.environ.get("OCTEN_API_KEY")
|
|
251
|
+
if not api_key:
|
|
252
|
+
sys.exit(
|
|
253
|
+
"OCTEN_API_KEY is not set. Export it before running "
|
|
254
|
+
"(do NOT paste the key into the chat)."
|
|
255
|
+
)
|
|
256
|
+
|
|
257
|
+
out = Path(args.out)
|
|
258
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
259
|
+
|
|
260
|
+
print(f"Query : {args.query or '[image search]'}")
|
|
261
|
+
print(f"Topics : {', '.join(args.topics)}")
|
|
262
|
+
|
|
263
|
+
octen_refs = []
|
|
264
|
+
per_topic = {}
|
|
265
|
+
for topic in args.topics:
|
|
266
|
+
raw = collect_topic(topic, args, api_key)
|
|
267
|
+
refs = process_topic(topic, raw, args, out)
|
|
268
|
+
per_topic[topic] = refs
|
|
269
|
+
octen_refs.extend(refs)
|
|
270
|
+
|
|
271
|
+
print(f"Results: {len(octen_refs)} total "
|
|
272
|
+
f"({', '.join(f'{t}={len(per_topic.get(t, []))}' for t in args.topics)})")
|
|
273
|
+
|
|
274
|
+
if not octen_refs:
|
|
275
|
+
print(
|
|
276
|
+
"NO RESULTS. Proceed using your own design judgment, tell the user no "
|
|
277
|
+
"reference was found, and consider broadening the query."
|
|
278
|
+
)
|
|
279
|
+
(out / "results.json").write_text(
|
|
280
|
+
json.dumps({"query": args.query, "topics": args.topics, "octen_refs": []},
|
|
281
|
+
ensure_ascii=False, indent=2)
|
|
282
|
+
)
|
|
283
|
+
return
|
|
284
|
+
|
|
285
|
+
headings = {
|
|
286
|
+
"design": "DESIGN refs (primary — structured summary + html_snippet)",
|
|
287
|
+
"general": "GENERAL refs (supplementary — visual inspiration only)",
|
|
288
|
+
}
|
|
289
|
+
# design first (primary), then general (supplementary), then any other topics.
|
|
290
|
+
ordered = [t for t in ("design", "general") if t in per_topic]
|
|
291
|
+
ordered += [t for t in args.topics if t not in ordered]
|
|
292
|
+
for topic in ordered:
|
|
293
|
+
print_topic_report(topic, per_topic.get(topic, []),
|
|
294
|
+
headings.get(topic, f"{topic.upper()} refs"))
|
|
295
|
+
|
|
296
|
+
(out / "results.json").write_text(
|
|
297
|
+
json.dumps({"query": args.query, "topics": args.topics, "octen_refs": octen_refs},
|
|
298
|
+
ensure_ascii=False, indent=2)
|
|
299
|
+
)
|
|
300
|
+
print(f"Manifest: {out / 'results.json'} (key: octen_refs)")
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
if __name__ == "__main__":
|
|
304
|
+
main()
|