Aller au contenu
Cette page n'est pas encore disponible dans votre langue. La version anglaise est affichée.

Embedding Map and Near-Duplicate Detection

Plot your items on a UMAP map in the admin dashboard, move chosen regions to the front of the queue, and find near-duplicate images before annotation starts.

Potato can draw your corpus as a 2D map in the admin dashboard and can list the items that duplicate each other. The embedding map embeds each item, projects the vectors with UMAP, and colors each point by the label annotators gave the item. An admin can select a region of the map and move the selected items to the front of the annotation queue. Near-duplicate detection groups items that show the same picture twice, such as consecutive video frames, and an admin can take the duplicates out of the assignment queue. Annotators see neither the map nor the duplicate groups. The map and the duplicate scan run on your own server and send no item content anywhere unless you configure an embedding endpoint of your own.

Config blocks for the map and the duplicate scan

Four config blocks are involved, and each has one job:

  • embedding_visualization draws the map on the Embeddings tab of the admin dashboard.
  • diversity_ordering computes and caches the vectors the map plots. In Potato 2.14.0 the map starts only when diversity ordering is enabled, or when assignment_strategy is diversity_clustering.
  • embeddings chooses the encoder for the map and for diversity ordering, and picks a text, image, audio, or video model from the items when you name none.
  • curation registers the admin catalog routes, which include the duplicate scan. The default duplicate scan hashes images and uses no embedding model at all.

The admin embedding map is a different feature from the corpus_map block. A corpus_map gives annotators a map of documents at /corpus/map for cross-document annotation, embeds text only, and reads the model named in corpus_map.embedding_model rather than the embeddings block.

Dependencies and pip extras

On every backend, the map needs umap-learn and sentence-transformers. The viz and embeddings extras install both packages:

bash
pip install "potato-annotation[viz,embeddings]"

NumPy and scikit-learn are core dependencies. Diversity ordering also needs sentence-transformers and turns itself off without the package. Potato builds the map only when diversity ordering is on, so an install without sentence-transformers shows no map, even for an audio corpus. The image backend needs Pillow beside sentence-transformers. The audio backend needs transformers and one of soundfile or librosa, and the video backend needs ffmpeg on the PATH. Without umap-learn, Potato hides the Embeddings tab and logs the install command.

Turning on the embedding map

Add these blocks to an existing config to show the map with every option at the default value:

yaml
diversity_ordering:
  enabled: true
embedding_visualization:
  enabled: true
  sample_size: 1000
  include_all_annotated: true
  label_source: mace
  umap:
    n_neighbors: 15
    min_dist: 0.1
    metric: cosine

Each option and its default are listed below:

OptionDefaultWhat the option controls
enabledtrueShows the map. A config with diversity ordering on and no embedding_visualization block shows the map too, because enabled defaults to true.
sample_size1000The most points the map draws. A positive integer.
include_all_annotatedtrueKeeps every annotated item on the map when Potato has to sample. Annotated items can then push the count past sample_size.
label_sourcemaceColors points by the MACE prediction (mace) or by the majority answer (majority).
umap.n_neighbors15The UMAP neighborhood size, an integer of at least 2.
umap.min_dist0.1How tightly UMAP packs points, between 0 and 1.
umap.metriccosineThe distance UMAP uses, one of cosine, euclidean, manhattan, and correlation.

Potato 2.14.0 also accepts embedding_model and image_embedding_model in the block, but the map encodes items with the model the embeddings block resolves to. Name the model under embeddings.model instead.

Map points and colors

The map plots the items diversity ordering has embedded. Diversity ordering embeds the first prefill_count items during startup (100 by default) and embeds further items as annotators finish the items. An item embedded after an annotation is encoded from the field item_properties.text_key names, not from embeddings.source_field, and on a media corpus that field is the wrong one. Set diversity_ordering.prefill_count to the size of your corpus to put every item on the map from the start. Potato caches the vectors in <output_annotation_dir>/.diversity_cache/, so a restart does not encode the same items again. The cache is keyed by item ID alone, and startup skips the cached items, so a change to embeddings.model or embeddings.backend keeps the old vectors. Delete the .diversity_cache folder after changing either key.

