| 12 | |
| 13 | |
| 14 | def retrieve(target_name, outpath, num_class_images): |
| 15 | num_images = 2*num_class_images |
| 16 | client = ClipClient(url="https://knn.laion.ai/knn-service", indice_name="laion_400m", num_images=num_images, aesthetic_weight=0.1) |
| 17 | |
| 18 | if len(target_name.split()): |
| 19 | target = '_'.join(target_name.split()) |
| 20 | else: |
| 21 | target = target_name |
| 22 | os.makedirs(f'{outpath}/{target}', exist_ok=True) |
| 23 | |
| 24 | if len(list(Path(f'{outpath}/{target}').iterdir())) >= num_class_images: |
| 25 | return |
| 26 | |
| 27 | while True: |
| 28 | results = client.query(text=target_name) |
| 29 | if len(results) >= num_class_images or num_images > 1e4: |
| 30 | break |
| 31 | else: |
| 32 | num_images = int(1.5*num_images) |
| 33 | client = ClipClient(url="https://knn.laion.ai/knn-service", indice_name="laion_400m", num_images=num_images, aesthetic_weight=0.1) |
| 34 | |
| 35 | count = 0 |
| 36 | urls = [] |
| 37 | captions = [] |
| 38 | |
| 39 | pbar = tqdm.tqdm(desc='downloading real regularization images', total=num_class_images) |
| 40 | |
| 41 | for each in results: |
| 42 | name = f'{outpath}/{target}/{count}.jpg' |
| 43 | success = True |
| 44 | while True: |
| 45 | try: |
| 46 | img = requests.get(each['url']) |
| 47 | success = True |
| 48 | break |
| 49 | except: |
| 50 | success = False |
| 51 | break |
| 52 | if success and img.status_code == 200: |
| 53 | try: |
| 54 | _ = Image.open(BytesIO(img.content)) |
| 55 | with open(name, 'wb') as f: |
| 56 | f.write(img.content) |
| 57 | urls.append(each['url']) |
| 58 | captions.append(each['caption']) |
| 59 | count += 1 |
| 60 | pbar.update(1) |
| 61 | except: |
| 62 | pass |
| 63 | if count > num_class_images: |
| 64 | break |
| 65 | |
| 66 | with open(f'{outpath}/caption.txt', 'w') as f: |
| 67 | for each in captions: |
| 68 | f.write(each.strip() + '\n') |
| 69 | |
| 70 | with open(f'{outpath}/urls.txt', 'w') as f: |
| 71 | for each in urls: |