# 做pilot study的时候用的渲染代码 from PIL import Image, ImageDraw, ImageFont import textwrap import json, os def read_jsonl(file_path): """ 读取 JSONL 文件并返回解析后的数据列表。 :param file_path: JSONL 文件的路径 :return: 包含所有 JSON 对象的列表 """ data = [] with open(file_path, 'r', encoding='utf-8') as f: for line in f: data.append(json.loads(line.strip())) return data # ======================== # 参数配置 # ======================== # 数据路径 json_path = "/vol/zhaoy/ds-ocr/data/CCI3-Data/CCI3_100-5k_sample100_interval500_per10/test.jsonl" data = read_jsonl(json_path) # 输出目录 output_root = "/vol/zhaoy/ds-ocr/data/CCI3-Data/CCI3_100-5k_sample100_interval500_per10" # 三个版本及对应字段 versions = { "normal": "content", "shuffled": "shuffled_content", "tiny_shuffled": "tiny_shuffled_content", } # 字体路径与大小 font_path = "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc" font_size = 64 font = ImageFont.truetype(font_path, font_size) # 每行最大字符数 max_chars_per_line = 40 # 中文 # max_chars_per_line = 100 # 英文 # ======================== # 主流程 # ======================== for version_name, field in versions.items(): # 创建输出文件夹 image_root = os.path.join(output_root, version_name, "images") os.makedirs(image_root, exist_ok=True) print(f"\n🖋 正在生成 {version_name} 版本的图片到 {image_root} ...") for item in data: text = item.get(field, "") if not text: print(f"⚠️ 跳过 {item['id']}:字段 {field} 为空。") continue # 自动换行 wrapped_text = textwrap.fill(text, width=max_chars_per_line) # 计算文本尺寸 dummy_img = Image.new("RGB", (10, 10)) draw = ImageDraw.Draw(dummy_img) bbox = draw.multiline_textbbox((0, 0), wrapped_text, font=font, spacing=10) text_w, text_h = bbox[2] - bbox[0], bbox[3] - bbox[1] # 加 padding padding = 50 img_w, img_h = text_w + 2 * padding, text_h + 2 * padding # 创建并绘制图片 img = Image.new("RGB", (img_w, img_h), (255, 255, 255)) draw = ImageDraw.Draw(img) draw.multiline_text( (padding, padding), wrapped_text, font=font, fill=(0, 0, 0), spacing=10, ) # 保存图片 image_path = os.path.join(image_root, f"{item['id']}.png") img.save(image_path) print(f"✅ {version_name} - 已生成 {item['id']} ({img_w}x{img_h})") print("\n🎨 所有版本图片生成完毕!")