#!/usr/bin/env python3 """Upload JPG/PNG files to ThinkerSet and write a CSV mapping local paths to links.""" import argparse import csv import getpass import hashlib import json import os from pathlib import Path import sys import tempfile import time from urllib.error import HTTPError, URLError from urllib.parse import urlencode from urllib.request import HTTPRedirectHandler, Request, build_opener API_URL = 'https://thinkerset.com/image-host/api/v1/images' LINK_PREFIX = 'https://thinkerset.com/image-host/i/' KEY_ENV = 'THINKERSET_IMAGE_API_KEY' MAX_BYTES = 8 * 1024 * 1024 IMAGE_SUFFIXES = {'.jpg', '.jpeg', '.png'} FIELDS = ('path', 'name', 'url', 'sha256', 'status', 'error') class NoRedirect(HTTPRedirectHandler): def redirect_request(self, req, fp, code, msg, headers, newurl): return None def collect_images(sources): paths = {} for source in sources: path = Path(source).expanduser().absolute() if path.is_dir(): files = sorted(item for item in path.rglob('*') if not item.is_symlink() and item.is_file()) elif path.is_file() and path.suffix.lower() in IMAGE_SUFFIXES: files = [path] else: raise ValueError(f'路径不存在或不是 JPG/PNG 文件:{source}') for item in files: if item.suffix.lower() in IMAGE_SUFFIXES: paths[item.resolve()] = None return paths def send_image(opener, key, name, content): request = Request(API_URL + '?' + urlencode({'name': name}), data=content, method='POST', headers={ 'Authorization': 'Bearer ' + key, 'Content-Type': 'application/octet-stream', 'Accept': 'application/json', }) for attempt in range(3): try: with opener.open(request, timeout=30) as response: return json.load(response) except HTTPError as error: with error: raw = error.read(4096) if error.code not in (408, 429, 500, 502, 503, 504) or attempt == 2: detail = '' try: value = json.loads(raw).get('detail') if isinstance(value, str): detail = ' · ' + value except (ValueError, AttributeError): pass raise ValueError(f'HTTP {error.code}{detail}') from None except (URLError, TimeoutError) as error: if attempt == 2: raise ValueError(f'连接图床失败:{error}') from None time.sleep(2 ** attempt) def upload_file(opener, key, path): with path.open('rb') as file: content = file.read(MAX_BYTES + 1) if not content or len(content) > MAX_BYTES: raise ValueError('图片应大于 0 字节且不超过 8 MiB') digest = hashlib.sha256(content).hexdigest() result = send_image(opener, key, path.name, content) if (not isinstance(result, dict) or result.get('name') != path.name.strip() or result.get('sha256') != digest or not str(result.get('url', '')).startswith(LINK_PREFIX)): raise ValueError('返回的文件名、哈希或直链与本地图片不符') return {'url': result['url'], 'sha256': digest, 'status': 'reused' if result.get('reused') else 'uploaded'} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('sources', nargs='+', help='JPG/PNG 文件或目录。目录会递归扫描。') parser.add_argument('-o', '--output', type=Path, default=Path('image-links.csv'), help='输出映射 CSV 的路径') args = parser.parse_args() try: paths = collect_images(args.sources) except (ValueError, OSError) as error: parser.error(str(error)) if not paths: parser.error('指定路径中没有 JPG/PNG 图片') key = os.environ.get(KEY_ENV, '').strip() if not key and sys.stdin.isatty(): key = getpass.getpass('ThinkerSet 上传密钥:').strip() if not key: parser.error(f'请在运行进程中设置环境变量 {KEY_ENV},或在终端输入上传密钥') output = args.output.expanduser().resolve() if output.suffix.lower() != '.csv': parser.error('输出文件必须使用 .csv 扩展名') output.parent.mkdir(parents=True, exist_ok=True) opener = build_opener(NoRedirect()) root = Path.cwd().resolve() failures = 0 temporary = None try: with tempfile.NamedTemporaryFile('w', encoding='utf-8-sig', newline='', dir=output.parent, prefix=f'.{output.name}-', delete=False) as file: temporary = Path(file.name) writer = csv.DictWriter(file, fieldnames=FIELDS) writer.writeheader() for path in paths: relative = path.relative_to(root) if path.is_relative_to(root) else path row = {'path': relative.as_posix(), 'name': path.name} try: row.update(upload_file(opener, key, path)) except (OSError, ValueError) as error: failures += 1 row.update(status='error', error=str(error)) writer.writerow(row) os.replace(temporary, output) finally: if temporary is not None: temporary.unlink(missing_ok=True) print(f'图片映射已保存到 {output}。成功 {len(paths) - failures} 张,失败 {failures} 张。') return int(failures > 0) if __name__ == '__main__': sys.exit(main())