|
| 1 | +import os |
| 2 | +import re |
| 3 | +import random |
| 4 | +from collections import defaultdict |
| 5 | +from pathlib import Path |
| 6 | +from typing import Dict, List, Tuple, Optional |
| 7 | + |
| 8 | +class TableDataOrganizer: |
| 9 | + def __init__(self, data_root: str): |
| 10 | + """ |
| 11 | + Initialize the organizer with the root data directory. |
| 12 | + Args: |
| 13 | + data_root: Path to the 'data' directory. |
| 14 | + """ |
| 15 | + self.data_root = Path(data_root) |
| 16 | + self.grouped_data: Dict[str, List[str]] = defaultdict(list) |
| 17 | + self._organize_data() |
| 18 | + |
| 19 | + def _organize_data(self): |
| 20 | + """Scans the data directory and groups images by table ID.""" |
| 21 | + # Regex to parse filenames: P_origin_{group}_{table}_{index}.png or P_origin_{group}_{table}.png |
| 22 | + # We want to group by "group_table" |
| 23 | + |
| 24 | + # Pattern covers: group, table, index (optional) |
| 25 | + # e.g., P_origin_1_11_0.png -> group=1, table=11, index=0 |
| 26 | + # e.g., P_origin_1_2.png -> group=1, table=2, index=-1 (conceptually) |
| 27 | + pattern = re.compile(r"P_origin_(\d+)_(\d+)(?:_(\d+))?\.png") |
| 28 | + |
| 29 | + if not self.data_root.exists(): |
| 30 | + print(f"Warning: Directory {self.data_root} does not exist.") |
| 31 | + return |
| 32 | + |
| 33 | + for root, _, files in os.walk(self.data_root): |
| 34 | + for file in files: |
| 35 | + if not file.endswith(".png"): |
| 36 | + continue |
| 37 | + |
| 38 | + match = pattern.match(file) |
| 39 | + if match: |
| 40 | + group_id = match.group(1) |
| 41 | + table_id = match.group(2) |
| 42 | + index = match.group(3) |
| 43 | + |
| 44 | + # If index is missing (e.g. single file per table), treat as 0 or handle logically |
| 45 | + # For sorting purposes, we can treat None as -1 so it comes first, or just 0 |
| 46 | + idx_val = int(index) if index is not None else -1 |
| 47 | + |
| 48 | + # Create a unique key for grouping: "group_{g}_table_{t}" |
| 49 | + key = f"P_origin_{group_id}_{table_id}" |
| 50 | + |
| 51 | + abs_path = str(Path(root) / file) |
| 52 | + self.grouped_data[key].append((idx_val, abs_path)) |
| 53 | + |
| 54 | + # Sort each group by index |
| 55 | + for key in self.grouped_data: |
| 56 | + # Sort by index (tuple first element) |
| 57 | + self.grouped_data[key].sort(key=lambda x: x[0]) |
| 58 | + # Keep only paths |
| 59 | + self.grouped_data[key] = [item[1] for item in self.grouped_data[key]] |
| 60 | + |
| 61 | + def get_batches(self, |
| 62 | + sampling: bool = False, |
| 63 | + min_k: int = 2, |
| 64 | + max_k: int = 3, |
| 65 | + num_samples: int = 1) -> Dict[str, List[List[str]]]: |
| 66 | + """ |
| 67 | + Generates batches of images for each table. |
| 68 | + |
| 69 | + Args: |
| 70 | + sampling: If True, randomly samples images. If False, returns all images as one batch. |
| 71 | + min_k: Minimum number of images to sample (inclusive, used if sampling=True). |
| 72 | + max_k: Maximum number of images to sample (inclusive, used if sampling=True). |
| 73 | + num_samples: Number of random batches to generate per table (used if sampling=True). |
| 74 | + |
| 75 | + Returns: |
| 76 | + A dictionary where keys are table identifiers and values are LISTS of image lists (batches). |
| 77 | + e.g. { |
| 78 | + "P_origin_1_11": [ ["path/to/img0", "path/to/img2"] ] |
| 79 | + } |
| 80 | + """ |
| 81 | + results = {} |
| 82 | + |
| 83 | + for key, images in self.grouped_data.items(): |
| 84 | + if not sampling: |
| 85 | + # Return all images as a single batch |
| 86 | + results[key] = [images] |
| 87 | + else: |
| 88 | + table_batches = [] |
| 89 | + n_images = len(images) |
| 90 | + |
| 91 | + # If there are fewer images than min_k, we can't really "sample" between min_k and max_k |
| 92 | + # strictly unless we allow duplicates or just take what we have. |
| 93 | + # Logic: if n_images < min_k, just use all images once (effectively no sampling choice). |
| 94 | + effective_min = min(n_images, min_k) |
| 95 | + effective_max = min(n_images, max_k) |
| 96 | + |
| 97 | + if n_images == 0: |
| 98 | + results[key] = [] |
| 99 | + continue |
| 100 | + |
| 101 | + for _ in range(num_samples): |
| 102 | + # Randomly choose k size |
| 103 | + # If effective_min == effective_max, then k is fixed |
| 104 | + k = random.randint(effective_min, effective_max) if effective_min <= effective_max else n_images |
| 105 | + |
| 106 | + # Sample k images |
| 107 | + # Note: random.sample throws error if k > population |
| 108 | + # We guarded with min(), so k <= n_images |
| 109 | + if k > 0: |
| 110 | + batch = sorted(random.sample(images, k)) |
| 111 | + table_batches.append(batch) |
| 112 | + else: |
| 113 | + # Should not happen typically unless file list is empty |
| 114 | + table_batches.append([]) |
| 115 | + |
| 116 | + results[key] = table_batches |
| 117 | + |
| 118 | + return results |
| 119 | + |
| 120 | +if __name__ == "__main__": |
| 121 | + # Test existing directory |
| 122 | + organizer = TableDataOrganizer("data") |
| 123 | + |
| 124 | + print("=== Default Mode (All Images) ===") |
| 125 | + batches_default = organizer.get_batches(sampling=False) |
| 126 | + # Print first 2 keys |
| 127 | + for k in list(batches_default.keys())[:2]: |
| 128 | + print(f"Table: {k}") |
| 129 | + for batch in batches_default[k]: |
| 130 | + print(f" Batch size: {len(batch)}") |
| 131 | + # print(batch) # Uncomment to see paths |
| 132 | + |
| 133 | + print("\n=== Sampling Mode (2-3 images) ===") |
| 134 | + batches_sampled = organizer.get_batches(sampling=True, min_k=2, max_k=3, num_samples=2) |
| 135 | + for k in list(batches_sampled.keys())[:2]: |
| 136 | + print(f"Table: {k}") |
| 137 | + for i, batch in enumerate(batches_sampled[k]): |
| 138 | + print(f" Sample {i+1}: size {len(batch)}") |
| 139 | + # print(batch) # Uncomment to see paths |
0 commit comments