掲示板<39>2026/3/10
from=TOZ

Pythonを利用⑮「math_checker_v5.py」

前回のプログラムで、1日300個ですが、着実にhtmlを読み取って、LaTeXに書き 直してくれることができました。今回のプログラムは元の画面と新しい画面を見比 べて確認し、OKか、または再度検討するかを区分けするプログラムです。 作業中の様子をお見せします。 ホームページのタグの関係で、プログラム中の「<」「>」は全角表示しています。
import os
import sys
import shutil
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QHBoxLayout, 
                             QVBoxLayout, QPushButton, QLabel, QMessageBox)
from PyQt6.QtWebEngineWidgets import QWebEngineView
from PyQt6.QtCore import Qt, QUrl

# --- 設定 ---
BASE_DIR = os.path.expanduser("~/ドキュメント/tozsunHP/whr-mathHP")
MATH_DIR = os.path.join(BASE_DIR, "math")
MODERN_DIR = os.path.join(BASE_DIR, "modern_math")
REDO_DIR = os.path.join(BASE_DIR, "yarinaosi_math")
# 進捗を記録するファイルのパス
PROGRESS_FILE = os.path.join(BASE_DIR, "progress.txt")

# 数式描画用スクリプト (MathJax)
MATHJAX_SCRIPT = """
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
<script>
  window.MathJax = {
    tex: { inlineMath: [['\\\\(', '\\\\)'], ['$', '$']], displayMath: [['\\\\[', '\\\\]'], ['$$', '$$']] }
  };
</script>
"""

class MathMaintenanceApp(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("数学HTML 2画面チェッカー V5 (進捗保存機能付き)")
        self.resize(1500, 900)
        
        if not os.path.exists(REDO_DIR): os.makedirs(REDO_DIR)
        
        # ファイルリストの取得
        all_files = os.listdir(MATH_DIR)
        self.file_list = sorted([f for f in all_files if f.startswith('sec') and f.endswith('.html')])
        
        # 進捗の読み込み
        self.current_index = self.load_progress()
        
        self.init_ui()
        self.load_files()

    def init_ui(self):
        main_layout = QVBoxLayout()
        view_layout = QHBoxLayout()
        
        # 2画面エリア
        l_box = QVBoxLayout(); l_box.addWidget(QLabel("【左】オリジナル (math)"))
        self.left_view = QWebEngineView(); l_box.addWidget(self.left_view)
        
        r_box = QVBoxLayout(); self.right_label = QLabel("【右】LaTeX変換後")
        r_box.addWidget(self.right_label)
        self.right_view = QWebEngineView(); r_box.addWidget(self.right_view)
        
        view_layout.addLayout(l_box); view_layout.addLayout(r_box)
        
        # ボタンエリア
        button_layout = QHBoxLayout()
        self.btn_prev = QPushButton("◀ 前へ (戻る)")
        self.btn_prev.setStyleSheet("background-color: #e0e0e0; font-weight: bold; font-size: 16px;")
        self.btn_prev.clicked.connect(self.prev_file)
        
        self.btn_insufficient = QPushButton("❌ なし または 不十分\n(やり直しフォルダへ)")
        self.btn_insufficient.setStyleSheet("background-color: #ffcccc; color: #b71c1c; font-weight: bold; font-size: 16px;")
        self.btn_insufficient.clicked.connect(self.handle_insufficient)
        
        self.btn_next = QPushButton("▶ 次へ (進む)")
        self.btn_next.setStyleSheet("background-color: #ccffcc; color: #1b5e20; font-weight: bold; font-size: 18px;")
        self.btn_next.clicked.connect(self.next_file)
        
        for b in [self.btn_prev, self.btn_insufficient, self.btn_next]:
            b.setMinimumHeight(75)
            button_layout.addWidget(b)

        self.status_label = QLabel(""); self.status_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        main_layout.addLayout(view_layout)
        main_layout.addWidget(self.status_label)
        main_layout.addLayout(button_layout)
        
        c = QWidget(); c.setLayout(main_layout); self.setCentralWidget(c)

    def load_files(self):
        if not self.file_list: return
        filename = self.file_list[self.current_index]
        self.status_label.setText(f"ファイル: {filename} ({self.current_index + 1} / {len(self.file_list)})")
        
        self.left_view.setUrl(QUrl.fromLocalFile(os.path.join(MATH_DIR, filename)))
        
        right_path = os.path.join(MODERN_DIR, filename)
        if os.path.exists(right_path):
            with open(right_path, 'r', encoding='utf-8') as f:
                content = f.read()
            self.right_view.setHtml(MATHJAX_SCRIPT + content)
            self.right_label.setText(f"【右】LaTeX変換後: {filename}")
        else:
            self.right_view.setHtml("<body style='background:#fee;'><h1 style='color:red; text-align:center; padding-top:100px;'>まだ変換されていません</h1></body>")
        
        # ファイルを読み込むたびに進捗を保存
        self.save_progress()

    def handle_insufficient(self):
        filename = self.file_list[self.current_index]
        src = os.path.join(MODERN_DIR, filename) if os.path.exists(os.path.join(MODERN_DIR, filename)) else os.path.join(MATH_DIR, filename)
        shutil.copy2(src, os.path.join(REDO_DIR, filename)); self.next_file()

    def prev_file(self):
        if self.current_index > 0: self.current_index -= 1; self.load_files()

    def next_file(self):
        if self.current_index < len(self.file_list) - 1: self.current_index += 1; self.load_files()
        else: QMessageBox.information(self, "完了", "すべてのファイルの確認が終わりました!")

    def save_progress(self):
        """現在のインデックスをファイルに保存する"""
        try:
            with open(PROGRESS_FILE, 'w', encoding='utf-8') as f:
                f.write(str(self.current_index))
        except Exception as e:
            print(f"進捗の保存に失敗しました: {e}")

    def load_progress(self):
        """保存されたインデックスを読み込む"""
        if os.path.exists(PROGRESS_FILE):
            try:
                with open(PROGRESS_FILE, 'r', encoding='utf-8') as f:
                    index = int(f.read().strip())
                    # 範囲外でないかチェック
                    if 0 <= index < len(self.file_list):
                        return index
            except (ValueError, Exception):
                return 0
        return 0

    def keyPressEvent(self, event):
        if event.key() == Qt.Key.Key_Right: self.next_file()
        if event.key() == Qt.Key.Key_Left: self.prev_file()

if __name__ == "__main__":
    app = QApplication(sys.argv); w = MathMaintenanceApp(); w.show(); sys.exit(app.exec())



← 一覧へ戻る