| import gradio as gr |
| import pandas as pd |
| from datasets import load_dataset |
| from deep_translator import GoogleTranslator |
| from huggingface_hub import login |
| import os |
|
|
| |
| |
| HF_TOKEN = os.environ.get("HF_TOKEN") |
|
|
| |
| |
| dataset = None |
| df = None |
| category_counts = None |
|
|
| |
| def load_and_process_data(): |
| """データセットをロードし、グローバル変数を初期化する""" |
| global dataset, df, category_counts |
| if dataset is not None: |
| return |
|
|
| try: |
| |
| if HF_TOKEN: |
| login(token=HF_TOKEN) |
| print("Hugging Face にログインしました。") |
| else: |
| print("警告: HF_TOKEN が設定されていません。ゲート付きデータセットにアクセスできません。") |
| |
| |
| print("データセットをロード中...") |
| dataset = load_dataset("cais/hle", split="test") |
| |
| |
| df = dataset.remove_columns(['image_preview', 'rationale_image']).to_pandas() |
| category_counts = df['category'].value_counts() |
| print(f"データセットのロードと前処理が完了しました。合計 {len(df)} 件のデータを読み込みました。") |
| except Exception as e: |
| print(f"データセットのロードエラー: {e}") |
| print("データセットへのアクセスには認証が必要です。HF_TOKENを設定してください。") |
| |
| df = pd.DataFrame(columns=['id', 'question', 'category']) |
| category_counts = pd.Series(dtype='int64') |
|
|
| |
| def translate_text(text, dest_lang='ja'): |
| """テキストを翻訳します""" |
| if not text or not isinstance(text, str): |
| return "" |
| try: |
| |
| translator = GoogleTranslator(source='auto', target=dest_lang) |
| return translator.translate(text) |
| except Exception as e: |
| print(f"翻訳エラー: {e}") |
| return f"翻訳エラー: {str(e)}" |
|
|
| |
| def on_category_change(selected_category): |
| """カテゴリが変更されたときに、問題のドロップダウンを更新する""" |
| if df is None or len(df) == 0: |
| return gr.Dropdown(choices=[], label="データセットが利用できません", interactive=False, value=None) |
| |
| if selected_category == "全カテゴリ": |
| filtered_indices = df.index |
| else: |
| filtered_indices = df[df['category'] == selected_category].index |
|
|
| |
| question_choices = [ |
| (f"{df.loc[idx, 'question'][:80]}...", idx) for idx in filtered_indices |
| ] |
|
|
| if not question_choices: |
| |
| return gr.Dropdown(choices=[], label="問題 (該当なし)", interactive=False, value=None) |
| else: |
| return gr.Dropdown(choices=question_choices, label="問題を選択", interactive=True, value=question_choices[0][1]) |
|
|
| def on_question_change(selected_index): |
| """問題が選択されたときに、すべての詳細表示を更新する""" |
| if selected_index is None or pd.isna(selected_index) or dataset is None: |
| |
| return ( |
| gr.Markdown(visible=False), |
| gr.Image(visible=False), |
| gr.Markdown(visible=False), |
| gr.Markdown(visible=False), |
| gr.Image(visible=False), |
| gr.Markdown(visible=False), |
| gr.JSON(visible=False) |
| ) |
|
|
| try: |
| |
| entry = dataset[int(selected_index)] |
|
|
| |
| q_trans = translate_text(entry['question']) |
| a_trans = translate_text(entry['answer']) |
| r_trans = translate_text(entry.get('rationale', '')) |
|
|
| |
| return ( |
| gr.Markdown(f"### 質問\n---\n**原文:**\n{entry['question']}\n\n**日本語訳:**\n{q_trans}", visible=True), |
| gr.Image(entry.get('image_preview'), label="質問画像", visible=bool(entry.get('image_preview'))), |
| gr.Markdown(f"### 回答\n---\n**原文:**\n{entry['answer']}\n\n**日本語訳:**\n{a_trans}", visible=True), |
| gr.Markdown(f"### 解説\n---\n**原文:**\n{entry.get('rationale', 'N/A')}\n\n**日本語訳:**\n{r_trans}", visible=bool(entry.get('rationale'))), |
| gr.Image(entry.get('rationale_image'), label="解説画像", visible=bool(entry.get('rationale_image'))), |
| gr.Markdown(f"**ID:** `{entry['id']}`<br>**分野:** `{entry['raw_subject']}`<br>**回答タイプ:** `{entry['answer_type']}`", visible=True), |
| gr.JSON({k: str(v) for k, v in entry.items()}, label="元のデータ", visible=True) |
| ) |
| except Exception as e: |
| error_msg = f"データ取得エラー: {str(e)}" |
| return ( |
| gr.Markdown(f"### エラー\n{error_msg}", visible=True), |
| gr.Image(visible=False), |
| gr.Markdown(visible=False), |
| gr.Markdown(visible=False), |
| gr.Image(visible=False), |
| gr.Markdown(visible=False), |
| gr.JSON(visible=False) |
| ) |
|
|
| |
| def create_demo(): |
| |
| load_and_process_data() |
|
|
| with gr.Blocks(theme=gr.themes.Soft(), title="HLE Dataset Viewer") as demo: |
| gr.Markdown("# Humanity's Last Exam (HLE) Dataset Viewer") |
| |
| if df is None or len(df) == 0: |
| gr.Markdown("⚠️ **データセットの読み込みに失敗しました**") |
| gr.Markdown("このデータセットはゲート付きで、アクセスには認証が必要です。") |
| gr.Markdown("**解決方法:**") |
| gr.Markdown("1. [Hugging Face](https://huggingface.co/cais/hle) でデータセットへのアクセス申請を行ってください") |
| gr.Markdown("2. 承認後、HF_TOKEN環境変数にあなたのHugging Faceトークンを設定してください") |
| return demo |
| |
| gr.Markdown("Hugging Face `cais/hle`データセットを探索し、日本語訳を確認できます。") |
|
|
| with gr.Row(): |
| with gr.Column(scale=1, min_width=350): |
| gr.Markdown("## 操作パネル") |
| |
| |
| if len(category_counts) > 0: |
| category_choices = ["全カテゴリ"] + sorted(category_counts.index.tolist()) |
| else: |
| category_choices = ["全カテゴリ"] |
| |
| category_dd = gr.Dropdown( |
| choices=category_choices, |
| value="全カテゴリ", |
| label="1. カテゴリを選択" |
| ) |
| question_dd = gr.Dropdown(label="2. 問題を選択", interactive=False) |
|
|
| gr.Markdown("### カテゴリ別問題数") |
| if len(category_counts) > 0: |
| gr.Dataframe(value=pd.DataFrame(category_counts).reset_index(), headers=['カテゴリ', '問題数'], interactive=False) |
| else: |
| gr.Markdown("データがありません") |
|
|
| with gr.Column(scale=3): |
| |
| question_md = gr.Markdown(visible=False) |
| question_img = gr.Image(label="質問画像", visible=False) |
| answer_md = gr.Markdown(visible=False) |
| rationale_md = gr.Markdown(visible=False) |
| rationale_img = gr.Image(label="解説画像", visible=False) |
| metadata_md = gr.Markdown(visible=False) |
| json_output = gr.JSON(label="元のデータ", visible=False) |
|
|
| |
| category_dd.change(fn=on_category_change, inputs=category_dd, outputs=question_dd) |
| question_dd.change(fn=on_question_change, inputs=question_dd, outputs=[ |
| question_md, question_img, answer_md, rationale_md, rationale_img, metadata_md, json_output |
| ]) |
|
|
| |
| if len(df) > 0: |
| demo.load(fn=on_category_change, inputs=category_dd, outputs=question_dd) |
|
|
| return demo |
|
|
| |
| if __name__ == "__main__": |
| app = create_demo() |
| app.launch() |