|
|
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) |
|
|
continue |
|
|
|
|
|
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: |
|
|
|
|
|
candidate = cur_line + token |
|
|
|
|
|
bbox = draw.textbbox((0,0), candidate, font=font) |
|
|
w = bbox[2] - bbox[0] |
|
|
if w <= max_width: |
|
|
cur_line = candidate |
|
|
else: |
|
|
if cur_line: |
|
|
lines.append(cur_line.rstrip()) |
|
|
|
|
|
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: |
|
|
|
|
|
cur_line = token.lstrip() |
|
|
else: |
|
|
|
|
|
|
|
|
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 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|