# python create_dataset.py # cd .. && huggingface-cli upload-large-folder anokimchen/geometric_shapes geometric_shapes --repo-type dataset && cd geometric_shapes # Python version: 3.10.10 (main, Mar 21 2023, 13:41:39) [Clang 14.0.6 ] # os: Built-in (part of Python 3.10.10) # random: Built-in (part of Python 3.10.10) # csv: 1.0 # numpy: 1.26.4 # matplotlib: 3.8.2 # tqdm: 4.67.1 # time: Built-in (part of Python 3.10.10) # json: 2.0.9 # multiprocessing: Built-in (part of Python 3.10.10) import os import random import csv import numpy as np import matplotlib matplotlib.use('Agg') # Set non-interactive backend import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as patches from tqdm import tqdm import time, json import multiprocessing as mp from functools import partial # List of shapes shapes = [ "circle", "square", "triangle", "rectangle", "pentagon", "hexagon", "heptagon", "octagon", "nonagon", "decagon", "hendecagon", "dodecagon", "tridecagon", "tetradecagon", "pentadecagon", "hexadecagon", "heptadecagon", "octadecagon", "enneadecagon", "icosagon", "ellipse", "parallelogram", "trapezoid", "rhombus", "star", "crescent", "heart", "cross", "arrow", "diamond", "kite", "oval", "semicircle", "sector", "torus", "annulus", "deltoid", "astroid", "superellipse", "hypotrochoid", "epitrochoid", "lemniscate", "quadrifolium", "trefoil", "clover", "bean", "peanut", "lune", "vesica piscis", "spherical cap", "spherical wedge", "spherical lune", "hypocycloid", "epicycloid" ] # Colors with their names colors = { 'red': '#FF0000', 'green': '#00FF00', 'blue': '#0000FF', 'yellow': '#FFFF00', 'cyan': '#00FFFF', 'magenta': '#FF00FF', 'purple': '#800080', 'orange': '#FFA500', 'pink': '#FFC0CB', 'brown': '#A52A2A', 'black': '#000000', 'white': '#FFFFFF', 'gray': '#808080', 'lime': '#32CD32', 'navy': '#000080', 'teal': '#008080', 'olive': '#808000', 'maroon': '#800000', 'coral': '#FF7F50', 'gold': '#FFD700', 'silver': '#C0C0C0', 'indigo': '#4B0082', 'turquoise': '#40E0D0', 'violet': '#EE82EE', 'khaki': '#F0E68C', 'salmon': '#FA8072', 'crimson': '#DC143C', 'lavender': '#E6E6FA', 'plum': '#DDA0DD', 'orchid': '#DA70D6', 'chocolate': '#D2691E' } # Size descriptions size_descriptions = { (0, 15): ["tiny", "minuscule", "microscopic", "very small", "itty-bitty"], (15, 30): ["small", "little", "petite", "diminutive", "compact"], (30, 50): ["medium", "moderate", "average", "intermediate", "mid-sized"], (50, 75): ["large", "big", "substantial", "sizable", "considerable"], (75, 90): ["very large", "huge", "enormous", "immense", "massive"], (90, 100): ["gigantic", "colossal", "gargantuan", "titanic", "mammoth"] } # Define polygon sides mapping at module level polygon_sides = { "pentagon": 5, "hexagon": 6, "heptagon": 7, "octagon": 8, "nonagon": 9, "decagon": 10, "hendecagon": 11, "dodecagon": 12, "tridecagon": 13, "tetradecagon": 14, "pentadecagon": 15, "hexadecagon": 16, "heptadecagon": 17, "octadecagon": 18, "enneadecagon": 19, "icosagon": 20 } def get_size_description(size_percent): for (min_val, max_val), descriptions in size_descriptions.items(): if min_val <= size_percent < max_val: return random.choice(descriptions) return random.choice(size_descriptions[(90, 100)]) # Default to largest if out of range def regular_polygon(sides, radius=0.4, rotation=0, center=(0.5, 0.5)): """Generate coordinates for a regular polygon.""" angles = np.linspace(0 + rotation, 2 * np.pi + rotation, sides + 1)[:-1] x = center[0] + radius * np.cos(angles) y = center[1] + radius * np.sin(angles) return list(zip(x, y)) def star_coords(points=5, inner_radius=0.2, outer_radius=0.4, center=(0.5, 0.5)): """Generate coordinates for a star.""" all_angles = np.linspace(0, 2 * np.pi, 2 * points, endpoint=False) radii = [outer_radius, inner_radius] * points x = center[0] + np.array([r * np.cos(a) for r, a in zip(radii, all_angles)]) y = center[1] + np.array([r * np.sin(a) for r, a in zip(radii, all_angles)]) return list(zip(x, y)) def draw_shape(shape, ax, size_factor=1.0): """Draw a shape with the given size factor (0.0 to 1.0).""" center = (0.5, 0.5) color_name = random.choice(list(colors.keys())) color_hex = colors[color_name] # Base size for scaling (as a fraction of available space) base_size = 0.4 * size_factor if shape == "circle": circle = plt.Circle(center, base_size, color=color_hex) ax.add_patch(circle) elif shape == "square": offset = 0.5 - base_size square = plt.Rectangle((offset, offset), 2*base_size, 2*base_size, color=color_hex) ax.add_patch(square) elif shape == "triangle": height = 2 * base_size base_width = 2 * base_size triangle = plt.Polygon([ (0.5, 0.5 + height/2), (0.5 - base_width/2, 0.5 - height/2), (0.5 + base_width/2, 0.5 - height/2) ], color=color_hex) ax.add_patch(triangle) elif shape == "rectangle": width = 2 * base_size height = 1.5 * base_size offset_x = 0.5 - width/2 offset_y = 0.5 - height/2 rectangle = plt.Rectangle((offset_x, offset_y), width, height, color=color_hex) ax.add_patch(rectangle) elif shape in polygon_sides: sides = polygon_sides[shape] polygon = plt.Polygon(regular_polygon(sides, radius=base_size), color=color_hex) ax.add_patch(polygon) elif shape == "ellipse" or shape == "oval": width = 2 * base_size height = 1.3 * base_size ellipse = patches.Ellipse(center, width, height, color=color_hex) ax.add_patch(ellipse) elif shape == "parallelogram": skew = base_size * 0.3 parallelogram = plt.Polygon([ (0.5-base_size, 0.5-base_size/2), (0.5+base_size-skew, 0.5-base_size/2), (0.5+base_size, 0.5+base_size/2), (0.5-base_size+skew, 0.5+base_size/2) ], color=color_hex) ax.add_patch(parallelogram) elif shape == "trapezoid": top_width = base_size * 1.2 bottom_width = base_size * 2 height = base_size * 1.5 trapezoid = plt.Polygon([ (0.5-bottom_width/2, 0.5-height/2), (0.5+bottom_width/2, 0.5-height/2), (0.5+top_width/2, 0.5+height/2), (0.5-top_width/2, 0.5+height/2) ], color=color_hex) ax.add_patch(trapezoid) elif shape == "rhombus" or shape == "diamond": width = base_size * 1.8 height = base_size * 1.8 rhombus = plt.Polygon([ (0.5, 0.5-height/2), (0.5+width/2, 0.5), (0.5, 0.5+height/2), (0.5-width/2, 0.5) ], color=color_hex) ax.add_patch(rhombus) elif shape == "star": star = plt.Polygon(star_coords( points=5, inner_radius=base_size * 0.5, outer_radius=base_size * 1.3 ), color=color_hex) ax.add_patch(star) elif shape == "crescent": # Create a crescent by taking the difference of two circles circle1 = plt.Circle(center, base_size, color=color_hex) offset = base_size * 0.3 circle2 = plt.Circle((0.5 + offset, 0.5), base_size * 0.9, color='white') ax.add_patch(circle1) ax.add_patch(circle2) elif shape == "heart": t = np.linspace(0, 2*np.pi, 100) x = 0.5 + base_size * (16 * np.sin(t)**3) / 16 y = 0.5 + base_size * (13 * np.cos(t) - 5 * np.cos(2*t) - 2 * np.cos(3*t) - np.cos(4*t)) / 16 heart = plt.Polygon(list(zip(x, y)), color=color_hex) ax.add_patch(heart) elif shape == "cross": width = base_size * 0.5 length = base_size * 1.5 cross = plt.Polygon([ (0.5-width/2, 0.5-length/2), (0.5+width/2, 0.5-length/2), (0.5+width/2, 0.5-width/2), (0.5+length/2, 0.5-width/2), (0.5+length/2, 0.5+width/2), (0.5+width/2, 0.5+width/2), (0.5+width/2, 0.5+length/2), (0.5-width/2, 0.5+length/2), (0.5-width/2, 0.5+width/2), (0.5-length/2, 0.5+width/2), (0.5-length/2, 0.5-width/2), (0.5-width/2, 0.5-width/2) ], color=color_hex) ax.add_patch(cross) elif shape == "arrow": arrow_length = base_size * 2 arrow_width = base_size * 0.8 arrow_head = base_size * 1.2 arrow = plt.Polygon([ (0.5-arrow_length/2, 0.5), (0.5+arrow_length/2-arrow_head, 0.5-arrow_width/2), (0.5+arrow_length/2-arrow_head, 0.5-arrow_width/4), (0.5+arrow_length/2, 0.5), (0.5+arrow_length/2-arrow_head, 0.5+arrow_width/4), (0.5+arrow_length/2-arrow_head, 0.5+arrow_width/2) ], color=color_hex) ax.add_patch(arrow) elif shape == "kite": width = base_size * 1.5 height = base_size * 2.2 kite = plt.Polygon([ (0.5, 0.5+height/2), (0.5+width/2, 0.5), (0.5, 0.5-height/2), (0.5-width/2, 0.5) ], color=color_hex) ax.add_patch(kite) elif shape == "semicircle": theta = np.linspace(0, np.pi, 100) x = center[0] + base_size * np.cos(theta) y = center[1] + base_size * np.sin(theta) # Add a straight line at the bottom x = np.append(x, [center[0] - base_size, center[0]]) y = np.append(y, [center[1], center[1]]) semicircle = plt.Polygon(list(zip(x, y)), color=color_hex) ax.add_patch(semicircle) elif shape == "sector": theta = np.linspace(0, np.pi/2, 100) x = center[0] + base_size * np.cos(theta) y = center[1] + base_size * np.sin(theta) # Add lines to center x = np.append(x, [center[0]]) y = np.append(y, [center[1]]) sector = plt.Polygon(list(zip(x, y)), color=color_hex) ax.add_patch(sector) elif shape == "torus" or shape == "annulus": # Create an annulus/torus by drawing two concentric circles outer = plt.Circle(center, base_size, fill=True, color=color_hex) inner = plt.Circle(center, base_size * 0.5, fill=True, color='white') ax.add_patch(outer) ax.add_patch(inner) elif shape == "deltoid": t = np.linspace(0, 2*np.pi, 100) a, b = base_size, base_size * 0.3 x = center[0] + a * np.cos(t) + b * np.cos(3*t) y = center[1] + a * np.sin(t) - b * np.sin(3*t) deltoid = plt.Polygon(list(zip(x, y)), color=color_hex) ax.add_patch(deltoid) elif shape == "astroid": t = np.linspace(0, 2*np.pi, 100) a = base_size * 1.3 x = center[0] + a * np.cos(t)**3 y = center[1] + a * np.sin(t)**3 astroid = plt.Polygon(list(zip(x, y)), color=color_hex) ax.add_patch(astroid) elif shape == "lemniscate": t = np.linspace(-np.pi/4, np.pi/4, 100) a = base_size * 0.7 x = center[0] + a * np.sqrt(2) * np.cos(t) / (np.sin(t)**2 + 1) y = center[1] + a * np.sqrt(2) * np.cos(t) * np.sin(t) / (np.sin(t)**2 + 1) # Add the bottom half t = np.linspace(3*np.pi/4, 5*np.pi/4, 100) x2 = center[0] + a * np.sqrt(2) * np.cos(t) / (np.sin(t)**2 + 1) y2 = center[1] + a * np.sqrt(2) * np.cos(t) * np.sin(t) / (np.sin(t)**2 + 1) x = np.append(x, x2) y = np.append(y, y2) plt.plot(x, y, color=color_hex, linewidth=4*size_factor) elif shape in ["quadrifolium", "trefoil", "clover"]: if shape == "quadrifolium": n = 4 # Four petals elif shape == "trefoil": n = 3 # Three petals else: # clover n = 4 # Four petals, same as quadrifolium t = np.linspace(0, 2*np.pi, 1000) a = base_size x = center[0] + a * np.cos(n*t) * np.cos(t) y = center[1] + a * np.cos(n*t) * np.sin(t) plt.plot(x, y, color=color_hex, linewidth=4*size_factor) elif shape in ["bean", "peanut"]: t = np.linspace(0, 2*np.pi, 100) a, b = base_size * 1.5, base_size * 0.7 x = center[0] + a * np.sin(t) y = center[1] + b * np.sin(t) * np.cos(t) bean = plt.Polygon(list(zip(x, y)), color=color_hex) ax.add_patch(bean) elif shape == "lune" or shape == "vesica piscis": # Create intersecting circles circle1 = plt.Circle((0.5 - base_size*0.3, 0.5), base_size, color=color_hex, alpha=0.7) circle2 = plt.Circle((0.5 + base_size*0.3, 0.5), base_size, color=color_hex, alpha=0.7) ax.add_patch(circle1) ax.add_patch(circle2) elif shape in ["hypocycloid", "epicycloid", "hypotrochoid", "epitrochoid"]: R = base_size * 1.2 # Radius of fixed circle r = base_size * 0.4 # Radius of rolling circle d = base_size * 0.2 # Distance from center of rolling circle t = np.linspace(0, 2*np.pi, 1000) if shape == "hypocycloid": x = center[0] + (R-r) * np.cos(t) + r * np.cos((R-r)*t/r) y = center[1] + (R-r) * np.sin(t) - r * np.sin((R-r)*t/r) elif shape == "epicycloid": x = center[0] + (R+r) * np.cos(t) - r * np.cos((R+r)*t/r) y = center[1] + (R+r) * np.sin(t) - r * np.sin((R+r)*t/r) elif shape == "hypotrochoid": x = center[0] + (R-r) * np.cos(t) + d * np.cos((R-r)*t/r) y = center[1] + (R-r) * np.sin(t) - d * np.sin((R-r)*t/r) elif shape == "epitrochoid": x = center[0] + (R+r) * np.cos(t) - d * np.cos((R+r)*t/r) y = center[1] + (R+r) * np.sin(t) - d * np.sin((R+r)*t/r) plt.plot(x, y, color=color_hex, linewidth=3*size_factor) elif shape in ["spherical cap", "spherical wedge", "spherical lune"]: if shape == "spherical cap": # Approximate with an ellipse ellipse = patches.Ellipse(center, base_size*2, base_size, color=color_hex) ax.add_patch(ellipse) elif shape == "spherical wedge": # Approximate with a sector theta = np.linspace(0, np.pi/3, 100) x = center[0] + base_size * np.cos(theta) y = center[1] + base_size * np.sin(theta) x = np.append(x, [center[0]]) y = np.append(y, [center[1]]) sector = plt.Polygon(list(zip(x, y)), color=color_hex) ax.add_patch(sector) elif shape == "spherical lune": # Approximate with a lune circle1 = plt.Circle((0.5 - base_size*0.3, 0.5), base_size, color=color_hex, alpha=0.7) circle2 = plt.Circle((0.5 + base_size*0.3, 0.5), base_size, color=color_hex, alpha=0.7) ax.add_patch(circle1) ax.add_patch(circle2) elif shape == "superellipse": t = np.linspace(0, 2*np.pi, 100) n = 4 # Controls the shape (higher n = more square-like) a, b = base_size * 1.5, base_size * 1.5 x = center[0] + a * np.sign(np.cos(t)) * np.abs(np.cos(t))**(2/n) y = center[1] + b * np.sign(np.sin(t)) * np.abs(np.sin(t))**(2/n) superellipse = plt.Polygon(list(zip(x, y)), color=color_hex) ax.add_patch(superellipse) else: # Default for any unhandled shapes text = f"{shape}" ax.text(0.5, 0.5, text, fontsize=16*size_factor, ha='center', va='center', color=color_hex) return color_name, size_factor * 100 # Return color name and size percentage def generate_caption(shape, color, size_percent): """Generate diverse captions in random order.""" size_description = get_size_description(size_percent) # Create the caption components components = [ f"a {shape}", f"a {color} shape", f"a {size_description} object", f"a shape that is {size_percent:.1f}% of maximum size" ] # Randomly select and order the components selected_components = random.sample(components, k=random.randint(2, 4)) # Join the components into a caption caption = " ".join(selected_components) # Sometimes completely randomize the order of words if random.random() < 0.25: all_words = caption.split() random.shuffle(all_words) caption = " ".join(all_words) alternatives = [ f"This image shows {caption}.", f"An illustration containing {caption}.", f"A {color} {size_description} {shape}.", f"The picture depicts {caption}.", f"{caption.capitalize()}.", f"A {size_description} {color} {shape} at {size_percent:.1f}% size.", f"The image features {caption}.", f"{size_description.capitalize()} {color} {shape}.", f"{shape.capitalize()} ({color}, {size_percent:.1f}% size).", f"{color.capitalize()} {shape} of {size_description} size." ] # Add more diversity to the captions alternatives.extend([ # Simple alternatives f"A {shape}.", f"{color.capitalize()} {shape}.", f"{caption}.", f"Image: {shape}.", f"A geometric figure.", # Descriptive alternatives f"A finely detailed {color} {shape} rendered with precision at {size_percent:.1f}% of standard dimensions.", f"The illustration presents a meticulously crafted {color} {shape}, notable for its {size_description} proportions and clean lines.", f"This high-quality visual representation features a {color} {shape} with dimensions calibrated to {size_percent:.1f}% of the reference size.", f"An expertly rendered {size_description} {color} {shape} displayed with attention to geometric accuracy.", f"The image showcases a precisely defined {color} {shape} with carefully maintained proportions at {size_percent:.1f}% scale.", # Minimal description f"{shape}.", f"{color}.", f"Figure.", f"Geometric.", f"Visual.", # All variables f"A {size_description} {color} {shape} rendered at {size_percent:.1f}% scale depicting {caption}.", f"This {size_description} {color} {shape} ({size_percent:.1f}%) represents {caption}.", f"Visual element: {size_description} {color} {shape}, {size_percent:.1f}%, {caption}.", f"{caption}: {size_description} {color} {shape} at {size_percent:.1f}% relative size.", f"{color.capitalize()} {size_description} {shape} ({size_percent:.1f}%) displaying {caption}.", # No variables (completely generic) f"A geometric shape.", f"A visual element.", f"A colored shape.", f"A geometric figure.", f"A visual representation.", # Technical focus f"Object class: {shape}; color: {color}; size modifier: {size_percent:.1f}%.", f"Visual asset: type={shape}, color={color}, size={size_percent:.1f}%, description='{caption}'.", f"Element[{shape}]: color={color}, scale={size_percent:.1f}%, desc='{caption}'.", f"Geometric representation (type: {shape}, color: {color}, scale: {size_percent:.1f}%).", f"Visual.render({shape}, {color}, {size_percent:.1f}%, '{caption}').", # Creative alternatives f"Behold, a {color} {shape} of {size_description} dimensions!", f"Gaze upon this {size_description} {color} {shape}, a testament to geometric elegance.", f"A wild {color} {shape} appears! It seems to be {size_description}.", f"The canvas reveals a {color} {shape}, sized at a modest {size_percent:.1f}% of potential.", f"Lo! A {color} {shape} of {size_description} proportions graces your vision.", # Mixed variable usage f"A {color} figure at {size_percent:.1f}% scale.", f"{size_description.capitalize()} {shape}.", f"{color.capitalize()} geometric element depicting {caption}.", f"Shape type: {shape}; Size: {size_description}.", f"This {color} element represents {caption}.", # Academic style f"The figure presents a {color} {shape} (n={size_percent:.1f}%, p<0.05) consistent with {caption}.", f"Fig. 1: {color.capitalize()} {shape} at {size_percent:.1f}% relative scale.", f"A {size_description} {color} {shape}, characteristic of category '{caption}'.", f"Visual stimulus: {color} {shape} (scale factor: {size_percent:.1f}).", f"Specimen: {color} {shape}, scaled to {size_percent:.1f}% of reference dimensions.", # Alternative sentence structures f"What you see is a {color} {shape}.", f"There exists a {size_description} {color} {shape} in this image.", f"Shown here: {color} {shape}, {size_description}.", f"Present in the visual field: one {color} {shape}.", f"Contained within: a {size_description} {color} {shape}.", # Using only some variables in different combinations f"A {color} form.", f"The {size_description} element.", f"{size_percent:.1f}% sized object.", f"{caption} represented by a {shape}.", f"{shape.capitalize()} expressing {caption}." ]) return random.choice(alternatives) def get_folder_name(image_index, images_per_folder=5000): """Generate folder name based on image index.""" folder_number = (image_index // images_per_folder) + 1 return f"dataset/images_{folder_number:03d}" def write_to_csv(file_path, data): """Write data to a CSV file.""" with open(file_path, mode='w', newline='') as file: writer = csv.writer(file) writer.writerow(["file_name", "caption"]) for folder_name, file_name, caption in data: writer.writerow([file_name, caption]) def generate_single_image_process(i, img_size=(512, 512), images_per_folder=5000): """Process-safe version of image generation.""" # Each process needs its own matplotlib backend setup import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt shape = random.choice(shapes) size_factor = random.uniform(0.1, 1.0) # Random size from 10% to 100% folder_name = get_folder_name(i, images_per_folder) os.makedirs(folder_name, exist_ok=True) file_name = f"image_{i+1}.png" file_path = os.path.join(folder_name, file_name) # Calculate figure size in inches based on desired pixel dimensions and DPI dpi = 100 # Standard DPI for matplotlib fig_size = (img_size[0] / dpi, img_size[1] / dpi) # Convert pixels to inches fig, ax = plt.subplots(figsize=fig_size, dpi=dpi) ax.set_xlim(0, 1) ax.set_ylim(0, 1) ax.set_xticks([]) ax.set_yticks([]) ax.set_frame_on(False) color_name, size_percent = draw_shape(shape, ax, size_factor) caption = generate_caption(shape, color_name, size_percent) # Save the figure with the exact dimensions plt.savefig(file_path, dpi=dpi, bbox_inches=None, pad_inches=0) # Disable bbox_inches and pad_inches plt.close(fig) # Write the caption to a CSV file in the same folder csv_path = os.path.join(folder_name, "metadata.csv") with open(csv_path, mode='a', newline='') as file: writer = csv.writer(file) # Write header only if the file is empty or doesn't exist if not os.path.exists(csv_path) or os.path.getsize(csv_path) == 0: writer.writerow(["file_name", "caption"]) writer.writerow([file_name, caption]) return folder_name, file_name, caption def generate_images_multiprocess(num_images=10, img_size=(512, 512), max_workers=None, images_per_folder=5000): """Generate images using multiple processes instead of threads.""" # Create dataset directory structure os.makedirs("dataset", exist_ok=True) start_time = time.time() # Determine number of workers if not specified if max_workers is None: max_workers = mp.cpu_count() # Create a pool of workers with mp.Pool(processes=max_workers) as pool: # Create a partial function with fixed img_size worker_func = partial(generate_single_image_process, img_size=img_size, images_per_folder=images_per_folder) # Map the function to the range of image indices results = list(tqdm( pool.imap(worker_func, range(num_images)), total=num_images, desc="Generating Images" )) end_time = time.time() print(f"Generated {num_images} images in {end_time - start_time:.2f} seconds") print(f"Size: {len(results)} images") if __name__ == "__main__": # You can adjust the number of workers based on your CPU # If left as None, it will use the default (typically the number of CPU cores) generate_images_multiprocess(num_images=100000, max_workers=10, img_size=(512, 512), images_per_folder=5000)