YUGOROU commited on
Commit
17c28e5
·
verified ·
1 Parent(s): 8907db3

Create 2nd version of eqbench-jaranslate_eqbench.py

Browse files
Files changed (1) hide show
  1. eqbench-ja/translate_eqbench_v2.py +693 -0
eqbench-ja/translate_eqbench_v2.py ADDED
@@ -0,0 +1,693 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ translate_eqbench_v2.py — EQ-Bench3 日本語化スクリプト (Version 2)
3
+
4
+ フロー:
5
+ 1. EQ-Bench3 の全データファイル (12ファイル) を読み込む
6
+ 2. vLLM(Qwen3.5-9B)経由で各ファイルを日本語に翻訳
7
+ 3. 翻訳結果を保存(チェックポイント対応・再開可能)
8
+ 4. 完成した日本語版ファイルを output/ に書き出し
9
+ 5. HF Hub にアップロード
10
+
11
+ 実行例:
12
+ python translate_eqbench_v2.py
13
+ python translate_eqbench_v2.py --dry-run # 最初の2シナリオのみ
14
+ python translate_eqbench_v2.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_v2.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
+ # ファイルタイプ:
49
+ # "scenario_split" : シナリオIDで分割 (######## 1 | ...)
50
+ # "note_split" : ノート形式で分割 (# 1\n<note>)
51
+ # "single" : 単一ファイル(全体を翻訳)
52
+ # "analysis_split" : 分析用シナリオ分割形式
53
+
54
+ TARGET_FILES: dict[str, dict] = {
55
+ # シナリオプロンプト(シナリオID分割)
56
+ "scenario_prompts.txt": {
57
+ "type": "scenario_split",
58
+ "description": "メインシナリオプロンプト",
59
+ },
60
+ # シナリオノート(ノート形式分割)
61
+ "scenario_notes.txt": {
62
+ "type": "note_split",
63
+ "description": "シナリオ採点ノート",
64
+ },
65
+ # メッセージ作成用マスタープロンプト
66
+ "scenario_master_prompt_message_drafting.txt": {
67
+ "type": "single",
68
+ "description": "メッセージ作成用マスタープロンプト",
69
+ },
70
+ # 分析用マスタープロンプト
71
+ "scenario_master_prompt_analysis.txt": {
72
+ "type": "single",
73
+ "description": "分析用マスタープロンプト",
74
+ },
75
+ # 汎用マスタープロンプト
76
+ "scenario_master_prompt.txt": {
77
+ "type": "single",
78
+ "description": "汎用マスタープロンプト",
79
+ },
80
+ # ルーブリック採点プロンプト(分析用)
81
+ "rubric_scoring_prompt_analysis.txt": {
82
+ "type": "single",
83
+ "description": "分析用ルーブリック採点プロンプト",
84
+ },
85
+ # ルーブリック採点プロンプト
86
+ "rubric_scoring_prompt.txt": {
87
+ "type": "single",
88
+ "description": "ルーブリック採点プロンプト",
89
+ },
90
+ # ルーブリック採点基準(分析用)
91
+ "rubric_scoring_criteria_analysis.txt": {
92
+ "type": "single",
93
+ "description": "分析用ルーブリック採点基準",
94
+ },
95
+ # ルーブリック採点基準
96
+ "rubric_scoring_criteria.txt": {
97
+ "type": "single",
98
+ "description": "ルーブリック採点基準",
99
+ },
100
+ # ペアワイズ比較プロンプト(分析用)
101
+ "pairwise_prompt_eqbench3_analysis.txt": {
102
+ "type": "single",
103
+ "description": "分析用ペアワイズ比較プロンプト",
104
+ },
105
+ # ペアワイズ比較プロンプト
106
+ "pairwise_prompt_eqbench3.txt": {
107
+ "type": "single",
108
+ "description": "ペアワイズ比較プロンプト",
109
+ },
110
+ # デブリーフプロンプト
111
+ "debrief_prompt.txt": {
112
+ "type": "single",
113
+ "description": "デブリーフプロンプト",
114
+ },
115
+ }
116
+
117
+ # ── 翻訳システムプロンプト ────────────────────────────────────
118
+ TRANSLATE_SYSTEM = """You are a professional translator specializing in Japanese localization of psychological and emotional intelligence assessment materials.
119
+
120
+ Your task is to translate English text into natural, fluent Japanese while:
121
+ 1. Preserving the original meaning, nuance, and emotional tone precisely
122
+ 2. Maintaining all formatting markers (######## , ####### , {{placeholder}}, etc.) exactly as-is
123
+ 3. Keeping scenario numbers, category names, and structural markers unchanged
124
+ 4. Using natural conversational Japanese appropriate for the social context described
125
+ 5. Preserving any special instructions in brackets [like this] translated into Japanese
126
+ 6. For role-play scenarios involving interpersonal conflict, use natural Japanese speech patterns including appropriate keigo or casual speech as the context demands
127
+ 7. Translating all proper nouns contextually (names can be kept or given Japanese equivalents)
128
+ 8. Keeping JSON keys, variable names, and code-like placeholders unchanged
129
+
130
+ Output ONLY the translated text with no explanations or commentary."""
131
+
132
+
133
+ # ── vLLM クライアント ─────────────────────────────────────────
134
+
135
+ class VLLMClient:
136
+ def __init__(self) -> None:
137
+ self._client = httpx.AsyncClient(
138
+ timeout=httpx.Timeout(REQUEST_TIMEOUT),
139
+ )
140
+ self._semaphore = asyncio.Semaphore(MAX_CONCURRENT)
141
+
142
+ async def close(self) -> None:
143
+ await self._client.aclose()
144
+
145
+ async def __aenter__(self) -> "VLLMClient":
146
+ return self
147
+
148
+ async def __aexit__(self, *_) -> None:
149
+ await self.close()
150
+
151
+ async def wait_for_server(self, max_wait: int = 300, interval: int = 5) -> None:
152
+ print(f"[client] vLLM サーバーの起動を待機中 (最大 {max_wait}s)...")
153
+ start = time.time()
154
+ while time.time() - start < max_wait:
155
+ try:
156
+ response = await self._client.get(f"{VLLM_BASE_URL}/models")
157
+ if response.status_code == 200:
158
+ print("[client] vLLM サーバーが起動しました。")
159
+ return
160
+ except Exception:
161
+ pass
162
+ await asyncio.sleep(interval)
163
+ raise TimeoutError(f"[client] vLLM サーバーが {max_wait}s 以内に起動しませんでした。")
164
+
165
+ async def translate(self, text: str) -> str:
166
+ """テキストを日本語に翻訳する。"""
167
+ payload = {
168
+ "model": TRANSLATE_MODEL,
169
+ "messages": [
170
+ {"role": "system", "content": TRANSLATE_SYSTEM},
171
+ {"role": "user", "content": f"Translate the following to Japanese:\n\n{text}"},
172
+ ],
173
+ "temperature": 0.1, # 翻訳は低温で安定させる
174
+ "top_p": 0.9,
175
+ "max_tokens": 8192, # 長いファイル対応
176
+ "chat_template_kwargs": {"enable_thinking": False},
177
+ }
178
+
179
+ last_exc = None
180
+ for attempt in range(MAX_RETRIES):
181
+ try:
182
+ async with self._semaphore:
183
+ response = await self._client.post(
184
+ f"{VLLM_BASE_URL}/chat/completions",
185
+ json=payload,
186
+ headers={"Content-Type": "application/json"},
187
+ )
188
+ response.raise_for_status()
189
+ result = response.json()
190
+ return result["choices"][0]["message"].get("content") or ""
191
+ except Exception as exc:
192
+ last_exc = exc
193
+ wait = 2 ** attempt
194
+ print(f"[client] リトライ {attempt+1}/{MAX_RETRIES} ({type(exc).__name__}) — {wait}s 待機")
195
+ await asyncio.sleep(wait)
196
+ raise RuntimeError(f"[client] 翻訳失敗: {last_exc}")
197
+
198
+
199
+ # ── パーサー関数群 ─────────────────────────────────────────────
200
+
201
+ def parse_scenario_prompts(filepath: Path) -> list[dict]:
202
+ """
203
+ scenario_prompts.txt を解析してシナリオリストを返す。
204
+
205
+ Returns:
206
+ [{"id": 1, "header": "...", "prompts": {"Prompt1": "...", "Prompt2": "..."}}, ...]
207
+ """
208
+ scenarios = []
209
+ current: dict | None = None
210
+ current_prompt_key: str | None = None
211
+ current_prompt_lines: list[str] = []
212
+
213
+ def _flush_prompt():
214
+ if current and current_prompt_key and current_prompt_lines:
215
+ current["prompts"][current_prompt_key] = "\n".join(current_prompt_lines).strip()
216
+ current_prompt_lines.clear()
217
+
218
+ with open(filepath, encoding="utf-8") as f:
219
+ for line in f:
220
+ line = line.rstrip("\n")
221
+
222
+ # シナリオヘッダー: ######## 1 | Work Dilemma | ...
223
+ if line.startswith("######## "):
224
+ _flush_prompt()
225
+ if current:
226
+ scenarios.append(current)
227
+ parts = line.split("|")
228
+ scenario_id = parts[0].replace("#", "").strip()
229
+ current = {
230
+ "id": int(scenario_id) if scenario_id.isdigit() else scenario_id,
231
+ "header": line,
232
+ "prompts": {},
233
+ }
234
+ current_prompt_key = None
235
+ current_prompt_lines = []
236
+
237
+ # プロンプトキー: ####### Prompt1
238
+ elif line.startswith("####### "):
239
+ _flush_prompt()
240
+ current_prompt_key = line.replace("#", "").strip()
241
+ current_prompt_lines = []
242
+
243
+ # プロンプト本文
244
+ else:
245
+ if current_prompt_key is not None:
246
+ current_prompt_lines.append(line)
247
+
248
+ _flush_prompt()
249
+ if current:
250
+ scenarios.append(current)
251
+
252
+ return scenarios
253
+
254
+
255
+ def parse_scenario_notes(filepath: Path) -> dict[str, str]:
256
+ """
257
+ scenario_notes.txt を解析する。
258
+ # 1\n<note>\n# 2\n<note> の形式。
259
+
260
+ Returns:
261
+ {"1": "<note>", "2": "<note>", ...}
262
+ """
263
+ notes = {}
264
+ current_key: str | None = None
265
+ current_lines: list[str] = []
266
+
267
+ def _flush():
268
+ if current_key and current_lines:
269
+ notes[current_key] = "\n".join(current_lines).strip()
270
+ current_lines.clear()
271
+
272
+ with open(filepath, encoding="utf-8") as f:
273
+ for line in f:
274
+ line = line.rstrip("\n")
275
+ if line.startswith("# ") and line[2:].strip().isdigit():
276
+ _flush()
277
+ current_key = line[2:].strip()
278
+ current_lines = []
279
+ else:
280
+ if current_key is not None:
281
+ current_lines.append(line)
282
+
283
+ _flush()
284
+ return notes
285
+
286
+
287
+ def parse_single_file(filepath: Path) -> str:
288
+ """単一ファイル全体を読み込む。"""
289
+ return filepath.read_text(encoding="utf-8")
290
+
291
+
292
+ # ── ビルダー関数群 ─────────────────────────────────────────────
293
+
294
+ def build_output_prompts(
295
+ scenarios: list[dict],
296
+ translated: dict[str, dict],
297
+ ) -> str:
298
+ """翻訳済みシナリオを scenario_prompts.txt 形式に再構築する。"""
299
+ lines = []
300
+ for scenario in scenarios:
301
+ sid = str(scenario["id"])
302
+ if sid in translated:
303
+ trans = translated[sid]
304
+ lines.append(trans.get("header", scenario["header"]))
305
+ for prompt_key, prompt_text in scenario["prompts"].items():
306
+ lines.append(f"####### {prompt_key}")
307
+ translated_text = trans.get("prompts", {}).get(prompt_key, prompt_text)
308
+ lines.append(translated_text)
309
+ lines.append("")
310
+ else:
311
+ # 未翻訳はオリジナルをそのまま
312
+ lines.append(scenario["header"])
313
+ for prompt_key, prompt_text in scenario["prompts"].items():
314
+ lines.append(f"####### {prompt_key}")
315
+ lines.append(prompt_text)
316
+ lines.append("")
317
+ return "\n".join(lines)
318
+
319
+
320
+ def build_output_notes(
321
+ original_notes: dict[str, str],
322
+ translated_notes: dict[str, str],
323
+ ) -> str:
324
+ """翻訳済みノートを scenario_notes.txt 形式に再構築する。"""
325
+ lines = []
326
+ for key, note in original_notes.items():
327
+ lines.append(f"# {key}")
328
+ lines.append(translated_notes.get(key, note))
329
+ lines.append("")
330
+ return "\n".join(lines)
331
+
332
+
333
+ # ── チェックポイント ──────────────────────────────────────────
334
+
335
+ def load_checkpoint() -> dict:
336
+ """
337
+ チェックポイント構造:
338
+ {
339
+ "files": {
340
+ "scenario_prompts.txt": {
341
+ "translated_scenarios": {...},
342
+ "status": "completed" | "in_progress"
343
+ },
344
+ "scenario_notes.txt": {
345
+ "translated_notes": {...},
346
+ "status": "completed" | "in_progress"
347
+ },
348
+ "single_file_name.txt": {
349
+ "translated": "...",
350
+ "status": "completed" | "in_progress"
351
+ },
352
+ ...
353
+ }
354
+ }
355
+ """
356
+ if CHECKPOINT_FILE.exists():
357
+ try:
358
+ return json.loads(CHECKPOINT_FILE.read_text(encoding="utf-8"))
359
+ except Exception:
360
+ pass
361
+ return {"files": {}}
362
+
363
+
364
+ def save_checkpoint(state: dict) -> None:
365
+ CHECKPOINT_FILE.parent.mkdir(parents=True, exist_ok=True)
366
+ CHECKPOINT_FILE.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
367
+
368
+
369
+ # ── 翻訳処理関数群 ────────────────────────────────────────────
370
+
371
+ async def translate_scenario_file(
372
+ client: VLLMClient,
373
+ filepath: Path,
374
+ file_key: str,
375
+ state: dict,
376
+ dry_run: bool,
377
+ lock: asyncio.Lock,
378
+ ) -> dict:
379
+ """シナリオ分割ファイルを翻訳する。"""
380
+ scenarios = parse_scenario_prompts(filepath)
381
+
382
+ if file_key not in state["files"]:
383
+ state["files"][file_key] = {"translated_scenarios": {}, "status": "in_progress"}
384
+
385
+ file_state = state["files"][file_key]
386
+ translated = file_state.get("translated_scenarios", {})
387
+
388
+ target_scenarios = scenarios[:2] if dry_run else scenarios
389
+ pending = [s for s in target_scenarios if str(s["id"]) not in translated]
390
+
391
+ print(f"[translate] {file_key}: シナリオ翻訳開始: {len(target_scenarios)}件 (未翻訳: {len(pending)}件)")
392
+
393
+ async def _translate_one(scenario: dict) -> None:
394
+ sid = str(scenario["id"])
395
+ trans_scenario: dict = {"header": scenario["header"], "prompts": {}}
396
+
397
+ for prompt_key, prompt_text in scenario["prompts"].items():
398
+ if not prompt_text.strip():
399
+ trans_scenario["prompts"][prompt_key] = prompt_text
400
+ continue
401
+ try:
402
+ translated_text = await client.translate(prompt_text)
403
+ trans_scenario["prompts"][prompt_key] = translated_text
404
+ except Exception as e:
405
+ print(f"\n[translate] WARNING: {file_key} シナリオ{sid}/{prompt_key} 翻訳失敗: {e}")
406
+ trans_scenario["prompts"][prompt_key] = prompt_text
407
+
408
+ async with lock:
409
+ translated[sid] = trans_scenario
410
+ file_state["translated_scenarios"] = translated
411
+ save_checkpoint(state)
412
+ print(f"[translate] {file_key} シナリオ {sid} 完了")
413
+
414
+ await asyncio.gather(*[_translate_one(s) for s in pending])
415
+
416
+ if not dry_run and len(translated) >= len(scenarios):
417
+ file_state["status"] = "completed"
418
+ save_checkpoint(state)
419
+
420
+ print(f"[translate] {file_key}: シナリオ翻訳完了: {len(translated)}件")
421
+ return {"scenarios": scenarios, "translated": translated}
422
+
423
+
424
+ async def translate_note_file(
425
+ client: VLLMClient,
426
+ filepath: Path,
427
+ file_key: str,
428
+ state: dict,
429
+ dry_run: bool,
430
+ lock: asyncio.Lock,
431
+ ) -> dict:
432
+ """ノート分割ファイルを翻訳する。"""
433
+ notes = parse_scenario_notes(filepath)
434
+
435
+ if file_key not in state["files"]:
436
+ state["files"][file_key] = {"translated_notes": {}, "status": "in_progress"}
437
+
438
+ file_state = state["files"][file_key]
439
+ translated_notes = file_state.get("translated_notes", {})
440
+
441
+ target_notes = dict(list(notes.items())[:2]) if dry_run else notes
442
+ pending = {k: v for k, v in target_notes.items() if k not in translated_notes}
443
+
444
+ print(f"[translate] {file_key}: ノート翻訳開始: {len(target_notes)}件 (未翻訳: {len(pending)}件)")
445
+
446
+ async def _translate_one(key: str, note: str) -> None:
447
+ try:
448
+ translated_text = await client.translate(note)
449
+ except Exception as e:
450
+ print(f"\n[translate] WARNING: {file_key} ノート#{key} 翻訳失敗: {e}")
451
+ translated_text = note
452
+ async with lock:
453
+ translated_notes[key] = translated_text
454
+ file_state["translated_notes"] = translated_notes
455
+ save_checkpoint(state)
456
+ print(f"[translate] {file_key} ノート #{key} 完了")
457
+
458
+ await asyncio.gather(*[_translate_one(k, v) for k, v in pending.items()])
459
+
460
+ if not dry_run and len(translated_notes) >= len(notes):
461
+ file_state["status"] = "completed"
462
+ save_checkpoint(state)
463
+
464
+ print(f"[translate] {file_key}: ノート翻訳完了: {len(translated_notes)}件")
465
+ return {"notes": notes, "translated": translated_notes}
466
+
467
+
468
+ async def translate_single_file(
469
+ client: VLLMClient,
470
+ filepath: Path,
471
+ file_key: str,
472
+ state: dict,
473
+ dry_run: bool,
474
+ lock: asyncio.Lock,
475
+ ) -> dict:
476
+ """単一ファイル全体を翻訳する。"""
477
+ content = parse_single_file(filepath)
478
+
479
+ if file_key not in state["files"]:
480
+ state["files"][file_key] = {"translated": None, "status": "in_progress"}
481
+
482
+ file_state = state["files"][file_key]
483
+
484
+ # 既に翻訳済みならスキップ
485
+ if file_state.get("translated"):
486
+ print(f"[translate] {file_key}: 既に翻訳済み、スキップ")
487
+ return {"original": content, "translated": file_state["translated"]}
488
+
489
+ print(f"[translate] {file_key}: 翻訳開始 ({len(content)} chars)")
490
+
491
+ try:
492
+ translated_text = await client.translate(content)
493
+ except Exception as e:
494
+ print(f"\n[translate] ERROR: {file_key} 翻訳失敗: {e}")
495
+ translated_text = content # 失敗時はオリジナルをそのまま
496
+
497
+ async with lock:
498
+ file_state["translated"] = translated_text
499
+ if not dry_run:
500
+ file_state["status"] = "completed"
501
+ save_checkpoint(state)
502
+
503
+ print(f"[translate] {file_key}: 翻訳完了")
504
+ return {"original": content, "translated": translated_text}
505
+
506
+
507
+ # ── HF アップロード ───────────────────────────────────────────
508
+
509
+ async def upload_to_hf(output_dir: Path) -> None:
510
+ if not HF_TOKEN:
511
+ print("[hub] HF_TOKEN 未設定のためアップロードをスキップ")
512
+ return
513
+ try:
514
+ from huggingface_hub import HfApi
515
+ api = HfApi(token=HF_TOKEN)
516
+ api.create_repo(repo_id=HF_REPO, repo_type="dataset", private=True, exist_ok=True)
517
+ for f in output_dir.glob("*.txt"):
518
+ api.upload_file(
519
+ path_or_fileobj=str(f),
520
+ path_in_repo=f"data/{f.name}",
521
+ repo_id=HF_REPO,
522
+ repo_type="dataset",
523
+ commit_message=f"update: {f.name}",
524
+ )
525
+ print(f"[hub] アップロード完了: {f.name}")
526
+ print(f"[hub] ✅ https://huggingface.co/datasets/{HF_REPO}")
527
+ except Exception as e:
528
+ print(f"[hub] アップロードエラー: {e}")
529
+ print(traceback.format_exc())
530
+
531
+
532
+ # ── メイン処理 ────────────────────────────────────────────────
533
+
534
+ async def process_file(
535
+ client: VLLMClient,
536
+ filename: str,
537
+ file_info: dict,
538
+ data_dir: Path,
539
+ state: dict,
540
+ dry_run: bool,
541
+ lock: asyncio.Lock,
542
+ ) -> tuple[str, dict] | None:
543
+ """単一ファイルの処理を行う。"""
544
+ filepath = data_dir / filename
545
+
546
+ if not filepath.exists():
547
+ print(f"[skip] {filename} が見つかりません: {filepath}")
548
+ return None
549
+
550
+ file_type = file_info["type"]
551
+ description = file_info["description"]
552
+
553
+ print(f"\n{'='*60}")
554
+ print(f"[file] {filename} ({description})")
555
+ print(f"[file] タイプ: {file_type}")
556
+ print(f"{'='*60}")
557
+
558
+ if file_type == "scenario_split":
559
+ result = await translate_scenario_file(client, filepath, filename, state, dry_run, lock)
560
+ return (filename, {"type": "scenario_split", **result})
561
+
562
+ elif file_type == "note_split":
563
+ result = await translate_note_file(client, filepath, filename, state, dry_run, lock)
564
+ return (filename, {"type": "note_split", **result})
565
+
566
+ elif file_type == "single":
567
+ result = await translate_single_file(client, filepath, filename, state, dry_run, lock)
568
+ return (filename, {"type": "single", **result})
569
+
570
+ else:
571
+ print(f"[warning] 不明なファイルタイプ: {file_type}")
572
+ return None
573
+
574
+
575
+ async def main(dry_run: bool, target_file: str | None) -> None:
576
+ start_time = datetime.now(timezone.utc)
577
+ print(f"{'='*60}")
578
+ print(f"EQ-Bench3 日本語化スクリプト v2")
579
+ print(f"開始: [{start_time.isoformat()}]")
580
+ print(f"{'='*60}")
581
+ print(f" EQ-Bench3 ディレクトリ: {EQBENCH_DIR}")
582
+ print(f" 出力ディレクトリ : {OUTPUT_DIR}")
583
+ print(f" 翻訳モデル : {TRANSLATE_MODEL}")
584
+ print(f" dry-run : {dry_run}")
585
+ print(f" 対象ファイル数 : {len(TARGET_FILES)}")
586
+ print()
587
+
588
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
589
+ data_dir = EQBENCH_DIR / "data"
590
+
591
+ # ── チェックポイント読み込み ──────────────────────────────
592
+ state = load_checkpoint()
593
+ completed_files = sum(1 for f in state.get("files", {}).values() if f.get("status") == "completed")
594
+ if completed_files > 0:
595
+ print(f"[checkpoint] 再開: {completed_files}/{len(TARGET_FILES)}ファイル処理済み")
596
+
597
+ # ── vLLM 接続 ─────────────────────────────────────────────
598
+ async with VLLMClient() as client:
599
+ await client.wait_for_server()
600
+
601
+ lock = asyncio.Lock()
602
+ results: dict[str, dict] = {}
603
+
604
+ # ── 各ファイルの翻訳実行 ──────────────────────────────
605
+ target_files_to_process = (
606
+ {target_file: TARGET_FILES[target_file]}
607
+ if target_file and target_file in TARGET_FILES
608
+ else TARGET_FILES
609
+ )
610
+
611
+ for filename, file_info in target_files_to_process.items():
612
+ result = await process_file(
613
+ client, filename, file_info, data_dir, state, dry_run, lock
614
+ )
615
+ if result:
616
+ results[result[0]] = result[1]
617
+
618
+ # ── 出力ファイル生成 ─────────────────────────────────────
619
+ print("\n" + "=" * 60)
620
+ print("[output] 出力ファイル生成中...")
621
+ print("=" * 60)
622
+
623
+ for filename, result in results.items():
624
+ output_path = OUTPUT_DIR / filename.replace(".txt", "_ja.txt")
625
+
626
+ if result["type"] == "scenario_split":
627
+ output_content = build_output_prompts(result["scenarios"], result["translated"])
628
+ elif result["type"] == "note_split":
629
+ output_content = build_output_notes(result["notes"], result["translated"])
630
+ elif result["type"] == "single":
631
+ output_content = result["translated"]
632
+ else:
633
+ continue
634
+
635
+ output_path.write_text(output_content, encoding="utf-8")
636
+ print(f"[output] ✅ {output_path.name}")
637
+
638
+ # オリジナルもコピー
639
+ original_path = data_dir / filename
640
+ if original_path.exists():
641
+ import shutil
642
+ shutil.copy(original_path, OUTPUT_DIR / filename.replace(".txt", "_en.txt"))
643
+
644
+ # ── HF アップロード ───────────────────────────────────────
645
+ if not dry_run:
646
+ await upload_to_hf(OUTPUT_DIR)
647
+
648
+ # チェックポイント削除(全完了時のみ)
649
+ if not dry_run and all(
650
+ state.get("files", {}).get(f, {}).get("status") == "completed"
651
+ for f in TARGET_FILES
652
+ ):
653
+ if CHECKPOINT_FILE.exists():
654
+ CHECKPOINT_FILE.unlink()
655
+ print("[checkpoint] チェックポイント削除(全ファイル完了)")
656
+
657
+ elapsed = (datetime.now(timezone.utc) - start_time).total_seconds()
658
+ print()
659
+ print("=" * 60)
660
+ print(f"翻訳完了 (所要時間: {elapsed/60:.1f}分)")
661
+ print(f"出力先: {OUTPUT_DIR}/")
662
+ print("=" * 60)
663
+
664
+
665
+ if __name__ == "__main__":
666
+ parser = argparse.ArgumentParser(description="EQ-Bench3 日本語化スクリプト v2")
667
+ parser.add_argument("--dry-run", action="store_true", help="最初の2シナリオのみ処理して動作確認")
668
+ parser.add_argument(
669
+ "--target-file",
670
+ choices=list(TARGET_FILES.keys()),
671
+ default=None,
672
+ help="翻訳対象ファイルを指定(デフォルト: 全ファイル)",
673
+ )
674
+ parser.add_argument(
675
+ "--list-files",
676
+ action="store_true",
677
+ help="対象ファイル一覧を表示して終了",
678
+ )
679
+ args = parser.parse_args()
680
+
681
+ if args.list_files:
682
+ print("翻訳対象ファイル一覧:")
683
+ print("-" * 60)
684
+ for filename, info in TARGET_FILES.items():
685
+ print(f" {filename}")
686
+ print(f" タイプ: {info['type']}")
687
+ print(f" 説明 : {info['description']}")
688
+ sys.exit(0)
689
+
690
+ if not os.environ.get("HF_TOKEN"):
691
+ print("[WARNING] HF_TOKEN が未設定です。HF アップロードはスキップされます。")
692
+
693
+ asyncio.run(main(dry_run=args.dry_run, target_file=args.target_file))