Providing Images as Context

View as Markdown

🎨 Data Designer Tutorial: Providing Images as Context for Vision-Based Data Generation

📚 What you'll learn

This notebook demonstrates how to provide images as context to generate text descriptions using vision-language models. The same multi_modal_context field can also carry audio or video context when the selected model supports those modalities.

  • Visual Document Processing: Converting images to chat-ready format for model consumption
  • 🔍 Vision-Language Generation: Using vision models to generate detailed summaries from images
  • 🧩 Media Context Pattern: Understanding how ImageContext, AudioContext, and VideoContext fit into the same configuration field

If this is your first time using Data Designer, we recommend starting with the first notebook in this tutorial series.

📦 Import Data Designer

  • data_designer.config provides access to the configuration API.

  • DataDesigner is the main interface for data generation.

Python
1# Standard library imports
2import base64
3import io
4import os
5import uuid
6
7# Third-party imports
8import pandas as pd
9import rich
10from datasets import load_dataset
11from IPython.display import display
12from rich.panel import Panel
13
14# Data Designer imports
15import data_designer.config as dd
16from data_designer.interface import DataDesigner
17

⚙️ Initialize the Data Designer interface

  • DataDesigner is the main object responsible for managing the data generation process.

  • When initialized without arguments, the default model providers are used.

Python
1data_designer = DataDesigner()
2

🏗️ Initialize the Data Designer Config Builder

  • The Data Designer config defines the dataset schema and generation process.

  • The config builder provides an intuitive interface for building this configuration.

  • When initialized without arguments, the default model configurations are used.

Python
1config_builder = dd.DataDesignerConfigBuilder()
2if os.environ.get("DATA_DESIGNER_SKIP_NVIDIA_VISION_HEALTH_CHECK"):
3 for model_config in config_builder.model_configs:
4 if model_config.alias == "nvidia-vision":
5 model_config.skip_health_check = True
6 break
7

🌱 Seed Dataset Creation

In this section, we'll prepare our visual documents as a seed dataset for summarization:

  • Loading Visual Documents: We use a small pets image dataset containing labeled images
  • Image Processing: Convert images to base64 format for vision model consumption
  • Metadata Extraction: Preserve relevant image information (label, etc.)

The seed dataset will be used to generate detailed text descriptions of each image.

Python
1# Dataset processing configuration
2IMG_COUNT = 512 # Number of images to process
3BASE64_IMAGE_HEIGHT = 512 # Standardized height for model input
4
5# Load the pets dataset (train split, ~23 MB total)
6img_dataset_cfg = {"path": "rokmr/pets", "split": "train"}
7
Python
1def resize_image(image, height: int):
2 """
3 Resize image while maintaining aspect ratio.
4
5 Args:
6 image: PIL Image object
7 height: Target height in pixels
8
9 Returns:
10 Resized PIL Image object
11 """
12 original_width, original_height = image.size
13 width = int(original_width * (height / original_height))
14 return image.resize((width, height))
15
16
17def convert_image_to_chat_format(record, height: int) -> dict:
18 """
19 Convert PIL image to base64 format for chat template usage.
20
21 Args:
22 record: Dataset record containing image and metadata
23 height: Target height for image resizing
24
25 Returns:
26 Updated record with base64_image and uuid fields
27 """
28 image = resize_image(record["image"], height)
29
30 img_buffer = io.BytesIO()
31 image.save(img_buffer, format="PNG")
32 byte_data = img_buffer.getvalue()
33 base64_encoded_data = base64.b64encode(byte_data)
34 base64_string = base64_encoded_data.decode("utf-8")
35
36 return record | {"base64_image": base64_string, "uuid": str(uuid.uuid4())}
37
Python
1# Load and process the image dataset
2print("📥 Loading and processing images...")
3
4img_dataset = load_dataset(**img_dataset_cfg).map(
5 convert_image_to_chat_format, fn_kwargs={"height": BASE64_IMAGE_HEIGHT}
6)
7img_dataset = pd.DataFrame(img_dataset[:IMG_COUNT])
8
9print(f"✅ Loaded {len(img_dataset)} images with columns: {list(img_dataset.columns)}")
10
Python
1img_dataset.head()
2
Python
1# Add the seed dataset containing our processed images
2df_seed = pd.DataFrame(img_dataset)[["uuid", "label", "base64_image"]]
3config_builder.with_seed_dataset(dd.DataFrameSeedSource(df=df_seed))
4

