harayoki commited on
Commit
1b402b1
·
verified ·
1 Parent(s): 467788b

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +1 -1
  2. gojidori.py +346 -0
app.py CHANGED
@@ -1,4 +1,4 @@
1
- from gomojidori import run_ui, get_arg_parser, DEFAULT_INPUT
2
 
3
  parser = get_arg_parser()
4
  args = parser.parse_args()
 
1
+ from gojidori import run_ui, get_arg_parser, DEFAULT_INPUT
2
 
3
  parser = get_arg_parser()
4
  args = parser.parse_args()
gojidori.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import svgwrite
3
+ from PIL import ImageFont, ImageDraw, Image
4
+ from pathlib import Path
5
+ from fontTools.ttLib import TTFont
6
+ import os
7
+ import tempfile
8
+ import re
9
+ import gradio as gr
10
+
11
+ __all__ = ["run_ui", "get_arg_parser", "DEFAULT_INPUT"]
12
+
13
+ FONT_DIR = Path(__file__).parent / "fonts"
14
+
15
+ DEFAULT_INPUT = (
16
+ "田中 一郎\n鈴木次郎\n乾 三平\n\n四条 保\n吾郎丸\n清六\nnana\n\n"
17
+ "八ノ戸 力\n万 久太郎\nⅩ\n一二三十一\n\n"
18
+ "12イエモン\n13日の金曜日\n"
19
+ "14日の土曜午後\n15日の日曜日深夜\n\n"
20
+ "東京都渋谷区渋谷町渋谷\n"
21
+ "Mac\nLinux\nWindows\n\n"
22
+ "Famicom_Guy\n"
23
+ "Michael_Lawson\n"
24
+ "Seven_Seven_Seven\n"
25
+ "May_the_force_be_with_you\n"
26
+ "ブースケ・サマンサオバタ\n"
27
+ "寿限無寿限無五劫の擦り切れ海砂利水魚の\n")
28
+
29
+ def list_fonts():
30
+ if not FONT_DIR.exists():
31
+ return []
32
+ return [f.name for f in FONT_DIR.iterdir() if f.suffix.lower() == ".ttf"]
33
+
34
+
35
+ def get_default_font(local_mode=True):
36
+ return (FONT_DIR / "NotoSansJP-Medium.ttf").as_posix()
37
+
38
+
39
+ def get_font_weight_name(font_path: str) -> str | None:
40
+ font = TTFont(font_path)
41
+ name_table = font['name']
42
+ for record in name_table.names:
43
+ if record.nameID == 2: # Subfamily(例:Bold, Regular)
44
+ return record.toStr()
45
+ return None
46
+
47
+
48
+ def draw_fixed_width_text(dwg, text, font, font_weight, y, area_x, base_area_width, font_color, min_scale):
49
+ text_parts = text.split(" ")
50
+ num_spaces = len(text_parts) - 1
51
+ merged = "".join(text_parts)
52
+ num_chars = len(merged)
53
+ if num_chars == 0:
54
+ return
55
+ font_family = font.getname()[0]
56
+ dont_weight_map = {
57
+ "regular": "normal",
58
+ "medium": "normal",
59
+ "bold": "bold",
60
+ "semibold": "bold",
61
+ "extrabold": "bold",
62
+ "black": "bold"
63
+ }
64
+ font_weight = dont_weight_map.get(font_weight.lower(), "normal")
65
+
66
+ # 1文字ずつフォントの幅を計算するためのダミー画像を作成
67
+ dummy_img = Image.new('RGB', (1000, 100), color='white')
68
+ draw = ImageDraw.Draw(dummy_img)
69
+ char_widths = [draw.textbbox((0, 0), c, font=font)[2] for c in text if c != ' ']
70
+
71
+ MID = "middle"
72
+ LFT = "start"
73
+ RGT = "end"
74
+ L_POS = area_x
75
+ R_POS = area_x + base_area_width
76
+ C_POS = area_x + base_area_width * 0.5
77
+ if font_color.startswith("rgba"):
78
+ # ex) rgba(200.73281250000002, 39.618318256578945, 39.618318256578945, 1)
79
+ mo = re.match(r'rgba\((.+),\s*(.+),\s*(.+),\s*(.+)\)', font_color)
80
+ if mo:
81
+ font_color = svgwrite.rgb(float(mo.group(1)), float(mo.group(2)), float(mo.group(3)))
82
+ else:
83
+ font_color = "black"
84
+
85
+ def put_text(texts, xx, yy, anchor, text_xscale=1.0):
86
+ if texts == "_":
87
+ # アンダースコアはスペースに置換
88
+ texts = " "
89
+ if text_xscale != 1.0:
90
+ transform_str = f"translate({xx}, {y}) scale({text_xscale}, 1) translate({-text_xscale}, {-y})"
91
+ text_group = dwg.g(transform=transform_str)
92
+ text_group.add(dwg.text(
93
+ texts,
94
+ insert=(0, yy),
95
+ text_anchor=anchor,
96
+ font_size=font.size,
97
+ font_family=font_family,
98
+ font_weight=font_weight,
99
+ fill=font_color
100
+ ))
101
+ dwg.add(text_group)
102
+ else:
103
+ dwg.add(dwg.text(
104
+ texts, insert=(xx, yy), text_anchor=anchor, font_size=font.size,
105
+ font_weight=font_weight,
106
+ font_family=font_family, fill=font_color
107
+ ))
108
+
109
+ if num_chars == 1:
110
+ put_text(text, C_POS, y, MID)
111
+ return
112
+
113
+ if num_chars == 2:
114
+ put_text(merged[0], L_POS, y, LFT)
115
+ put_text(merged[1], R_POS, y, RGT)
116
+ return
117
+
118
+ if num_chars == 3:
119
+ put_text(merged[0], L_POS, y, LFT)
120
+ put_text(merged[2], R_POS, y, RGT)
121
+ if num_spaces == 1:
122
+ if len(text_parts[0]) < len(text_parts[1]):
123
+ # 名前の方が2文字 真ん中は右に寄せる
124
+ put_text(merged[1], C_POS, y, LFT)
125
+ else:
126
+ # 苗字の方が2文字 真ん中は左に寄せる
127
+ put_text(merged[1], C_POS, y,RGT)
128
+ else:
129
+ # 等間隔配置
130
+ put_text(merged[1], C_POS, y, MID)
131
+ return
132
+
133
+ first_w = char_widths[0]
134
+ last_w = char_widths[-1]
135
+ total_char_width = sum(char_widths)
136
+ margin_rest = base_area_width - total_char_width
137
+ step = (R_POS - L_POS) / (num_chars - 1)
138
+
139
+ if num_chars == 4:
140
+ if num_spaces == 1:
141
+ if len(text_parts[0]) == len(text_parts[1]):
142
+ # 1文字目と4文字目の位置は固定
143
+ put_text(merged[0], L_POS, y, LFT)
144
+ put_text(merged[-1], R_POS, y, RGT)
145
+ # 苗字も名前も2文字 すこしそれzれに寄せる
146
+ for i in range(1, num_chars - 1):
147
+ pos = L_POS + step * i
148
+ put_text(merged[i], pos, y, MID)
149
+ return
150
+ else:
151
+ # 苗字と名前の間に全角スペースを入れて5文字ぴったりにする
152
+ put_text(text_parts[0] + " " + text_parts[1], L_POS, y, LFT)
153
+ return
154
+ else:
155
+ # num_spaces が 1 以外の場合は均等に配置
156
+ pos = L_POS
157
+ for i in range(num_chars):
158
+ put_text(merged[i], pos, y, LFT)
159
+ pos += (margin_rest / (num_chars - 1) + char_widths[i])
160
+ return
161
+
162
+ if num_chars == 5:
163
+ # 5文字の場合は普通に均等配置
164
+ pos = L_POS
165
+ for i in range(num_chars):
166
+ put_text(merged[i], pos, y, LFT)
167
+ pos += (margin_rest / (num_chars - 1) + char_widths[i])
168
+ return
169
+
170
+ # 6文字以上の場合 文字幅を縮める
171
+ spacer = 1.0
172
+ # text_xscale = max(min_scale, 5 / num_chars)
173
+ text_xscale = base_area_width / (total_char_width + spacer * (num_chars - 1))
174
+ text_xscale = max(text_xscale, min_scale)
175
+ # print(f"文字数: {num_chars}, 縮小率: {text_xscale} {min_scale}")
176
+ pos = L_POS + 0.5 * (base_area_width - total_char_width * text_xscale - spacer * (num_chars - 1))
177
+ for i in range(num_chars):
178
+ put_text(merged[i], pos, y, LFT, text_xscale=text_xscale)
179
+ pos += spacer + char_widths[i] * text_xscale
180
+
181
+
182
+ def render_text_to_svg(
183
+ text, font_path, font_size, font_space, min_scale,
184
+ line_height, space_line_height, svg_width, output_file: str | None, font_color, debug=False):
185
+ font = ImageFont.truetype(str(font_path), font_size)
186
+ lines = text.split('\n')
187
+ svg_height = 0
188
+ heights = []
189
+ regex = re.compile(r'^\s*(.+)\s*$')
190
+
191
+ font_weight = get_font_weight_name(font_path)
192
+ # print(f"フォント: {font_path.name} ({font_weight})")
193
+
194
+ for line in lines:
195
+ # 頭にスペースがあれば除去
196
+ mo = regex.match(line)
197
+ if mo:
198
+ line = regex.match(line).group(1)
199
+ if line == "":
200
+ heights.append(space_line_height)
201
+ svg_height += space_line_height
202
+ else:
203
+ heights.append(line_height)
204
+ svg_height += line_height
205
+ dwg = svgwrite.Drawing(output_file, size=(svg_width, svg_height))
206
+
207
+ # 基準となる5文字分の合計幅を計算(スペースを除外)
208
+ dummy_five = "あいうえお"
209
+ dummy_img = Image.new('RGB', (1000, 100), color='white')
210
+ draw = ImageDraw.Draw(dummy_img)
211
+ base_widths = [draw.textbbox((0, 0), c, font=font)[2] for c in dummy_five]
212
+ base_area_width = sum(base_widths) + font_space * 4
213
+ area_x = (svg_width - base_area_width) / 2
214
+
215
+ if debug:
216
+ # 位置確認用の罫線の描画
217
+ dwg.add(dwg.line(
218
+ start=(svg_width / 2, 0), end=(svg_width / 2, svg_height), stroke="lightblue", stroke_dasharray="5,5"))
219
+ dwg.add(dwg.line(start=(area_x, 0), end=(area_x, svg_height), stroke="lightblue"))
220
+ dwg.add(dwg.line(
221
+ start=(area_x + base_area_width, 0), end=(area_x + base_area_width, svg_height), stroke="lightblue"))
222
+
223
+ dwg.add(dwg.line(start=(0, 0), end=(0, svg_height), stroke="lightblue"))
224
+ dwg.add(dwg.line(start=(svg_width, 0), end=(svg_width, svg_height), stroke="lightblue"))
225
+
226
+ y_cursor = 0
227
+ for line, h in zip(lines, heights):
228
+ draw_fixed_width_text(
229
+ dwg, line, font, font_weight, y=y_cursor + font_size, area_x=area_x,
230
+ base_area_width=base_area_width, font_color=font_color, min_scale=min_scale
231
+ )
232
+ y_cursor += h
233
+ if output_file:
234
+ dwg.save()
235
+ return dwg.tostring()
236
+
237
+
238
+ def run_ui(args):
239
+ font_files = list_fonts()
240
+ font_choices = font_files if font_files else ["(フォントなし)"]
241
+ # NotoSansJPが含まれるものを前に持ってくる
242
+ font_choices.sort(key=lambda x: "NotoSansJP" not in x)
243
+
244
+ def generate_svg(text, font_name, font_size, font_space, min_scale, line_height, space_line_height,
245
+ svg_width, text_color, debug, scale):
246
+ output_filename = args.output
247
+ font_path = FONT_DIR / font_name
248
+ if not font_path.exists():
249
+ with open("error.txt", "w", encoding="utf-8") as f:
250
+ f.write("フォントが見つかりませんでした。")
251
+ return "エラー: フォントが見つかりません。", None
252
+ svg_content = render_text_to_svg(
253
+ text, font_path, int(font_size), int(font_space), float(min_scale), int(line_height), int(space_line_height),
254
+ int(svg_width), None, text_color, debug
255
+ )
256
+ # print(f"SVG: {svg_content[:100]}...")
257
+ scale = scale or "0.25"
258
+ scale_float = float(scale)
259
+ width_style = f"width: {int(int(svg_width) * scale_float)}px;"
260
+ scaled_svg = \
261
+ f'<div style="transform: scale({scale}); transform-origin: top left; {width_style}">{svg_content}</div>'
262
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".svg", mode="w", encoding="utf-8") as f:
263
+ f.write(svg_content)
264
+ output_filename = f.name
265
+ return output_filename, scaled_svg
266
+ default_text = args.input or ""
267
+ iface = gr.Interface(
268
+ fn=generate_svg,
269
+ inputs=[
270
+ gr.Textbox(label="テキスト入力", lines=8, value=default_text, placeholder="各行に人名 '苗字 名前'"),
271
+ gr.Dropdown(
272
+ choices=font_choices, label="フォント選択",
273
+ value=os.path.basename(
274
+ args.font) if args.font and os.path.basename(args.font) in font_choices else font_choices[0]),
275
+ gr.Number(label="フォントサイズ", value=args.font_size),
276
+ gr.Number(label="フォントスペース", value=args.font_space),
277
+ gr.Number(label="最小縮小率", value=args.min_scale),
278
+ gr.Number(label="行の高さ", value=args.line_height),
279
+ gr.Number(label="スペースのみの行の高さ", value=args.space_line_height),
280
+ gr.Number(label="SVGの横幅", value=args.width),
281
+ gr.ColorPicker(label="文字色", value=args.font_color),
282
+ gr.Checkbox(label="デバッグ表示(ガイド線)", value=args.debug),
283
+ gr.Dropdown(label="表示倍率", choices=["0.1", "0.25", "0.33", "0.5", "0.75", "1.0"], value="0.5")
284
+ ],
285
+ outputs=[
286
+ gr.File(label="SVGファイル ダウンロード"),
287
+ gr.HTML(label="プレビュー")
288
+ ],
289
+ title="*5字取り* スタッフロールSVG作成ツール",
290
+ description="5字取りルールに則り、入力されたスタッフロールテキストをSVGファイルに変換します。"
291
+ )
292
+ iface.launch()
293
+
294
+
295
+ def get_arg_parser():
296
+ parser = argparse.ArgumentParser(description='5字取りルールで入力スタッフロールテキストをSVGに変換する')
297
+ parser.add_argument('-f', '--font', default=get_default_font(), help='フォントファイル(ttf)のパス')
298
+ parser.add_argument('-s', '--font-size', type=int, default=50, help='フォントサイズ')
299
+ parser.add_argument('-sp', '--font-space', type=int, default=2, help='フォントスペース')
300
+ parser.add_argument('-ms', '--min-scale', type=float, default=0.55, help='最小縮小スケール')
301
+ parser.add_argument('-c', '--font-color', type=str, default="#000000", help='フォントカラー')
302
+ parser.add_argument('-l', '--line-height', type=int, default=80, help='行の高さ')
303
+ parser.add_argument('--space-line-height', type=int, default=40, help='スペースのみの行の高さ')
304
+ parser.add_argument('-w', '--width', type=int, default=1280, help='SVGの横幅')
305
+ parser.add_argument('-i', '--input', help='入力テキストファイル')
306
+ parser.add_argument('-o', '--output', help='出力SVGファイル名', default="")
307
+ parser.add_argument('--debug', action='store_true', help='デバッグ表示(中央線・ガイド)')
308
+ parser.add_argument('--ui', action='store_true', help='GradioによるUIを表示する')
309
+ return parser
310
+
311
+
312
+ def main():
313
+ parser = get_arg_parser()
314
+ args = parser.parse_args()
315
+ if args.input:
316
+ with open(args.input, 'r', encoding='utf-8') as file:
317
+ args.input = file.read()
318
+ else:
319
+ args.input = DEFAULT_INPUT
320
+ if args.ui:
321
+ run_ui(args)
322
+ else:
323
+ if not args.output:
324
+ input_basename = os.path.splitext(os.path.basename(args.input))[0]
325
+ args.output = f"{input_basename}.svg"
326
+ regex_color = r'^#[0-9a-fA-F]{6}$'
327
+ assert re.match(regex_color, args.font_color) is not None, "フォントカラーは #RRGGBB 形式で指定してください"
328
+ if args.font:
329
+ assert os.path.exists(args.font), "フォントファイルが見つかりません"
330
+ render_text_to_svg(
331
+ text=args.input,
332
+ font_path=args.font,
333
+ font_size=args.font_size,
334
+ font_space=args.font_space,
335
+ min_scale=args.min_scale,
336
+ line_height=args.line_height,
337
+ space_line_height=args.space_line_height,
338
+ svg_width=args.width,
339
+ output_file=args.output,
340
+ font_color=args.font_color,
341
+ debug=args.debug
342
+ )
343
+
344
+
345
+ if __name__ == '__main__':
346
+ main()