markdawn 0.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
markdawn/test.py ADDED
@@ -0,0 +1,440 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ md_to_html.py — 数式対応 Markdown → HTML コンバーター
4
+ KaTeX によるレンダリングに対応したスタイリッシュな HTML を生成します。
5
+
6
+ 使い方:
7
+ python md_to_html.py input.md
8
+ python md_to_html.py input.md -o output.html
9
+ python md_to_html.py input.md --title "カスタムタイトル" --subtitle "サブタイトル"
10
+ python md_to_html.py input.md --accent "#2c5f8a" --lang en
11
+ """
12
+
13
+ import argparse
14
+ import re
15
+ import sys
16
+ from pathlib import Path
17
+ from html import escape
18
+
19
+
20
+ # ─────────────────────────────────────────
21
+ # 数式プレースホルダー (mistune が数式を壊さないよう保護)
22
+ # ─────────────────────────────────────────
23
+ class MathProtector:
24
+ """$...$ と $$...$$ をプレースホルダーで保護し、HTML変換後に復元する"""
25
+
26
+ def __init__(self):
27
+ self._store: dict[str, str] = {}
28
+ self._counter = 0
29
+
30
+ def _key(self) -> str:
31
+ k = f"\x00MATH{self._counter}\x00"
32
+ self._counter += 1
33
+ return k
34
+
35
+ def protect(self, text: str) -> str:
36
+ # ブロック数式 $$...$$ を先に処理
37
+ def replace_block(m):
38
+ k = self._key()
39
+ self._store[k] = f"$$\n{m.group(1).strip()}\n$$"
40
+ return f"\n\n{k}\n\n"
41
+
42
+ text = re.sub(r'\$\$(.*?)\$\$', replace_block, text, flags=re.DOTALL)
43
+
44
+ # インライン数式 $...$
45
+ def replace_inline(m):
46
+ k = self._key()
47
+ self._store[k] = f"${m.group(1)}$"
48
+ return k
49
+
50
+ text = re.sub(r'\$(?!\$)(.+?)(?<!\$)\$', replace_inline, text)
51
+ return text
52
+
53
+ def restore(self, html: str) -> str:
54
+ for k, v in self._store.items():
55
+ html = html.replace(escape(k), v) # escape() された版
56
+ html = html.replace(k, v) # そのままの版
57
+ return html
58
+
59
+
60
+ # ─────────────────────────────────────────
61
+ # Markdown → HTML 変換
62
+ # ─────────────────────────────────────────
63
+ def md_to_html_body(md_text: str) -> tuple[str, str]:
64
+ """
65
+ Markdown テキストを HTML ボディ文字列に変換する。
66
+ 戻り値: (html_body, detected_title)
67
+ """
68
+ protector = MathProtector()
69
+ md_text = protector.protect(md_text)
70
+
71
+ # mistune が利用可能なら使用、なければ簡易変換にフォールバック
72
+ try:
73
+ import mistune
74
+ html_body = mistune.html(md_text)
75
+ except ImportError:
76
+ html_body = _simple_md_to_html(md_text)
77
+
78
+ html_body = protector.restore(html_body)
79
+
80
+ # H1 からタイトルを取得(あれば)
81
+ m = re.search(r'<h1[^>]*>(.*?)</h1>', html_body, re.IGNORECASE | re.DOTALL)
82
+ detected_title = re.sub(r'<[^>]+>', '', m.group(1)).strip() if m else ""
83
+
84
+ return html_body, detected_title
85
+
86
+
87
+ def _simple_md_to_html(text: str) -> str:
88
+ """mistune 未インストール時の簡易フォールバック変換"""
89
+ lines = text.split('\n')
90
+ html_lines = []
91
+ in_code = False
92
+ in_list = False
93
+ buffer = []
94
+
95
+ def flush_paragraph():
96
+ nonlocal buffer
97
+ if buffer:
98
+ content = ' '.join(buffer).strip()
99
+ if content:
100
+ html_lines.append(f'<p>{inline_format(content)}</p>')
101
+ buffer = []
102
+
103
+ def inline_format(s: str) -> str:
104
+ s = re.sub(r'\*\*(.+?)\*\*', r'<strong>\1</strong>', s)
105
+ s = re.sub(r'\*(.+?)\*', r'<em>\1</em>', s)
106
+ s = re.sub(r'`(.+?)`', r'<code>\1</code>', s)
107
+ s = re.sub(r'\[(.+?)\]\((.+?)\)', r'<a href="\2">\1</a>', s)
108
+ return s
109
+
110
+ for line in lines:
111
+ # コードブロック
112
+ if line.startswith('```'):
113
+ if not in_code:
114
+ flush_paragraph()
115
+ lang = line[3:].strip()
116
+ html_lines.append(f'<pre><code class="language-{lang}">' if lang else '<pre><code>')
117
+ in_code = True
118
+ else:
119
+ html_lines.append('</code></pre>')
120
+ in_code = False
121
+ continue
122
+
123
+ if in_code:
124
+ html_lines.append(escape(line))
125
+ continue
126
+
127
+ # 見出し
128
+ hm = re.match(r'^(#{1,6})\s+(.*)', line)
129
+ if hm:
130
+ flush_paragraph()
131
+ if in_list:
132
+ html_lines.append('</ul>')
133
+ in_list = False
134
+ level = len(hm.group(1))
135
+ html_lines.append(f'<h{level}>{inline_format(hm.group(2))}</h{level}>')
136
+ continue
137
+
138
+ # 水平線
139
+ if re.match(r'^[-*_]{3,}\s*$', line):
140
+ flush_paragraph()
141
+ html_lines.append('<hr>')
142
+ continue
143
+
144
+ # リスト
145
+ lm = re.match(r'^[-*+]\s+(.*)', line)
146
+ if lm:
147
+ flush_paragraph()
148
+ if not in_list:
149
+ html_lines.append('<ul>')
150
+ in_list = True
151
+ html_lines.append(f'<li>{inline_format(lm.group(1))}</li>')
152
+ continue
153
+
154
+ if in_list and not lm:
155
+ html_lines.append('</ul>')
156
+ in_list = False
157
+
158
+ # 空行
159
+ if line.strip() == '':
160
+ flush_paragraph()
161
+ continue
162
+
163
+ buffer.append(inline_format(line))
164
+
165
+ flush_paragraph()
166
+ if in_list:
167
+ html_lines.append('</ul>')
168
+
169
+ return '\n'.join(html_lines)
170
+
171
+
172
+ # ─────────────────────────────────────────
173
+ # HTML テンプレート生成
174
+ # ─────────────────────────────────────────
175
+ HTML_TEMPLATE = """\
176
+ <!DOCTYPE html>
177
+ <html lang="{lang}">
178
+ <head>
179
+ <meta charset="UTF-8">
180
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
181
+ <title>{title}</title>
182
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/katex.min.css">
183
+ <script defer src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/katex.min.js"></script>
184
+ <script defer src="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.16.9/contrib/auto-render.min.js"
185
+ onload="renderMathInElement(document.body, {{
186
+ delimiters: [
187
+ {{left: '$$', right: '$$', display: true}},
188
+ {{left: '$', right: '$', display: false}}
189
+ ],
190
+ throwOnError: false
191
+ }});"></script>
192
+ <style>
193
+ :root {{
194
+ --text: {color_text};
195
+ --bg: {color_bg};
196
+ --accent: {color_accent};
197
+ --accent-light: {color_accent_light};
198
+ --border: {color_border};
199
+ --code-bg: {color_code_bg};
200
+ }}
201
+
202
+ * {{ box-sizing: border-box; margin: 0; padding: 0; }}
203
+
204
+ body {{
205
+ font-family: {font_family};
206
+ font-size: 16px;
207
+ line-height: 1.85;
208
+ color: var(--text);
209
+ background: var(--bg);
210
+ max-width: 820px;
211
+ margin: 0 auto;
212
+ padding: 48px 32px 80px;
213
+ }}
214
+
215
+ h1 {{ display: none; }}
216
+
217
+ h2 {{
218
+ font-size: 1.35rem;
219
+ color: var(--accent);
220
+ border-left: 4px solid var(--accent);
221
+ padding: 6px 0 6px 14px;
222
+ margin: 2.4em 0 0.9em;
223
+ }}
224
+
225
+ h3 {{
226
+ font-size: 1.1rem;
227
+ color: #2a4060;
228
+ margin: 1.8em 0 0.6em;
229
+ padding-bottom: 3px;
230
+ border-bottom: 1px solid var(--border);
231
+ }}
232
+
233
+ h4 {{
234
+ font-size: 1rem;
235
+ font-weight: bold;
236
+ margin: 1.4em 0 0.4em;
237
+ }}
238
+
239
+ p {{ margin: 0.7em 0; }}
240
+
241
+ ul, ol {{ margin: 0.6em 0 0.6em 1.5em; }}
242
+ li {{ margin: 0.3em 0; }}
243
+
244
+ strong {{ color: #1a3a5c; }}
245
+
246
+ code {{
247
+ font-family: 'SFMono-Regular', 'Consolas', 'Menlo', monospace;
248
+ font-size: 0.87em;
249
+ background: var(--code-bg);
250
+ border: 1px solid var(--border);
251
+ border-radius: 4px;
252
+ padding: 1px 5px;
253
+ }}
254
+
255
+ pre {{
256
+ background: var(--code-bg);
257
+ border: 1px solid var(--border);
258
+ border-radius: 8px;
259
+ padding: 20px 24px;
260
+ overflow-x: auto;
261
+ margin: 1.2em 0;
262
+ font-size: 0.88em;
263
+ line-height: 1.6;
264
+ }}
265
+
266
+ pre code {{
267
+ background: none;
268
+ border: none;
269
+ padding: 0;
270
+ }}
271
+
272
+ .katex-display {{
273
+ margin: 1.2em 0;
274
+ overflow-x: auto;
275
+ padding: 6px 0;
276
+ }}
277
+
278
+ hr {{
279
+ border: none;
280
+ border-top: 1px solid var(--border);
281
+ margin: 2.5em 0;
282
+ }}
283
+
284
+ table {{
285
+ border-collapse: collapse;
286
+ width: 100%;
287
+ margin: 1.2em 0;
288
+ font-size: 0.95em;
289
+ }}
290
+
291
+ th, td {{
292
+ border: 1px solid var(--border);
293
+ padding: 8px 14px;
294
+ text-align: left;
295
+ }}
296
+
297
+ th {{
298
+ background: var(--accent-light);
299
+ color: var(--accent);
300
+ font-weight: bold;
301
+ }}
302
+
303
+ blockquote {{
304
+ border-left: 3px solid var(--accent);
305
+ background: var(--accent-light);
306
+ margin: 1em 0;
307
+ padding: 10px 16px;
308
+ border-radius: 0 6px 6px 0;
309
+ }}
310
+
311
+ a {{ color: var(--accent); }}
312
+
313
+ .header-bar {{
314
+ background: var(--accent);
315
+ color: white;
316
+ border-radius: 8px;
317
+ padding: 22px 28px;
318
+ margin-bottom: 2.5em;
319
+ }}
320
+
321
+ .header-bar .main-title {{
322
+ font-size: 1.4rem;
323
+ font-weight: bold;
324
+ margin: 0 0 4px;
325
+ }}
326
+
327
+ .header-bar .subtitle {{
328
+ font-size: 0.88rem;
329
+ opacity: 0.8;
330
+ }}
331
+ </style>
332
+ </head>
333
+ <body>
334
+
335
+ {header_html}
336
+
337
+ {body_html}
338
+
339
+ </body>
340
+ </html>
341
+ """
342
+
343
+
344
+ def build_header(title: str, subtitle: str) -> str:
345
+ if not title:
346
+ return ""
347
+ subtitle_html = f'\n <div class="subtitle">{escape(subtitle)}</div>' if subtitle else ""
348
+ return (
349
+ f'<div class="header-bar">\n'
350
+ f' <div class="main-title">{escape(title)}</div>'
351
+ f'{subtitle_html}\n'
352
+ f'</div>'
353
+ )
354
+
355
+
356
+ def hex_to_light(hex_color: str, lightness: float = 0.92) -> str:
357
+ """アクセントカラーから薄い背景色を自動生成"""
358
+ h = hex_color.lstrip('#')
359
+ if len(h) != 6:
360
+ return "#e8f0f8"
361
+ r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
362
+ r2 = int(r + (255 - r) * lightness)
363
+ g2 = int(g + (255 - g) * lightness)
364
+ b2 = int(b + (255 - b) * lightness)
365
+ return f"#{r2:02x}{g2:02x}{b2:02x}"
366
+
367
+
368
+ # ─────────────────────────────────────────
369
+ # メイン処理
370
+ # ─────────────────────────────────────────
371
+ def convert(
372
+ input_path: str,
373
+ output_path: str | None = None,
374
+ title: str | None = None,
375
+ subtitle: str = "",
376
+ accent: str = "#2c5f8a",
377
+ lang: str = "ja",
378
+ ) -> Path:
379
+ src = Path(input_path)
380
+ if not src.exists():
381
+ sys.exit(f"Error: ファイルが見つかりません: {src}")
382
+
383
+ md_text = src.read_text(encoding="utf-8")
384
+ html_body, detected_title = md_to_html_body(md_text)
385
+
386
+ # タイトル決定(優先順位: 引数 > Markdown の H1 > ファイル名)
387
+ final_title = title or detected_title or src.stem
388
+
389
+ header_html = build_header(final_title, subtitle)
390
+
391
+ accent_light = hex_to_light(accent)
392
+ # border は accent を少し薄く
393
+ h = accent.lstrip('#')
394
+ r, g, b = int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)
395
+ border_color = f"#{min(r+80,255):02x}{min(g+80,255):02x}{min(b+80,255):02x}"
396
+
397
+ html = HTML_TEMPLATE.format(
398
+ lang=lang,
399
+ title=escape(final_title),
400
+ color_text="#1a1a2e",
401
+ color_bg="#ffffff",
402
+ color_accent=accent,
403
+ color_accent_light=accent_light,
404
+ color_border=border_color,
405
+ color_code_bg="#f4f6f9",
406
+ font_family="'Hiragino Kaku Gothic ProN', 'Noto Sans JP', 'Yu Gothic', sans-serif",
407
+ header_html=header_html,
408
+ body_html=html_body,
409
+ )
410
+
411
+ out = Path(output_path) if output_path else src.with_suffix(".html")
412
+ out.write_text(html, encoding="utf-8")
413
+ print(f"✅ 出力: {out}")
414
+ return out
415
+
416
+
417
+ def main():
418
+ parser = argparse.ArgumentParser(
419
+ description="数式対応 Markdown → HTML コンバーター (KaTeX)"
420
+ )
421
+ parser.add_argument("input", help="入力 Markdown ファイル")
422
+ parser.add_argument("-o", "--output", default=None, help="出力 HTML ファイル(省略時は同名 .html)")
423
+ parser.add_argument("--title", default=None, help="ヘッダーバーのタイトル(省略時は H1 またはファイル名)")
424
+ parser.add_argument("--subtitle", default="", help="ヘッダーバーのサブタイトル")
425
+ parser.add_argument("--accent", default="#2c5f8a",help="アクセントカラー(16進数, 例: #2c5f8a)")
426
+ parser.add_argument("--lang", default="ja", help="HTML の lang 属性(例: ja, en)")
427
+ args = parser.parse_args()
428
+
429
+ convert(
430
+ input_path=args.input,
431
+ output_path=args.output,
432
+ title=args.title,
433
+ subtitle=args.subtitle,
434
+ accent=args.accent,
435
+ lang=args.lang,
436
+ )
437
+
438
+
439
+ if __name__ == "__main__":
440
+ main()
@@ -0,0 +1,19 @@
1
+ Metadata-Version: 2.1
2
+ Name: markdawn
3
+ Version: 0.0.0
4
+ Summary: A tool that converts markdown containing mathematical formulas into HTML as beautiful as dawn
5
+ Home-page: https://github.co.jp/
6
+ Author: bib_inf
7
+ Author-email: contact.bibinf@gmail.com
8
+ License: CC0 v1.0
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Topic :: Software Development :: Libraries
11
+ Classifier: License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication
12
+ Description-Content-Type: text/markdown
13
+ Requires-Dist: ezpip
14
+
15
+ 執筆中
16
+
17
+ English description follows Japanese.
18
+
19
+ ---
@@ -0,0 +1,5 @@
1
+ markdawn/test.py,sha256=RQhYSeyQEwgSqYC3xzWHDdPRXj_W0Wx__Cv2HAG4xww,13522
2
+ markdawn-0.0.0.dist-info/METADATA,sha256=WoQS6M5eno9CAhHhT9iloEjIJXUS0KFH6Sc3Z7mYxPc,575
3
+ markdawn-0.0.0.dist-info/WHEEL,sha256=2wepM1nk4DS4eFpYrW1TTqPcoGNfHhhO_i5m4cOimbo,92
4
+ markdawn-0.0.0.dist-info/top_level.txt,sha256=KHKd79uyTsenNynj28dgBxB_C7YQcXIOJBE4_2NnSqQ,9
5
+ markdawn-0.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: bdist_wheel (0.38.4)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ markdawn