Commit
·
94a4b0c
1
Parent(s):
eecc583
Add scripts
Browse files- LICENSE.txt +5 -0
- safe_text_image_pairs_ja_en_txt_per_image.py +177 -0
LICENSE.txt
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Dataset License (CC0, JP glyphs + EN descriptions)
|
2 |
+
|
3 |
+
Copyright (c) 2025 YOUR_NAME
|
4 |
+
All images (Japanese text) and English descriptions are synthetic and authored by the dataset creator.
|
5 |
+
Released under CC0-1.0 (Public Domain Dedication).
|
safe_text_image_pairs_ja_en_txt_per_image.py
ADDED
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
# -*- coding: utf-8 -*-
|
3 |
+
"""
|
4 |
+
日本語文字画像 + 英語説明文(CC0)
|
5 |
+
・日本語文字列は外部ファイルから読み込み(1行1語)
|
6 |
+
・背景は白、文字は黒で固定
|
7 |
+
・説明文は色を明記
|
8 |
+
・出力は train/ 直下
|
9 |
+
"""
|
10 |
+
|
11 |
+
import csv, random, argparse, hashlib, datetime
|
12 |
+
from pathlib import Path
|
13 |
+
from dataclasses import dataclass
|
14 |
+
from PIL import Image, ImageDraw, ImageFont
|
15 |
+
import numpy as np
|
16 |
+
|
17 |
+
# --------------------
|
18 |
+
# 定数
|
19 |
+
# --------------------
|
20 |
+
DEFAULT_FONTS_DIR = Path("./fonts")
|
21 |
+
TRAIN_DIR = Path("./train")
|
22 |
+
LINE_SPACING = 1.25
|
23 |
+
|
24 |
+
@dataclass
|
25 |
+
class Example:
|
26 |
+
jp_text: str
|
27 |
+
en_desc: str
|
28 |
+
|
29 |
+
# --------------------
|
30 |
+
# 外部ファイルから単語読み込み
|
31 |
+
# --------------------
|
32 |
+
def load_words(file_path: Path):
|
33 |
+
if not file_path.exists():
|
34 |
+
raise FileNotFoundError(f"指定された単語ファイルが見つかりません: {file_path}")
|
35 |
+
with open(file_path, "r", encoding="utf-8") as f:
|
36 |
+
words = [line.strip() for line in f if line.strip()]
|
37 |
+
if not words:
|
38 |
+
raise ValueError(f"単語ファイルが空です: {file_path}")
|
39 |
+
return words
|
40 |
+
|
41 |
+
# --------------------
|
42 |
+
# データ生成
|
43 |
+
# --------------------
|
44 |
+
def gen_examples(n:int, seed:int, words:list[str]):
|
45 |
+
random.seed(seed)
|
46 |
+
exs = []
|
47 |
+
for _ in range(n):
|
48 |
+
jp = random.choice(words)
|
49 |
+
desc = f'This image is saying "{jp}". The background is white. The letter is black.'
|
50 |
+
exs.append(Example(jp_text=jp, en_desc=desc))
|
51 |
+
return exs
|
52 |
+
|
53 |
+
# --------------------
|
54 |
+
# フォント
|
55 |
+
# --------------------
|
56 |
+
def list_fonts(font_dir:Path):
|
57 |
+
fonts = [p for p in font_dir.glob("*") if p.suffix.lower() in (".ttf",".otf",".ttc",".otc")]
|
58 |
+
if not fonts:
|
59 |
+
raise FileNotFoundError(f"フォントが見つかりません: {font_dir} にOFL/PDの日本語フォントを置いてください")
|
60 |
+
return fonts
|
61 |
+
|
62 |
+
# --------------------
|
63 |
+
# 描画(背景:白、文字:黒)
|
64 |
+
# --------------------
|
65 |
+
def draw_horizontal(text, font_path:Path, size, max_font_size, min_font_size, margin_px):
|
66 |
+
W,H = size
|
67 |
+
img = Image.new("RGB", (W,H), (255,255,255)) # 白背景
|
68 |
+
draw = ImageDraw.Draw(img)
|
69 |
+
for fs in range(max_font_size, min_font_size-1, -2):
|
70 |
+
font = ImageFont.truetype(str(font_path), fs)
|
71 |
+
bbox = draw.textbbox((0,0), text, font=font)
|
72 |
+
w, h = bbox[2] - bbox[0], bbox[3] - bbox[1]
|
73 |
+
if w <= W - 2*margin_px and h <= H - 2*margin_px:
|
74 |
+
break
|
75 |
+
x = (W - w)//2
|
76 |
+
y = (H - h)//2
|
77 |
+
draw.text((x, y), text, font=font, fill=(0,0,0)) # 黒
|
78 |
+
return img
|
79 |
+
|
80 |
+
def draw_vertical(text, font_path:Path, size, max_font_size, min_font_size, margin_px):
|
81 |
+
W,H = size
|
82 |
+
img = Image.new("RGB", (W,H), (255,255,255)) # 白背景
|
83 |
+
draw = ImageDraw.Draw(img)
|
84 |
+
for fs in range(max_font_size, min_font_size-1, -2):
|
85 |
+
font = ImageFont.truetype(str(font_path), fs)
|
86 |
+
line_h = font.getbbox("Hg")[3] - font.getbbox("Hg")[1]
|
87 |
+
step = int(line_h * LINE_SPACING)
|
88 |
+
total_h = len(text) * step if text else step
|
89 |
+
if text:
|
90 |
+
widths = []
|
91 |
+
for c in text:
|
92 |
+
cb = draw.textbbox((0,0), c, font=font)
|
93 |
+
widths.append(cb[2] - cb[0])
|
94 |
+
col_w = max(widths)
|
95 |
+
else:
|
96 |
+
cb = draw.textbbox((0,0), "あ", font=font)
|
97 |
+
col_w = cb[2] - cb[0]
|
98 |
+
if col_w <= W - 2*margin_px and total_h <= H - 2*margin_px:
|
99 |
+
break
|
100 |
+
x = (W - col_w)//2
|
101 |
+
y = (H - total_h)//2
|
102 |
+
for i, ch in enumerate(text):
|
103 |
+
draw.text((x, y + i*step), ch, font=font, fill=(0,0,0)) # 黒
|
104 |
+
return img
|
105 |
+
|
106 |
+
# --------------------
|
107 |
+
# その他
|
108 |
+
# --------------------
|
109 |
+
def sha1_of_text(t:str)->str:
|
110 |
+
import hashlib
|
111 |
+
return hashlib.sha1(t.encode("utf-8")).hexdigest()[:16]
|
112 |
+
|
113 |
+
def write_license_file():
|
114 |
+
text = f"""Dataset License (CC0, JP glyphs + EN descriptions)
|
115 |
+
|
116 |
+
Copyright (c) {datetime.date.today().year} YOUR_NAME
|
117 |
+
All images (Japanese text) and English descriptions are synthetic and authored by the dataset creator.
|
118 |
+
Released under CC0-1.0 (Public Domain Dedication).
|
119 |
+
"""
|
120 |
+
Path("./LICENSE.txt").write_text(text, encoding="utf-8")
|
121 |
+
|
122 |
+
def append_assets_registry(font_paths):
|
123 |
+
reg_path = Path("./provenance/assets_registry.csv")
|
124 |
+
reg_path.parent.mkdir(parents=True, exist_ok=True)
|
125 |
+
new = not reg_path.exists()
|
126 |
+
with open(reg_path, "a", newline="", encoding="utf-8") as f:
|
127 |
+
w = csv.writer(f)
|
128 |
+
if new:
|
129 |
+
w.writerow(["asset_type","path","license","notes"])
|
130 |
+
for p in font_paths:
|
131 |
+
w.writerow(["font", str(p), "SIL Open Font License (assumed)", "同梱時は各フォントのLICENSEを添付"])
|
132 |
+
|
133 |
+
# --------------------
|
134 |
+
# メイン
|
135 |
+
# --------------------
|
136 |
+
def main(n_train, seed, mode, img_size, max_font_size, min_font_size, margin_px, words_file):
|
137 |
+
random.seed(seed); np.random.seed(seed)
|
138 |
+
TRAIN_DIR.mkdir(parents=True, exist_ok=True)
|
139 |
+
write_license_file()
|
140 |
+
fonts = list_fonts(DEFAULT_FONTS_DIR)
|
141 |
+
append_assets_registry(fonts)
|
142 |
+
|
143 |
+
# 外部ファイルから単語リスト読み込み
|
144 |
+
words = load_words(words_file)
|
145 |
+
|
146 |
+
def render(jp_text, font_path, writing_mode):
|
147 |
+
if writing_mode == "horizontal":
|
148 |
+
return draw_horizontal(jp_text, font_path, img_size, max_font_size, min_font_size, margin_px)
|
149 |
+
elif writing_mode == "vertical":
|
150 |
+
return draw_vertical(jp_text, font_path, img_size, max_font_size, min_font_size, margin_px)
|
151 |
+
|
152 |
+
exs = gen_examples(n_train, seed, words)
|
153 |
+
for i, ex in enumerate(exs):
|
154 |
+
font = random.choice(fonts)
|
155 |
+
writing_mode = random.choice(["horizontal","vertical"]) if mode=="both" else mode
|
156 |
+
img = render(ex.jp_text, font, writing_mode)
|
157 |
+
uid = sha1_of_text(f"{i}-{ex.jp_text}-{font.name}-{writing_mode}-{img_size}-{max_font_size}-{min_font_size}")
|
158 |
+
img_path = TRAIN_DIR/f"{uid}.png"
|
159 |
+
txt_path = TRAIN_DIR/f"{uid}.txt"
|
160 |
+
img.save(img_path)
|
161 |
+
txt_path.write_text(ex.en_desc, encoding="utf-8")
|
162 |
+
|
163 |
+
print(f"Done. {n_train} samples in {TRAIN_DIR}")
|
164 |
+
|
165 |
+
if __name__ == "__main__":
|
166 |
+
ap = argparse.ArgumentParser()
|
167 |
+
ap.add_argument("--n_train", type=int, default=1000)
|
168 |
+
ap.add_argument("--seed", type=int, default=0)
|
169 |
+
ap.add_argument("--mode", type=str, default="both", choices=["horizontal","vertical","both"])
|
170 |
+
ap.add_argument("--img_size", type=int, nargs=2, metavar=("WIDTH","HEIGHT"), default=(640,640))
|
171 |
+
ap.add_argument("--max_font_size", type=int, default=54)
|
172 |
+
ap.add_argument("--min_font_size", type=int, default=28)
|
173 |
+
ap.add_argument("--margin_px", type=int, default=28)
|
174 |
+
ap.add_argument("--words_file", type=Path, required=True, help="日本語単語リストファイル(UTF-8, 1行1語)")
|
175 |
+
args = ap.parse_args()
|
176 |
+
main(args.n_train, args.seed, args.mode, tuple(args.img_size), args.max_font_size, args.min_font_size, args.margin_px, args.words_file)
|
177 |
+
|