Blog/Meme/tools/upload.py

44 lines
1.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 使用upgit上传指定文件夹图片并生成对应json文件
import os
import json
import subprocess
import re
image_folder = "wechat" # 想要上传的图片文件路径
output_file = f"{image_folder}.json" # 最终生成的json文件
image_data = {"name": "微信", "type": "image", "items": []} # json文件中的元数据
def natural_sort_key(s):
# 使用正则表达式提取字符串中的数字,作为排序的依据
return [int(text) if text.isdigit() else text.lower() for text in re.split(r'(\d+)', s)]
def upload_images(directory, output_json):
if not os.path.isdir(directory):
print("指定的目录不存在")
return
# 获取文件列表并按照文件名中的数字排序
filenames = sorted(os.listdir(directory), key=natural_sort_key)
for filename in filenames:
filepath = os.path.join(directory, filename)
if os.path.isfile(filepath):
try:
result = subprocess.run(["upgit", filepath], capture_output=True, text=True)
url = result.stdout.strip()
if result.returncode == 0 and url:
image_data["items"].append({"key": os.path.splitext(filename)[0], "val": url})
print(f"上传成功: {filename} -> {url}")
else:
print(f"上传失败: {filename}")
except Exception as e:
print(f"发生错误: {filename}, {str(e)}")
with open(output_json, "w", encoding="utf-8") as f:
json.dump(image_data, f, ensure_ascii=False, indent=2)
print(f"JSON 文件已生成: {output_json}")
if __name__ == "__main__":
upload_images(image_folder, output_file)