image imagewidth (px) 1.8k 3.23k |
|---|
YAML Metadata Warning:empty or missing yaml metadata in repo card
Check out the documentation for more information.
In the Summer of 2024, in Yarmouth on Cape Cod, Massachusettes, I purchased a box of computer/tech junk at a church "fair" (bag sale). Recently, upon closer inspection I discovered that I purchased a seagate USB disk drive containing computer backups and a CVS-made Photo Series with a video. It seems to be the ancient family photos of a "Whittemore" family. Some of the images seem to be scenes of on Cape Cod and Martha's Vinyard. Hopefully, someone in that family will find these photos and copy them for posterity. Others might find the oldest images useful for AI developement, facial recognition, or for developing AI methods of identifying ancestral/family ties based on facial recognition.
You can write a powerful Python script to automatically index all the images in that Hugging Face repository and then retrieve any of them on demand to your local machine.
The best way to interact with Hugging Face is by using their official library, huggingface_hub. This avoids fragile web scraping and uses their public API.
How It Works
build_image_index() function:
It uses list_repo_files from the huggingface_hub library to get a complete list of every file in the specified dataset repository.
It then filters this list to make sure we only include files with common image extensions (.jpg, .png, etc.).
Finally, it loads these filenames into a pandas DataFrame, which serves as a clean, searchable index. This is printed to the screen so you can easily see what's available to download.
retrieve_images() function:
It takes the index and your list of desired filenames as input.
It first ensures the destination folder on your laptop exists, creating it if necessary.
It iterates through your list (IMAGES_TO_DOWNLOAD). For each filename, it checks if it exists in the index to avoid errors.
The core of the retrieval is the hf_hub_download function. You simply tell it which repository and which file you want, and it handles the download securely and efficiently.
The argument local_dir_use_symlinks=False is important; it guarantees that the script places a physical copy of the image in your DESTINATION_FOLDER rather than a shortcut to a central cache folder.
Here is a complete solution.
Prerequisite: Install Required Python Libraries
You will need to install two libraries. Open a Command Prompt or PowerShell and run the following command:
pip install huggingface_hub pandas
huggingface_hub: The official library for interacting with the Hugging Face Hub (where the dataset is stored).
pandas: Used to create a clean, searchable index of the image files.
The Python Script: Index and Retrieve
This single script can perform both indexing and retrieval. You simply configure what you want it to do in the main section.
How to Use:
Save the code below as a Python file (e.g., retrieve_hf_images.py).
Modify the three variables in the "CONFIGURATION" section at the bottom of the script:
DESTINATION_FOLDER: Set the path where you want to save the downloaded images.
IMAGES_TO_DOWNLOAD: Create a list of the exact filenames you want to retrieve. You can find these by looking at the dataset page or by first running the script just to see the index.
Run the script from your terminal: python retrieve_hf_images.py
import pandas as pd from huggingface_hub import list_repo_files, hf_hub_download
--- REPOSITORY DETAILS ---
This identifies the specific dataset on Hugging Face
REPO_ID = "MartialTerran/WHITTEMORE_FAMILY_MEMORIES_Ancient_PHOTOS_scanned" REPO_TYPE = "dataset"
def build_image_index(): """ Connects to the Hugging Face repository and creates a searchable index of all images.
Returns:
pandas.DataFrame: A DataFrame with a 'filename' column listing all images.
"""
print(f"Connecting to Hugging Face repository: {REPO_ID}...")
try:
# Get a list of all files in the repository
all_files = list_repo_files(repo_id=REPO_ID, repo_type=REPO_TYPE)
# Filter this list to include only common image file formats
supported_formats = ('.jpg', '.jpeg', '.png', '.bmp', '.gif')
image_files = [f for f in all_files if f.lower().endswith(supported_formats)]
if not image_files:
print("Warning: No image files found in the repository.")
return pd.DataFrame({'filename': []})
print(f"Successfully found {len(image_files)} images.")
# Create a pandas DataFrame to act as our index
index_df = pd.DataFrame(image_files, columns=['filename'])
return index_df
except Exception as e:
print(f"An error occurred while building the index: {e}")
return None
def retrieve_images(image_index, filenames_to_get, output_folder): """ Downloads specified images from the Hugging Face repository to a local folder.
Args:
image_index (pandas.DataFrame): The DataFrame containing the list of available files.
filenames_to_get (list): A list of string filenames to download.
output_folder (str): The local path to save the downloaded images.
"""
if image_index is None or image_index.empty:
print("Cannot retrieve images because the index is empty or invalid.")
return
# Create the destination folder if it doesn't already exist
os.makedirs(output_folder, exist_ok=True)
print(f"\nStarting download process. Files will be saved to: {output_folder}")
available_files = set(image_index['filename'])
for filename in filenames_to_get:
# Check if the requested file is in our index of available images
if filename in available_files:
print(f" - Downloading '{filename}'...")
try:
# Use the hf_hub_download function to get the file
hf_hub_download(
repo_id=REPO_ID,
repo_type=REPO_TYPE,
filename=filename,
local_dir=output_folder,
local_dir_use_symlinks=False # Ensures a true file copy on all systems
)
print(f" - Successfully saved '{filename}'")
except Exception as e:
print(f" - Failed to download '{filename}'. Error: {e}")
else:
print(f" - Warning: '{filename}' not found in the repository index. Skipping.")
if name == "main":
# --- STEP 1: INDEXING ---
# The script always builds the index first so you know what's available.
image_index = build_image_index()
if image_index is not None and not image_index.empty:
print("\n--- Available Image Index ---")
# To see all files, uncomment the line below
# pd.set_option('display.max_rows', None)
print(image_index)
print("---------------------------\n")
# --- STEP 2: RETRIEVAL ---
# --- CONFIGURATION ---
# 1. Set the folder on your laptop where images should be saved.
DESTINATION_FOLDER = r"C:\Retrieved_Family_Photos"
# 2. List the exact filenames of the images you want to retrieve.
# (Copy and paste from the index printed above)
IMAGES_TO_DOWNLOAD = [
"025.jpg",
"041.jpg",
"a_file_that_does_not_exist.jpg" # Example of a file that will be skipped
]
# --- END CONFIGURATION ---
retrieve_images(image_index, IMAGES_TO_DOWNLOAD, DESTINATION_FOLDER)
print("\nAutomation script finished.")
license: cc-by-4.0
- Downloads last month
- 12