Linguistic_Prior / scripts /1_render_images_v3.py
gaotiexinqu's picture
Upload folder using huggingface_hub
7f605ec verified
from PIL import Image, ImageDraw, ImageFont
import re, os, json
from tqdm import tqdm
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
def save_jsonl(data, file_path):
"""
将数据保存为 JSONL 文件。
:param data: 要保存的数据(Python 对象的列表)
:param file_path: 保存的 JSONL 文件路径
"""
with open(file_path, 'w', encoding='utf-8') as f:
for item in data:
f.write(json.dumps(item, ensure_ascii=False) + '\n')
def split_tokens_for_wrapping(text):
"""
将文本切分为用于换行的 tokens:
- 英文单词/数字/标点尽量按空格分块
- 连续中文或其它无空格脚本按字符切分
返回 token 列表(保持原始顺序)
"""
tokens = []
# 使用正则把英文单词/空格段和非空格段分开
# 这个策略:先按空格分段,然后对每段若含中文则拆成单字符,否则保留整段
for part in re.split(r'(\s+)', text):
if part == "":
continue
if part.isspace():
tokens.append(part) # 保留空格作为独立 token(便于保持空格)
continue
# 如果包含 CJK 文字,则把它拆成单字符(更安全)
if re.search(r'[\u4e00-\u9fff]', part):
tokens.extend(list(part))
else:
# 非中文段按单词/标点继续拆分(保持单词完整)
# 但如果单词非常长,也允许按字符拆分(后面处理)
tokens.append(part)
return tokens
def wrap_text_pixel(draw, text, font, max_width):
"""
基于像素宽度把 text 换行,返回行列表。
draw: ImageDraw.Draw 实例(用于测量)
"""
tokens = split_tokens_for_wrapping(text)
lines = []
cur_line = ""
for token in tokens:
# 试拼接 token(注意保留空格)
candidate = cur_line + token
# 使用 textbbox 更准确(返回 bbox 四元组)
bbox = draw.textbbox((0,0), candidate, font=font)
w = bbox[2] - bbox[0]
if w <= max_width:
cur_line = candidate
else:
if cur_line: # 把当前行推入,token 放到下一行
lines.append(cur_line.rstrip()) # 去掉尾部多余空格
# 如果 token 自己也超长(单词无空格且宽度>max_width),按字符拆分
token_bbox = draw.textbbox((0,0), token, font=font)
token_w = token_bbox[2] - token_bbox[0]
if token_w > max_width and len(token) > 1:
# 按字符贪心拆分
sub = ""
for ch in token:
cand2 = sub + ch
if draw.textbbox((0,0), cand2, font=font)[2] - draw.textbbox((0,0), cand2, font=font)[0] <= max_width:
sub = cand2
else:
if sub:
lines.append(sub)
sub = ch
if sub:
cur_line = sub
else:
cur_line = ""
else:
# token 能单独放下一行
cur_line = token.lstrip() # 去掉起始空格
else:
# cur_line 为空但 token 仍超过 max_width(非常长的单词/无空格序列)
# 按字符拆分
sub = ""
for ch in token:
cand2 = sub + ch
if draw.textbbox((0,0), cand2, font=font)[2] - draw.textbbox((0,0), cand2, font=font)[0] <= max_width:
sub = cand2
else:
if sub:
lines.append(sub)
sub = ch
if sub:
cur_line = sub
else:
cur_line = ""
if cur_line:
lines.append(cur_line.rstrip())
return lines
def text_to_image_precise(text, output_path="output.png",
font_path=None, font_size=24,
max_width=1600, padding=40,
bg_color="white", text_color="black",
line_spacing=1.0, min_width=200):
"""
基于像素测量的文本渲染,避免超出边距。
"""
# 字体
if font_path is None:
font_path = "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc"
font = ImageFont.truetype(font_path, font_size)
# 先创建临时画布用于测量
tmp_img = Image.new("RGB", (10, 10), color=bg_color)
draw = ImageDraw.Draw(tmp_img)
# 对每一段(以换行分隔)分别换行,然后合并成最终行列表
final_lines = []
for paragraph in text.split("\n"):
paragraph = paragraph.rstrip("\n")
if paragraph == "":
final_lines.append("") # 保持空行
continue
wrapped = wrap_text_pixel(draw, paragraph, font, max_width)
final_lines.extend(wrapped)
# 计算实际内容宽度(取最长行的像素宽度)
max_line_w = 0
for line in final_lines:
bbox = draw.textbbox((0,0), line, font=font)
w = bbox[2] - bbox[0]
if w > max_line_w:
max_line_w = w
content_width = max(min_width, max_line_w)
img_width = int(content_width + 2 * padding)
# 字高与行距
ascent, descent = font.getmetrics()
line_height = int((ascent + descent) * line_spacing)
img_height = line_height * len(final_lines) + 2 * padding
# 创建最终图片并绘制
img = Image.new("RGB", (img_width, img_height), color=bg_color)
draw_final = ImageDraw.Draw(img)
y = padding
for line in final_lines:
draw_final.text((padding, y), line, fill=text_color, font=font)
y += line_height
os.makedirs(os.path.dirname(output_path), exist_ok=True)
img.save(output_path)
print(f"✅ 图片已保存到: {output_path} (size: {img_width}x{img_height})")
return img # 方便调试时返回 PIL.Image 对象
# 示例用法
if __name__ == "__main__":
mapping = {
"形近字替换": "similar_char",
"音近/同音字替换": "phonetic_char",
"语序颠倒": "word_order",
"字符增衍": "char_insertion",
"字符缺失": "char_deletion"
}
image_root = "/vol/zhaoy/ds-ocr/data/CCI3-Data/CCI3_5k-10k_sample100_interval500_per10_last_mode/"
meta_path = "/vol/zhaoy/ds-ocr/data/CCI3-Data/CCI3_5k-10k_sample100_interval500_per10_last_mode/output_processed_last-mode.jsonl"
data = read_jsonl(meta_path)
for item in tqdm(data):
for dim, v in item["rewrite"].items():
for extent in v["extents"]:
text = extent["edited"]
ned = extent["NED"]
image_path = os.path.join(image_root, "images", mapping[dim], os.path.basename(item["image_path"]).replace(".png", f"_ned-{ned}.png"))
extent["image_path"] = os.path.join("images", mapping[dim], os.path.basename(item["image_path"]).replace(".png", f"_ned-{ned}.png"))
text_to_image_precise(text, image_path, font_size=28)
save_jsonl(data, meta_path) # 随便覆盖,只是加了个["image_path"]
# sample_text = """这是一段示例文本。这是一段示例文本。这是一段示例文本。这是一段示例文本。这是一段示例文本。这是一段示例文本。这是一段示例文本。这是一段示例文本。v
# 可以包含多行内容,用于渲染成白底黑字的论文插图风格。
# 支持中文和英文混排 English example line."""
# text_to_image_precise(sample_text, "/vol/text_image.png", font_size=28)