|
| 1 | +from datasets import load_dataset |
| 2 | +import os |
| 3 | +import requests |
| 4 | +from PIL import Image |
| 5 | +from io import BytesIO |
| 6 | +import backoff |
| 7 | +import webdataset as wds |
| 8 | +from tqdm import tqdm |
| 9 | + |
| 10 | + |
| 11 | +# 画像をダウンロード |
| 12 | +@backoff.on_exception( |
| 13 | + backoff.expo, # 指数バックオフ |
| 14 | + requests.exceptions.RequestException, # 対象例外 |
| 15 | + max_tries=5, # 最大リトライ回数 |
| 16 | +) |
| 17 | +def download_image(image_url: str) -> Image: |
| 18 | + user_agent_string = ( |
| 19 | + "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0" |
| 20 | + ) |
| 21 | + response = requests.get( |
| 22 | + image_url, headers={"User-Agent": user_agent_string}, timeout=10 |
| 23 | + ) |
| 24 | + response.raise_for_status() |
| 25 | + image = Image.open(BytesIO(response.content)).convert("RGB") |
| 26 | + return image |
| 27 | + |
| 28 | + |
| 29 | +def download_image_wrap(image_url: str) -> Image: |
| 30 | + try: |
| 31 | + return download_image(image_url) |
| 32 | + except Exception as e: |
| 33 | + print(f"Failed to process {image_url}: {e}") |
| 34 | + return None |
| 35 | + |
| 36 | + |
| 37 | +def get_domain_from_question(question: str) -> str: |
| 38 | + for keyword, domain in domain_dict.items(): |
| 39 | + if keyword in question: |
| 40 | + return domain |
| 41 | + |
| 42 | + |
| 43 | +ds = load_dataset("line-corporation/JIC-VQA", split="train") |
| 44 | + |
| 45 | +input_texts = [] |
| 46 | +answers = [] |
| 47 | +images = [] |
| 48 | +question_ids = [] |
| 49 | +domains = [] |
| 50 | + |
| 51 | +domain_dict = { |
| 52 | + "花": "jaflower30", |
| 53 | + "食べ物": "jafood101", |
| 54 | + "ランドマーク": "jalandmark10", |
| 55 | + "施設": "jafacility20", |
| 56 | +} |
| 57 | + |
| 58 | +output_dir = "dataset/jic_vqa" |
| 59 | +os.makedirs(output_dir, exist_ok=True) |
| 60 | +if not os.path.exists(f"{output_dir}/images.tar"): |
| 61 | + with wds.TarWriter(f"{output_dir}/images.tar") as sink: |
| 62 | + for i, example in tqdm(enumerate(ds), total=len(ds)): |
| 63 | + image_url = example["url"] |
| 64 | + image = download_image_wrap(image_url) |
| 65 | + # resize |
| 66 | + if image is not None: |
| 67 | + image = image.resize((224, 224)) |
| 68 | + image = image.convert("RGB") |
| 69 | + if image is None: |
| 70 | + continue |
| 71 | + sample = { |
| 72 | + "__key__": str(example["id"]), |
| 73 | + "jpg": image, |
| 74 | + "txt": example["category"], |
| 75 | + "url.txt": image_url, |
| 76 | + "question.txt": example["question"], |
| 77 | + } |
| 78 | + sink.write(sample) |
| 79 | + |
| 80 | +ds = load_dataset("webdataset", data_files=f"{output_dir}/images.tar", split="train") |
| 81 | +print(ds) |
| 82 | +print(ds[0]) |
| 83 | + |
| 84 | +ds = ds.remove_columns(["__url__"]) |
| 85 | +ds = ds.rename_columns( |
| 86 | + { |
| 87 | + "txt": "category", |
| 88 | + "url.txt": "url", |
| 89 | + "question.txt": "question", |
| 90 | + } |
| 91 | +) |
| 92 | + |
| 93 | +# Phase 2: Load images and populate data structures |
| 94 | +ds = ds.map( |
| 95 | + lambda x: { |
| 96 | + "input_text": x["question"].decode("utf-8"), |
| 97 | + "url": x["url"].decode("utf-8").encode("utf-8"), |
| 98 | + "answer": str(x["category"]), |
| 99 | + "image": x["jpg"], |
| 100 | + "question_id": int(x["__key__"]), |
| 101 | + "domain": get_domain_from_question(str(x["question"].decode("utf-8"))), |
| 102 | + } |
| 103 | +) |
| 104 | +ds = ds.remove_columns(["question", "__key__", "jpg"]) |
| 105 | + |
| 106 | +print(ds) |
| 107 | +print(ds[0]) |
| 108 | +# {'category': 'ガソリンスタンド', 'url': b'https://live.staticflickr.com/5536/11190751074_f97587084e_o.jpg', 'input_text': "この画像にはどの施設が映っていますか?次の四つの選択肢から正しいものを選んでください: ['スーパーマーケット', 'コンビニ', '駐車場', 'ガソリンスタンド']", 'answer': 'ガソリンスタンド', 'image': <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=224x224 at 0x7F83A660F710>, 'question_id': '11190751074', 'domain': 'jafacility20'} |
| 109 | +ds.to_parquet("dataset/jic_vqa.parquet") |
0 commit comments