When more items are embedded than sample_size allows, Potato keeps the annotated items and draws a random sample of the unannotated ones. UMAP then projects the sampled vectors to two dimensions with a fixed random seed of 42. Potato lowers n_neighbors to one less than the number of points on a small project, and a project with fewer than three embedded items shows no map.

Point colors depend on label_source. With mace, each point takes the MACE prediction for the first scheme in the MACE results. Potato colors the whole map by the majority answer instead when MACE is off, fails, or has no schemas to predict. An item with no MACE prediction stays gray even when the item has a majority answer. With majority, Potato reads the first radio, select, or multiselect scheme in the config and counts one answer per annotator. A multiselect answer counts as one label made of the chosen options joined with +. Gray marks an item with no label, and a tie between answers also leaves the point gray. Labels take colors from a fixed palette of ten, in turn.

The stats bar above the map shows four counts. Visualized is the number of plotted points, and Labels is the number of distinct labels. Annotated and Unannotated count over all embedded items, and the sample can leave some of those items off the map. A card in the same bar names the modality, the item field, the backend, and the model that produced the vectors. Check the card first when the map looks wrong.

Selecting items and reordering the queue

The map is a Plotly scatter plot with the lasso tool active. Hovering over a point or clicking a point fills the side panel with the item's ID, label, and annotation count. For a text item the panel shows the first 200 characters of the embedded field, and for an image item the panel shows the image. For an audio or video item the panel shows the file path as text.

Selections build a priority queue:

  1. Draw a lasso or a box around a region, or click points one at a time to add the points to the current selection.
  2. Click Add to Queue to save the selection as a priority group. Potato numbers the groups in the order you add them.
  3. Repeat for other regions, and remove a group with the group's × button if needed.
  4. Click Apply Reordering.

Applying the reordering interleaves the groups and moves the selected items to the front of the shared queue. Selections [A, B, C] at priority 1 and [X, Y] at priority 2 become A, X, B, Y, C, followed by every other item in the old order. An annotator who completes only part of the queue then still sees items from each region. The new order matters under the strategies that serve items in queue order, which are fixed_order (the default), active_learning, and batch. The diversity_clustering strategy re-orders items by cluster, and the random strategy ignores the order. Items already assigned to an annotator stay with that annotator. The map never assigns items to a particular annotator.

Refresh Visualization recomputes the projection. The dashboard reads the map through four admin endpoints, which accept the admin API key:

EndpointWhat the endpoint does
GET /admin/api/embedding_viz/dataReturns the points, labels, colors, and stats. ?force_refresh=true recomputes the projection.
POST /admin/api/embedding_viz/reorderTakes {"selections": [{"instance_ids": [...], "priority": 1}], "interleave": true} and reorders the queue.
POST /admin/api/embedding_viz/refreshClears the cached projection and recomputes the projection.
GET /admin/api/embedding_viz/statsReports whether UMAP and NumPy are installed, the embedding count, and the settings in use.

Encoder choice in the embeddings block

The embeddings block chooses one encoder for the embedding map and for diversity ordering. Every key is optional, and the block below shows the defaults:

yaml
embeddings:
  backend: auto        # auto, text, image, audio, video, or custom
  model: null          # the backend's default model when unset
  source_field: null   # the item field to embed; detected when unset
  cache_dir: null      # output_annotation_dir when unset
  media_root: null     # folder that relative media paths resolve against

With backend: auto, Potato reads the first 50 items and looks for media. A field counts as image, audio, or video when the field's value ends in a media extension (.jpg, .wav, .mp4, and others), or when the field has a media name such as image_url, audio_url, or video_url and the value looks like a path or URL. Media wins over text, because the text field of a media task often repeats one prompt on every item. The field found on the most sampled items wins, and a tie goes to image first. With no media field, Potato embeds the field that item_properties.text_key names. With neither, the map shows "nothing to embed" and asks for embeddings.source_field. Naming a backend without a field makes Potato pick the field for that backend from the items.

