my-wikihow-dataset / download.py
StarThomas1002's picture
Upload folder using huggingface_hub
4c895ac verified
import os
import json
import requests
# 定义文件路径
json_path = '/home/yiyangai/stephenqs/datasets/wikihow/health_filtered.json'
image_dir = '/home/yiyangai/stephenqs/datasets/wikihow/images' # 保存图片的目录
output_json_path = '/home/yiyangai/stephenqs/datasets/wikihow/health-filtered-updated.json'
# 创建保存图片的目录,如果不存在则创建
os.makedirs(image_dir, exist_ok=True)
# 读取原始JSON文件
with open(json_path, 'r', encoding='utf-8') as file:
data = json.load(file)
# 遍历所有方法和步骤以下载图片并更新路径
for example in data:
for method in example.get("methods", []):
for step in method.get("steps", []):
img_url = step.get("img")
if img_url:
# 提取图片文件名
img_name = os.path.basename(img_url)
img_path = os.path.join(image_dir, img_name)
# 下载图片并保存到指定路径
try:
response = requests.get(img_url)
response.raise_for_status()
with open(img_path, 'wb') as img_file:
img_file.write(response.content)
# 更新JSON中的图片路径
step["img"] = img_path
except requests.exceptions.RequestException as e:
print(f"Failed to download {img_url}: {e}")
# 将更新后的数据保存到一个新的JSON文件
with open(output_json_path, 'w', encoding='utf-8') as outfile:
json.dump(data, outfile, ensure_ascii=False, indent=4)
print("图片下载完成,JSON文件已更新并保存。")