Upload extensions_built_in/dataset_tools/SyncFromCollection.py with huggingface_hub
Browse files
extensions_built_in/dataset_tools/SyncFromCollection.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import shutil
|
| 3 |
+
from collections import OrderedDict
|
| 4 |
+
import gc
|
| 5 |
+
from typing import List
|
| 6 |
+
|
| 7 |
+
import torch
|
| 8 |
+
from tqdm import tqdm
|
| 9 |
+
|
| 10 |
+
from .tools.dataset_tools_config_modules import DatasetSyncCollectionConfig, RAW_DIR, NEW_DIR
|
| 11 |
+
from .tools.sync_tools import get_unsplash_images, get_pexels_images, get_local_image_file_names, download_image, \
|
| 12 |
+
get_img_paths
|
| 13 |
+
from jobs.process import BaseExtensionProcess
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def flush():
|
| 17 |
+
torch.cuda.empty_cache()
|
| 18 |
+
gc.collect()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class SyncFromCollection(BaseExtensionProcess):
|
| 22 |
+
|
| 23 |
+
def __init__(self, process_id: int, job, config: OrderedDict):
|
| 24 |
+
super().__init__(process_id, job, config)
|
| 25 |
+
|
| 26 |
+
self.min_width = config.get('min_width', 1024)
|
| 27 |
+
self.min_height = config.get('min_height', 1024)
|
| 28 |
+
|
| 29 |
+
# add our min_width and min_height to each dataset config if they don't exist
|
| 30 |
+
for dataset_config in config.get('dataset_sync', []):
|
| 31 |
+
if 'min_width' not in dataset_config:
|
| 32 |
+
dataset_config['min_width'] = self.min_width
|
| 33 |
+
if 'min_height' not in dataset_config:
|
| 34 |
+
dataset_config['min_height'] = self.min_height
|
| 35 |
+
|
| 36 |
+
self.dataset_configs: List[DatasetSyncCollectionConfig] = [
|
| 37 |
+
DatasetSyncCollectionConfig(**dataset_config)
|
| 38 |
+
for dataset_config in config.get('dataset_sync', [])
|
| 39 |
+
]
|
| 40 |
+
print(f"Found {len(self.dataset_configs)} dataset configs")
|
| 41 |
+
|
| 42 |
+
def move_new_images(self, root_dir: str):
|
| 43 |
+
raw_dir = os.path.join(root_dir, RAW_DIR)
|
| 44 |
+
new_dir = os.path.join(root_dir, NEW_DIR)
|
| 45 |
+
new_images = get_img_paths(new_dir)
|
| 46 |
+
|
| 47 |
+
for img_path in new_images:
|
| 48 |
+
# move to raw
|
| 49 |
+
new_path = os.path.join(raw_dir, os.path.basename(img_path))
|
| 50 |
+
shutil.move(img_path, new_path)
|
| 51 |
+
|
| 52 |
+
# remove new dir
|
| 53 |
+
shutil.rmtree(new_dir)
|
| 54 |
+
|
| 55 |
+
def sync_dataset(self, config: DatasetSyncCollectionConfig):
|
| 56 |
+
if config.host == 'unsplash':
|
| 57 |
+
get_images = get_unsplash_images
|
| 58 |
+
elif config.host == 'pexels':
|
| 59 |
+
get_images = get_pexels_images
|
| 60 |
+
else:
|
| 61 |
+
raise ValueError(f"Unknown host: {config.host}")
|
| 62 |
+
|
| 63 |
+
results = {
|
| 64 |
+
'num_downloaded': 0,
|
| 65 |
+
'num_skipped': 0,
|
| 66 |
+
'bad': 0,
|
| 67 |
+
'total': 0,
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
photos = get_images(config)
|
| 71 |
+
raw_dir = os.path.join(config.directory, RAW_DIR)
|
| 72 |
+
new_dir = os.path.join(config.directory, NEW_DIR)
|
| 73 |
+
raw_images = get_local_image_file_names(raw_dir)
|
| 74 |
+
new_images = get_local_image_file_names(new_dir)
|
| 75 |
+
|
| 76 |
+
for photo in tqdm(photos, desc=f"{config.host}-{config.collection_id}"):
|
| 77 |
+
try:
|
| 78 |
+
if photo.filename not in raw_images and photo.filename not in new_images:
|
| 79 |
+
download_image(photo, new_dir, min_width=self.min_width, min_height=self.min_height)
|
| 80 |
+
results['num_downloaded'] += 1
|
| 81 |
+
else:
|
| 82 |
+
results['num_skipped'] += 1
|
| 83 |
+
except Exception as e:
|
| 84 |
+
print(f" - BAD({photo.id}): {e}")
|
| 85 |
+
results['bad'] += 1
|
| 86 |
+
continue
|
| 87 |
+
results['total'] += 1
|
| 88 |
+
|
| 89 |
+
return results
|
| 90 |
+
|
| 91 |
+
def print_results(self, results):
|
| 92 |
+
print(
|
| 93 |
+
f" - new:{results['num_downloaded']}, old:{results['num_skipped']}, bad:{results['bad']} total:{results['total']}")
|
| 94 |
+
|
| 95 |
+
def run(self):
|
| 96 |
+
super().run()
|
| 97 |
+
print(f"Syncing {len(self.dataset_configs)} datasets")
|
| 98 |
+
all_results = None
|
| 99 |
+
failed_datasets = []
|
| 100 |
+
for dataset_config in tqdm(self.dataset_configs, desc="Syncing datasets", leave=True):
|
| 101 |
+
try:
|
| 102 |
+
results = self.sync_dataset(dataset_config)
|
| 103 |
+
if all_results is None:
|
| 104 |
+
all_results = {**results}
|
| 105 |
+
else:
|
| 106 |
+
for key, value in results.items():
|
| 107 |
+
all_results[key] += value
|
| 108 |
+
|
| 109 |
+
self.print_results(results)
|
| 110 |
+
except Exception as e:
|
| 111 |
+
print(f" - FAILED: {e}")
|
| 112 |
+
if 'response' in e.__dict__:
|
| 113 |
+
error = f"{e.response.status_code}: {e.response.text}"
|
| 114 |
+
print(f" - {error}")
|
| 115 |
+
failed_datasets.append({'dataset': dataset_config, 'error': error})
|
| 116 |
+
else:
|
| 117 |
+
failed_datasets.append({'dataset': dataset_config, 'error': str(e)})
|
| 118 |
+
continue
|
| 119 |
+
|
| 120 |
+
print("Moving new images to raw")
|
| 121 |
+
for dataset_config in self.dataset_configs:
|
| 122 |
+
self.move_new_images(dataset_config.directory)
|
| 123 |
+
|
| 124 |
+
print("Done syncing datasets")
|
| 125 |
+
self.print_results(all_results)
|
| 126 |
+
|
| 127 |
+
if len(failed_datasets) > 0:
|
| 128 |
+
print(f"Failed to sync {len(failed_datasets)} datasets")
|
| 129 |
+
for failed in failed_datasets:
|
| 130 |
+
print(f" - {failed['dataset'].host}-{failed['dataset'].collection_id}")
|
| 131 |
+
print(f" - ERR: {failed['error']}")
|