FashionCLIP Documentation

repository·master·Indexed 19 days ago

https://github.com/patrickjohncyh/fashion-clip

FashionCLIP is a CLIP-like model fine-tuned on over 700K fashion-related image-text pairs for domain-specific tasks including retrieval, classification, and fashion parsing. The library provides a high-level API via the FashionCLIP and FCLIPDataset classes for generating embeddings, performing zero-shot classification, and product retrieval. It is compatible with the Hugging Face Transformers API and supports local or S3-based image sources.

Tokens
2.5K
Snippets
11
Records
11
Agent score
18%

What's inside FashionCLIP

  1. How FCLIPDataset works

    master

    The FCLIPDataset class encapsulates catalog information and provides helper functions for data exploration and visualization. It is used to manage the relationship between images and their metadata (captions/IDs).

    Initialization Parameters:

    • name (str): Name of the dataset.
    • image_source_path (str): Absolute path to images (supports local or S3).
    • image_source_type (str): Type of source (local or s3).
    • catalog (List[dict], optional): List of dictionaries containing at minimum the keys ['id', 'image', 'caption'].
    from fashion_clip import FCLIPDataset
    
    # Using a pre-included dataset
    dataset = FCLIPDataset(name='FF', 
                           image_source_path='path/to/images', 
                           image_source_type='local')
    
    # Using a custom dataset
    my_catalog = [{'id': 1, 'image': 'x.jpg', 'caption': 'image x'}]
    dataset = FCLIPDataset(name='my_dataset', 
                           image_source_path='path/to/images', 
                           image_source_type='local', 
                           catalog=my_catalog)
  2. How the FashionCLIP class works

    master

    The FashionCLIP class is the primary abstraction for performing high-level tasks like multi-modal retrieval, zero-shot classification, and localization. It takes a Hugging Face CLIP model name (or local path) and an FCLIPDataset instance.

    If an unknown dataset/model combination is provided, it generates embeddings upon instantiation; otherwise, it pulls pre-computed vectors from S3.

    Initialization Parameters:

    • model_name (str): Name of the model OR path to a local model.
    • dataset (FCLIPDataset): The dataset instance to use.
    • normalize (bool): Option to convert embeddings to unit norm.
    • approx (bool): Option to use approximate nearest neighbors.
    from fashion_clip import FCLIPDataset, FashionCLIP
    
    dataset = FCLIPDataset(name='FF', 
                           image_source_path='path/to/images', 
                           image_source_type='local')
    
    fclip = FashionCLIP('fasihon-clip', dataset)
  3. Set up FCLIPDataset with local or remote data

    master

    To use FashionCLIP, you must first wrap your product data in an FCLIPDataset. The dataset expects a catalog which is a list of dictionaries. Each dictionary representing a product must contain the following keys:

    • id: A unique identifier for the product.
    • image: The filename of the image.
    • caption: A text description of the product.

    Currently, images are assumed to be stored in a local folder, though the API supports s3 via image_source_type.

    # Example: Loading a local dataset
    catalog = [
        {'id': 1, 'image': '16867424.jpg', 'caption': 'light red polo shirt'},
        {'id': 2, 'image': '16790484.jpg', 'caption': 'an adidas sneaker'},
        {'id': 3, 'image': '16198646.jpg', 'caption': 'dark red polo shirt'},
    ]
    
    dataset = FCLIPDataset(
        'farfetch_local',
        image_source_path='./images',
        image_source_type='local',
        catalog=catalog
    )
  4. Use FashionCLIP via Hugging Face Transformers API

    master

    Since FashionCLIP is hosted on Hugging Face, you can use the standard transformers library to load the model and processor for zero-shot tasks like image-text similarity scoring.

    from PIL import Image
    import requests
    from transformers import CLIPProcessor, CLIPModel
    
    model = CLIPModel.from_pretrained("patrickjohncyh/fashion-clip")
    processor = CLIPProcessor.from_pretrained("patrickjohncyh/fashion-clip")
    
    image = Image.open("images/image1.jpg")
    
    inputs = processor(text=["a photo of a red shoe", "a photo of a black shoe"],
                       images=image, return_tensors="pt", padding=True)
    
    outputs = model(**inputs)
    logits_per_image = outputs.logits_per_image  # this is the image-text similarity score
    probs = logits_per_image.softmax(dim=1)  
    print(probs)
  5. Generate image and text embeddings with FashionCLIP

    master

    Use the FashionCLIP class to encode lists of images and texts into embeddings. To perform similarity comparisons (like dot product), you should manually normalize the resulting embeddings to unit norm using np.linalg.norm.

    from fashion_clip.fashion_clip import FashionCLIP
    import numpy as np
    
    fclip = FashionCLIP('fashion-clip')
    
    # we create image embeddings and text embeddings
    image_embeddings = fclip.encode_images(images, batch_size=32)
    text_embeddings = fclip.encode_text(texts, batch_size=32)
    
    # we normalize the embeddings to unit norm (so that we can use dot product instead of cosine similarity to do comparisons)
    image_embeddings = image_embeddings/np.linalg.norm(image_embeddings, ord=2, axis=-1, keepdims=True)
    text_embeddings = text_embeddings/np.linalg.norm(text_embeddings, ord=2, axis=-1, keepdims=True)
  6. Perform product retrieval

    master

    Use fclip.retrieval to find products in your initialized FCLIPDataset that match a text query. The method returns a list of candidate indices from the dataset.

    # Retrieve products matching the query 'shoes'
    candidates = fclip.retrieval(['shoes'])
    print(candidates)
    
    # Display the results using the dataset object
    # dataset.ids[candidates[0]] retrieves the actual IDs for the top match
    _ = dataset.display_products(dataset.ids[candidates[0]], fields=tuple(['id']))
  7. Instantiate the FashionCLIP object

    master

    Create a FashionCLIP instance by providing a model identifier and an FCLIPDataset instance.

    Model options:

    • A pre-trained model name (e.g., 'fashion-clip' or 'openai/clip-vit-base-patch32').
    • A path to a local model file.

    Note on performance: If the specific combination of model and dataset has been processed before, FashionCLIP will download pre-processed vectors via hashing. Otherwise, it will generate new vectors for the dataset upon instantiation.

    from fashion_clip.fashion_clip import FashionCLIP
    
    # Instantiate with a pre-trained model and your dataset
    fclip = FashionCLIP('fashion-clip', dataset)
  8. Perform zero-shot classification

    master

    Use fclip.zero_shot_classification to classify one or more images against a list of text labels. This method does not rely on pre-processed vectors from the dataset but performs inference on the provided image paths.

    test_captions = ["nike sneakers", "adidas sneakers", "converse", "a gucci dress"]
    test_img_path = 'images/16790484.jpg'
    
    # Returns classification results for the provided image paths
    fclip.zero_shot_classification([test_img_path], test_captions)