make_sphinx_files.py ダウンロード/コピー
make_sphinx_files.py
make_sphinx_files.py
1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3"""Sphinxドキュメント生成プロセスを自動化するスクリプト。
4
5このスクリプトは、PythonスクリプトのDocstring追加、プログラム説明生成、
6SphinxドキュメントのためのreStructuredText (RST) ファイルやMarkdownファイルの
7作成など、一連のドキュメント生成ルーチンを一括で実行します。
8
9対象のPythonスクリプトに対し、AIによるDocstringの挿入、実行ログの取得、
10ダウンロードリンク付きのソースコード表示、APIリファレンス、および
11コード品質評価のドキュメントを自動生成し、Sphinxプロジェクトの
12ディレクトリ構造に適合させます。
13
14:doc:`make_sphinx_files_usage`
15"""
16
17import os
18import sys
19import argparse
20import shutil
21import subprocess
22import traceback
23from pathlib import Path
24from datetime import datetime
25
26
27SCRIPT_FULLPATH = os.path.abspath(sys.argv[0])
28SCRIPT_DIR = os.path.dirname(SCRIPT_FULLPATH)
29SCRIPT_BASENAME = os.path.splitext(os.path.basename(SCRIPT_FULLPATH))[0]
30
31ADD_DOCSTRING_PATH = os.path.join(SCRIPT_DIR, "add_docstring.py")
32EXPLAIN_PROGRAM_PATH = os.path.join(SCRIPT_DIR, "explain_program5.py")
33
34
35def relative_from_source(argv0: str) -> str:
36 """指定されたパスから 'source' ディレクトリ以降の相対パスの親ディレクトリ名を抽出します。
37
38 `argv0` が `path/to/source/subdir/file.py` のような形式の場合、
39 `subdir` を返します。'source' がパスに含まれない場合は空文字列を返します。
40 これはSphinxのドキュメント構造におけるサブディレクトリの解決に使用されます。
41
42 :param argv0: プログラムの実行パス (sys.argv[0] など)。
43 :returns: 'source' ディレクトリからの相対パスの親ディレクトリ名。'source'が見つからない場合は空文字列。
44 :rtype: str
45 """
46 p = Path(argv0).resolve()
47 parts = p.parts
48
49 try:
50 idx = parts.index("source")
51 except ValueError:
52 return ""
53
54 rel_path = Path(*parts[idx + 1:])
55 return str(rel_path.parent)
56
57
58def run_step(message, cmd_list):
59 """指定されたコマンドリストを実行し、その結果を表示します。
60
61 外部コマンドの実行状況をユーザーに通知し、エラーが発生した場合は
62 それを報告します。コマンドの標準出力と標準エラー出力は表示されませんが、
63 返却コードがゼロでない場合はエラーとみなします。
64
65 :param message: 実行するステップを説明するメッセージ。
66 :param cmd_list: 実行するコマンドとその引数のリスト。
67 :returns: コマンドが正常に実行された場合はTrue、エラーが発生した場合はFalse。
68 :rtype: bool
69 """
70 print(f"\n>>> {message}")
71 print(f" コマンド: {' '.join(cmd_list)}")
72 try:
73 result = subprocess.run(cmd_list, text=True, errors="ignore")
74 if result.returncode != 0:
75 print("!!! エラーが発生しました")
76 return False
77 return True
78 except Exception as e:
79 print(f"!!! 実行エラー: {e}")
80 return False
81
82
83def make_init_py(path):
84 """指定されたパスに空の `__init__.py` ファイルを作成します。
85
86 既にファイルが存在する場合は作成せずにメッセージを表示します。
87 Pythonパッケージとして認識させるために使用されます。
88
89 :param path: 作成する `__init__.py` ファイルのパス。
90 :type path: str
91 :returns: None
92 """
93 if os.path.exists(path):
94 print(f">>> Step: {path} が見つかりました。")
95 else:
96 print(f">>> Step: {path} を作成中...")
97 with open(path, "w", encoding="utf-8") as f:
98 f.write("")
99 print(f" Done: {path}")
100
101
102def make_index_template(path, module_path):
103 """プロジェクト全体のメイン `index.template` ファイルを作成または更新します。
104
105 `index.template` が存在しない場合は新規作成し、`toctree` ディレクティブに
106 新しいモジュールのインデックスファイルを追加します。
107 既に存在する場合は、新しいモジュールパスを追記します。
108 これにより、Sphinxのメインドキュメントから各モジュールへのリンクが設定されます。
109
110 :param path: `index.template` ファイルのパス。
111 :type path: str
112 :param module_path: Sphinxドキュメントツリーに追加するモジュールのパス(例: `subdir/modulename`)。
113 :type module_path: str
114 :returns: None
115 """
116 if os.path.exists(path):
117 print(f">>> Step: {path} に追加中...")
118 with open(path, "a", encoding="utf-8") as f:
119 f.write(f" {module_path}_index\n")
120 print(f" Done: {path}")
121 else:
122 print(f">>> Step: {path} を作成中...")
123 content = f"""\
124プロジェクト全体ドキュメント
125============================
126
127.. toctree::
128 :maxdepth: 2
129 :caption: メインメニュー:
130 :hidden:
131 :glob:
132
133 {module_path}_index
134"""
135 with open(path, "w", encoding="utf-8") as f:
136 f.write(content)
137 print(f" Done: {path}")
138
139
140def make_index_rst(index_rst, base_name, package_path):
141 """特定のPythonスクリプトに対する `_index.rst` ファイルを作成します。
142
143 このファイルは、スクリプトのドキュメントのトップレベルインデックスとして機能し、
144 `_download`, `_usage`, `_quality`, `_examples`, `_api` などの
145 主要なセクションへのリンクを `toctree` ディレクティブで設定します。
146
147 :param index_rst: 作成する `_index.rst` ファイルのパス。
148 :type index_rst: str
149 :param base_name: スクリプトのベース名(拡張子なし)。
150 :type base_name: str
151 :param package_path: スクリプトの完全なパッケージパス(例: `subdir.modulename`)。
152 :type package_path: str
153 :returns: None
154 """
155 print(f">>> Step: {index_rst} を作成中...")
156 index_content = f"""{base_name} ドキュメント
157============================================================================
158
159.. toctree::
160 :maxdepth: 1
161
162 {base_name}_download
163 {base_name}_usage
164 {base_name}_quality
165 {base_name}_examples
166 {base_name}_api
167"""
168 with open(index_rst, "w", encoding="utf-8") as f:
169 f.write(index_content)
170 print(f" Done: {index_rst}")
171
172
173def make_download_rst(download_rst, base_name, script_rel_path):
174 """スクリプトのダウンロードとソースコード表示のための `.rst` ファイルを作成します。
175
176 このファイルは、`:download:` ロールを使用してスクリプトファイルへのダウンロードリンクを提供し、
177 `.. literalinclude::` ディレクティブを使用して、ユーザーがドキュメント内で
178 ソースコードを直接確認できるようにします。これにより、コードの配布と閲覧が容易になります。
179
180 :param download_rst: 作成するダウンロード `.rst` ファイルのパス。
181 :type download_rst: str
182 :param base_name: スクリプトのベース名(拡張子なし)。
183 :type base_name: str
184 :param script_rel_path: ソースディレクトリからのスクリプトの相対パス。
185 :type script_rel_path: str
186 :returns: None
187 """
188 print(f">>> Step: {download_rst} を作成中...")
189
190 script_name = os.path.basename(script_rel_path)
191
192 download_content = f"""{script_name} ダウンロード/コピー
193========================================================
194
195:download:`{script_name} をダウンロード <{script_rel_path}>`
196
197.. dropdown:: {script_name}
198 :color: primary
199 :icon: file-code
200
201 .. literalinclude:: {script_rel_path}
202 :language: python
203 :linenos:
204 :caption: {script_name}
205"""
206 with open(download_rst, "w", encoding="utf-8") as f:
207 f.write(download_content)
208
209 print(f" Done: {download_rst}")
210
211
212def make_api_rst(api_rst, base_name, package_path):
213 """スクリプトのAPIドキュメントを生成するための `.rst` ファイルを作成します。
214
215 このファイルは、Sphinxの `automodule` ディレクティブを利用して、
216 指定されたパッケージパスから関数、クラス、メソッドなどを自動的に抽出し、
217 APIリファレンスを生成します。これにより、コードの構造と公開インターフェースが
218 ドキュメント化されます。
219
220 :param api_rst: 作成するAPI `.rst` ファイルのパス。
221 :type api_rst: str
222 :param base_name: スクリプトのベース名(拡張子なし)。
223 :type base_name: str
224 :param package_path: スクリプトの完全なパッケージパス(例: `subdir.modulename`)。
225 :type package_path: str
226 :returns: None
227 """
228 print(f">>> Step: {api_rst} を作成中...")
229 api_content = f"""{base_name} プログラム仕様
230============================================================================
231
232.. currentmodule:: {package_path}
233
234.. automodule:: {package_path}
235 :members:
236 :undoc-members:
237 :show-inheritance:
238"""
239 with open(api_rst, "w", encoding="utf-8") as f:
240 f.write(api_content)
241 print(f" Done: {api_rst}")
242
243
244def make_examples_md(examples_md, infile, base_name):
245 """スクリプトの実行例を示すMarkdownファイルを作成します。
246
247 この関数は、対象スクリプトの `--help` 出力を取得し、
248 現在のディレクトリ内でスクリプト名で始まる関連する画像ファイル
249 (.png, .jpg, .jpeg) やデータファイル (.csv, .xlsx, .xls, .txt) を検索します。
250 それらの情報をMarkdown形式で整形し、実行例のテンプレートファイルを生成します。
251
252 :param examples_md: 作成する実行例Markdownファイルのパス。
253 :type examples_md: str
254 :param infile: 対象となるPythonスクリプトファイル。
255 :type infile: str
256 :param base_name: スクリプトのベース名(拡張子なし)。
257 :type base_name: str
258 :returns: None
259 """
260 print(f">>> Step: {examples_md} テンプレートを作成中...")
261
262 image_files = sorted(
263 f for f in os.listdir(".")
264 if f.startswith(base_name)
265 and f.lower().endswith((".png", ".jpg", ".jpeg"))
266 )
267
268 data_files = sorted(
269 f for f in os.listdir(".")
270 if f.startswith(base_name)
271 and f.lower().endswith((".csv", ".xlsx", ".xls", ".txt"))
272 )
273
274 print("Image files:", image_files)
275 print("Data files:", data_files)
276
277 print(" help logを取得します")
278 result = subprocess.run(
279 [sys.executable, infile, "--help"],
280 text=True,
281 capture_output=True,
282 errors="ignore",
283 )
284
285 print(" return code:", result.returncode)
286
287 if result.returncode == 0:
288 help_log = result.stdout + "\n" + result.stderr
289 else:
290 help_log = (
291 "(ヘルプの自動取得に失敗しました。"
292 "ここに実行ログを貼り付けてください)"
293 )
294
295 if data_files:
296 data_section = "## データファイル\n"
297 for df in data_files:
298 data_section += f"- [{df}](./{df})\n"
299 data_section += "\n"
300 else:
301 data_section = (
302 "## 生成されたデータファイル\n"
303 "(データファイルが見つかりませんでした)\n\n"
304 )
305
306 if image_files:
307 image_section = "## 画像ファイル\n\n"
308 for img in image_files:
309 image_section += f"- [{img}](./{img})\n"
310 image_section += f"\n\n"
311 else:
312 image_section = (
313 "## 生成された画像一覧\n"
314 "(画像ファイルが見つかりませんでした)\n\n"
315 )
316
317 examples_content = f"""# {base_name} 実行例
318
319## help出力 `{base_name}.py --help`
320
321<pre style="background-color: #f4f4f4; border: 1px solid #ccc; padding: 10px; border-radius: 5px; font-family: 'Courier New', Courier, monospace; overflow-x: auto;">
322{help_log}
323</pre>
324
325{data_section}
326
327{image_section}
328"""
329
330 with open(examples_md, "w", encoding="utf-8") as f:
331 f.write(examples_content)
332
333 print(f" Done: {examples_md}")
334
335
336def check_updated(file1, file2):
337 """2つのファイルの更新日時を比較し、一方のファイルが他方より新しいかどうかを判定します。
338
339 この関数は、`file1` が存在しない場合は `False` を返します。
340 `file2` が存在しない場合は、`file1` が新しいとみなし `True` を返します。
341 両方存在する場合は、`file1` の最終更新日時が `file2` のそれ以上である場合に `True` を返します。
342
343 :param file1: 比較対象の最初のファイルパス。
344 :type file1: str
345 :param file2: 比較対象の2番目のファイルパス。
346 :type file2: str
347 :returns: `file1` が `file2` より新しい、または `file2` が存在しない場合は `True`、それ以外は `False`。
348 :rtype: bool
349 """
350 if not os.path.exists(file1):
351 return False
352 if not os.path.exists(file2):
353 return True
354
355 t1 = os.path.getmtime(file1)
356 dt1 = datetime.fromtimestamp(t1)
357 t2 = os.path.getmtime(file2)
358 dt2 = datetime.fromtimestamp(t2)
359
360 print(f"File stamps: {file1} : {dt1}")
361 print(f" {file2} : {dt2}")
362
363 return t1 >= t2
364
365
366def main(args):
367 """Sphinxドキュメント生成の主要な処理フローを実行します。
368
369 この関数は、`__init__.py` の作成、`index.template` の更新、
370 各種 `.rst` および `.md` ファイルの生成、Docstring追加ツールの実行、
371 コード品質評価ツールの実行、および生成されたDocstring付きファイルの
372 適用を行います。入力ファイル、サブディレクトリ、プロンプトファイル、
373 API設定などのコマンドライン引数に基づいて動作を制御します。
374
375 :param args: コマンドライン引数をパースした `argparse.Namespace` オブジェクト。
376 :type args: argparse.Namespace
377 :returns: None
378 """
379 infile = args.infile
380
381 if not os.path.exists(infile):
382 print(f"エラー: 入力ファイル '{infile}' が見つかりません。")
383 return
384
385 base_name = os.path.splitext(os.path.basename(infile))[0]
386 date_str = datetime.now().strftime("%Y%m%d")
387
388 init_py = "__init__.py"
389 index_template = "index.template"
390 docstring_out = f"{base_name}_docstring.py"
391 backup_file = f"{base_name}_{date_str}.py"
392
393 usage_md = f"{base_name}_usage.md"
394 quality_md = f"{base_name}_quality.md"
395 examples_md = f"{base_name}_examples.md"
396 index_rst = f"{base_name}_index.rst"
397 download_rst = f"{base_name}_download.rst"
398 api_rst = f"{base_name}_api.rst"
399
400 if args.subdir is not None and args.subdir != "":
401 module_path = os.path.join(args.subdir, base_name)
402 package_path = f"{args.subdir}.{base_name}"
403 else:
404 module_path = base_name
405 package_path = module_path
406
407 print("=" * 60)
408 print(f" プロジェクト: {base_name} のSphinxファイル自動生成を開始します")
409 print(f" モジュールパス: {module_path}")
410 print(f" パッケージパス: {package_path}")
411 print("=" * 60)
412
413 make_init_py(init_py)
414
415 if os.path.exists(index_template):
416 print(f"** Warning: [{index_template}] exists. Skip to create.")
417 else:
418 make_index_template(index_template, module_path)
419
420 if args.update_index:
421 print(
422 f"** Message: [Force update {index_rst} "
423 f"due to {args.update_index=}]."
424 )
425 make_index_rst(index_rst, base_name, package_path)
426 elif os.path.exists(index_rst):
427 print(f"** Warning: [{index_rst}] exists. Skip to create.")
428 else:
429 make_index_rst(index_rst, base_name, package_path)
430
431 if os.path.exists(download_rst):
432 print(f"** Warning: [{download_rst}] exists. Skip to create.")
433 else:
434 make_download_rst(download_rst, base_name, infile)
435
436 if os.path.exists(api_rst):
437 print(f"** Warning: [{api_rst}] exists. Skip to create.")
438 else:
439 make_api_rst(api_rst, base_name, package_path)
440
441 if os.path.exists(examples_md):
442 print(f"** Warning: [{examples_md}] exists. Skip to create.")
443 else:
444 make_examples_md(examples_md, infile, base_name)
445
446 args_list = [
447 "--api", args.api,
448 "--update", str(args.update),
449 "--overwrite", str(args.overwrite),
450 "--pause", str(args.pause),
451 ]
452 if args.model:
453 args_list.extend(["--model", args.model])
454 if args.reasoning_effort:
455 args_list.extend(["--reasoning-effort", args.reasoning_effort])
456
457 if not check_updated(infile, usage_md):
458 print(
459 f"Step EXPLAIN_PROGRAM_PATH: {infile}が"
460 f"{usage_md}より古いのでスキップします"
461 )
462 else:
463 if not run_step(
464 "Step: EXPLAIN_PROGRAM_PATH を実行してusageを生成中...",
465 [
466 sys.executable,
467 EXPLAIN_PROGRAM_PATH,
468 infile,
469 usage_md,
470 "--inifile",
471 args.prompt_explain,
472 *args_list,
473 ],
474 ):
475 return
476
477 if not check_updated(infile, docstring_out):
478 print(
479 f"Step ADD_DOCSTRING_PATH: {infile}が"
480 f"{docstring_out}より古いのでスキップします"
481 )
482 else:
483 if not run_step(
484 "Step: ADD_DOCSTRING_PATH を実行してDocstringを追加中...",
485 [
486 sys.executable,
487 ADD_DOCSTRING_PATH,
488 infile,
489 "--inifile",
490 args.prompt_add_docstring,
491 *args_list,
492 ],
493 ):
494 return
495
496 print(">>> Step: オリジナルファイルのバックアップを作成中...")
497 if os.path.exists(infile):
498 shutil.copy2(infile, backup_file)
499 print(f" Done: {infile} -> {backup_file}")
500 else:
501 print("!!! バックアップ対象のファイルが見つかりません。")
502 return
503
504 if os.path.exists(docstring_out) and os.path.exists(infile):
505 t_doc = os.path.getmtime(docstring_out)
506 size_byte = os.path.getsize(docstring_out)
507 t_in = os.path.getmtime(infile)
508
509 dt_doc = datetime.fromtimestamp(t_doc)
510 dt_in = datetime.fromtimestamp(t_in)
511
512 print(
513 f"File stamps: {docstring_out} : "
514 f"{dt_doc} ({size_byte} bytes)"
515 )
516 print(f" {infile} : {dt_in}")
517
518 if size_byte == 0:
519 print(
520 f" {docstring_out} はダミーファイルのため、"
521 "ファイルコピーは行いません"
522 )
523 elif t_doc <= t_in:
524 print(" infile の方が新しいのでファイルコピーは行いません")
525 else:
526 print(
527 f">>> Step: 生成されたDocstring版ファイルを "
528 f"{infile} にリネーム中..."
529 )
530 if os.path.exists(docstring_out):
531 os.replace(docstring_out, infile)
532 print(f" Done: {docstring_out} -> {infile}")
533
534 with open(docstring_out, "w", encoding="utf-8") as fp:
535 fp.write("")
536
537 print(f" ダミーの空ファイル {docstring_out} を作りました")
538 else:
539 print(
540 "!!! Docstring版ファイルが生成されていなかったため、"
541 "リネームをスキップします。"
542 )
543 return
544
545 if args.prompt_quality:
546 if not run_step(
547 "Step: EXPLAIN_PROGRAM_PATH を実行してコード品質評価を生成中...",
548 [
549 sys.executable,
550 EXPLAIN_PROGRAM_PATH,
551 infile,
552 quality_md,
553 "--inifile",
554 args.prompt_quality,
555 *args_list,
556 ],
557 ):
558 return
559 else:
560 print(
561 "** Warning: --prompt_quality が指定されていないため、"
562 "quality生成をスキップします。"
563 )
564
565 print("\n" + "=" * 60)
566 print(" 全ての自動生成プロセスが正常に終了しました。")
567 print("=" * 60)
568
569
570def initialize():
571 """コマンドライン引数をパースするための `ArgumentParser` を初期化します。
572
573 スクリプトの目的と、`infile`、`subdir`、`prompt_explain`、
574 `prompt_quality`、`prompt_add_docstring`、`api`、`model`、
575 `reasoning_effort`、`update_index`、`update`、`overwrite`、
576 `pause` といった引数を定義します。
577 各引数には説明とデフォルト値が設定されています。
578
579 :returns: 設定された `ArgumentParser` オブジェクト。
580 :rtype: argparse.ArgumentParser
581 """
582 parser = argparse.ArgumentParser(
583 description=(
584 "Sphinxドキュメント生成の一連のルーチン"
585 "(Docstring追加、バックアップ、解説生成、RST作成)"
586 "を自動化します。"
587 )
588 )
589
590 parser.add_argument(
591 "infile",
592 help="対象となるPythonスクリプトファイル名 (例: mu_fit.py)",
593 )
594 parser.add_argument(
595 "--subdir",
596 default=None,
597 help="sourceディレクトリからの相対パス",
598 )
599
600 parser.add_argument(
601 "--prompt_explain",
602 default="explain_program5.ini",
603 help="usage生成用プロンプトファイルのパス",
604 )
605 parser.add_argument(
606 "--prompt_quality",
607 default="prompt_quality.ini",
608 help="quality生成用プロンプトファイルのパス",
609 )
610 parser.add_argument(
611 "--prompt_add_docstring",
612 default="",
613 help="add_docstring.pyに渡すプロンプトファイルのパス",
614 )
615
616 parser.add_argument(
617 "--api",
618 choices=["openai", "openai5", "google", "gemini", "lmstudio"],
619 default="google",
620 help="子LLMプログラムに渡すAPI種別",
621 )
622 parser.add_argument(
623 "--model",
624 default=None,
625 help="子LLMプログラムに渡すモデル名。例: qwen/qwen3.8-27b",
626 )
627 parser.add_argument(
628 "--reasoning-effort",
629 choices=["low", "medium", "xhigh"],
630 default=None,
631 help="LM StudioのQwen3.8用推論量。省略時はモデル既定値",
632 )
633 parser.add_argument("--update_index", type=int, default=0)
634 parser.add_argument("-u", "--update", type=int, default=1)
635 parser.add_argument("-w", "--overwrite", type=int, default=0)
636 parser.add_argument("-p", "--pause", type=int, default=0)
637
638 return parser
639
640
641def read_args(parser):
642 """`ArgumentParser` から引数を読み込み、必要な追加処理を行います。
643
644 `reasoning_effort` が `lmstudio` 以外のAPIと組み合わせて指定された場合に
645 エラーを発生させます。また、`subdir` が指定されていない場合は
646 `relative_from_source` を呼び出して自動的に設定します。
647
648 :param parser: 設定済みの `ArgumentParser` オブジェクト。
649 :type parser: argparse.ArgumentParser
650 :returns: パースされ、処理された `argparse.Namespace` オブジェクト。
651 :rtype: argparse.Namespace
652 :raises SystemExit: `reasoning_effort` と `api` の組み合わせが無効な場合。
653 """
654 args = parser.parse_args()
655
656 if args.reasoning_effort and args.api != "lmstudio":
657 parser.error(
658 "--reasoning-effort は --api lmstudio と組み合わせて指定してください"
659 )
660
661 if args.subdir is None:
662 args.subdir = relative_from_source(args.infile)
663
664 return args
665
666
667if __name__ == "__main__":
668 print()
669 print(f"=== {sys.argv[0]} ===")
670 print(f"{EXPLAIN_PROGRAM_PATH=}")
671 print(f"{ADD_DOCSTRING_PATH=}")
672
673 parser = initialize()
674 args = read_args(parser)
675
676 print()
677 print("Args:")
678 print(f" {args.infile=}")
679 print(f" {args.subdir=}")
680 print(f" {args.api=}")
681 print(f" {args.model=}")
682 print(f" {args.reasoning_effort=}")
683 print(f" {args.update=}")
684 print(f" {args.overwrite=}")
685 print(f" {args.pause=}")
686 print(f" {args.prompt_explain=}")
687 print(f" {args.prompt_quality=}")
688 print(f" {args.prompt_add_docstring=}")
689 print(f" {args.update=}")
690 print(f" {args.overwrite=}")
691 print(f" {args.update_index=}")
692 print(f" {args.pause=}")
693
694 try:
695 main(args)
696 except Exception:
697 print("\n" + "!" * 60)
698 print(" 予期せぬ致命的なエラーが発生しました。")
699 traceback.print_exc()
700 print("!" * 60)
701 sys.exit(1)