🧩 Media context and model capabilities

multi_modal_context accepts media context descriptors such as ImageContext, AudioContext, and VideoContext. Data Designer reads the referenced seed columns and serializes them for the model request, but the selected model still determines which modalities are valid.

This notebook uses image context only because image-capable VLMs are broadly available. Before combining image, audio, and video in one column, choose a model alias backed by an omni or otherwise modality-compatible model, and check that the provider accepts every context type you send.

For base64 seed columns, store the raw base64 payload without a data:<media-type>;base64, prefix and specify the media format on the context object:

media_context = [
    dd.ImageContext(
        column_name="image_base64",
        data_type=dd.ModalityDataType.BASE64,
        image_format=dd.ImageFormat.PNG,
    ),
    dd.AudioContext(
        column_name="audio_base64",
        data_type=dd.ModalityDataType.BASE64,
        audio_format=dd.AudioFormat.MP3,
    ),
    dd.VideoContext(
        column_name="video_base64",
        data_type=dd.ModalityDataType.BASE64,
        video_format=dd.VideoFormat.MP4,
    ),
]

URL-backed media can use data_type=dd.ModalityDataType.URL, subject to the provider's URL support and file-size limits. Local audio/video paths require explicit URL mode and require the model endpoint to have filesystem access to the same paths, typically a colocated vLLM server configured for local media access.

Python
1# Add a column to generate detailed image descriptions
2config_builder.add_column(
3 dd.LLMTextColumnConfig(
4 name="description",
5 model_alias="nvidia-vision",
6 prompt=(
7 "Provide a detailed description of the content in this image in Markdown format. "
8 "Describe the main subject, background, colors, and any notable details."
9 ),
10 multi_modal_context=[dd.ImageContext(column_name="base64_image")],
11 )
12)
13
14data_designer.validate(config_builder)
15

🔁 Iteration is key – preview the dataset!

  1. Use the preview method to generate a sample of records quickly.

  2. Inspect the results for quality and format issues.

  3. Adjust column configurations, prompts, or parameters as needed.

  4. Re-run the preview until satisfied.

Python
1preview = data_designer.preview(config_builder, num_records=2)
2
Python
1# Run this cell multiple times to cycle through the 2 preview records.
2preview.display_sample_record()
3
Python
1# The preview dataset is available as a pandas DataFrame.
2preview.dataset
3

📊 Analyze the generated data

  • Data Designer automatically generates a basic statistical analysis of the generated data.

  • This analysis is available via the analysis property of generation result objects.

Python
1# Print the analysis as a table.
2preview.analysis.to_report()
3

🔎 Visual Inspection

Let's compare the original image with the generated description to validate quality:

Python
1# Compare original image with generated description
2index = 0 # Change this to view different examples
3
4# Merge preview data with original images for comparison
5comparison_dataset = preview.dataset.merge(pd.DataFrame(img_dataset)[["uuid", "image"]], how="left", on="uuid")
6
7# Extract the record for display
8record = comparison_dataset.iloc[index]
9
10print("📄 Original Image:")
11display(resize_image(record.image, BASE64_IMAGE_HEIGHT))
12
13print("\n📝 Generated Description:")
14rich.print(Panel(record.description, title="Image Description", title_align="left"))
15

🆙 Scale up!

  • Happy with your preview data?

  • Use the create method to submit larger Data Designer generation jobs.

Python
1results = data_designer.create(config_builder, num_records=10, dataset_name="tutorial-4")
2
Python
1# Load the generated dataset as a pandas DataFrame.
2dataset = results.load_dataset()
3
4dataset.head()
5
Python
1# Load the analysis results into memory.
2analysis = results.load_analysis()
3
4analysis.to_report()
5

⏭️ Next Steps

Now that you've learned how to use visual context for image summarization in Data Designer, explore more:

  • Experiment with different vision models for specific image types

  • Try different prompt variations to generate specialized descriptions (e.g., technical details, key findings)

  • Combine image, audio, or video context with other column types after confirming your selected model supports those modalities

  • Apply this pattern to other vision tasks like image captioning, OCR validation, or visual question answering

  • Generating images with Data Designer