|
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) |
|
|
|
|
|
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) |
|
|
|
|
|
step["img"] = img_path |
|
|
|
except requests.exceptions.RequestException as e: |
|
print(f"Failed to download {img_url}: {e}") |
|
|
|
|
|
with open(output_json_path, 'w', encoding='utf-8') as outfile: |
|
json.dump(data, outfile, ensure_ascii=False, indent=4) |
|
|
|
print("图片下载完成,JSON文件已更新并保存。") |
|
|