banner
Riceneeder

Riceneeder

白天研究生,晚上研究死
github
email

OpenAIの高品質なMarkdownファイル翻訳を利用する

前に SCI 文献の PDF を Markdown 形式に変換するツールを書きましたが、今度はそのツールを補完するために作成されたもので、変換が完了したらすぐに文献を中国語に翻訳できます。

まず依存関係をインストールします。

pip install openai

業務コードは以下の通りです:

import openai
import json
import logging
from concurrent.futures import ThreadPoolExecutor, as_completed

# ログ記録の設定
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class MarkdownTranslator:
    def __init__(self, config_file):
        self.config = self.load_config(config_file)
        openai.api_key = self.config.get('OPENAI_API_KEY')
        openai.base_url = self.config.get('OPENAI_API_BASE')
        openai.default_headers = {"x-foo": "true"}

    # 設定ファイルからOpenAI APIキーとカスタムサーバーアドレスを取得
    def load_config(self, config_file):
        try:
            with open(config_file, 'r', encoding='utf-8') as file:
                config = json.load(file)
                return config
        except Exception as e:
            logging.error(f"設定ファイル {config_file} の読み込みエラー: {e}")
            raise

    # Markdownファイルを読み込む
    def read_markdown(self, file_path):
        try:
            with open(file_path, 'r', encoding='utf-8') as file:
                return file.read()
        except Exception as e:
            logging.error(f"ファイル {file_path} の読み込みエラー: {e}")
            raise

    # 翻訳された内容を新しいMarkdownファイルに書き込む
    def write_markdown(self, file_path, content):
        try:
            with open(file_path, 'w', encoding='utf-8') as file:
                file.write(content)
        except Exception as e:
            logging.error(f"ファイル {file_path} の書き込みエラー: {e}")
            raise

    # 翻訳関数
    def translate_text(self, text, source_lang='en', target_lang='zh'):
        try:
            response = openai.chat.completions.create(
                model="gpt-4o-mini",
                messages=[
                    {
                        "role": "user",
                        "content": f"以下の{source_lang}のテキストを{target_lang}に翻訳してください:\n{text}"
                    }
                ]
            )
            return response.choices[0].message.content.strip()
        except Exception as e:
            logging.error(f"テキスト翻訳エラー: {e}")
            return text  # 翻訳失敗時に原文を返す

    # Markdown内容を処理する
    def process_markdown_content(self, content, source_lang, target_lang):
        lines = content.split('\n')
        translated_lines = []

        def translate_line(index, line):
            if line.strip():  # 空行を無視
                translated_line = self.translate_text(line, source_lang, target_lang)
                translated_lines.append((index, translated_line))
            else:
                translated_lines.append((index, ''))  # 空行を保持

        with ThreadPoolExecutor(max_workers=10) as executor:
            futures = [executor.submit(translate_line, i, line) for i, line in enumerate(lines)]
            for future in as_completed(futures):
                future.result()  # すべてのスレッドの完了を待つ

        # 元の順序でソート
        translated_lines.sort(key=lambda x: x[0])
        return '\n'.join(line for _, line in translated_lines)

    # ファイルを翻訳する
    def translate_file(self, input_file, output_file, source_lang='en', target_lang='zh'):
        # パラメータを表示
        logging.info(f"{source_lang}から{target_lang}へのファイル翻訳中...")
        logging.info(f"OpenAi_key: {openai.api_key}")
        logging.info(f"OpenAi_base: {openai.base_url}")

        # 元のMarkdownファイルを読み込む
        markdown_content = self.read_markdown(input_file)

        # 内容を処理して翻訳
        translated_content = self.process_markdown_content(markdown_content, source_lang, target_lang)

        # 新しいMarkdownファイルに書き込む
        self.write_markdown(output_file, translated_content)

if __name__ == "__main__":
    # 入力と出力ファイルのパス
    input_file_path = 'input.md'   # 入力のMarkdownファイル
    output_file_path = 'output.md'  # 出力のMarkdownファイル

    # オプションの源言語と目標言語
    source_language = 'en'  # 源言語(デフォルトは英語)
    target_language = 'zh'  # 目標言語(デフォルトは中国語)

    translator = MarkdownTranslator('config.json')
    translator.translate_file(input_file_path, output_file_path, source_language, target_language)

config.json ファイルの内容は以下の通りです:

{
    "OPENAI_API_KEY": "your_openai_api_key",
    "OPENAI_API_BASE": "https://api.openai.com" # OpenAI API形式に適合するカスタムサーバーアドレスを使用できます
}

このツールの使い方も非常に簡単で、入力の Markdown ファイルのパスと出力の Markdown ファイルのパス、さらにオプションの源言語と目標言語を指定するだけで、Markdown ファイル内の英語の内容を中国語に翻訳できます。

読み込み中...
文章は、創作者によって署名され、ブロックチェーンに安全に保存されています。