Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat: automatic cluster labels for the image map

Lincoln Steind23c8bc4b6ba
diff --git a/invokeai/app/api/routers/image_map.py b/invokeai/app/api/routers/image_map.py
index 9d1eacb838..2384b95a54 100644
--- a/invokeai/app/api/routers/image_map.py
+++ b/invokeai/app/api/routers/image_map.py
@@ -61,6 +61,11 @@ class ImageMapPointsResponse(BaseModel):
description="The effective DBSCAN eps used for these points (adaptive default resolved, clamps applied). "
"Pass it back explicitly to get an identical clustering from a later request.",
)
+ visible_hash: Optional[str] = Field(
+ default=None,
+ description="Fingerprint of the visible image set these points were computed over; compare across "
+ "image-map responses to detect accessible-set drift between requests.",
+ )
updated_at: Optional[str] = Field(default=None, description="When the served projection was computed")
@@ -239,7 +244,7 @@ async def get_image_map_points(
# loop time per poll on a 500k-image gallery, stalling every other request
# in the process; the retry decision is made below instead, from the one
# fact it actually needs.
- def build_points() -> tuple[list[ImageMapPoint], Optional[float], bool]:
+ def build_points() -> tuple[list[ImageMapPoint], Optional[float], bool, str]:
accessible = set(current_names)
visible_mask = np.fromiter(
(name in accessible for name in record.image_names), dtype=bool, count=len(record.image_names)
@@ -269,6 +274,7 @@ async def get_image_map_points(
],
resolved_eps,
True,
+ scope_hash(model_id, visible_names),
)
try:
@@ -304,9 +310,10 @@ async def get_image_map_points(
],
resolved_eps,
bool(visible_mask.any()),
+ scope_hash(model_id, visible_names),
)
- points, resolved_eps, any_visible = await asyncio.to_thread(build_points)
+ points, resolved_eps, any_visible, visible_hash = await asyncio.to_thread(build_points)
retrying = False
if not stale and current_names and not any_visible:
@@ -325,6 +332,7 @@ async def get_image_map_points(
stale=stale,
point_count=len(points),
cluster_eps=resolved_eps,
+ visible_hash=visible_hash,
updated_at=record.updated_at,
)
@@ -619,6 +627,132 @@ async def search_image_map_by_image(
)
+class ImageMapClusterLabel(BaseModel):
+ """The best vocabulary label for one cluster."""
+
+ label: str = Field(description="Best-matching vocabulary phrase")
+ alternates: list[str] = Field(description="Runner-up phrases")
+ score: float = Field(description="Cosine similarity of the best phrase to the cluster centroid")
+
+
+class ImageMapClusterLabelsResponse(BaseModel):
+ """Automatic labels for the current user's visible clusters, keyed by cluster id."""
+
+ labels: dict[str, ImageMapClusterLabel] = Field(description="Cluster id -> label; noise (-1) is omitted")
+ visible_hash: Optional[str] = Field(
+ default=None,
+ description="Fingerprint of the visible image set these labels were clustered over; clients must discard "
+ "labels whose visible_hash does not match their points response",
+ )
+ updated_at: Optional[str] = Field(
+ default=None,
+ description="The projection these labels were computed against; clients must discard labels whose projection does not match their points",
+ )
+
+
+@image_map_router.get(
+ "/cluster_labels", operation_id="get_image_map_cluster_labels", response_model=ImageMapClusterLabelsResponse
+)
+async def get_image_map_cluster_labels(
+ current_user: CurrentUserOrDefault,
+ eps: Optional[float] = ClusterEpsQuery,
+ min_samples: int = ClusterMinSamplesQuery,
+ top_k: int = Query(default=3, ge=1, le=10, description="Candidate labels per cluster"),
+) -> ImageMapClusterLabelsResponse:
+ """Labels the user's visible clusters with the most similar vocabulary phrases.
+
+ Clustering mirrors `/points` (same eps semantics, computed over the
+ caller's currently-accessible points), so cluster ids line up with the
+ served map. Pass the `cluster_eps` reported by `/points` so both requests
+ cluster with the same eps; cluster ids can still differ if the accessible
+ set changes between the requests, so compare the two responses'
+ `visible_hash` (and `updated_at`) and discard labels on mismatch.
+ Requires the embedding model's text encoder; the first call per model
+ embeds the whole vocabulary and is slow.
+ """
+ from invokeai.app.services.image_index.cluster_labels import label_clusters
+
+ services = ApiDependencies.invoker.services
+ model_id = services.image_index.model_id
+ if model_id is None:
+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="The image index is not enabled")
+
+ user_id, is_admin = _scope(current_user)
+ record = services.image_index_records.get_projection(user_id, model_id)
+ if record is None or record.point_count == 0:
+ return ImageMapClusterLabelsResponse(labels={})
+
+ try:
+ vocabulary, vocab_embeddings = await asyncio.to_thread(services.image_index.get_vocab_embeddings)
+ except TextSearchUnavailableError as e:
+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
+
+ current_names = services.image_index_records.list_accessible_embedded_images(
+ None if is_admin else user_id, model_id
+ )
+
+ def build() -> tuple[dict[int, dict], str]:
+ accessible = set(current_names)
+ mask = np.fromiter(
+ (name in accessible for name in record.image_names), dtype=bool, count=len(record.image_names)
+ )
+ # Exactly the mask /points applies, non-finite filter included. Without
+ # it this endpoint's visible_hash is computed over a different set of
+ # names than the one /points reports, so every response the client
+ # receives fails the hash comparison it is told to make and all labels
+ # are discarded — and the clustering below is handed a NaN, which
+ # sklearn raises on, 500ing this user until their gallery changes.
+ mask &= np.isfinite(record.coords).all(axis=1)
+ visible_names = [name for name, keep in zip(record.image_names, mask, strict=True) if keep]
+ visible_hash = scope_hash(model_id, visible_names)
+ if not visible_names:
+ return {}, visible_hash
+ visible_coords = record.coords[mask]
+ try:
+ if 0 < visible_coords.shape[0] <= MAX_CLUSTERED_POINTS:
+ # cluster_at_eps on a resolved eps, matching /points: passing an
+ # already-resolved eps to compute_clusters re-resolves it, so
+ # the labels here could come from a different eps than the
+ # cluster_eps /points reported and the client passed back.
+ cluster_ids = cluster_at_eps(
+ visible_coords, resolve_cluster_eps(visible_coords, eps, min_samples), min_samples
+ )
+ else:
+ cluster_ids = compute_clusters(visible_coords, eps=eps, min_samples=min_samples)
+ except Exception:
+ # /points degrades to unclustered rather than 500ing; labels over no
+ # clusters is the same degradation, and the client already discards
+ # a label set whose visible_hash does not match its points.
+ services.logger.exception(f"Image map: clustering failed for user '{user_id}'; serving no labels")
+ return {}, visible_hash
+ cluster_by_name = dict(zip(visible_names, cluster_ids, strict=True))
+ # The accessible matrix comes from the same LRU the search endpoint
+ # uses — this endpoint fires after every points refresh, and a full
+ # BLOB read per request would not scale to large galleries.
+ accessible_names, accessible_matrix = services.image_index.get_accessible_embeddings(
+ None if is_admin else user_id
+ )
+ row_by_name = {name: index for index, name in enumerate(accessible_names)}
+ found_names = [name for name in visible_names if name in row_by_name]
+ if not found_names:
+ return {}, visible_hash
+ embeddings = accessible_matrix[[row_by_name[name] for name in found_names]]
+ aligned = np.fromiter((cluster_by_name[name] for name in found_names), dtype=np.int64, count=len(found_names))
+ return label_clusters(aligned, embeddings, vocabulary, vocab_embeddings, top_k=top_k), visible_hash
+
+ labels, visible_hash = await asyncio.to_thread(build)
+ return ImageMapClusterLabelsResponse(
+ labels={
+ str(cluster_id): ImageMapClusterLabel(
+ alternates=info["alternates"], label=info["label"], score=info["score"]
+ )
+ for cluster_id, info in labels.items()
+ },
+ visible_hash=visible_hash,
+ updated_at=record.updated_at,
+ )
+
+
@image_map_router.post(
"/refresh",
operation_id="refresh_image_map",
diff --git a/invokeai/app/services/image_index/cluster_labels.py b/invokeai/app/services/image_index/cluster_labels.py
new file mode 100644
index 0000000000..95b9a20549
--- /dev/null
+++ b/invokeai/app/services/image_index/cluster_labels.py
@@ -0,0 +1,132 @@
+"""Vocabulary-based automatic cluster labeling, ported from PhotoMapAI.
+
+Each vocabulary phrase is embedded through the index's text encoder with a
+prompt-template ensemble (the standard zero-shot CLIP recipe: encode every
+template, L2-normalize, mean-pool, re-normalize). A cluster's label is the
+vocabulary phrase most similar to the L2-normalized centroid of its members'
+image embeddings.
+"""
+
+import hashlib
+from pathlib import Path
+
+import numpy as np
+
+from invokeai.app.services.image_index.image_index_common import EMBEDDING_DTYPE
+
+# Photo-heavy with a few non-photo templates so AI-generated drawings and
+# paintings score reasonably too (PhotoMapAI's ensemble).
+PROMPT_TEMPLATES: tuple[str, ...] = (
+ "a photo of a {}",
+ "a photo of the {}",
+ "a picture of {}",
+ "an image of {}",
+ "a drawing of {}",
+ "a painting of {}",
+ "{}",
+)
+
+_VOCAB_PATH = Path(__file__).parent / "cluster_vocab.txt"
+
+
+def load_vocabulary() -> list[str]:
+ """Load the bundled labeling vocabulary (deduplicated, order-preserving)."""
+ phrases: list[str] = []
+ seen: set[str] = set()
+ for line in _VOCAB_PATH.read_text(encoding="utf-8").splitlines():
+ phrase = line.strip()
+ if not phrase or phrase.startswith("#"):
+ continue
+ key = phrase.casefold()
+ if key in seen:
+ continue
+ seen.add(key)
+ phrases.append(phrase)
+ return phrases
+
+
+# Bump when the text-embedding recipe changes (tokenization/padding/pooling):
+# cached phrase embeddings computed under an old recipe must be discarded.
+_EMBEDDING_RECIPE = "pad-per-model-v2"
+
+
+def vocab_fingerprint(phrases: list[str]) -> str:
+ """Content hash of the vocabulary + templates + embedding recipe."""
+ digest = hashlib.sha256()
+ digest.update(_EMBEDDING_RECIPE.encode("utf-8"))
+ digest.update(b"\x00")
+ for template in PROMPT_TEMPLATES:
+ digest.update(template.encode("utf-8"))
+ digest.update(b"\x00")
+ for phrase in phrases:
+ digest.update(phrase.encode("utf-8"))
+ digest.update(b"\x00")
+ return digest.hexdigest()
+
+
+def ensemble_phrase_embeddings(embed_texts, phrases: list[str], batch_size: int = 64) -> np.ndarray:
+ """Embed phrases through every prompt template and mean-pool.
+
+ Args:
+ embed_texts: Callable[[list[str]], np.ndarray] returning (N, D)
+ L2-normalized embeddings.
+ phrases: Vocabulary phrases.
+ batch_size: Phrases per encoder call (each batch encodes
+ batch_size * len(PROMPT_TEMPLATES) strings).
+
+ Returns:
+ (len(phrases), D) float32, L2-normalized.
+ """
+ vectors: list[np.ndarray] = []
+ for start in range(0, len(phrases), batch_size):
+ batch = phrases[start : start + batch_size]
+ texts = [template.format(phrase) for phrase in batch for template in PROMPT_TEMPLATES]
+ embedded = np.asarray(embed_texts(texts), dtype=EMBEDDING_DTYPE)
+ per_phrase = embedded.reshape(len(batch), len(PROMPT_TEMPLATES), -1).mean(axis=1)
+ vectors.append(per_phrase)
+ matrix = np.concatenate(vectors) if vectors else np.empty((0, 0), dtype=EMBEDDING_DTYPE)
+ norms = np.linalg.norm(matrix, axis=1, keepdims=True)
+ norms[norms == 0] = 1.0
+ return (matrix / norms).astype(EMBEDDING_DTYPE)
+
+
+def label_clusters(
+ cluster_labels: np.ndarray,
+ image_embeddings: np.ndarray,
+ vocabulary: list[str],
+ vocab_embeddings: np.ndarray,
+ top_k: int = 3,
+) -> dict[int, dict]:
+ """Top-k vocabulary labels for every non-noise cluster.
+
+ Args:
+ cluster_labels: (N,) DBSCAN labels, row-aligned with image_embeddings.
+ image_embeddings: (N, D) L2-normalized image embeddings.
+ vocabulary: Phrases, row-aligned with vocab_embeddings.
+ vocab_embeddings: (V, D) L2-normalized phrase embeddings.
+ top_k: Number of candidate labels per cluster.
+
+ Returns:
+ {cluster_id: {"label": str, "alternates": [str], "score": float}};
+ noise (-1) is omitted.
+ """
+ results: dict[int, dict] = {}
+ for cluster_id in sorted({int(label) for label in cluster_labels if label >= 0}):
+ members = image_embeddings[cluster_labels == cluster_id]
+ if members.shape[0] == 0:
+ continue
+ centroid = members.mean(axis=0)
+ norm = np.linalg.norm(centroid)
+ if norm == 0:
+ continue
+ centroid = centroid / norm
+ scores = vocab_embeddings @ centroid.astype(vocab_embeddings.dtype)
+ count = min(top_k, len(vocabulary))
+ top = np.argpartition(-scores, count - 1)[:count]
+ top = top[np.argsort(-scores[top])]
+ results[cluster_id] = {
+ "alternates": [vocabulary[index] for index in top[1:]],
+ "label": vocabulary[top[0]],
+ "score": float(scores[top[0]]),
+ }
+ return results
diff --git a/invokeai/app/services/image_index/cluster_vocab.txt b/invokeai/app/services/image_index/cluster_vocab.txt
new file mode 100644
index 0000000000..02440f4dd5
--- /dev/null
+++ b/invokeai/app/services/image_index/cluster_vocab.txt
@@ -0,0 +1,1694 @@
+# Cluster-labeling vocabulary for PhotoMapAI.
+# Auto-generated by scripts/build_vocab.py — do NOT edit auto sections by hand.
+# Hand-curated additions go below the CURATED sentinel line and are preserved
+# across re-runs of the build script.
+
+# === Places365 (CSAILVision/places365, CC) ===
+airfield
+airplane cabin
+airport terminal
+alcove
+alley
+amphitheater
+amusement arcade
+amusement park
+aquarium
+aqueduct
+arcade
+arch
+archaelogical excavation
+archive
+army base
+art gallery
+art school
+art studio
+artists loft
+asia temple
+assembly line
+attic
+auditorium
+auto factory
+auto showroom
+badlands
+ball pit
+ballroom
+bamboo forest
+bank vault
+banquet hall
+bar
+barn
+barndoor
+baseball field
+baseball stadium
+basement
+bathroom
+beach
+beach house
+beauty salon
+bedchamber
+bedroom
+beer garden
+beer hall
+berth
+biology laboratory
+boardwalk
+boat deck
+boathouse
+bookstore
+botanical garden
+bowling alley
+boxing ring
+bridge
+broadleaf forest
+building facade
+bullring
+burial chamber
+bus interior
+butchers shop
+butte
+cafeteria
+campsite
+campus
+candy store
+canyon
+car interior
+carrousel
+castle
+catacomb
+cemetery
+chalet
+chemistry lab
+childs room
+classroom
+clean room
+cliff
+closet
+clothing store
+coast
+cockpit
+coffee shop
+computer room
+conference center
+conference room
+construction site
+corn field
+corral
+corridor
+cottage
+courthouse
+courtyard
+creek
+crevasse
+crosswalk
+cultivated field
+dam
+delicatessen
+department store
+desert road
+dining hall
+dining room
+discotheque
+door elevator
+dorm room
+downtown
+dressing room
+driveway
+drugstore
+elevator lobby
+elevator shaft
+embassy
+engine room
+entrance hall
+excavation
+exterior balcony
+exterior gazebo
+fabric store
+farm
+fastfood restaurant
+field road
+fire escape
+fire station
+fishpond
+food court
+football field
+football stadium
+forest path
+forest road
+formal garden
+fountain
+galley
+gas station
+gift shop
+glacier
+golf course
+grotto
+harbor
+hardware store
+hayfield
+heliport
+highway
+hockey arena
+home office
+home theater
+hospital
+hospital room
+hot spring
+hotel room
+house
+ice cream parlor
+ice floe
+ice shelf
+iceberg
+igloo
+indoor basketball court
+indoor bazaar
+indoor booth
+indoor bow window
+indoor bus station
+indoor church
+indoor escalator
+indoor flea market
+indoor florist shop
+indoor garage
+indoor general store
+indoor greenhouse
+indoor gymnasium
+indoor hangar
+indoor ice skating rink
+indoor jacuzzi
+indoor library
+indoor market
+indoor movie theater
+indoor museum
+indoor parking garage
+indoor pub
+indoor shopping mall
+indoor stage
+indoor swimming pool
+industrial area
+interior balcony
+islet
+jail cell
+japanese garden
+jewelry shop
+junkyard
+kasbah
+kindergarden classroom
+kitchen
+lagoon
+landfill
+landing deck
+laundromat
+lawn
+lecture room
+legislative chamber
+lighthouse
+living room
+loading dock
+lobby
+lock chamber
+locker room
+mansion
+manufactured home
+marsh
+martial arts gym
+mausoleum
+medina
+mezzanine
+motel
+mountain
+mountain path
+mountain snowy
+music studio
+natural canal
+natural history museum
+natural lake
+nursery
+nursing home
+oast house
+ocean
+ocean deep underwater
+office
+office building
+office cubicles
+oilrig
+operating room
+orchard
+orchestra pit
+outdoor apartment building
+outdoor athletic field
+outdoor bazaar
+outdoor cabin
+outdoor church
+outdoor diner
+outdoor doorway
+outdoor garage
+outdoor general store
+outdoor greenhouse
+outdoor hangar
+outdoor hotel
+outdoor hunting lodge
+outdoor ice skating rink
+outdoor inn
+outdoor kennel
+outdoor library
+outdoor market
+outdoor mosque
+outdoor museum
+outdoor parking garage
+outdoor stage
+outdoor swimming pool
+outdoor synagogue
+outdoor volleyball court
+pagoda
+palace
+pantry
+park
+parking lot
+pasture
+patio
+pavilion
+performance arena
+pet shop
+pharmacy
+phone booth
+physics laboratory
+picnic area
+pier
+pizzeria
+platform subway station
+platform train station
+playground
+playroom
+plaza
+pond
+porch
+promenade
+public atrium
+racecourse
+raceway
+raft
+railroad track
+rainforest
+reception
+recreation room
+repair shop
+residential neighborhood
+restaurant
+restaurant kitchen
+restaurant patio
+rice paddy
+river
+rock arch
+rodeo arena
+roof garden
+rope bridge
+ruin
+runway
+sand desert
+sandbox
+sauna
+schoolhouse
+science museum
+server room
+shed
+shoe shop
+shop bakery
+shopfront
+shower
+ski resort
+ski slope
+sky
+skyscraper
+slum
+snowfield
+soccer field
+soccer stadium
+stable
+staircase
+storage room
+street
+supermarket
+sushi bar
+swamp
+swimming hole
+television room
+television studio
+throne room
+ticket booth
+topiary garden
+tower
+toyshop
+train interior
+tree farm
+tree house
+trench
+tundra
+urban canal
+utility room
+valley
+vegetable garden
+vegetation desert
+veterinarians office
+viaduct
+village
+vineyard
+volcano
+waiting room
+water moat
+water park
+water tower
+waterfall
+watering hole
+wave
+wet bar
+wheat field
+wild field
+wind farm
+windmill
+yard
+youth hostel
+zen garden
+
+# === OpenImages V7 boxable (Google, CC-BY 4.0) ===
+accordion
+adhesive tape
+aircraft
+alarm clock
+alpaca
+ambulance
+animal
+ant
+antelope
+apple
+armadillo
+artichoke
+auto part
+axe
+backpack
+bagel
+baked goods
+balance beam
+ball (object)
+balloon
+banana
+band-aid
+banjo
+barge
+barrel
+baseball bat
+baseball glove
+bat (animal)
+bathroom accessory
+bathroom cabinet
+bathtub
+beaker
+bear
+beard
+bed
+bee
+beehive
+beer
+beetle
+bell pepper
+belt
+bench
+bicycle
+bicycle helmet
+bicycle wheel
+bidet
+billboard
+billiard table
+binoculars
+bird
+blender
+blue jay
+boat
+bomb
+book
+bookcase
+boot
+bottle
+bottle opener
+bow and arrow
+bowl
+bowling equipment
+box
+boy
+brassiere
+bread
+briefcase
+broccoli
+bronze sculpture
+brown bear
+building
+bull
+burrito
+bus
+bust
+butterfly
+cabbage
+cabinetry
+cake
+cake stand
+calculator
+camel
+camera
+can opener
+canary
+candle
+candy
+cannon
+canoe
+cantaloupe
+car
+carnivore
+carrot
+cart
+cassette deck
+cat
+cat furniture
+caterpillar
+cattle
+ceiling fan
+cello
+centipede
+chainsaw
+chair
+cheese
+cheetah
+chest of drawers
+chicken
+chime
+chisel
+chopsticks
+christmas tree
+clock
+clothing
+coat
+cocktail
+cocktail shaker
+coconut
+coffee (drink)
+coffee cup
+coffee table
+coffeemaker
+coin
+common fig
+common sunflower
+computer keyboard
+computer monitor
+computer mouse
+container
+convenience store
+cookie
+cooking spray
+corded phone
+cosmetics
+couch
+countertop
+cowboy hat
+crab
+cream
+cricket ball
+crocodile
+croissant
+crown
+crutch
+cucumber
+cupboard
+curtain
+cutting board
+dagger
+dairy product
+deer
+desk
+dessert
+diaper
+dice
+digital clock
+dinosaur
+dishwasher
+dog
+dog bed
+doll
+dolphin
+door
+door handle
+doughnut
+dragonfly
+drawer
+dress
+drill (tool)
+drink
+drinking straw
+drum
+duck
+dumbbell
+eagle
+earring
+egg
+elephant
+envelope
+eraser
+face powder
+facial tissue holder
+falcon
+fashion accessory
+fast food
+fax
+fedora
+filing cabinet
+fire hydrant
+fireplace
+fish
+fixed-wing aircraft
+flag
+flashlight
+flower
+flowerpot
+flute
+flying disc
+food
+food processor
+football
+football helmet
+footwear
+fork
+fox
+french fries
+french horn
+frog
+fruit
+frying pan
+furniture
+garden asparagus
+gas stove
+giraffe
+girl
+glasses
+glove
+goat
+goggles
+goldfish
+golf ball
+golf cart
+gondola
+goose
+grape
+grapefruit
+grinder
+guacamole
+guitar
+hair dryer
+hair spray
+hamburger
+hammer
+hamster
+hand dryer
+handbag
+handgun
+harbor seal
+harmonica
+harp
+harpsichord
+hat
+headphones
+heater
+hedgehog
+helicopter
+helmet
+high heels
+hiking equipment
+hippopotamus
+home appliance
+honeycomb
+horizontal bar
+horse
+hot dog
+houseplant
+human arm
+human body
+human ear
+human eye
+human face
+human foot
+human hair
+human hand
+human head
+human leg
+human mouth
+human nose
+humidifier
+ice cream
+indoor rower
+infant bed
+insect
+invertebrate
+ipod
+isopod
+jacket
+jacuzzi
+jaguar (animal)
+jeans
+jellyfish
+jet ski
+jug
+juice
+kangaroo
+kettle
+kitchen & dining room table
+kitchen appliance
+kitchen knife
+kitchen utensil
+kitchenware
+kite
+knife
+koala
+ladder
+ladle
+ladybug
+lamp
+land vehicle
+lantern
+laptop
+lavender (plant)
+lemon (plant)
+leopard
+light bulb
+light switch
+lily
+limousine
+lion
+lipstick
+lizard
+lobster
+loveseat
+luggage and bags
+lynx
+magpie
+mammal
+man
+mango
+maple
+maraca
+marine invertebrates
+marine mammal
+measuring cup
+mechanical fan
+medical equipment
+microphone
+microwave oven
+milk
+miniskirt
+mirror
+missile
+mixer
+mixing bowl
+mobile phone
+monkey
+moths and butterflies
+motorcycle
+mouse
+muffin
+mug
+mule
+mushroom
+musical instrument
+musical keyboard
+nail (construction)
+necklace
+nightstand
+oboe
+office supplies
+orange (fruit)
+organ (musical instrument)
+ostrich
+otter
+oven
+owl
+oyster
+paddle
+palm tree
+pancake
+panda
+paper cutter
+paper towel
+parachute
+parking meter
+parrot
+pasta
+pastry
+peach
+pear
+pen
+pencil case
+pencil sharpener
+penguin
+perfume
+person
+personal care
+personal flotation device
+piano
+picnic basket
+picture frame
+pig
+pillow
+pineapple
+pitcher (container)
+pizza
+pizza cutter
+plant
+plastic bag
+plate
+platter
+plumbing fixture
+polar bear
+pomegranate
+popcorn
+porcupine
+poster
+potato
+power plugs and sockets
+pressure cooker
+pretzel
+printer
+pumpkin
+punching bag
+rabbit
+raccoon
+racket
+radish
+ratchet (device)
+raven
+rays and skates
+red panda
+refrigerator
+remote control
+reptile
+rhinoceros
+rifle
+ring binder
+rocket
+roller skates
+rose
+rugby ball
+ruler
+salad
+salt and pepper shakers
+sandal
+sandwich
+saucer
+saxophone
+scale
+scarf
+scissors
+scoreboard
+scorpion
+screwdriver
+sculpture
+sea lion
+sea turtle
+seafood
+seahorse
+seat belt
+segway
+serving tray
+sewing machine
+shark
+sheep
+shelf
+shellfish
+shirt
+shorts
+shotgun
+shrimp
+sink
+skateboard
+ski
+skirt
+skull
+skunk
+slow cooker
+snack
+snail
+snake
+snowboard
+snowman
+snowmobile
+snowplow
+soap dispenser
+sock
+sofa bed
+sombrero
+sparrow
+spatula
+spice rack
+spider
+spoon
+sports equipment
+sports uniform
+squash (plant)
+squid
+squirrel
+stairs
+stapler
+starfish
+stationary bicycle
+stethoscope
+stool
+stop sign
+strawberry
+street light
+stretcher
+studio couch
+submarine
+submarine sandwich
+suit
+suitcase
+sun hat
+sunglasses
+surfboard
+sushi
+swan
+swim cap
+swimming pool
+swimwear
+sword
+syringe
+table
+table tennis racket
+tablet computer
+tableware
+taco
+tank
+tap
+tart
+taxi
+tea
+teapot
+teddy bear
+telephone
+television
+tennis ball
+tennis racket
+tent
+tiara
+tick
+tie
+tiger
+tin can
+tire
+toaster
+toilet
+toilet paper
+tomato
+tool
+toothbrush
+torch
+tortoise
+towel
+toy
+traffic light
+traffic sign
+train
+training bench
+treadmill
+tree
+tripod
+trombone
+trousers
+truck
+trumpet
+turkey
+turtle
+umbrella
+unicycle
+van
+vase
+vegetable
+vehicle
+vehicle registration plate
+violin
+volleyball (ball)
+waffle
+waffle iron
+wall clock
+wardrobe
+washing machine
+waste container
+watch
+watercraft
+watermelon
+weapon
+whale
+wheel
+wheelchair
+whisk
+whiteboard
+willow
+window
+window blind
+wine
+wine glass
+wine rack
+winter melon
+wok
+woman
+wood-burning stove
+woodpecker
+worm
+wrench
+zebra
+zucchini
+
+# === OpenImages V7 top-1000 by validation-set human-verified frequency (Google, CC-BY 4.0) ===
+abdomen
+active undergarment
+adolescent
+adult
+adventure
+advertising
+aeolian landform
+aerial photography
+aerospace engineering
+agriculture
+air force
+air show
+air sports
+air travel
+aircraft engine
+airline
+airliner
+airplane
+alcoholic beverage
+amber (color)
+amphibian
+ancient history
+ancient roman architecture
+animal sports
+annual plant
+antique
+antique car
+aqua
+archaeological site
+architecture
+arecales
+army
+art
+arthropod
+asphalt
+astronomical object
+astronomy
+athlete
+athletics
+audi
+audience
+auto racing
+auto show
+automotive design
+automotive exterior
+automotive tire
+aviation
+azure
+baby
+backyard
+bag
+baking
+ball game
+bangs
+banner
+barechested
+baseball (sport)
+basket
+bat-and-ball games
+bay
+beak
+beauty
+bedrock
+beige
+bell peppers and chili peppers
+berry
+bicycle frame
+bicycle racing
+big cats
+bikini
+biome
+bird of prey
+birthday cake
+bitter orange
+bivalve
+black
+black hair
+black-and-white
+blond
+blossom
+blue
+bmw (brand)
+board game
+boardsport
+boating
+body of water
+bouquet
+bovine
+branch
+brand
+brass instrument
+breakfast
+brick
+bridge (structure)
+brown
+brown hair
+brunch
+bucatini
+bud
+bulldog
+bumper
+buttercream
+button
+cactus
+cadillac (brand)
+caffeine
+caffè macchiato
+café au lait
+cage
+cake decorating
+camera lens
+cameras & optics
+canal
+cap
+cappuccino
+carbonara
+carpet
+cartoon
+carving
+cave
+ceiling
+ceramic
+championship
+channel
+charadriiformes
+cheek
+chevrolet
+child
+chili pepper
+chin
+chinese noodles
+chocolate
+chocolate cake
+chordophone
+choreography
+chow mein
+ciabatta
+circle
+citrus
+city
+city car
+classic car
+classical music
+clergy
+close-up
+cloud
+cockapoo
+cocktail dress
+coffee milk
+cold weapon
+collage
+collar (apparel)
+college baseball
+column
+combat sport
+commercial vehicle
+communication device
+compact car
+compact sport utility vehicle
+competition event
+computer hardware
+concept car
+confectionery
+contact sport
+convertible
+cookies and crackers
+cooking
+coral
+coral reef
+coral reef fish
+costume
+coupé
+cream (drink)
+crop (plant)
+crossover suv
+crowd
+crustacean
+cuisine
+cup
+currency
+curry
+cycle sport
+cycling
+dance
+danish pastry
+darkness
+decor
+desert
+design
+diagram
+digital camera
+dinner
+dish
+display device
+distilled beverage
+document
+dog breed
+dog sports
+domestic long-haired cat
+domestic rabbit
+domestic short-haired cat
+drawing
+drinkware
+duathlon
+east siberian laika
+education
+electricity
+electronic device
+electronic instrument
+electronics
+emberizidae
+endurance sports
+english bulldog
+entertainment
+equestrian sport
+equestrianism
+espresso
+estate
+european shorthair
+evening
+event
+evergreen
+executive car
+exercise
+exhibition
+extreme sport
+eyebrow
+eyelash
+facade
+facial hair
+factory
+family car
+fashion
+fashion design
+fauna
+fell
+fence
+ferrari s.p.a.
+festival
+fictional character
+field
+fighter aircraft
+figurine
+finch
+finger
+fire
+firearm
+fish (food)
+fishing
+flame
+flatbread
+flight
+flightless bird
+floor
+flooring
+flora
+floral design
+floribunda
+floristry
+flower arranging
+flowering plant
+font
+food grain
+football player
+ford
+forehead
+forest
+formal wear
+formation
+fowl
+freezing
+fried food
+frigate
+full-size car
+fungus
+gadget
+galliformes
+game
+garden
+garden roses
+gemstone
+geology
+glacial landform
+glass
+glass bottle
+glen of imaal terrier
+golf
+gown
+grass
+grass family
+grassland
+gravy
+grazing
+green
+greenland dog
+grey
+grille
+grilling
+grocery store
+guard dog
+gun
+hair coloring
+hairstyle
+handwriting
+hardwood
+hatchback
+havanese
+headgear
+helicopter rotor
+heptathlon
+herb
+herd
+highland
+hill
+historic site
+history
+hockey
+home
+honda
+horizon
+horn (animal)
+horse harness
+hot rod
+hound
+human
+hut
+ice
+ice skating
+icing
+illustration
+individual sport
+indoor games and sports
+industry
+infrastructure
+interaction
+interior design
+iron (material)
+island
+jar
+jeep
+jet aircraft
+jewellery
+jungle
+junk food
+keyboard
+kitten
+labrador retriever
+lady
+lake
+lamborghini
+lamborghini (brand)
+landmark
+landscape
+lane
+latte
+lavender (color)
+layered hair
+leaf
+leaf vegetable
+learning
+leather
+leg
+leisure
+light
+light aircraft
+light commercial vehicle
+light fixture
+lighting
+lilac (color)
+limb
+line
+lip
+liqueur
+loch
+logo
+long hair
+lunch
+luxury vehicle
+machine
+macro photography
+magenta
+male person
+mane
+map
+mare
+marine biology
+market
+marketplace
+maroon
+martial arts
+mask
+mast
+meadow
+meal
+meat
+medical
+medicinal mushroom
+membrane-winged insect
+mercedes-benz
+metal
+metropolitan area
+microcontroller
+mid-size car
+military
+military aircraft
+military helicopter
+military officer
+military person
+military vehicle
+miniature poodle
+minibus
+mode of transport
+model
+model car
+modern art
+modern dance
+molluscs
+monastery
+money
+monochrome
+monochrome photography
+monoplane
+monument
+morning
+motor ship
+motor vehicle
+motorcycling
+motorsport
+mountain range
+multimedia
+muscle
+muscle car
+music
+musical theatre
+musician
+mythology
+nail (body part)
+narrow-body aircraft
+natural environment
+nature
+nature reserve
+naval ship
+navy
+neck
+neighbourhood
+new world monkey
+night
+nissan
+noodle
+noodle soup
+number
+off-road vehicle
+off-roading
+official
+old english bulldog
+old world monkey
+open-wheel car
+orange (color)
+organ (biology)
+organism
+outdoor recreation
+outdoor shoe
+outdoor structure
+outer space
+outerwear
+pack animal
+paint
+painting
+paper
+pattern
+people
+perching bird
+percussion
+performance
+performance art
+performance car
+performing arts
+personal computer hardware
+personal luxury car
+personal protective equipment
+pest
+pet
+petal
+photo shoot
+photograph
+physical fitness
+pickup truck
+pink
+pizza cheese
+place of worship
+plain
+plant stem
+plantation
+plateau
+play
+player
+pollinator
+poodle crossbreed
+porcelain
+porsche
+portrait
+portrait photography
+prairie
+priest
+produce
+propeller (aircraft)
+propeller-driven aircraft
+property
+public space
+public transport
+puppy
+purple
+rabbits and hares
+race car
+race track
+racing
+racquet sport
+railway
+rallycross
+rallying
+rapid
+real estate
+recreation
+recreational fishing
+red
+reef
+reflection
+reflex camera
+rein
+religion
+reservoir
+residential area
+retail
+rice
+ridge
+rim
+road
+road bicycle
+road cycling
+road surface
+roasting
+rock
+rodent
+rolling stock
+roof
+room
+rope
+ruins
+running
+runway (aviation)
+rural area
+saarlooswolfdog
+safari
+sail
+sailboat
+sailing
+sailing ship
+sand
+savanna
+scaled reptile
+schnoodle
+screenshot
+sea
+seabird
+sedan
+senior citizen
+shack
+shell
+ship
+shoe
+shooting
+shore
+shorebird
+shrub (plant)
+sign
+signage
+silver
+sirloin steak
+sitting
+skating
+sketch
+skin
+sleeve
+small to medium-sized cats
+smartphone
+smile
+smoke
+sneakers
+snout
+snow
+soccer
+social group
+soft drink
+soil
+soldier
+soup
+space
+spaghetti
+spaghetti aglio e olio
+spaniel
+speech
+speedboat
+sport utility vehicle
+sports
+sports car
+sports sedan
+sports venue
+spring (season)
+stadium
+stage
+stallion
+star
+statue
+steak
+steamed rice
+steppe
+stew
+stick and ball games
+stock car racing
+stone carving
+stream
+string instrument
+subcompact car
+subshrub
+sugar paste
+summit
+sunlight
+supercar
+supermini
+supper
+surface water sports
+sweetness
+swimmer
+swimming
+symbol
+symmetry
+t-shirt
+tabby cat
+tabletop game
+takeoff
+tan
+tarmac
+team
+team sport
+temple
+temple (body part)
+tennis
+terrain
+terrier
+text
+textile
+thigh
+thorax
+tile
+toddler
+toe
+torso
+tourism
+tourist attraction
+tournament
+town
+toyota
+track
+track and field athletics
+tractor
+tradition
+transport
+troop
+trunk (tree)
+twig
+ultralight aviation
+undergarment
+underwater
+uniform
+vacation
+vegetarian food
+vegetation
+vintage car
+violet (color)
+volkswagen
+volkswagen golf
+volvo cars
+wadi
+walking
+walkway
+wall
+water
+water bird
+water feature
+water sport
+watercourse
+watercraft rowing
+waterway
+wave (noun)
+wetland
+whipped cream
+whiskers
+white
+wide-body aircraft
+wild cat
+wilderness
+wildflower
+wildlife
+wind
+wind instrument
+wind wave
+windsport
+wing
+winter
+winter sport
+wire
+wolfdog
+wood
+wood stain
+woodland
+wool
+writing
+yellow
+youth
+zoo
+
+# End users who installed via pip can add extra phrases without editing
+# this file by creating cluster_vocab_extra.txt in the photomap config
+# directory (e.g. ~/.config/photomap/ on Linux, sibling of config.yaml).
+
+
+# Hand-added phrases below the next line are preserved across re-runs. One phrase per line, lowercase; empty lines and # comments are OK.
+# CURATED LABELS
+
diff --git a/invokeai/app/services/image_index/image_index_base.py b/invokeai/app/services/image_index/image_index_base.py
index 25f9f9e000..ba43450c0a 100644
--- a/invokeai/app/services/image_index/image_index_base.py
+++ b/invokeai/app/services/image_index/image_index_base.py
@@ -69,6 +69,19 @@ class ImageIndexServiceBase(ABC):
"""
pass
+ @abstractmethod
+ def get_vocab_embeddings(self) -> tuple[list[str], np.ndarray]:
+ """Get the cluster-labeling vocabulary and its phrase embeddings.
+
+ Slow on the first call per model (the whole vocabulary is embedded
+ through the text tower, then disk-cached); cheap afterwards. Call off
+ the event loop.
+
+ Raises:
+ TextSearchUnavailableError: No usable text encoder is installed.
+ """
+ pass
+
@abstractmethod
def search_similar(self, user_id: str | None, query_embedding: np.ndarray, limit: int) -> list[tuple[str, float]]:
"""Rank the user's accessible embedded images by cosine similarity.
diff --git a/invokeai/app/services/image_index/image_index_default.py b/invokeai/app/services/image_index/image_index_default.py
index 0132a6e946..ecf707687e 100644
--- a/invokeai/app/services/image_index/image_index_default.py
+++ b/invokeai/app/services/image_index/image_index_default.py
@@ -170,6 +170,9 @@ class ImageIndexService(ImageIndexServiceBase):
# similarity search, so repeated queries skip re-reading BLOBs.
self._search_cache: dict[str, tuple[list[str], np.ndarray]] = {}
self._search_cache_lock = threading.Lock()
+ # (vocabulary, embeddings) for cluster labeling; RAM + disk cached.
+ self._vocab_cache: Optional[tuple[list[str], np.ndarray]] = None
+ self._vocab_lock = threading.Lock()
@property
def model_id(self) -> str | None:
@@ -203,6 +206,10 @@ class ImageIndexService(ImageIndexServiceBase):
return _normalize_query_vector(matrix[0])
def embed_text(self, text: str) -> np.ndarray:
+ return self._embed_texts([text])[0]
+
+ def _embed_texts(self, texts: list[str]) -> np.ndarray:
+ """Batched text embedding, (N, D) L2-normalized."""
if self._model_id is None:
raise TextSearchUnavailableError("The image index is not running")
@@ -210,13 +217,55 @@ class ImageIndexService(ImageIndexServiceBase):
with torch.no_grad():
# SigLIP was trained with pad-to-max-length; pad-to-longest degrades
# its text embeddings. CLIP uses ordinary longest-padding.
- inputs = tokenizer(
- [text], padding="max_length" if is_siglip else True, return_tensors="pt", truncation=True
- )
+ inputs = tokenizer(texts, padding="max_length" if is_siglip else True, return_tensors="pt", truncation=True)
outputs = model(**inputs)
- embedding = outputs.pooler_output[0] if is_siglip else outputs.text_embeds[0]
- vector = embedding.float().cpu().numpy()
- return _normalize_query_vector(vector)
+ embeddings = outputs.pooler_output if is_siglip else outputs.text_embeds
+ matrix = embeddings.float().cpu().numpy()
+ # Row by row through the shared guard rather than a bulk float32 divide:
+ # that computes the norm in float64 and refuses a zero or non-finite one
+ # instead of quietly emitting a NaN row, which would go on to score NaN
+ # against everything it is compared with.
+ return np.stack([_normalize_query_vector(row) for row in matrix])
+
+ def get_vocab_embeddings(self) -> tuple[list[str], np.ndarray]:
+ from invokeai.app.services.image_index.cluster_labels import (
+ ensemble_phrase_embeddings,
+ load_vocabulary,
+ vocab_fingerprint,
+ )
+
+ with self._vocab_lock:
+ if self._vocab_cache is not None:
+ return self._vocab_cache
+ if self._invoker is None or self._model_id is None:
+ raise TextSearchUnavailableError("The image index is not running")
+
+ vocabulary = load_vocabulary()
+ fingerprint = vocab_fingerprint(vocabulary)
+ # The model hash contains ':' (e.g. 'blake3:...'), illegal in
+ # Windows filenames.
+ model_tag = self._model_id.replace(":", "_")[:24]
+ cache_path = self._invoker.services.configuration.db_path.parent / f"cluster_vocab_{model_tag}.npz"
+
+ if cache_path.exists():
+ try:
+ cached = np.load(cache_path, allow_pickle=False)
+ if str(cached["fingerprint"]) == fingerprint:
+ self._vocab_cache = (vocabulary, cached["embeddings"].astype(EMBEDDING_DTYPE))
+ return self._vocab_cache
+ except Exception:
+ self._invoker.services.logger.warning("Discarding unreadable cluster vocabulary cache")
+
+ # First run for this model: embedding ~1700 phrases x 7 templates
+ # takes tens of seconds — hence the disk cache.
+ embeddings = ensemble_phrase_embeddings(self._embed_texts, vocabulary)
+ try:
+ cache_path.parent.mkdir(parents=True, exist_ok=True)
+ np.savez(cache_path, embeddings=embeddings, fingerprint=np.str_(fingerprint))
+ except Exception:
+ self._invoker.services.logger.warning(f"Could not write cluster vocabulary cache to {cache_path}")
+ self._vocab_cache = (vocabulary, embeddings)
+ return self._vocab_cache
def _get_text_encoder(self) -> tuple[Any, Any, bool]:
with self._text_encoder_lock:
diff --git a/invokeai/frontend/web/openapi.json b/invokeai/frontend/web/openapi.json
index 8373ff21da..39a2498253 100644
--- a/invokeai/frontend/web/openapi.json
+++ b/invokeai/frontend/web/openapi.json
@@ -6598,6 +6598,91 @@
}
}
},
+ "/api/v1/image_map/cluster_labels": {
+ "get": {
+ "tags": ["image_map"],
+ "summary": "Get Image Map Cluster Labels",
+ "description": "Labels the user's visible clusters with the most similar vocabulary phrases.\n\nClustering mirrors `/points` (same eps semantics, computed over the\ncaller's currently-accessible points), so cluster ids line up with the\nserved map. Pass the `cluster_eps` reported by `/points` so both requests\ncluster with the same eps; cluster ids can still differ if the accessible\nset changes between the requests, so compare the two responses'\n`visible_hash` (and `updated_at`) and discard labels on mismatch.\nRequires the embedding model's text encoder; the first call per model\nembeds the whole vocabulary and is slow.",
+ "operationId": "get_image_map_cluster_labels",
+ "security": [
+ {
+ "HTTPBearer": []
+ }
+ ],
+ "parameters": [
+ {
+ "name": "eps",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "number",
+ "maximum": 2.0,
+ "minimum": 0.01
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "DBSCAN eps for clustering. Defaults to an adaptive value derived from the projection's k-distance distribution. Clamped server-side relative to the projection's coordinate span.",
+ "title": "Eps"
+ },
+ "description": "DBSCAN eps for clustering. Defaults to an adaptive value derived from the projection's k-distance distribution. Clamped server-side relative to the projection's coordinate span."
+ },
+ {
+ "name": "min_samples",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "maximum": 100,
+ "minimum": 2,
+ "description": "DBSCAN min_samples for clustering",
+ "default": 10,
+ "title": "Min Samples"
+ },
+ "description": "DBSCAN min_samples for clustering"
+ },
+ {
+ "name": "top_k",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "maximum": 10,
+ "minimum": 1,
+ "description": "Candidate labels per cluster",
+ "default": 3,
+ "title": "Top K"
+ },
+ "description": "Candidate labels per cluster"
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful Response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ImageMapClusterLabelsResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/api/v1/image_map/refresh": {
"post": {
"tags": ["image_map"],
@@ -41684,6 +41769,72 @@
"$ref": "#/components/schemas/ImageOutput"
}
},
+ "ImageMapClusterLabel": {
+ "properties": {
+ "label": {
+ "type": "string",
+ "title": "Label",
+ "description": "Best-matching vocabulary phrase"
+ },
+ "alternates": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Alternates",
+ "description": "Runner-up phrases"
+ },
+ "score": {
+ "type": "number",
+ "title": "Score",
+ "description": "Cosine similarity of the best phrase to the cluster centroid"
+ }
+ },
+ "type": "object",
+ "required": ["label", "alternates", "score"],
+ "title": "ImageMapClusterLabel",
+ "description": "The best vocabulary label for one cluster."
+ },
+ "ImageMapClusterLabelsResponse": {
+ "properties": {
+ "labels": {
+ "additionalProperties": {
+ "$ref": "#/components/schemas/ImageMapClusterLabel"
+ },
+ "type": "object",
+ "title": "Labels",
+ "description": "Cluster id -> label; noise (-1) is omitted"
+ },
+ "visible_hash": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Visible Hash",
+ "description": "Fingerprint of the visible image set these labels were clustered over; clients must discard labels whose visible_hash does not match their points response"
+ },
+ "updated_at": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Updated At",
+ "description": "The projection these labels were computed against; clients must discard labels whose projection does not match their points"
+ }
+ },
+ "type": "object",
+ "required": ["labels"],
+ "title": "ImageMapClusterLabelsResponse",
+ "description": "Automatic labels for the current user's visible clusters, keyed by cluster id."
+ },
"ImageMapPoint": {
"properties": {
"x": {
@@ -41762,6 +41913,18 @@
"title": "Cluster Eps",
"description": "The effective DBSCAN eps used for these points (adaptive default resolved, clamps applied). Pass it back explicitly to get an identical clustering from a later request."
},
+ "visible_hash": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Visible Hash",
+ "description": "Fingerprint of the visible image set these points were computed over; compare across image-map responses to detect accessible-set drift between requests."
+ },
"updated_at": {
"anyOf": [
{
diff --git a/invokeai/frontend/web/src/services/api/schema.ts b/invokeai/frontend/web/src/services/api/schema.ts
index c3c44c989d..40482fd254 100644
--- a/invokeai/frontend/web/src/services/api/schema.ts
+++ b/invokeai/frontend/web/src/services/api/schema.ts
@@ -1591,6 +1591,35 @@ export type paths = {
patch?: never;
trace?: never;
};
+ "/api/v1/image_map/cluster_labels": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Get Image Map Cluster Labels
+ * @description Labels the user's visible clusters with the most similar vocabulary phrases.
+ *
+ * Clustering mirrors `/points` (same eps semantics, computed over the
+ * caller's currently-accessible points), so cluster ids line up with the
+ * served map. Pass the `cluster_eps` reported by `/points` so both requests
+ * cluster with the same eps; cluster ids can still differ if the accessible
+ * set changes between the requests, so compare the two responses'
+ * `visible_hash` (and `updated_at`) and discard labels on mismatch.
+ * Requires the embedding model's text encoder; the first call per model
+ * embeds the whole vocabulary and is slow.
+ */
+ get: operations["get_image_map_cluster_labels"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/v1/image_map/refresh": {
parameters: {
query?: never;
@@ -17387,6 +17416,50 @@ export type components = {
*/
type: "img_lerp";
};
+ /**
+ * ImageMapClusterLabel
+ * @description The best vocabulary label for one cluster.
+ */
+ ImageMapClusterLabel: {
+ /**
+ * Label
+ * @description Best-matching vocabulary phrase
+ */
+ label: string;
+ /**
+ * Alternates
+ * @description Runner-up phrases
+ */
+ alternates: string[];
+ /**
+ * Score
+ * @description Cosine similarity of the best phrase to the cluster centroid
+ */
+ score: number;
+ };
+ /**
+ * ImageMapClusterLabelsResponse
+ * @description Automatic labels for the current user's visible clusters, keyed by cluster id.
+ */
+ ImageMapClusterLabelsResponse: {
+ /**
+ * Labels
+ * @description Cluster id -> label; noise (-1) is omitted
+ */
+ labels: {
+ [key: string]: components["schemas"]["ImageMapClusterLabel"];
+ };
+ /**
+ * Visible Hash
+ * @description Fingerprint of the visible image set these labels were clustered over; clients must discard labels whose visible_hash does not match their points response
+ */
+ visible_hash?: string | null;
+ /**
+ * Updated At
+ * @description The projection these labels were computed against; clients must discard labels whose projection does not match their points
+ */
+ updated_at?: string | null;
+ };
/**
* ImageMapPoint
* @description One image's position on the 2D semantic map.
@@ -17449,6 +17522,11 @@ export type components = {
* @description The effective DBSCAN eps used for these points (adaptive default resolved, clamps applied). Pass it back explicitly to get an identical clustering from a later request.
*/
cluster_eps?: number | null;
+ /**
+ * Visible Hash
+ * @description Fingerprint of the visible image set these points were computed over; compare across image-map responses to detect accessible-set drift between requests.
+ */
+ visible_hash?: string | null;
/**
* Updated At
* @description When the served projection was computed
@@ -46408,6 +46486,42 @@ export interface operations {
};
};
};
+ get_image_map_cluster_labels: {
+ parameters: {
+ query?: {
+ /** @description DBSCAN eps for clustering. Defaults to an adaptive value derived from the projection's k-distance distribution. Clamped server-side relative to the projection's coordinate span. */
+ eps?: number | null;
+ /** @description DBSCAN min_samples for clustering */
+ min_samples?: number;
+ /** @description Candidate labels per cluster */
+ top_k?: number;
+ };
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ImageMapClusterLabelsResponse"];
+ };
+ };
+ /** @description Validation Error */
+ 422: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["HTTPValidationError"];
+ };
+ };
+ };
+ };
refresh_image_map: {
parameters: {
query?: never;
diff --git a/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts b/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts
index fab8fbc43e..262546852c 100644
--- a/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/accountOwnedUiStores.test.ts
@@ -18,6 +18,7 @@ describe('account-owned workbench UI stores', () => {
requestLayerProperties('user-a-layer', 'filter');
// Partial stand-in: the snapshot only needs to be observably non-empty.
imageMapStore.patchSnapshot({
+ clusterLabels: { '0': 'cats' },
data: { pointCount: 1, state: 'ready' } as unknown as ImageMapPoints,
indexCounts: { embedded: 1, failed: 0, pending: 0, total: 1 },
loadState: 'loaded',
@@ -34,6 +35,7 @@ describe('account-owned workbench UI stores', () => {
expect(imageMapSnapshot.loadState).toBe('idle');
expect(imageMapSnapshot.error).toBeNull();
expect(imageMapSnapshot.indexCounts).toBeNull();
+ expect(imageMapSnapshot.clusterLabels).toBeNull();
unregisterModal();
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/api.ts b/invokeai/frontend/webv2/src/workbench/image-map/api.ts
index 4792531e2c..4a65014de7 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/api.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/api.ts
@@ -19,6 +19,10 @@ export interface ImageMapPoints {
pointCount: number;
/** The configured embedding model's name; only set when state is 'model_missing'. */
modelName: string | null;
+ /** The effective DBSCAN eps these points were clustered with; pass it back to reproduce the clustering. */
+ clusterEps: number | null;
+ /** Fingerprint of the visible image set; label responses with a different hash were clustered over a drifted set. */
+ visibleHash: string | null;
updatedAt: string | null;
}
@@ -35,10 +39,13 @@ interface BackendImageMapPointsResponse {
stale: boolean;
point_count: number;
model_name?: string | null;
+ cluster_eps?: number | null;
+ visible_hash?: string | null;
updated_at: string | null;
}
const mapPoints = (body: BackendImageMapPointsResponse): ImageMapPoints => ({
+ clusterEps: body.cluster_eps ?? null,
modelName: body.model_name ?? null,
pointCount: body.point_count,
points: body.points.map((point) => ({
@@ -50,6 +57,7 @@ const mapPoints = (body: BackendImageMapPointsResponse): ImageMapPoints => ({
stale: body.stale,
state: body.state,
updatedAt: body.updated_at ?? null,
+ visibleHash: body.visible_hash ?? null,
});
export const fetchImageMapPoints = async (options?: { eps?: number; minSamples?: number }): Promise<ImageMapPoints> => {
@@ -78,3 +86,39 @@ export const requestImageMapRefresh = async (): Promise<boolean> => {
return body.enqueued;
};
+
+export interface ImageMapClusterLabels {
+ labels: Record<string, string>;
+ /** Fingerprint of the visible image set the labels were clustered over. */
+ visibleHash: string | null;
+ /** The projection these labels were computed against. */
+ updatedAt: string | null;
+}
+
+export const fetchImageMapClusterLabels = async (options?: {
+ eps?: number;
+ minSamples?: number;
+}): Promise<ImageMapClusterLabels> => {
+ const query = new URLSearchParams();
+
+ if (options?.eps !== undefined) {
+ query.set('eps', String(options.eps));
+ }
+
+ if (options?.minSamples !== undefined) {
+ query.set('min_samples', String(options.minSamples));
+ }
+
+ const queryString = query.toString();
+ const body = await apiFetchJson<{
+ labels: Record<string, { label: string }>;
+ visible_hash?: string | null;
+ updated_at?: string | null;
+ }>(`/api/v1/image_map/cluster_labels${queryString ? `?${queryString}` : ''}`);
+
+ return {
+ labels: Object.fromEntries(Object.entries(body.labels).map(([clusterId, info]) => [clusterId, info.label])),
+ updatedAt: body.updated_at ?? null,
+ visibleHash: body.visible_hash ?? null,
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts
index 1e3489b4ae..3b1ee97f7a 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/clusterSelection.test.ts
@@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest';
import type { ImageMapPoint } from './api';
import { collectClusterSelection } from './clusterSelection';
-import { buildHighlightedPointsTrace, HIGHLIGHTED_POINTS_TRACE } from './imageMapTraces';
+import { buildClusterAnnotations, buildHighlightedPointsTrace, HIGHLIGHTED_POINTS_TRACE } from './imageMapTraces';
const point = (imageName: string, x: number, y: number, cluster: number): ImageMapPoint => ({
cluster,
@@ -48,3 +48,27 @@ describe('buildHighlightedPointsTrace', () => {
expect(multi.marker.line).toEqual({ color: '#FFFFFF', width: 1 });
});
});
+
+describe('buildClusterAnnotations', () => {
+ it('places one annotation per labeled cluster, centered above its topmost point', () => {
+ const varied = [point('a.png', 0, 1, 0), point('b.png', 3, 5, 0), point('c.png', 1, 3, 0)];
+ const annotations = buildClusterAnnotations(varied, { '0': 'landscapes' });
+
+ expect(annotations).toHaveLength(1);
+ const landscapes = annotations[0];
+ // Centered on the cluster's x centroid, anchored above its topmost point
+ // with a pixel lift so the label never covers the points it names.
+ expect(landscapes?.x).toBeCloseTo(4 / 3);
+ expect(landscapes?.y).toBeCloseTo(5);
+ expect(landscapes?.yanchor).toBe('bottom');
+ expect(landscapes?.yshift).toBeGreaterThan(0);
+ // Readable on any theme: white text on a dark pill.
+ expect(landscapes?.font.color).toBe('#FFFFFF');
+ });
+
+ it('skips noise, unlabeled clusters, and null label maps', () => {
+ expect(buildClusterAnnotations(POINTS, null)).toEqual([]);
+ const onlyOne = buildClusterAnnotations(POINTS, { '1': 'portraits' });
+ expect(onlyOne.map((annotation) => annotation.text)).toEqual(['portraits']);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
index 927e960851..6ff095e06c 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMap.test.ts
@@ -21,6 +21,7 @@ import {
} from './imageMapTraces';
const BACKEND_RESPONSE = {
+ cluster_eps: 0.42,
point_count: 2,
points: [
{ cluster: 0, image_name: 'a.png', x: 1.5, y: -2 },
@@ -29,6 +30,7 @@ const BACKEND_RESPONSE = {
stale: false,
state: 'ready',
updated_at: '2026-08-02 12:00:00',
+ visible_hash: 'hash-1',
};
describe('image map api', () => {
@@ -44,6 +46,8 @@ describe('image map api', () => {
expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/points');
expect(result.state).toBe('ready');
expect(result.pointCount).toBe(2);
+ expect(result.clusterEps).toBe(0.42);
+ expect(result.visibleHash).toBe('hash-1');
expect(result.points[0]).toEqual({ cluster: 0, imageName: 'a.png', x: 1.5, y: -2 });
});
@@ -82,7 +86,14 @@ describe('image map api', () => {
describe('image map store', () => {
beforeEach(() => {
mocks.apiFetchJson.mockReset();
- imageMapStore.setSnapshot({ data: null, error: null, indexCounts: null, loadState: 'idle', renderError: null });
+ imageMapStore.setSnapshot({
+ clusterLabels: null,
+ data: null,
+ error: null,
+ indexCounts: null,
+ loadState: 'idle',
+ renderError: null,
+ });
});
it('loads points into the snapshot', async () => {
@@ -96,6 +107,97 @@ describe('image map store', () => {
expect(snapshot.error).toBeNull();
});
+ it('passes the points response eps through to the cluster labels fetch', async () => {
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return Promise.resolve({
+ labels: { '0': { label: 'cats' } },
+ updated_at: BACKEND_RESPONSE.updated_at,
+ visible_hash: BACKEND_RESPONSE.visible_hash,
+ });
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+
+ await refreshImageMapPoints();
+
+ // The labels endpoint must receive the exact eps the map was clustered
+ // with; the adaptive default could resolve differently on a drifted set.
+ await vi.waitFor(() => {
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/cluster_labels?eps=0.42');
+ expect(imageMapStore.getSnapshot().clusterLabels).toEqual({ '0': 'cats' });
+ });
+ });
+
+ it('discards label responses clustered over a drifted visible set', async () => {
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return Promise.resolve({
+ labels: { '0': { label: 'cats' } },
+ updated_at: BACKEND_RESPONSE.updated_at,
+ visible_hash: 'hash-2',
+ });
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+
+ await refreshImageMapPoints();
+
+ await vi.waitFor(() => {
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/cluster_labels?eps=0.42');
+ });
+ // Flush the response handler: cluster ids from a different visible set
+ // must not be applied to the rendered map.
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+ expect(imageMapStore.getSnapshot().clusterLabels).toBeNull();
+ });
+
+ it('ignores a stale labels failure after a newer request already set labels', async () => {
+ // L1: points land, but the labels request hangs and will fail late.
+ let rejectFirstLabels: (reason: unknown) => void = () => {};
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return new Promise((_resolve, reject) => {
+ rejectFirstLabels = reject;
+ });
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+ await refreshImageMapPoints();
+ await vi.waitFor(() => {
+ expect(mocks.apiFetchJson).toHaveBeenCalledWith('/api/v1/image_map/cluster_labels?eps=0.42');
+ });
+
+ // L2: a newer refresh whose labels resolve first.
+ mocks.apiFetchJson.mockImplementation((url: string) => {
+ if (url.startsWith('/api/v1/image_map/cluster_labels')) {
+ return Promise.resolve({
+ labels: { '0': { label: 'cats' } },
+ updated_at: BACKEND_RESPONSE.updated_at,
+ visible_hash: BACKEND_RESPONSE.visible_hash,
+ });
+ }
+
+ return Promise.resolve(BACKEND_RESPONSE);
+ });
+ await refreshImageMapPoints();
+ await vi.waitFor(() => {
+ expect(imageMapStore.getSnapshot().clusterLabels).toEqual({ '0': 'cats' });
+ });
+
+ // L1's late failure is stale: it must not wipe the labels L2 set.
+ rejectFirstLabels(new Error('slow failure'));
+ await new Promise((resolve) => {
+ setTimeout(resolve, 0);
+ });
+ expect(imageMapStore.getSnapshot().clusterLabels).toEqual({ '0': 'cats' });
+ });
+
it('records errors and keeps prior data', async () => {
mocks.apiFetchJson.mockResolvedValue(BACKEND_RESPONSE);
await refreshImageMapPoints();
@@ -183,6 +285,7 @@ describe('snapshot transitions', () => {
// Asserting `error === null` after a success is vacuous when the fixture
// starts at null; seed a real error first so the clearing is what is tested.
imageMapStore.setSnapshot({
+ clusterLabels: null,
data: null,
error: 'boom',
indexCounts: null,
@@ -209,6 +312,7 @@ describe('snapshot transitions', () => {
// Without this the WebGL error is permanent for the session: the view stops
// mounting the plot, and nothing else ever resets renderError.
imageMapStore.setSnapshot({
+ clusterLabels: null,
data: null,
error: null,
indexCounts: null,
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts
index 48f26a956d..1516572f3b 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapSettings.ts
@@ -5,3 +5,7 @@
export const getImageMapClickSelectsCluster = (values: Record<string, unknown>): boolean =>
values.clickSelectsCluster === true;
+
+/** Labels are drawn unless the user has turned them off. */
+export const getImageMapShowClusterLabels = (values: Record<string, unknown>): boolean =>
+ values.showClusterLabels !== false;
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
index f97d4d49d5..67ef4a7b2a 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapStore.ts
@@ -8,7 +8,7 @@ import { getApiErrorMessage } from '@platform/transport/http';
import type { ImageMapPoints } from './api';
-import { fetchImageMapPoints } from './api';
+import { fetchImageMapClusterLabels, fetchImageMapPoints } from './api';
/**
* Read model for the semantic image map, shared by the widget body and any
@@ -30,6 +30,8 @@ export interface ImageMapSnapshot {
error: string | null;
/** Embedding-index progress; only ever pushed to admins by the backend. */
indexCounts: ImageIndexCounts | null;
+ /** Cluster id -> automatic label; null when unavailable (e.g. no text encoder). */
+ clusterLabels: Record<string, string> | null;
/**
* The plot canvas itself failed (WebGL unavailable). Distinct from `error`,
* which means a fetch failed: with `error` the cached points are still worth
@@ -40,6 +42,7 @@ export interface ImageMapSnapshot {
}
const EMPTY_IMAGE_MAP_SNAPSHOT: ImageMapSnapshot = {
+ clusterLabels: null,
data: null,
error: null,
indexCounts: null,
@@ -58,6 +61,9 @@ registerAccountOwnedResource({
clear: () => {
inflight = null;
rerunRequested = false;
+ // Orphan any in-flight labels request so its completion (or failure)
+ // cannot touch the next account's labels.
+ labelsSequence += 1;
imageMapStore.setSnapshot(EMPTY_IMAGE_MAP_SNAPSHOT);
},
name: 'image-map',
@@ -89,6 +95,7 @@ export const refreshImageMapPoints = (): Promise<void> => {
// transient WebGL failure, so a fresh point set must get a fresh attempt
// at drawing rather than staying stuck on the previous canvas failure.
imageMapStore.patchSnapshot({ data, error: null, loadState: 'loaded', renderError: null });
+ refreshClusterLabels(data);
})
.catch((error: unknown) => {
if (!isAccountScopeCurrent(owner)) {
@@ -118,6 +125,67 @@ export const refreshImageMapPoints = (): Promise<void> => {
return refresh;
};
+let labelsSequence = 0;
+
+const areLabelMapsEqual = (left: Record<string, string> | null, right: Record<string, string>): boolean => {
+ if (left === null) {
+ return false;
+ }
+
+ const keys = Object.keys(right);
+
+ return keys.length === Object.keys(left).length && keys.every((key) => left[key] === right[key]);
+};
+
+/**
+ * Labels are decoration: fetched best-effort after the points land. Cluster
+ * ids are only meaningful against the projection the points came from, so a
+ * label response for a different projection — or one overtaken by a newer
+ * request — is discarded rather than mislabeling clusters.
+ */
+const refreshClusterLabels = (data: ImageMapPoints): void => {
+ if (data.state !== 'ready') {
+ // Nothing to label; a disabled index would 409 on every refresh. Bump the
+ // sequence so an in-flight labels response cannot repopulate the labels
+ // this clears.
+ labelsSequence += 1;
+ imageMapStore.patchSnapshot({ clusterLabels: null });
+
+ return;
+ }
+
+ labelsSequence += 1;
+ const sequence = labelsSequence;
+ // Pass the points' effective eps so both requests cluster with the same
+ // value — the adaptive default is derived from the visible set, which can
+ // drift between the two requests. Same eps alone does not pin cluster ids
+ // under drift; the visibleHash comparison below discards those responses.
+ void fetchImageMapClusterLabels(data.clusterEps !== null ? { eps: data.clusterEps } : undefined)
+ .then((response) => {
+ const current = imageMapStore.getSnapshot();
+
+ if (
+ sequence !== labelsSequence ||
+ response.updatedAt !== current.data?.updatedAt ||
+ response.visibleHash !== current.data?.visibleHash
+ ) {
+ return;
+ }
+
+ if (!areLabelMapsEqual(current.clusterLabels, response.labels)) {
+ imageMapStore.patchSnapshot({ clusterLabels: response.labels });
+ }
+ })
+ .catch(() => {
+ // Same staleness rule as success: only the newest request may clear the
+ // labels. A slow stale request failing after a newer one already set
+ // fresh labels must not wipe them.
+ if (sequence === labelsSequence) {
+ imageMapStore.patchSnapshot({ clusterLabels: null });
+ }
+ });
+};
+
export const ensureImageMapLoaded = (): void => {
if (imageMapStore.getSnapshot().loadState === 'idle') {
void refreshImageMapPoints();
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts
index 48f767c95b..a6f27fd244 100644
--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapTraces.ts
@@ -111,7 +111,11 @@ export const buildCurrentImageTrace = (): ScatterTrace => ({
const GRID_LINE_COLOR = 'rgba(128, 128, 128, 0.16)';
const GRID_ZERO_COLOR = 'rgba(128, 128, 128, 0.32)';
-export const buildMapLayout = (initialRanges?: AxisRanges | null): Partial<Layout> => ({
+export const buildMapLayout = (
+ initialRanges?: AxisRanges | null,
+ annotations: ClusterAnnotation[] = []
+): Partial<Layout> => ({
+ annotations: annotations as unknown as Layout['annotations'],
dragmode: 'pan',
margin: { b: 0, l: 0, r: 0, t: 0 },
paper_bgcolor: 'rgba(0,0,0,0)',
@@ -144,3 +148,61 @@ export const buildMapLayout = (initialRanges?: AxisRanges | null): Partial<Layou
zerolinewidth: 1,
},
});
+
+export interface ClusterAnnotation {
+ x: number;
+ y: number;
+ text: string;
+ showarrow: false;
+ font: { color: string; size: number };
+ bgcolor: string;
+ borderpad: number;
+ opacity: number;
+ xanchor: 'center';
+ yanchor: 'bottom';
+ yshift: number;
+}
+
+/**
+ * One text annotation per labeled cluster: centered horizontally on the
+ * cluster but anchored just above its topmost point (a fixed pixel lift, so
+ * zoom never lands the label on the points it names). White-on-dark pill
+ * styling is theme-independent — it reads on every map background.
+ * Pure so placement math is testable; plotly consumes the array via layout.
+ */
+export const buildClusterAnnotations = (
+ points: ImageMapPoint[],
+ labelsByCluster: Record<string, string> | null
+): ClusterAnnotation[] => {
+ if (!labelsByCluster) {
+ return [];
+ }
+
+ const sums = new Map<number, { count: number; x: number; maxY: number }>();
+
+ for (const point of points) {
+ if (point.cluster < 0 || !(String(point.cluster) in labelsByCluster)) {
+ continue;
+ }
+
+ const entry = sums.get(point.cluster) ?? { count: 0, maxY: -Infinity, x: 0 };
+ entry.count += 1;
+ entry.x += point.x;
+ entry.maxY = Math.max(entry.maxY, point.y);
+ sums.set(point.cluster, entry);
+ }
+
+ return [...sums.entries()].map(([cluster, { count, x, maxY }]) => ({
+ bgcolor: 'rgba(0,0,0,0.65)',
+ borderpad: 2,
+ font: { color: '#FFFFFF', size: 10 },
+ opacity: 1,
+ showarrow: false,
+ text: labelsByCluster[String(cluster)],
+ x: x / count,
+ xanchor: 'center',
+ y: maxY,
+ yanchor: 'bottom',
+ yshift: 8,
+ }));
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.test.ts
index 65f9fe7fba..db5f8752f3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapDataRuntime.test.ts
@@ -39,7 +39,14 @@ describe('attachImageMapDataRuntime', () => {
mocks.onConnectionChange.mockReset().mockReturnValue(() => {});
mocks.refreshImageMapPoints.mockReset();
mocks.getAuthSession.mockReset().mockReturnValue({ user: null });
- imageMapStore.setSnapshot({ data: null, error: null, indexCounts: null, loadState: 'idle', renderError: null });
+ imageMapStore.setSnapshot({
+ clusterLabels: null,
+ data: null,
+ error: null,
+ indexCounts: null,
+ loadState: 'idle',
+ renderError: null,
+ });
});
it('refreshes on projection-ready only after the map has been loaded once', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx
index 46ed07959b..07e6d1f3c6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapHeaderActions.tsx
@@ -1,31 +1,48 @@
import type { WidgetViewProps } from '@workbench/widgetContracts';
import { ToggleIconButton } from '@platform/ui';
-import { getImageMapClickSelectsCluster } from '@workbench/image-map/imageMapSettings';
+import {
+ getImageMapClickSelectsCluster,
+ getImageMapShowClusterLabels,
+} from '@workbench/image-map/imageMapSettings';
import { useWidgetValuesSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
-import { GroupIcon } from 'lucide-react';
+import { GroupIcon, TagsIcon } from 'lucide-react';
import { useCallback } from 'react';
/**
- * Header toggle for cluster-selection mode: when on, clicking a map point
- * selects its whole cluster in the gallery instead of just the one image.
- * Persisted in the widget's values, like the gallery's own view settings.
+ * Header toggles for the map's two click/display modes: whether a click selects
+ * the whole cluster, and whether cluster labels are drawn. Both persist in the
+ * widget's values, like the gallery's own view settings.
*/
export const ImageMapHeaderActions = (_props: WidgetViewProps) => {
const { widgets } = useWorkbenchCommands();
const clickSelectsCluster = useWidgetValuesSelector('image-map', getImageMapClickSelectsCluster);
- const handleToggle = useCallback(
+ const showClusterLabels = useWidgetValuesSelector('image-map', getImageMapShowClusterLabels);
+ const handleToggleClusterMode = useCallback(
(checked: boolean) => widgets.patchValues('image-map', { clickSelectsCluster: checked }),
[widgets]
);
+ const handleToggleLabels = useCallback(
+ (checked: boolean) => widgets.patchValues('image-map', { showClusterLabels: checked }),
+ [widgets]
+ );
return (
- <ToggleIconButton
- checked={clickSelectsCluster}
- icon={GroupIcon}
- label="Toggle cluster selection mode"
- tooltip={clickSelectsCluster ? 'Click selects the whole cluster' : 'Click selects one image'}
- onCheckedChange={handleToggle}
- />
+ <>
+ <ToggleIconButton
+ checked={showClusterLabels}
+ icon={TagsIcon}
+ label="Toggle cluster labels"
+ tooltip={showClusterLabels ? 'Cluster labels shown' : 'Cluster labels hidden'}
+ onCheckedChange={handleToggleLabels}
+ />
+ <ToggleIconButton
+ checked={clickSelectsCluster}
+ icon={GroupIcon}
+ label="Toggle cluster selection mode"
+ tooltip={clickSelectsCluster ? 'Click selects the whole cluster' : 'Click selects one image'}
+ onCheckedChange={handleToggleClusterMode}
+ />
+ </>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx
index 9caa4d2dc5..9e29d24cfb 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx
@@ -13,6 +13,7 @@ import { collectClusterSelection } from '@workbench/image-map/clusterSelection';
import { imageMapStore } from '@workbench/image-map/imageMapStore';
import {
buildAllPointsTrace,
+ buildClusterAnnotations,
buildCurrentImageTrace,
buildHighlightedPointsTrace,
buildMapLayout,
@@ -117,9 +118,16 @@ const findTraceIndex = (plot: PlotElement, name: string): number =>
* module is lazy-loaded so the plotly bundle stays out of the app's critical
* path.
*/
-const ImageMapPlot = ({ clickSelectsCluster = false }: { clickSelectsCluster?: boolean }) => {
+const ImageMapPlot = ({
+ clickSelectsCluster = false,
+ showClusterLabels = true,
+}: {
+ clickSelectsCluster?: boolean;
+ showClusterLabels?: boolean;
+}) => {
const containerRef = useRef<HTMLDivElement | null>(null);
const points = imageMapStore.useSelector((snapshot) => snapshot.data?.points ?? null);
+ const clusterLabels = imageMapStore.useSelector((snapshot) => snapshot.clusterLabels);
const selectedImageName = useWidgetValuesSelector(
'gallery',
(values) => getSelectedGalleryImageFromValues(values)?.imageName ?? null
@@ -208,7 +216,12 @@ const ImageMapPlot = ({ clickSelectsCluster = false }: { clickSelectsCluster?: b
}
}
- void Plotly.react(container, traces as Plotly.Data[], buildMapLayout(initialRanges), {
+ const layout = buildMapLayout(
+ initialRanges,
+ buildClusterAnnotations(points, showClusterLabels ? clusterLabels : null)
+ );
+
+ void Plotly.react(container, traces as Plotly.Data[], layout, {
displayModeBar: false,
// Custom wheel/pinch zoom below; plotly's own scrollZoom has
// long-standing Safari issues.
@@ -296,7 +309,7 @@ const ImageMapPlot = ({ clickSelectsCluster = false }: { clickSelectsCluster?: b
return () => {
disposed = true;
};
- }, [points, selectCluster, selectImage]);
+ }, [clusterLabels, points, selectCluster, selectImage, showClusterLabels]);
// Highlight overlay: the gallery's multi-selection, restyled in place.
useEffect(() => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
index 14089f6f48..d6aa4ca54c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapWidgetView.tsx
@@ -1,7 +1,10 @@
import type { WidgetViewProps } from '@workbench/widgetContracts';
import { Button, Center, Spinner, Stack, Text } from '@chakra-ui/react';
-import { getImageMapClickSelectsCluster } from '@workbench/image-map/imageMapSettings';
+import {
+ getImageMapClickSelectsCluster,
+ getImageMapShowClusterLabels,
+} from '@workbench/image-map/imageMapSettings';
import { ensureImageMapLoaded, imageMapStore, refreshImageMapPoints } from '@workbench/image-map/imageMapStore';
import { useWidgetValuesSelector } from '@workbench/WorkbenchContext';
import { lazy, Suspense, useEffect } from 'react';
@@ -31,6 +34,7 @@ const plotLoadingFallback = (
export const ImageMapWidgetView = (_props: WidgetViewProps) => {
const { data, error, loadState, renderError } = imageMapStore.useSnapshot();
const clickSelectsCluster = useWidgetValuesSelector('image-map', getImageMapClickSelectsCluster);
+ const showClusterLabels = useWidgetValuesSelector('image-map', getImageMapShowClusterLabels);
useEffect(() => {
ensureImageMapLoaded();
@@ -63,7 +67,7 @@ export const ImageMapWidgetView = (_props: WidgetViewProps) => {
// mounted and the spinner where the plot will appear.
return (
<Suspense fallback={plotLoadingFallback}>
- <ImageMapPlot clickSelectsCluster={clickSelectsCluster} />
+ <ImageMapPlot clickSelectsCluster={clickSelectsCluster} showClusterLabels={showClusterLabels} />
</Suspense>
);
}
diff --git a/pyproject.toml b/pyproject.toml
index 677e61262b..53b4c7c66a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -257,6 +257,7 @@ version = { attr = "invokeai.version.__version__" }
"invokeai.backend.anima" = ["tokenizer/*.json"]
"invokeai.backend.qwen3" = ["tokenizer/*.json", "tokenizer/*.json.gz"]
"invokeai.backend.t5" = ["tokenizer/*.json"]
+"invokeai.app.services.image_index" = ["*.txt"]
"invokeai.app.services.workflow_records.default_workflows" = ["*.json"]
"invokeai.backend.hidiffusion" = ["sd_module_key/*.txt"]
"invokeai.app.services.style_preset_records" = ["*.json"]
diff --git a/tests/app/routers/test_image_map.py b/tests/app/routers/test_image_map.py
index 8ac63116cb..3e7e94397e 100644
--- a/tests/app/routers/test_image_map.py
+++ b/tests/app/routers/test_image_map.py
@@ -39,6 +39,7 @@ class FakeImageIndexService(ImageIndexServiceBase):
def __init__(self, model_id: str | None = MODEL_ID) -> None:
self._model_id = model_id
+ self.index_records: ImageIndexRecordsSqlite | None = None
self.projection_requests: list[tuple[str, bool]] = []
self.spent_failed_scopes: dict[str, str] = {}
self.search_calls: list[tuple[str | None, int]] = []
@@ -73,12 +74,27 @@ class FakeImageIndexService(ImageIndexServiceBase):
return vector
def get_accessible_embeddings(self, user_id: str | None) -> tuple[list[str], np.ndarray]:
- return [], np.empty((0, 0), dtype=np.float32)
+ # Wired to the real records store by the mock_services fixture so
+ # endpoints exercising the accessible matrix see seeded embeddings.
+ if self.index_records is None:
+ return [], np.empty((0, 0), dtype=np.float32)
+ names = self.index_records.list_accessible_embedded_images(user_id, MODEL_ID)
+ return self.index_records.get_embeddings(names, MODEL_ID)
def search_similar(self, user_id: str | None, query_embedding: np.ndarray, limit: int) -> list[tuple[str, float]]:
self.search_calls.append((user_id, limit))
return self.search_results[:limit]
+ def get_vocab_embeddings(self) -> tuple[list[str], np.ndarray]:
+ from invokeai.app.services.image_index.image_index_base import TextSearchUnavailableError
+
+ if self.text_unavailable:
+ raise TextSearchUnavailableError("no text encoder installed")
+ # A tiny vocabulary aligned with the seeded DIM-dimensional space:
+ # phrase i points along axis i.
+ vocabulary = ["alpha", "beta", "gamma", "delta"]
+ return vocabulary, np.eye(DIM, dtype=np.float32)
+
def request_projection(
self,
user_id: str,
@@ -130,7 +146,7 @@ def mock_services(image_index_service: FakeImageIndexService) -> InvocationServi
logger = InvokeAILogger.get_logger()
db = create_mock_sqlite_database(configuration, logger)
- return InvocationServices(
+ services = InvocationServices(
board_image_records=SqliteBoardImageRecordStorage(db=db),
board_images=None, # type: ignore
board_records=SqliteBoardRecordStorage(db=db),
@@ -169,10 +185,13 @@ def mock_services(image_index_service: FakeImageIndexService) -> InvocationServi
video_records=None, # type: ignore
board_video_records=None, # type: ignore
gallery=None, # type: ignore
- image_index_records=ImageIndexRecordsSqlite(db=db),
+ image_index_records=(index_records := ImageIndexRecordsSqlite(db=db)),
image_index=image_index_service,
external_generation=None, # type: ignore
)
+ image_index_service.index_records = index_records
+
+ return services
@pytest.fixture
@@ -951,3 +970,105 @@ def test_multiuser_image_search_enforces_read_access_and_user_scope(
headers=user2_headers,
)
assert image_index_service.search_calls[-1] == (user2_id, 100)
+
+
+# --- Cluster labels ---
+
+
+def test_cluster_labels_align_with_served_clusters(mock_invoker: Invoker, client: TestClient) -> None:
+ # Two tight pairs; each pair's images embed along a distinct axis, so the
+ # expected label is that axis's vocabulary phrase.
+ def axis_vec(index: int) -> np.ndarray:
+ v = np.zeros(DIM, dtype=np.float32)
+ v[index] = 1.0
+ return v
+
+ for name, vec in [
+ ("a1.png", axis_vec(0)),
+ ("a2.png", axis_vec(0)),
+ ("b1.png", axis_vec(1)),
+ ("b2.png", axis_vec(1)),
+ ]:
+ _save_unembedded_image(mock_invoker, name)
+ _records(mock_invoker).upsert_embedding(name, MODEL_ID, vec)
+ coords = np.array([[0.0, 0.0], [0.4, 0.0], [30.0, 30.0], [30.4, 30.0]], dtype=np.float32)
+ _seed_projection(mock_invoker, SYSTEM_USER_ID, ["a1.png", "a2.png", "b1.png", "b2.png"], coords)
+
+ points = client.get("/api/v1/image_map/points", params={"eps": 0.5, "min_samples": 2}).json()
+ labels = client.get("/api/v1/image_map/cluster_labels", params={"eps": 0.5, "min_samples": 2, "top_k": 2}).json()[
+ "labels"
+ ]
+
+ label_by_name = {p["image_name"]: p["cluster"] for p in points["points"]}
+ a_cluster = str(label_by_name["a1.png"])
+ b_cluster = str(label_by_name["b1.png"])
+ assert labels[a_cluster]["label"] == "alpha"
+ assert labels[b_cluster]["label"] == "beta"
+ assert labels[a_cluster]["score"] > 0.9
+ assert len(labels[a_cluster]["alternates"]) == 1
+
+ # Adaptive default: with eps omitted on BOTH endpoints, each resolves the
+ # same adaptive value over the same visible set, so labels still align.
+ points = client.get("/api/v1/image_map/points", params={"min_samples": 2}).json()
+ assert points["cluster_eps"] is not None
+ labels_response = client.get("/api/v1/image_map/cluster_labels", params={"min_samples": 2, "top_k": 2}).json()
+ # Matching fingerprints are the client's proof the two responses were
+ # computed over the same visible set.
+ assert labels_response["visible_hash"] == points["visible_hash"]
+ labels = labels_response["labels"]
+ label_by_name = {p["image_name"]: p["cluster"] for p in points["points"]}
+ assert labels[str(label_by_name["a1.png"])]["label"] == "alpha"
+ assert labels[str(label_by_name["b1.png"])]["label"] == "beta"
+
+ # Pinned round trip: the reported eps is accepted back verbatim.
+ labels = client.get(
+ "/api/v1/image_map/cluster_labels",
+ params={"eps": points["cluster_eps"], "min_samples": 2, "top_k": 2},
+ ).json()["labels"]
+ assert labels[str(label_by_name["a1.png"])]["label"] == "alpha"
+ assert labels[str(label_by_name["b1.png"])]["label"] == "beta"
+
+
+def test_cluster_labels_survive_a_non_finite_row_the_way_points_does(mock_invoker: Invoker, client: TestClient) -> None:
+ """A projection row predating the writer's isfinite guard.
+
+ /points drops the non-finite rows, so labels computed over the undropped set
+ hash a different name list: every response fails the visible_hash comparison
+ the client is told to make, and all labels are discarded. Handing the NaN to
+ sklearn also raised, 500ing the user until their gallery changed.
+ """
+ names = ["a1.png", "a2.png", "bad.png"]
+ for index, name in enumerate(names):
+ vector = np.zeros(DIM, dtype=np.float32)
+ vector[index % 2] = 1.0
+ _save_unembedded_image(mock_invoker, name)
+ _records(mock_invoker).upsert_embedding(name, MODEL_ID, vector)
+ coords = np.array([[0.0, 0.0], [0.2, 0.0], [np.nan, np.nan]], dtype=np.float32)
+ _seed_projection(mock_invoker, SYSTEM_USER_ID, names, coords)
+
+ points = client.get("/api/v1/image_map/points", params={"min_samples": 2}).json()
+ labels_response = client.get("/api/v1/image_map/cluster_labels", params={"min_samples": 2})
+
+ assert labels_response.status_code == 200
+ assert [p["image_name"] for p in points["points"]] == ["a1.png", "a2.png"]
+ assert labels_response.json()["visible_hash"] == points["visible_hash"], (
+ "labels the client cannot match to its points are labels it throws away"
+ )
+
+
+def test_cluster_labels_unavailable_text_encoder_conflicts(
+ mock_invoker: Invoker, image_index_service: FakeImageIndexService, client: TestClient
+) -> None:
+ _seed_embedded_image(mock_invoker, "a.png")
+ _seed_projection(mock_invoker, SYSTEM_USER_ID, ["a.png"], np.zeros((1, 2), dtype=np.float32))
+ image_index_service.text_unavailable = True
+
+ assert client.get("/api/v1/image_map/cluster_labels").status_code == 409
+
+
+def test_cluster_labels_empty_without_projection(client: TestClient) -> None:
+ assert client.get("/api/v1/image_map/cluster_labels").json() == {
+ "labels": {},
+ "updated_at": None,
+ "visible_hash": None,
+ }
diff --git a/tests/app/services/image_index/test_cluster_labels.py b/tests/app/services/image_index/test_cluster_labels.py
new file mode 100644
index 0000000000..5f094d3959
--- /dev/null
+++ b/tests/app/services/image_index/test_cluster_labels.py
@@ -0,0 +1,57 @@
+"""Tests for the vocabulary-based cluster labeling math."""
+
+import numpy as np
+
+from invokeai.app.services.image_index.cluster_labels import (
+ PROMPT_TEMPLATES,
+ ensemble_phrase_embeddings,
+ label_clusters,
+ load_vocabulary,
+ vocab_fingerprint,
+)
+
+
+def test_load_vocabulary_is_nonempty_and_deduplicated() -> None:
+ vocabulary = load_vocabulary()
+ assert len(vocabulary) > 500
+ assert not any(phrase.startswith("#") for phrase in vocabulary)
+ assert len({phrase.casefold() for phrase in vocabulary}) == len(vocabulary)
+
+
+def test_vocab_fingerprint_changes_with_content() -> None:
+ assert vocab_fingerprint(["a", "b"]) != vocab_fingerprint(["a", "c"])
+ assert vocab_fingerprint(["a", "b"]) == vocab_fingerprint(["a", "b"])
+
+
+def test_ensemble_phrase_embeddings_pools_templates_and_normalizes() -> None:
+ calls: list[list[str]] = []
+
+ def fake_embed(texts: list[str]) -> np.ndarray:
+ calls.append(texts)
+ # Deterministic per-string vectors.
+ rng = np.random.default_rng(len(texts))
+ return rng.standard_normal((len(texts), 8)).astype(np.float32)
+
+ matrix = ensemble_phrase_embeddings(fake_embed, ["cat", "dog", "barn"], batch_size=2)
+
+ assert matrix.shape == (3, 8)
+ assert np.allclose(np.linalg.norm(matrix, axis=1), 1.0, atol=1e-5)
+ # Batch of 2 phrases + batch of 1, each with every template expanded.
+ assert [len(texts) for texts in calls] == [2 * len(PROMPT_TEMPLATES), 1 * len(PROMPT_TEMPLATES)]
+ assert calls[0][0] == PROMPT_TEMPLATES[0].format("cat")
+
+
+def test_label_clusters_picks_nearest_phrase_per_cluster() -> None:
+ vocab = ["x-things", "y-things", "z-things"]
+ vocab_embeddings = np.eye(3, dtype=np.float32)
+ # Cluster 0 along x, cluster 1 along y, one noise point along z.
+ image_embeddings = np.array([[1, 0, 0], [0.9, 0.1, 0], [0, 1, 0], [0.1, 0.9, 0], [0, 0, 1]], dtype=np.float32)
+ cluster_labels = np.array([0, 0, 1, 1, -1])
+
+ labels = label_clusters(cluster_labels, image_embeddings, vocab, vocab_embeddings, top_k=2)
+
+ assert set(labels) == {0, 1}
+ assert labels[0]["label"] == "x-things"
+ assert labels[1]["label"] == "y-things"
+ assert labels[0]["alternates"] == ["y-things"]
+ assert 0 < labels[0]["score"] <= 1.0