feat: PR#9 - EQ-Bench3 日本語化スクリプト
#9
by YUGOROU - opened
- eqbench-ja/serve_translate.sh +51 -0
- eqbench-ja/setup_translate.sh +65 -0
- eqbench-ja/translate_eqbench.py +479 -0
eqbench-ja/serve_translate.sh
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# =============================================================================
|
| 3 |
+
# serve_translate.sh — EQ-Bench 日本語化用 vLLM サーバー起動スクリプト
|
| 4 |
+
# ベースモデル: Qwen/Qwen3.5-9B(日英翻訳品質が高い)
|
| 5 |
+
# setup.sh からフォーク。翻訳タスク向けに最適化(長文対応・高精度設定)
|
| 6 |
+
# =============================================================================
|
| 7 |
+
# 使用方法:
|
| 8 |
+
# chmod +x serve_translate.sh && ./serve_translate.sh
|
| 9 |
+
#
|
| 10 |
+
# 環境変数で挙動を上書き可能:
|
| 11 |
+
# TRANSLATE_MODEL=Qwen/Qwen3.5-9B ./serve_translate.sh
|
| 12 |
+
# =============================================================================
|
| 13 |
+
|
| 14 |
+
set -euo pipefail
|
| 15 |
+
|
| 16 |
+
MODEL="${TRANSLATE_MODEL:-Qwen/Qwen3.5-9B}"
|
| 17 |
+
PORT="${VLLM_PORT:-8000}"
|
| 18 |
+
HOST="${VLLM_HOST:-0.0.0.0}"
|
| 19 |
+
GPU_UTIL="${VLLM_GPU_UTIL:-0.88}"
|
| 20 |
+
MAX_MODEL_LEN="${VLLM_MAX_MODEL_LEN:-8192}"
|
| 21 |
+
TENSOR_PARALLEL="${VLLM_TENSOR_PARALLEL:-1}"
|
| 22 |
+
DTYPE="${VLLM_DTYPE:-auto}"
|
| 23 |
+
MAX_NUM_SEQS="${VLLM_MAX_NUM_SEQS:-32}"
|
| 24 |
+
|
| 25 |
+
echo "=== vLLM 翻訳サーバー起動 ==="
|
| 26 |
+
echo " モデル : ${MODEL}"
|
| 27 |
+
echo " ポート : ${PORT}"
|
| 28 |
+
echo " GPU 使用率 : ${GPU_UTIL}"
|
| 29 |
+
echo " 最大コンテキスト: ${MAX_MODEL_LEN}"
|
| 30 |
+
echo " 並列度 : ${TENSOR_PARALLEL}"
|
| 31 |
+
echo ""
|
| 32 |
+
|
| 33 |
+
python -c "import vllm; print(f' vLLM バージョン : {vllm.__version__}')" 2>/dev/null || true
|
| 34 |
+
echo ""
|
| 35 |
+
|
| 36 |
+
# Qwen3.5 は Vision encoder を内蔵した VLM(pipeline_tag: image-text-to-text)のため
|
| 37 |
+
# --language-model-only が必須。このフラグなしでは vLLM が vision モードで起動しようとし
|
| 38 |
+
# テキスト専用タスクでエラーまたはパフォーマンス劣化が発生する。
|
| 39 |
+
# 参考: HF model card https://huggingface.co/Qwen/Qwen3.5-9B (image-text-to-text)
|
| 40 |
+
# --enable-prefix-caching: 翻訳プロンプトの共通システムプロンプト部分をキャッシュ
|
| 41 |
+
exec vllm serve "${MODEL}" \
|
| 42 |
+
--host "${HOST}" \
|
| 43 |
+
--port "${PORT}" \
|
| 44 |
+
--dtype "${DTYPE}" \
|
| 45 |
+
--gpu-memory-utilization "${GPU_UTIL}" \
|
| 46 |
+
--max-model-len "${MAX_MODEL_LEN}" \
|
| 47 |
+
--tensor-parallel-size "${TENSOR_PARALLEL}" \
|
| 48 |
+
--max-num-seqs "${MAX_NUM_SEQS}" \
|
| 49 |
+
--language-model-only \
|
| 50 |
+
--enable-prefix-caching \
|
| 51 |
+
--trust-remote-code
|
eqbench-ja/setup_translate.sh
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# =============================================================================
|
| 3 |
+
# setup_translate.sh — EQ-Bench 日本語化環境セットアップ
|
| 4 |
+
# teememo-synth の setup.sh からフォーク。
|
| 5 |
+
# EQ-Bench3 のクローンと翻訳スクリプトのインストールを行う。
|
| 6 |
+
# =============================================================================
|
| 7 |
+
|
| 8 |
+
set -euo pipefail
|
| 9 |
+
|
| 10 |
+
EQBENCH_REPO="https://github.com/EQ-bench/eqbench3.git"
|
| 11 |
+
WORKSPACE="/workspace/eqbench-ja"
|
| 12 |
+
SCRIPTS_REPO="${HF_SCRIPTS_REPO:-https://huggingface.co/datasets/YUGOROU/Test-2/resolve/main/eqbench-ja}"
|
| 13 |
+
|
| 14 |
+
echo "[setup] =============================="
|
| 15 |
+
echo "[setup] EQ-Bench 日本語化セットアップ"
|
| 16 |
+
echo "[setup] =============================="
|
| 17 |
+
|
| 18 |
+
# ── 依存パッケージ ──────────────────────────────────────────
|
| 19 |
+
echo "[setup] 依存パッケージのインストール..."
|
| 20 |
+
apt-get install -y tmux git curl 2>/dev/null || true
|
| 21 |
+
pip install -U huggingface_hub uv 2>/dev/null || true
|
| 22 |
+
uv pip install --system httpx tqdm 2>/dev/null || true
|
| 23 |
+
|
| 24 |
+
# ── EQ-Bench3 クローン ─────────────────────────────────────
|
| 25 |
+
mkdir -p "${WORKSPACE}"
|
| 26 |
+
if [ -d "${WORKSPACE}/eqbench3" ]; then
|
| 27 |
+
echo "[setup] EQ-Bench3 既存リポジトリを更新中..."
|
| 28 |
+
git -C "${WORKSPACE}/eqbench3" pull --ff-only || true
|
| 29 |
+
else
|
| 30 |
+
echo "[setup] EQ-Bench3 をクローン中..."
|
| 31 |
+
git clone --depth=1 "${EQBENCH_REPO}" "${WORKSPACE}/eqbench3"
|
| 32 |
+
fi
|
| 33 |
+
echo "[setup] EQ-Bench3 クローン完了: ${WORKSPACE}/eqbench3"
|
| 34 |
+
|
| 35 |
+
# ── 翻訳スクリプトのダウンロード ──────────────────────────
|
| 36 |
+
echo "[setup] 翻訳スクリプトをダウンロード中..."
|
| 37 |
+
mkdir -p "${WORKSPACE}"
|
| 38 |
+
|
| 39 |
+
for script in translate_eqbench.py serve_translate.sh; do
|
| 40 |
+
curl -fL -H "Authorization: Bearer ${HF_TOKEN}" \
|
| 41 |
+
"${SCRIPTS_REPO}/${script}" \
|
| 42 |
+
-o "${WORKSPACE}/${script}"
|
| 43 |
+
echo "[setup] ダウンロード完了: ${script}"
|
| 44 |
+
done
|
| 45 |
+
|
| 46 |
+
chmod +x "${WORKSPACE}/serve_translate.sh"
|
| 47 |
+
|
| 48 |
+
# ── 出力ディレクトリ ───────────────────────────────────────
|
| 49 |
+
mkdir -p "${WORKSPACE}/output"
|
| 50 |
+
|
| 51 |
+
echo "[setup] セットアップ完了"
|
| 52 |
+
echo "[setup] 作業ディレクトリ: ${WORKSPACE}"
|
| 53 |
+
echo "[setup] serve_translate.sh に実行権限を付与済み"
|
| 54 |
+
echo ""
|
| 55 |
+
echo "[setup] 起動手順:"
|
| 56 |
+
echo " # 1. tmuxセッション作成"
|
| 57 |
+
echo " tmux new-session -d -s eq_tmux"
|
| 58 |
+
echo " tmux new-window -t eq_tmux -n serve"
|
| 59 |
+
echo " tmux send-keys -t eq_tmux:serve 'cd ${WORKSPACE} && ./serve_translate.sh' Enter"
|
| 60 |
+
echo ""
|
| 61 |
+
echo " # 2. vLLM起動確認後、翻訳実行"
|
| 62 |
+
echo " cd ${WORKSPACE}"
|
| 63 |
+
echo " export HF_TOKEN='hf_xxxx'"
|
| 64 |
+
echo " export HF_USERNAME='YUGOROU'"
|
| 65 |
+
echo " python translate_eqbench.py"
|
eqbench-ja/translate_eqbench.py
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
translate_eqbench.py — EQ-Bench3 日本語化スクリプト
|
| 3 |
+
|
| 4 |
+
フロー:
|
| 5 |
+
1. EQ-Bench3 の scenario_prompts.txt と scenario_notes.txt を読み込む
|
| 6 |
+
2. vLLM(Qwen3.5-9B)経由で各シナリオを日本語に翻訳
|
| 7 |
+
3. 翻訳結果を保存(チェックポイント対応・再開可能)
|
| 8 |
+
4. 完成した日本語版ファイルを output/ に書き出し
|
| 9 |
+
5. HF Hub にアップロード
|
| 10 |
+
|
| 11 |
+
実行例:
|
| 12 |
+
python translate_eqbench.py
|
| 13 |
+
python translate_eqbench.py --dry-run # 最初の2シナリオのみ
|
| 14 |
+
python translate_eqbench.py --target-file scenario_notes.txt # ノートのみ
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import asyncio
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import sys
|
| 24 |
+
import time
|
| 25 |
+
import traceback
|
| 26 |
+
from datetime import datetime, timezone
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
import httpx
|
| 30 |
+
from tqdm import tqdm
|
| 31 |
+
|
| 32 |
+
# ── 設定 ──────────────────────────────────────────────────────
|
| 33 |
+
VLLM_BASE_URL: str = os.environ.get("VLLM_BASE_URL", "http://localhost:8000/v1")
|
| 34 |
+
TRANSLATE_MODEL: str = os.environ.get("TRANSLATE_MODEL", "Qwen/Qwen3.5-9B")
|
| 35 |
+
HF_TOKEN: str = os.environ.get("HF_TOKEN", "")
|
| 36 |
+
HF_USERNAME: str = os.environ.get("HF_USERNAME", "YUGOROU")
|
| 37 |
+
HF_REPO: str = os.environ.get("HF_REPO", f"{HF_USERNAME}/teememo-eq-bench-ja")
|
| 38 |
+
|
| 39 |
+
EQBENCH_DIR: Path = Path(os.environ.get("EQBENCH_DIR", "/workspace/eqbench-ja/eqbench3"))
|
| 40 |
+
OUTPUT_DIR: Path = Path(os.environ.get("OUTPUT_DIR", "/workspace/eqbench-ja/output"))
|
| 41 |
+
CHECKPOINT_FILE: Path = Path(os.environ.get("CHECKPOINT_FILE", "/workspace/eqbench-ja/output/.checkpoint_translate.json"))
|
| 42 |
+
|
| 43 |
+
MAX_CONCURRENT: int = int(os.environ.get("MAX_CONCURRENT", "4"))
|
| 44 |
+
MAX_RETRIES: int = int(os.environ.get("MAX_RETRIES", "3"))
|
| 45 |
+
REQUEST_TIMEOUT: float = float(os.environ.get("REQUEST_TIMEOUT", "180.0"))
|
| 46 |
+
|
| 47 |
+
# ── 翻訳システムプロンプト ────────────────────────────────────
|
| 48 |
+
TRANSLATE_SYSTEM = """You are a professional translator specializing in Japanese localization of psychological and emotional intelligence assessment materials.
|
| 49 |
+
|
| 50 |
+
Your task is to translate English text into natural, fluent Japanese while:
|
| 51 |
+
1. Preserving the original meaning, nuance, and emotional tone precisely
|
| 52 |
+
2. Maintaining all formatting markers (######## , ####### , etc.) exactly as-is
|
| 53 |
+
3. Keeping scenario numbers, category names, and structural markers unchanged
|
| 54 |
+
4. Using natural conversational Japanese appropriate for the social context described
|
| 55 |
+
5. Preserving any special instructions in brackets [like this] translated into Japanese
|
| 56 |
+
6. For role-play scenarios involving interpersonal conflict, use natural Japanese speech patterns including appropriate keigo or casual speech as the context demands
|
| 57 |
+
7. Translating all proper nouns contextually (names can be kept or given Japanese equivalents)
|
| 58 |
+
|
| 59 |
+
Output ONLY the translated text with no explanations or commentary."""
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# ── vLLM クライアント ─────────────────────────────────────────
|
| 63 |
+
|
| 64 |
+
class VLLMClient:
|
| 65 |
+
def __init__(self) -> None:
|
| 66 |
+
self._client = httpx.AsyncClient(
|
| 67 |
+
timeout=httpx.Timeout(REQUEST_TIMEOUT),
|
| 68 |
+
)
|
| 69 |
+
self._semaphore = asyncio.Semaphore(MAX_CONCURRENT)
|
| 70 |
+
|
| 71 |
+
async def close(self) -> None:
|
| 72 |
+
await self._client.aclose()
|
| 73 |
+
|
| 74 |
+
async def __aenter__(self) -> "VLLMClient":
|
| 75 |
+
return self
|
| 76 |
+
|
| 77 |
+
async def __aexit__(self, *_) -> None:
|
| 78 |
+
await self.close()
|
| 79 |
+
|
| 80 |
+
async def wait_for_server(self, max_wait: int = 300, interval: int = 5) -> None:
|
| 81 |
+
print(f"[client] vLLM サーバーの起動を待機中 (最大 {max_wait}s)...")
|
| 82 |
+
start = time.time()
|
| 83 |
+
while time.time() - start < max_wait:
|
| 84 |
+
try:
|
| 85 |
+
response = await self._client.get(f"{VLLM_BASE_URL}/models")
|
| 86 |
+
if response.status_code == 200:
|
| 87 |
+
print("[client] vLLM サーバーが起動しました。")
|
| 88 |
+
return
|
| 89 |
+
except Exception:
|
| 90 |
+
pass
|
| 91 |
+
await asyncio.sleep(interval)
|
| 92 |
+
raise TimeoutError(f"[client] vLLM サーバーが {max_wait}s 以内に起動しませんでした。")
|
| 93 |
+
|
| 94 |
+
async def translate(self, text: str) -> str:
|
| 95 |
+
"""テキストを日本語に翻訳する。"""
|
| 96 |
+
payload = {
|
| 97 |
+
"model": TRANSLATE_MODEL,
|
| 98 |
+
"messages": [
|
| 99 |
+
{"role": "system", "content": TRANSLATE_SYSTEM},
|
| 100 |
+
{"role": "user", "content": f"Translate the following to Japanese:\n\n{text}"},
|
| 101 |
+
],
|
| 102 |
+
"temperature": 0.1, # 翻訳は低温で安定させる
|
| 103 |
+
"top_p": 0.9,
|
| 104 |
+
"max_tokens": 4096,
|
| 105 |
+
"chat_template_kwargs": {"enable_thinking": False},
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
last_exc = None
|
| 109 |
+
for attempt in range(MAX_RETRIES):
|
| 110 |
+
try:
|
| 111 |
+
async with self._semaphore:
|
| 112 |
+
response = await self._client.post(
|
| 113 |
+
f"{VLLM_BASE_URL}/chat/completions",
|
| 114 |
+
json=payload,
|
| 115 |
+
headers={"Content-Type": "application/json"},
|
| 116 |
+
)
|
| 117 |
+
response.raise_for_status()
|
| 118 |
+
result = response.json()
|
| 119 |
+
return result["choices"][0]["message"].get("content") or ""
|
| 120 |
+
except Exception as exc:
|
| 121 |
+
last_exc = exc
|
| 122 |
+
wait = 2 ** attempt
|
| 123 |
+
print(f"[client] リトライ {attempt+1}/{MAX_RETRIES} ({type(exc).__name__}) — {wait}s 待機")
|
| 124 |
+
await asyncio.sleep(wait)
|
| 125 |
+
raise RuntimeError(f"[client] 翻訳失敗: {last_exc}")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# ── scenario_prompts.txt パーサー ─────────────────────────────
|
| 129 |
+
|
| 130 |
+
def parse_scenario_prompts(filepath: Path) -> list[dict]:
|
| 131 |
+
"""
|
| 132 |
+
scenario_prompts.txt を解析してシナリオリストを返す。
|
| 133 |
+
|
| 134 |
+
Returns:
|
| 135 |
+
[{"id": 1, "header": "...", "prompts": {"Prompt1": "...", "Prompt2": "..."}}, ...]
|
| 136 |
+
"""
|
| 137 |
+
scenarios = []
|
| 138 |
+
current: dict | None = None
|
| 139 |
+
current_prompt_key: str | None = None
|
| 140 |
+
current_prompt_lines: list[str] = []
|
| 141 |
+
|
| 142 |
+
def _flush_prompt():
|
| 143 |
+
if current and current_prompt_key and current_prompt_lines:
|
| 144 |
+
current["prompts"][current_prompt_key] = "\n".join(current_prompt_lines).strip()
|
| 145 |
+
current_prompt_lines.clear()
|
| 146 |
+
|
| 147 |
+
with open(filepath, encoding="utf-8") as f:
|
| 148 |
+
for line in f:
|
| 149 |
+
line = line.rstrip("\n")
|
| 150 |
+
|
| 151 |
+
# シナリオヘッダー: ######## 1 | Work Dilemma | ...
|
| 152 |
+
if line.startswith("######## "):
|
| 153 |
+
_flush_prompt()
|
| 154 |
+
if current:
|
| 155 |
+
scenarios.append(current)
|
| 156 |
+
parts = line.split("|")
|
| 157 |
+
scenario_id = parts[0].replace("#", "").strip()
|
| 158 |
+
current = {
|
| 159 |
+
"id": int(scenario_id) if scenario_id.isdigit() else scenario_id,
|
| 160 |
+
"header": line,
|
| 161 |
+
"prompts": {},
|
| 162 |
+
}
|
| 163 |
+
current_prompt_key = None
|
| 164 |
+
current_prompt_lines = []
|
| 165 |
+
|
| 166 |
+
# プロンプトキー: ####### Prompt1
|
| 167 |
+
elif line.startswith("####### "):
|
| 168 |
+
_flush_prompt()
|
| 169 |
+
current_prompt_key = line.replace("#", "").strip()
|
| 170 |
+
current_prompt_lines = []
|
| 171 |
+
|
| 172 |
+
# プロンプト本文
|
| 173 |
+
else:
|
| 174 |
+
if current_prompt_key is not None:
|
| 175 |
+
current_prompt_lines.append(line)
|
| 176 |
+
|
| 177 |
+
_flush_prompt()
|
| 178 |
+
if current:
|
| 179 |
+
scenarios.append(current)
|
| 180 |
+
|
| 181 |
+
return scenarios
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def parse_scenario_notes(filepath: Path) -> dict[str, str]:
|
| 185 |
+
"""
|
| 186 |
+
scenario_notes.txt を解析する。
|
| 187 |
+
# 1\n<note>\n# 2\n<note> の形式。
|
| 188 |
+
|
| 189 |
+
Returns:
|
| 190 |
+
{"1": "<note>", "2": "<note>", ...}
|
| 191 |
+
"""
|
| 192 |
+
notes = {}
|
| 193 |
+
current_key: str | None = None
|
| 194 |
+
current_lines: list[str] = []
|
| 195 |
+
|
| 196 |
+
def _flush():
|
| 197 |
+
if current_key and current_lines:
|
| 198 |
+
notes[current_key] = "\n".join(current_lines).strip()
|
| 199 |
+
current_lines.clear()
|
| 200 |
+
|
| 201 |
+
with open(filepath, encoding="utf-8") as f:
|
| 202 |
+
for line in f:
|
| 203 |
+
line = line.rstrip("\n")
|
| 204 |
+
if line.startswith("# ") and line[2:].strip().isdigit():
|
| 205 |
+
_flush()
|
| 206 |
+
current_key = line[2:].strip()
|
| 207 |
+
current_lines = []
|
| 208 |
+
else:
|
| 209 |
+
if current_key is not None:
|
| 210 |
+
current_lines.append(line)
|
| 211 |
+
|
| 212 |
+
_flush()
|
| 213 |
+
return notes
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
# ── チェックポイント ──────────────────────────────────────────
|
| 217 |
+
|
| 218 |
+
def load_checkpoint() -> dict:
|
| 219 |
+
if CHECKPOINT_FILE.exists():
|
| 220 |
+
try:
|
| 221 |
+
return json.loads(CHECKPOINT_FILE.read_text(encoding="utf-8"))
|
| 222 |
+
except Exception:
|
| 223 |
+
pass
|
| 224 |
+
return {"translated_scenarios": {}, "translated_notes": {}}
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def save_checkpoint(state: dict) -> None:
|
| 228 |
+
CHECKPOINT_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 229 |
+
CHECKPOINT_FILE.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
# ── 出力ファイル生成 ───────────────────────────────────────────
|
| 233 |
+
|
| 234 |
+
def build_output_prompts(
|
| 235 |
+
scenarios: list[dict],
|
| 236 |
+
translated: dict[str, dict],
|
| 237 |
+
) -> str:
|
| 238 |
+
"""翻訳済みシナリオを scenario_prompts.txt 形式に再構築する。"""
|
| 239 |
+
lines = []
|
| 240 |
+
for scenario in scenarios:
|
| 241 |
+
sid = str(scenario["id"])
|
| 242 |
+
if sid in translated:
|
| 243 |
+
trans = translated[sid]
|
| 244 |
+
lines.append(trans.get("header", scenario["header"]))
|
| 245 |
+
for prompt_key, prompt_text in scenario["prompts"].items():
|
| 246 |
+
lines.append(f"####### {prompt_key}")
|
| 247 |
+
translated_text = trans.get("prompts", {}).get(prompt_key, prompt_text)
|
| 248 |
+
lines.append(translated_text)
|
| 249 |
+
lines.append("")
|
| 250 |
+
else:
|
| 251 |
+
# 未翻訳はオリジナルをそのまま
|
| 252 |
+
lines.append(scenario["header"])
|
| 253 |
+
for prompt_key, prompt_text in scenario["prompts"].items():
|
| 254 |
+
lines.append(f"####### {prompt_key}")
|
| 255 |
+
lines.append(prompt_text)
|
| 256 |
+
lines.append("")
|
| 257 |
+
return "\n".join(lines)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def build_output_notes(
|
| 261 |
+
original_notes: dict[str, str],
|
| 262 |
+
translated_notes: dict[str, str],
|
| 263 |
+
) -> str:
|
| 264 |
+
"""翻訳済みノートを scenario_notes.txt 形式に再構築する。"""
|
| 265 |
+
lines = []
|
| 266 |
+
for key, note in original_notes.items():
|
| 267 |
+
lines.append(f"# {key}")
|
| 268 |
+
lines.append(translated_notes.get(key, note))
|
| 269 |
+
lines.append("")
|
| 270 |
+
return "\n".join(lines)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
# ── HF アップロード ───────────────────────────────────────────
|
| 274 |
+
|
| 275 |
+
async def upload_to_hf(output_dir: Path) -> None:
|
| 276 |
+
if not HF_TOKEN:
|
| 277 |
+
print("[hub] HF_TOKEN 未設定のためアップロードをスキップ")
|
| 278 |
+
return
|
| 279 |
+
try:
|
| 280 |
+
from huggingface_hub import HfApi
|
| 281 |
+
api = HfApi(token=HF_TOKEN)
|
| 282 |
+
api.create_repo(repo_id=HF_REPO, repo_type="dataset", private=True, exist_ok=True)
|
| 283 |
+
for f in output_dir.glob("*.txt"):
|
| 284 |
+
api.upload_file(
|
| 285 |
+
path_or_fileobj=str(f),
|
| 286 |
+
path_in_repo=f"data/{f.name}",
|
| 287 |
+
repo_id=HF_REPO,
|
| 288 |
+
repo_type="dataset",
|
| 289 |
+
commit_message=f"update: {f.name}",
|
| 290 |
+
)
|
| 291 |
+
print(f"[hub] アップロード完了: {f.name}")
|
| 292 |
+
print(f"[hub] ✅ https://huggingface.co/datasets/{HF_REPO}")
|
| 293 |
+
except Exception as e:
|
| 294 |
+
print(f"[hub] アップロードエラー: {e}")
|
| 295 |
+
print(traceback.format_exc())
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
# ── メイン処理 ────────────────────────────────────────────────
|
| 299 |
+
|
| 300 |
+
async def translate_scenarios(
|
| 301 |
+
client: VLLMClient,
|
| 302 |
+
scenarios: list[dict],
|
| 303 |
+
state: dict,
|
| 304 |
+
dry_run: bool,
|
| 305 |
+
lock: asyncio.Lock,
|
| 306 |
+
) -> dict:
|
| 307 |
+
"""全シナリオを asyncio.gather で並列翻訳する。"""
|
| 308 |
+
translated = state.get("translated_scenarios", {})
|
| 309 |
+
target_scenarios = scenarios[:2] if dry_run else scenarios
|
| 310 |
+
pending = [s for s in target_scenarios if str(s["id"]) not in translated]
|
| 311 |
+
|
| 312 |
+
print(f"[translate] シナリオ翻訳開始: {len(target_scenarios)}件 (未翻訳: {len(pending)}件)")
|
| 313 |
+
|
| 314 |
+
async def _translate_one(scenario: dict) -> None:
|
| 315 |
+
sid = str(scenario["id"])
|
| 316 |
+
trans_scenario: dict = {"header": scenario["header"], "prompts": {}}
|
| 317 |
+
|
| 318 |
+
for prompt_key, prompt_text in scenario["prompts"].items():
|
| 319 |
+
if not prompt_text.strip():
|
| 320 |
+
trans_scenario["prompts"][prompt_key] = prompt_text
|
| 321 |
+
continue
|
| 322 |
+
try:
|
| 323 |
+
translated_text = await client.translate(prompt_text)
|
| 324 |
+
trans_scenario["prompts"][prompt_key] = translated_text
|
| 325 |
+
except Exception as e:
|
| 326 |
+
print(f"\n[translate] WARNING: シナリオ{sid}/{prompt_key} 翻訳失敗: {e}")
|
| 327 |
+
trans_scenario["prompts"][prompt_key] = prompt_text
|
| 328 |
+
|
| 329 |
+
async with lock:
|
| 330 |
+
translated[sid] = trans_scenario
|
| 331 |
+
state["translated_scenarios"] = translated
|
| 332 |
+
save_checkpoint(state)
|
| 333 |
+
print(f"[translate] シナリオ {sid} 完了")
|
| 334 |
+
|
| 335 |
+
await asyncio.gather(*[_translate_one(s) for s in pending])
|
| 336 |
+
|
| 337 |
+
print(f"[translate] シナリオ翻訳完了: {len(translated)}件")
|
| 338 |
+
return translated
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
async def translate_notes(
|
| 342 |
+
client: VLLMClient,
|
| 343 |
+
notes: dict[str, str],
|
| 344 |
+
state: dict,
|
| 345 |
+
dry_run: bool,
|
| 346 |
+
lock: asyncio.Lock,
|
| 347 |
+
) -> dict:
|
| 348 |
+
"""採点ノートを asyncio.gather で並列翻訳する。"""
|
| 349 |
+
translated_notes = state.get("translated_notes", {})
|
| 350 |
+
target_notes = dict(list(notes.items())[:2]) if dry_run else notes
|
| 351 |
+
pending = {k: v for k, v in target_notes.items() if k not in translated_notes}
|
| 352 |
+
|
| 353 |
+
print(f"[translate] ノート翻訳開始: {len(target_notes)}件 (未翻訳: {len(pending)}件)")
|
| 354 |
+
|
| 355 |
+
async def _translate_one(key: str, note: str) -> None:
|
| 356 |
+
try:
|
| 357 |
+
translated_text = await client.translate(note)
|
| 358 |
+
except Exception as e:
|
| 359 |
+
print(f"\n[translate] WARNING: ノート#{key} 翻訳失敗: {e}")
|
| 360 |
+
translated_text = note
|
| 361 |
+
async with lock:
|
| 362 |
+
translated_notes[key] = translated_text
|
| 363 |
+
state["translated_notes"] = translated_notes
|
| 364 |
+
save_checkpoint(state)
|
| 365 |
+
print(f"[translate] ノート #{key} 完了")
|
| 366 |
+
|
| 367 |
+
await asyncio.gather(*[_translate_one(k, v) for k, v in pending.items()])
|
| 368 |
+
|
| 369 |
+
print(f"[translate] ノート翻訳完了: {len(translated_notes)}件")
|
| 370 |
+
return translated_notes
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
async def main(dry_run: bool, target_file: str | None) -> None:
|
| 374 |
+
start_time = datetime.now(timezone.utc)
|
| 375 |
+
print(f"=== EQ-Bench3 日本語化開始 [{start_time.isoformat()}] ===")
|
| 376 |
+
print(f" EQ-Bench3 ディレクトリ: {EQBENCH_DIR}")
|
| 377 |
+
print(f" 出力ディレクトリ : {OUTPUT_DIR}")
|
| 378 |
+
print(f" 翻訳モデル : {TRANSLATE_MODEL}")
|
| 379 |
+
print(f" dry-run : {dry_run}")
|
| 380 |
+
print()
|
| 381 |
+
|
| 382 |
+
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
|
| 383 |
+
|
| 384 |
+
# ── データ読み込み ──────────────────────────────────────────
|
| 385 |
+
prompts_file = EQBENCH_DIR / "data" / "scenario_prompts.txt"
|
| 386 |
+
notes_file = EQBENCH_DIR / "data" / "scenario_notes.txt"
|
| 387 |
+
|
| 388 |
+
if not prompts_file.exists():
|
| 389 |
+
print(f"[ERROR] scenario_prompts.txt が見つかりません: {prompts_file}")
|
| 390 |
+
print(" 先に setup_translate.sh を実行してください。")
|
| 391 |
+
sys.exit(1)
|
| 392 |
+
|
| 393 |
+
print(f"[data] scenario_prompts.txt 読み込み中...")
|
| 394 |
+
scenarios = parse_scenario_prompts(prompts_file)
|
| 395 |
+
print(f"[data] シナリオ数: {len(scenarios)}")
|
| 396 |
+
|
| 397 |
+
print(f"[data] scenario_notes.txt 読み込み中...")
|
| 398 |
+
notes = parse_scenario_notes(notes_file)
|
| 399 |
+
print(f"[data] ノート数: {len(notes)}")
|
| 400 |
+
|
| 401 |
+
# ── チェックポイント読み込み ──────────────────────────────
|
| 402 |
+
state = load_checkpoint()
|
| 403 |
+
done_s = len(state.get("translated_scenarios", {}))
|
| 404 |
+
done_n = len(state.get("translated_notes", {}))
|
| 405 |
+
if done_s > 0 or done_n > 0:
|
| 406 |
+
print(f"[checkpoint] 再開: シナリオ{done_s}件・ノート{done_n}件 処理済み")
|
| 407 |
+
|
| 408 |
+
# ── vLLM 接続 ─────────────────────────────────────────────
|
| 409 |
+
async with VLLMClient() as client:
|
| 410 |
+
await client.wait_for_server()
|
| 411 |
+
|
| 412 |
+
lock = asyncio.Lock() # チェックポイント書き込みの競合を防ぐ
|
| 413 |
+
|
| 414 |
+
# ── 翻訳実行 ────────────────────────────────────────────
|
| 415 |
+
do_scenarios = target_file is None or target_file == "scenario_prompts.txt"
|
| 416 |
+
do_notes = target_file is None or target_file == "scenario_notes.txt"
|
| 417 |
+
|
| 418 |
+
if do_scenarios:
|
| 419 |
+
translated_scenarios = await translate_scenarios(client, scenarios, state, dry_run, lock)
|
| 420 |
+
else:
|
| 421 |
+
translated_scenarios = state.get("translated_scenarios", {})
|
| 422 |
+
|
| 423 |
+
if do_notes:
|
| 424 |
+
translated_notes = await translate_notes(client, notes, state, dry_run, lock)
|
| 425 |
+
else:
|
| 426 |
+
translated_notes = state.get("translated_notes", {})
|
| 427 |
+
|
| 428 |
+
# ── 出力ファイル生成 ─────────────────────────────────────
|
| 429 |
+
print("[output] 出力ファイル生成中...")
|
| 430 |
+
|
| 431 |
+
prompts_out = OUTPUT_DIR / "scenario_prompts_ja.txt"
|
| 432 |
+
prompts_out.write_text(
|
| 433 |
+
build_output_prompts(scenarios, translated_scenarios),
|
| 434 |
+
encoding="utf-8",
|
| 435 |
+
)
|
| 436 |
+
print(f"[output] ✅ {prompts_out}")
|
| 437 |
+
|
| 438 |
+
notes_out = OUTPUT_DIR / "scenario_notes_ja.txt"
|
| 439 |
+
notes_out.write_text(
|
| 440 |
+
build_output_notes(notes, translated_notes),
|
| 441 |
+
encoding="utf-8",
|
| 442 |
+
)
|
| 443 |
+
print(f"[output] ✅ {notes_out}")
|
| 444 |
+
|
| 445 |
+
# オリジナルもコピーしておく(比較用)
|
| 446 |
+
import shutil
|
| 447 |
+
shutil.copy(prompts_file, OUTPUT_DIR / "scenario_prompts_en.txt")
|
| 448 |
+
shutil.copy(notes_file, OUTPUT_DIR / "scenario_notes_en.txt")
|
| 449 |
+
|
| 450 |
+
# ── HF アップロード ───────────────────────────────────────
|
| 451 |
+
if not dry_run:
|
| 452 |
+
await upload_to_hf(OUTPUT_DIR)
|
| 453 |
+
|
| 454 |
+
# チェックポイント削除
|
| 455 |
+
if CHECKPOINT_FILE.exists() and not dry_run:
|
| 456 |
+
CHECKPOINT_FILE.unlink()
|
| 457 |
+
|
| 458 |
+
elapsed = (datetime.now(timezone.utc) - start_time).total_seconds()
|
| 459 |
+
print()
|
| 460 |
+
print(f"=== 翻訳完了 (所要時間: {elapsed/60:.1f}分) ===")
|
| 461 |
+
print(f" 出力: {OUTPUT_DIR}/scenario_prompts_ja.txt")
|
| 462 |
+
print(f" 出力: {OUTPUT_DIR}/scenario_notes_ja.txt")
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
if __name__ == "__main__":
|
| 466 |
+
parser = argparse.ArgumentParser(description="EQ-Bench3 日本語化スクリプト")
|
| 467 |
+
parser.add_argument("--dry-run", action="store_true", help="最初の2シナリオのみ処理して動作確認")
|
| 468 |
+
parser.add_argument(
|
| 469 |
+
"--target-file",
|
| 470 |
+
choices=["scenario_prompts.txt", "scenario_notes.txt"],
|
| 471 |
+
default=None,
|
| 472 |
+
help="翻訳対象ファイルを指定(デフォルト: 両方)",
|
| 473 |
+
)
|
| 474 |
+
args = parser.parse_args()
|
| 475 |
+
|
| 476 |
+
if not os.environ.get("HF_TOKEN"):
|
| 477 |
+
print("[WARNING] HF_TOKEN が未設定です。HF アップロードはスキップされます。")
|
| 478 |
+
|
| 479 |
+
asyncio.run(main(dry_run=args.dry_run, target_file=args.target_file))
|