The table below lists each backend, the default model the backend loads, and the packages the backend needs:

BackendDefault modelNeeds
textall-MiniLM-L6-v2sentence-transformers
imageclip-ViT-B-32sentence-transformers and Pillow
audiolaion/clap-htsat-unfusedtransformers, plus soundfile or librosa
videoclip-ViT-B-32, over sampled framesthe image dependencies and ffmpeg on the PATH
customyour own encoderwhatever your encoder needs

The audio backend reads up to max_seconds of each clip (30 by default) at 48 kHz. With librosa installed, Potato resamples recordings at other rates. With only soundfile installed, Potato skips a recording at another rate. The video backend takes one frame per second from the first frames × 8 seconds of each clip, keeps frames evenly spaced frames (4 by default), and averages the frames' CLIP vectors. The video vectors therefore group clips by scene and subject, and carry no information about motion.

Potato stores image, audio, and video vectors under a .embeddings folder in cache_dir. An image path that is not absolute resolves against the folder Potato runs from, then against media_root. Set media_root when your data file names images relative to another folder.

Data sent off the server

The text, image, audio, and video backends run on your server. The embedding libraries download model weights the first time a model is used, and item content stays on the server. The image backend does not fetch http:// or https:// image references. Potato counts such an item as unreadable and gives the item a zero vector. The video backend does fetch remote clips, because Potato passes http:// and https:// references to ffmpeg, which downloads the frames from the remote host.

A custom backend sends item content wherever you point the backend. With entrypoint, Potato calls a Python function in the same process:

yaml
embeddings:
  backend: custom
  modality: image                            # the name the map card shows
  source_field: slide_url
  entrypoint: "mylab.encoders:embed_batch"   # list of str in, list of vectors out

With endpoint, Potato posts batches over HTTP:

yaml
embeddings:
  backend: custom
  modality: image
  source_field: image_url
  endpoint: "http://localhost:8900/embed"
  headers: {Authorization: "Bearer YOUR_TOKEN"}
  batch_size: 32

Each request body is {"inputs": [...]} with the values of source_field, plus "model" when embeddings.model is set. Potato sends the field values themselves. For a text item the value is the text, and for a media item the value is a path or URL, never the media file. The endpoint replies with {"embeddings": [[...]]} or with the OpenAI shape {"data": [{"embedding": [...]}]}. A reply with the wrong number of vectors is an error. Requests time out after timeout seconds (60 by default). Point endpoint at a host outside your network only when the item text may leave the network.

Finding near-duplicates

Duplicate items cost two annotations each and raise agreement, because two annotators agree easily about the same picture shown twice. The duplicate scan is part of the admin catalog, which Potato registers when the config enables curation:

yaml
curation:
  enabled: true

Potato 2.14.0 offers the scan as an admin API with no dashboard button. Call the scan with the admin API key:

bash
curl -H "X-API-Key: $ADMIN_KEY" \
  "http://localhost:8000/admin/catalog/api/duplicates?method=phash&max_distance=5"

The response gives n_items, n_groups, n_duplicates, duplicate_rate, largest_group, and a groups list. Each group names a keeper, the duplicates, the members, the size, and the method that grouped the members. A phash scan also reports n_hashed and n_unreadable.

The default method, phash, computes a 64-bit difference hash of each image on a 9 × 8 grayscale grid. A difference hash compares neighboring pixels and so tolerates re-encoding, mild rescaling, and brightness shifts. max_distance is the number of differing bits, out of 64, at which two images count as duplicates. The default is 5, and 0 catches only identical re-encodings. The scan needs Pillow.

The scan looks for an image path in the scheme fields source_field, image_key, and video_key, then in item_properties (image_key, media_key, and text_key), then in the fields image_url, file_name, image, path, and media. A path resolves as an absolute path, under task_dir, or as a file of the same name in <task_dir>/media/. Potato skips http://, https://, and data: references rather than downloading the files. When no item can be hashed, the note field says so and states that the result is not a finding of zero duplicates. A text corpus, or a corpus of remote image URLs, returns that note.

The second method, embedding, groups items whose cosine similarity is at least min_similarity (0.97 by default):

bash
curl -H "X-API-Key: $ADMIN_KEY" \
  "http://localhost:8000/admin/catalog/api/duplicates?method=embedding&min_similarity=0.97"

The embedding method reads the curation index, which the Build index button on the /admin/catalog page builds. The index embeds the field named by curation.text_key, or the item's text, with curation.model_name (all-MiniLM-L6-v2 by default), and ignores the embeddings block. Use the embedding method for reworded text. Two different frames of the one scene sit close together in embedding space, so the hash is the better test for images. Potato keeps the index in memory, so build the index again after a restart. Semantic Curation covers the index and the catalog's other uses.

Both methods group transitively. When A is near B and B is near C, all three share a group even if A and C are farther apart than the threshold. A slow camera pan therefore lands in one group instead of several overlapping pairs. The keeper is the member whose ID sorts first, so a second scan proposes the same keepers. Groups come back largest first.

Acting on duplicate groups

Post the duplicates of a group, without the keeper, to stop Potato assigning the duplicates:

bash
curl -X POST -H "X-API-Key: $ADMIN_KEY" -H "Content-Type: application/json" \
  -d '{"instance_ids": ["f0013", "f0014"]}' \
  http://localhost:8000/admin/catalog/api/duplicates/exclude

Potato removes the items from the queue of items not yet complete and deletes nothing. The items stay in the project, and annotations already made on the items stay in the output. The response lists excluded, n_excluded, and n_requested. Assigning an item leaves the item in the queue, so an item assigned but not finished is excluded and counted, and the annotator who already holds the item keeps the item. An item already complete is not in the queue and is not counted as excluded.

Potato holds the exclusion in memory. A restart reloads the data file and puts the excluded items back in the queue. Applying a reordering on the embedding map rebuilds the queue and puts the excluded items back as well. Send the exclude request again after a restart or a reordering.

Performance on large corpora

The embedding map draws at most sample_size points, 1,000 by default. Potato caches the projection for one set of item IDs. Once the embedded items outnumber sample_size, each load of the map draws a new random sample of unannotated items, so the cached projection does not match and UMAP runs again. Set sample_size at or above the number of embedded items to keep the cached projection, or lower sample_size to shorten each run. A large prefill_count lengthens the first startup, because Potato encodes the prefill items before the server starts. Later startups read the vectors from the cache.

The duplicate scan opens and hashes every local image on each request and compares every pair of hashes. The time a scan takes grows with the square of the item count. Run the scan once before annotation starts, and again after adding data.

Example project

The config below shows an image corpus on the embedding map and turns on the duplicate scan. Each line of data/frames.jsonl names one frame, as in {"id": "f0001", "image_url": "media/f0001.jpg"}. With backend: auto, Potato detects the .jpg paths and embeds the frames with CLIP, so the config needs no embeddings block. prefill_count and sample_size are both 2,000, so a corpus of up to 2,000 frames appears on the map in full and keeps the cached projection.

yaml
annotation_task_name: "Camera trap frames"
task_dir: "."
output_annotation_dir: "annotation_output"
data_files:
  - data/frames.jsonl
item_properties:
  id_key: id
  text_key: image_url
instance_display:
  fields:
    - key: image_url
      type: image
annotation_schemes:
  - annotation_type: radio
    name: species
    description: "Which animal is in the frame?"
    labels:
      - deer
      - fox
      - empty
diversity_ordering:
  enabled: true
  prefill_count: 2000
embedding_visualization:
  enabled: true
  sample_size: 2000
  label_source: majority
curation:
  enabled: true
user_config:
  allow_all_users: true

Start the server from the project folder, so the relative image paths resolve:

bash
potato start config.yaml -p 8000

Open http://localhost:8000/admin, enter the admin API key, and click the Embeddings tab. Run the phash scan from the section above to list duplicate frames. Potato also ships a text example in examples/advanced/embedding-visualization, with 52 sentiment items and label_source: majority.

Further reading

For implementation details, see the source documentation.