AutoFigure でテキストから科学図を生成するエージェント型パイプライン構築
本文の状態
日本語全文を表示中
詳細モードで約12分の本文を読めます。
同じ出来事の情報源
この情報源を基点に整理
MarkTechPost
ResearAI が公開した AutoFigure は、テキスト記述や論文内容から科学的な図表を自動生成するツールキットであり、アジェンシー型ドキュメントインテリジェンスのパイプライン可視化に活用できる。
AI深層分析を開く2026年8月22日 08:01
AI深層分析
キーポイント
AutoFigure の機能と目的
このツールはテキスト記述や構造化された方法論の説明から、出版レベルの科学的図表を直接生成するための実用的なキットとして設計されている。
環境構築と依存関係の解決
チュートリアルでは Pillow 互換性の問題などの依存関係を修正し、SVG および PNG 出力に必要なレンダリングツールを準備する手順が示されている。
アジェンシー型パイプラインの可視化
API ベースの生成ワークフローを設定し、詳細なアジェンシー型ドキュメントインテリジェンスのパイプラインを出版スタイルの科学的図表に変換する事例が紹介されている。
出力形式とアーカイブ機能
オフライン SVG レンダリングのテスト、生成ファイルの確認、サンプル論文および PDF の作成に加え、最終成果物を再利用可能なギャラリーや ZIP アーカイブとしてエクスポートする機能が実装されている。
エージェント型ドキュメントインテリジェンスのパイプライン構成
PDF やスキャン報告書などの多様な長文ドキュメントを処理し、正規化層で構造化した後に、要約や抽出など専門モジュールへルーティングする左から右へのアーキテクチャを採用している。
重要な引用
In this tutorial, we explore AutoFigure as a practical toolkit for generating scientific figures directly from text descriptions, paper-like content, and structured methodological explanations.
Create a publication-ready scientific method figure for an agentic long-document intelligence system.
"A low-cost orchestration layer selects smaller or larger LLMs depending on complexity, confidence, and budget."
"The final output is an analyst-ready workspace containing a summary, extracted fields, exact tables, cited answers, and audit logs."
編集コメントを表示
編集コメント
このツールは、複雑な AI パイプラインを直感的な図表に変換する実用的なアプローチを示しており、技術文書の作成プロセスに新たな可能性をもたらす。開発者が依存関係の調整や API 連携を通じてカスタマイズできる点も注目される。
Source Article
元記事を日本語で読む
本文に関係しない購読案内、埋め込み通知、サイト内プロモーションは除いています。
本チュートリアルでは、テキスト説明や論文風のコンテンツ、構造化された手法解説から直接科学的図を生成するための実用的なツールキット「AutoFigure」について探ります。ここでは AutoFigure の完全な環境セットアップを行い、Pillow などの依存関係に関する互換性問題を解決し、SVG および PNG 出力に必要なレンダリングツールを整備します。
その後、カスタム参照図を作成し、API ベースの生成ワークフローを設定して、詳細なエージェント型ドキュメントインテリジェンスパイプラインを出版用スタイルの科学的図に変換するプロセスを実践します。その過程で、オフラインでの SVG レンダリングテストや生成ファイルの確認、サンプル論文と PDF の作成、最終出力を再利用可能なギャラリーおよび ZIP アーカイブへのエクスポートも併せて行います。
Copy CodeCopiedUse a different Browser
import os
import sys
import json
import time
import glob
import shutil
import textwrap
import subprocess
import importlib
from pathlib import Path
from getpass import getpass
REPO_URL = "https://github.com/ResearAI/AutoFigure.git"
REPO_DIR = Path("/content/AutoFigure")
OUTPUT_ROOT = Path("/content/autofigure_colab_outputs")
PROVIDER = os.environ.get("AUTOFIGURE_PROVIDER", "openrouter")
DEFAULT_MODELS = {
"openrouter": "google/gemini-3.1-pro-preview",
"gemini": "gemini-3.1-pro-preview",
"bianxie": "gemini-3.1-pro-preview",
}
GENERATION_MODEL = os.environ.get(
"AUTOFIGURE_MODEL",
DEFAULT_MODELS.get(PROVIDER, "google/gemini-3.1-pro-preview")
)
MAX_ITERATIONS = int(os.environ.get("AUTOFIGURE_MAX_ITERATIONS", "1"))
QUALITY_THRESHOLD = float(os.environ.get("AUTOFIGURE_QUALITY_THRESHOLD", "8.5"))
RUN_TEXT_TO_FIGURE = True
RUN_PAPER_TO_FIGURE = False
RUN_MXGRAPH_DEMO = False
RUN_IMAGE_ENHANCEMENT = False
TEXT_OUTPUT_FORMAT = "svg"
MXGRAPH_OUTPUT_FORMAT = "mxgraphxml"
ART_STYLE = (
"clean publication-ready scientific illustration, precise alignment, subtle shadows, "
"clear academic typography, high contrast, minimal clutter"
)
FIGURE_DESCRIPTION = """
出版準備が整った科学メソッド図を作成し、エージェント型長文書知能システムの全体像を示します。
この図は、左から右へと流れるアーキテクチャで以下のパイプラインを説明するものです:
- 長文書がシステムに入力されます。PDF、スキャンされたレポート、Markdown ファイル、表、あるいは複雑なレイアウトを持つ混合ドキュメントなどが対象となります。
"""
- ドキュメント正規化レイヤーが、生テキスト、セクション階層、表、図、メタデータを抽出します。
- ルーティングプランナーは、各セクションを要約、フィールド抽出、表再構築、視覚分析、または引用根拠付けのいずれに振り分けるかを決定します。
- 専門的なエキスパートモジュールが振り分けられたチャンクを処理します:
- 要約エキスパートは階層的な要約を作成します。
- 抽出エキスパートは JSON フィールドを返します。
- 表エキスパートは正確な表を再構築します。
- 視覚エキスパートはチャートや図を記述します。
- 引用エキスパートは主張と証拠スパンをリンクさせます。
- 低コストのオーケストレーションレイヤーが、複雑さ、信頼度、予算に応じて小規模または大規模な LLM を選択します。
- 検証レイヤーはスキーマの有効性、ソース根拠、表の一貫性、および信頼度をチェックします。
- 最終出力は、要約、抽出フィールド、正確な表、引用された回答、監査ログを含む分析担当者向けのワークスペースです。
設計要件:
- 横長の 16:9 レイアウトを使用する。
- 明確なモジュールボックス、矢印、ラベルを使用する。
- コスト制御、信頼度スコアリング、監査可能性のための小さな注釈を追加する。
- デコレーションによるノイズを避ける。
- 金融やエンタープライズ文書知能の読者にも理解しやすいフローにする。"
MINI_PAPER_MARKDOWN = """
長文財務レポート向けの効率的なエージェント型ドキュメント知能
概要
我々は、長く多様な財務ドキュメントから要約、事実、表、根拠付き回答を抽出するための、エージェント型ドキュメント知能アーキテクチャを提案します。
手法
本手法では、まず入力される各ドキュメントを構造化されたドキュメントグラフに正規化します。このグラフには、セクションノード、パラグラフノード、テーブルノード、図表ノード、およびメタデータノードが含まれています。ルーティングプランナーは、モダリティ(情報形態)、複雑さ、必要な出力スキーマに基づいて、各ノードを専門的なエキスパートに割り当てます。
システムには 5 つのエキスパートが用意されています。サマライゼーションエキスパートはセクションレベルのチャンクから階層的な要約を生成します。抽出エキスパートは、エンティティ、日付、リスク、財務指標、義務に関する厳格な JSON スキーマにデータを埋め込みます。テーブルエキスパートは正確なテーブルを再構築し、行と列の整合性を検証します。ビジュアルエキスパートはチャートや図表を記述します。引用エキスパートは生成されたすべての主張をソーステキストのスパンに対応付けます。
予算意識型のオーケストレーション層がモデルサイズを動的に選択します。単純なチャンクは低コストモデルで処理され、複雑なチャンクはより強力なモデルへエスカレートされます。その後、検証層がスキーマの有効性、引用による裏付け、数値の整合性、テーブルの完全性をチェックします。チェックに失敗した場合は修復のために再ルーティングされます。
実験
財務報告書やアナリストレポートを対象に、抽出精度、グラウンディング(根拠)の精密さ、テーブル再構築の品質、および総推論コストを評価します。
def run(cmd, cwd=None, check=True, quiet=False):
print(f"\n$ {cmd}")
process = subprocess.run(
cmd,
shell=True,
cwd=str(cwd) if cwd else None,
text=True,
stdout=subprocess.PIPE if quiet else None,stderr=subprocess.STDOUT if quiet else None,
)
if quiet and process.stdout:
print(process.stdout[-5000:])
if check and process.returncode != 0:
raise RuntimeError(f"Command failed with exit code {process.returncode}: {cmd}")
return process
def heading(title):
print("\n" + "=" * 100)
print(title)
print("=" * 100)
def safe_read(path, max_chars=2500):
path = Path(path)
if not path.exists():
return ""
text = path.read_text(encoding="utf-8", errors="ignore")
return text[:max_chars] + ("\n... [truncated]" if len(text) > max_chars else "")
def clear_loaded_modules(prefixes):
for name in list(sys.modules):
if any(name == prefix or name.startswith(prefix + ".") for prefix in prefixes):
del sys.modules[name]
def get_colab_secret(names):
try:
from google.colab import userdata
for name in names:
try:
value = userdata.get(name)
if value:
return value
except Exception:
pass
except Exception:
pass
return None
def collect_api_key(provider):
env_candidates = [
"AUTOFIGURE_API_KEY",
"OPENROUTER_API_KEY",
"GOOGLE_API_KEY",
"GEMINI_API_KEY",
"BIANXIE_API_KEY",
]
for key_name in env_candidates:
value = os.environ.get(key_name)
if value:
print(f"Using API key from environment variable: {key_name}")
return value
secret_candidates = {
"openrouter": ["AUTOFIGURE_API_KEY", "OPENROUTER_API_KEY"],
"gemini": ["AUTOFIGURE_API_KEY", "GOOGLE_API_KEY", "GEMINI_API_KEY"],
"bianxie": ["AUTOFIGURE_API_KEY", "BIANXIE_API_KEY"],
}.get(provider, ["AUTOFIGURE_API_KEY"])
value = get_colab_secret(secret_candidates)
if value:
print("Using API key from Colab Secrets.")
return value
value = getpass(f"Paste your {provider} API key, or press Enter to skip cloud generation: ").strip()
return value
まず、主要なパスやプロバイダー設定、モデル構成、チュートリアルのオプションをインポートして定義します。その後、AutoFigure 生成で使用する詳細な図の説明とサンプル論文の内容も準備しておきます。さらに、コマンドの実行、セクション見出しの表示、ファイルの安全な読み込み、読み込まれたモジュールのクリア、そして API キーの安全な取得を行うためのヘルパー関数を作成します。
Copy CodeCopiedUse a different Browser
def display_file_if_possible(path, title=None):
path = Path(path) if path else None
if not path or not path.exists():
print(f"Missing file: {path}")
return
try:
from IPython.display import display, Image as IPImage, SVG, Markdown
if title:
display(Markdown(f"### {title}"))
suffix = path.suffix.lower()
if suffix == ".png":
display(IPImage(filename=str(path)))
elif suffix == ".svg":
display(SVG(filename=str(path)))
elif suffix in [".json", ".md", ".txt", ".drawio"]:
print(safe_read(path, max_chars=5000))
else:
print(path)
except Exception as exc:
print(f"Could not display {path}: {exc}")
def make_output_gallery(output_dir):
output_dir = Path(output_dir)
gallery_path = output_dir / "gallery.html"
blocks = []
for p in sorted(output_dir.rglob("*.png")):
rel = p.relative_to(output_dir)
blocks.append(f"""
{rel}
""")
for p in sorted(output_dir.rglob("*.svg")):
rel = p.relative_to(output_dir)
svg_text = p.read_text(encoding="utf-8", errors="ignore")
blocks.append(f"""
{rel}
{svg_text}
""")
for p in sorted(output_dir.rglob("*.drawio")):
rel = p.relative_to(output_dir)
code = p.read_text(encoding="utf-8", errors="ignore")[:4000]
blocks.append(f"""
{rel}
Editable draw.io mxGraph XML file.
{code}出力ディレクトリ内のすべての generation_report.json ファイルをソートして順に処理します。各ファイルの相対パスを取得し、JSON データを読み込んで整形した上で先頭 7000 文字を抽出します。読み込みに失敗した場合は、エラーを無視してテキストデータをそのまま先頭 7000 文字分取得します。
{rel}
{report_text}AutoFigure Colab ガラリー
AutoFigure Colab ガラリー
gallery_path.write_text(html, encoding="utf-8")
return gallery_path
def summarize_generation_result(result, label):
print("\n" + "-" * 100)
print(label)
print("-" * 100)
print(f"Success: {result.success}")
print(f"Final score: {result.final_score}")
print(f"Iterations used: {result.iterations_used}")
print(f"SVG path: {result.svg_path}")
print(f"mxGraph path: {result.mxgraph_path}")
print(f"Preview path: {result.preview_path}")
print(f"Enhanced path: {result.enhanced_path}")
print(f"Enhanced paths: {result.enhanced_paths}")
print(f"Error: {result.error}")
if result.logs:
print("\nRecent logs:")
for log in result.logs[-20:]:
print(f"- {log}")
display_file_if_possible(result.preview_path, f"{label}: PNG Preview")
if result.svg_path:
display_file_if_possible(result.svg_path, f"{label}: SVG")
if result.mxgraph_path:
display_file_if_possible(result.mxgraph_path, f"{label}: mxGraph XML")
report_candidates = []
for candidate in [result.svg_path, result.mxgraph_path, result.preview_path]:
if candidate:
report_candidates.append(Path(candidate).parent / "generation_report.json")
for report_path in report_candidates:
if report_path.exists():
print("\nGeneration report preview:")
print(safe_read(report_path, max_chars=6000))
try:
import pandas as pd
from IPython.display import display
report = json.loads(report_path.read_text(encoding="utf-8"))
rows = []
for row in report.get("iteration_history", []):
rows.append({
"iteration": row.get("iteration"),
"quality_score": row.get("quality_score"),
"improvement": row.get("improvement"),
"has_critique": row.get("critique") is not None,
})
if rows:
display(pd.DataFrame(rows))
except Exception as exc:
print(f"Could not tabulate report: {exc}")
break
生成されたファイルを Colab 内で直接表示するためのユーティリティ関数を定義しました。PNG、SVG、JSON、Markdown、テキスト、draw.io の出力に対応しています。また、AutoFigure で生成されたすべての成果物を一度に確認できる整理されたページを作成する HTML ギャラリー生成機能も実装しました。さらに、生成メタデータの表示やプレビューの展開、そして読みやすい形式での反復履歴レポートの提示を行う結果サマリー関数も追加しています。
Copy CodeCopiedUse a different Browser
1. AutoFigure と Colab の依存関係のインストール
出力ディレクトリを作成します。
OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)パッケージリストを更新し、必要なライブラリをインストールします。
run("apt-get update -qq", quiet=True)
run(
"apt-get install -y -qq "
"libcairo2 libpango-1.0-0 libpangocairo-1.0-0 "
"libgdk-pixbuf-2.0-0 libffi-dev shared-mime-info",
quiet=True,
)既存の PIL や autofigure モジュールをクリアし、pip を最新化してセットアップします。
clear_loaded_modules(["PIL", "autofigure"])
run(f"{sys.executable} -m pip install -q -U pip 'setuptools'")ランタイムを再起動して、このセル全体を再実行してください。
raise excデモとして MXGraph を使用する場合は、Chromium ブラウザをインストールします。
if RUN_MXGRAPH_DEMO:
run(f"{sys.executable} -m playwright install chromium", quiet=True)リポジトリのパスを追加して環境を整えます。
sys.path.insert(0, str(REPO_DIR))2. AutoFigure SDK のインポート
必要なクラスと関数を読み込みます。
from autofigure import AutoFigureAgent, Config
from autofigure.generator import (
validate_code_syntax,
code_to_png,
get_initial_prompt_template,
)
from autofigure.extractor import MethodologyExtractorインポートが成功したことを確認します。
print("AutoFigure imported successfully.")
print(f"Repository directory: {REPO_DIR}")
print(f"Output root: {OUTPUT_ROOT}")3. オフライン SVG の事前チェック:検証とレンダリング
オフライン検証用のディレクトリを作成します。
preflight_dir = OUTPUT_ROOT / "00_offline_preflight"
preflight_dir.mkdir(parents=True, exist_ok=True)サンプルとなる SVG 定義を確認します。
AutoFigure Offline Rendering Check
Text Prompt
method description
AutoFigure
generate → evaluate → refine
Figure
SVG + PNG output
</article>```
必要なシステムパッケージをインストールし、Pillow の互換性問題を解決した上で、AutoFigure リポジトリをクローンします。その後、SDK および PDF・Web 関連の依存関係をインストールします。
環境が準備できたことを確認したら、AutoFigure の主要クラスとジェネレーターユーティリティを読み込みます。API を使用して生成を行う前に、オフラインでの SVG 検証と PNG レンダリングテストを実行し、レンダリングパイプラインが正常に動作することを確認します。
```python
is_valid, validation_message = validate_code_syntax(sample_svg, "svg")
print(f"SVG syntax valid: {is_valid}")
print(f"Validation message: {validation_message}")
sample_svg_path = preflight_dir / "offline_preflight.svg"
sample_png_path = preflight_dir / "offline_preflight.png"
sample_svg_path.write_text(sample_svg, encoding="utf-8")
render_ok, processed_svg = code_to_png(
sample_svg,
str(sample_png_path),
attempt_repair=False,
output_format="svg",
)
print(f"Rendered PNG: {render_ok} -> {sample_png_path}")
display_file_if_possible(sample_png_path, "Offline preflight PNG")4. カスタム参照図の作成
カスタムの参照用ディレクトリを OUTPUT_ROOT の下に 01_custom_references という名前で生成し、その中に reference_architecture_style.png というファイルを作成します。画像サイズは幅 1333 ピクセル、高さ 750 ピクセルに設定し、背景色を白で塗りつぶした新しい画像オブジェクトを用意します。
フォントの読み込みを試みますが、失敗した場合はフォント変数を None にして処理を続行できるようにしています。具体的には、タイトル用(36 ポイント)、ボックス見出し用(24 ポイント)、サブタイトル用(18 ポイント)のフォントを指定します。
画像上に「Reference Layout: Modular Scientific Pipeline」というタイトルを描画し、その下に 4 つの主要なコンポーネントを表す矩形ボックスを配置します。各ボックスには、入力(Input)、プランナー(Planner)、エキスパート(Experts)、検証者(Verifier)という役割と、それぞれの機能(文書処理、タスク別ルーティング、要約/表/視覚処理、根拠のある出力生成)が記載されます。
ループ処理で各ボックスの描画を行い、角丸処理を施した灰色の枠線を描きます。ボックス内には見出しとサブタイトルを中央揃えで配置し、ボックス間の矢印も計算して接続します。
{code}原文を表示
In this tutorial, we explore AutoFigure as a practical toolkit for generating scientific figures directly from text descriptions, paper-like content, and structured methodological explanations. In this tutorial, we set up the complete AutoFigure environment, fix dependency issues such as Pillow compatibility, and prepare the required rendering tools for SVG and PNG outputs. We then build a custom reference figure, configure an API-backed generation workflow, and use AutoFigure to convert a detailed agentic document intelligence pipeline into a publication-style scientific diagram. Along the way, we also test offline SVG rendering, inspect the generated files, create a sample paper and PDF, and export the final outputs to a reusable gallery and a zip archive.
Copy CodeCopiedUse a different Browser
import os
import sys
import json
import time
import glob
import shutil
import textwrap
import subprocess
import importlib
from pathlib import Path
from getpass import getpass
REPO_URL = "https://github.com/ResearAI/AutoFigure.git"
REPO_DIR = Path("/content/AutoFigure")
OUTPUT_ROOT = Path("/content/autofigure_colab_outputs")
PROVIDER = os.environ.get("AUTOFIGURE_PROVIDER", "openrouter")
DEFAULT_MODELS = {
"openrouter": "google/gemini-3.1-pro-preview",
"gemini": "gemini-3.1-pro-preview",
"bianxie": "gemini-3.1-pro-preview",
}
GENERATION_MODEL = os.environ.get(
"AUTOFIGURE_MODEL",
DEFAULT_MODELS.get(PROVIDER, "google/gemini-3.1-pro-preview")
)
MAX_ITERATIONS = int(os.environ.get("AUTOFIGURE_MAX_ITERATIONS", "1"))
QUALITY_THRESHOLD = float(os.environ.get("AUTOFIGURE_QUALITY_THRESHOLD", "8.5"))
RUN_TEXT_TO_FIGURE = True
RUN_PAPER_TO_FIGURE = False
RUN_MXGRAPH_DEMO = False
RUN_IMAGE_ENHANCEMENT = False
TEXT_OUTPUT_FORMAT = "svg"
MXGRAPH_OUTPUT_FORMAT = "mxgraphxml"
ART_STYLE = (
"clean publication-ready scientific illustration, precise alignment, subtle shadows, "
"clear academic typography, high contrast, minimal clutter"
)
FIGURE_DESCRIPTION = """
Create a publication-ready scientific method figure for an agentic long-document intelligence system.
The figure should explain the following pipeline in a left-to-right architecture:
- Long documents enter the system. They may be PDFs, scanned reports, markdown files, tables, or mixed-layout documents.
- A document normalization layer extracts raw text, section hierarchy, tables, figures, and metadata.
- A routing planner decides whether each section should go to summarization, field extraction, table reconstruction, visual analysis, or citation grounding.
- Specialized expert modules process the routed chunks:
- Summarizer expert creates hierarchical summaries.
- Extraction expert returns JSON fields.
- Table expert reconstructs exact tables.
- Visual expert describes charts and diagrams.
- Citation expert links claims to evidence spans.
- A low-cost orchestration layer selects smaller or larger LLMs depending on complexity, confidence, and budget.
- A verification layer checks schema validity, source grounding, table consistency, and confidence.
- The final output is an analyst-ready workspace containing a summary, extracted fields, exact tables, cited answers, and audit logs.
Design requirements:
- Use a wide 16:9 layout.
- Use clear module boxes, arrows, and labels.
- Add small callouts for cost control, confidence scoring, and auditability.
- Avoid decorative clutter.
- Make the flow understandable for a finance or enterprise document intelligence audience.
"""
MINI_PAPER_MARKDOWN = """
Efficient Agentic Document Intelligence for Long Financial Reports
Abstract
We propose an agentic document intelligence architecture for extracting summaries, facts, tables,
and grounded answers from long, heterogeneous financial documents.
Method
Our method first normalizes each incoming document into a structured document graph. The graph
contains section nodes, paragraph nodes, table nodes, figure nodes, and metadata nodes. A routing
planner assigns each node to a specialized expert according to modality, complexity, and required
output schema.
The system uses five experts. The summarization expert produces hierarchical summaries from
section-level chunks. The extraction expert fills strict JSON schemas for entities, dates, risks,
financial metrics, and obligations. The table expert reconstructs exact tables and validates row-column
alignment. The visual expert describes charts and diagrams. The citation expert maps every generated
claim to source spans.
A budget-aware orchestration layer selects model size dynamically. Simple chunks are processed by
low-cost models, while complex chunks are escalated to stronger models. A verification layer then
checks schema validity, citation support, numerical consistency, and table integrity. Failed checks are
routed back for repair.
Experiments
We evaluate on financial filings and analyst reports using extraction accuracy, grounding precision,
table reconstruction quality, and total inference cost.
"""
def run(cmd, cwd=None, check=True, quiet=False):
print(f"\n$ {cmd}")
process = subprocess.run(
cmd,
shell=True,
cwd=str(cwd) if cwd else None,
text=True,
stdout=subprocess.PIPE if quiet else None,
stderr=subprocess.STDOUT if quiet else None,
)
if quiet and process.stdout:
print(process.stdout[-5000:])
if check and process.returncode != 0:
raise RuntimeError(f"Command failed with exit code {process.returncode}: {cmd}")
return process
def heading(title):
print("\n" + "=" * 100)
print(title)
print("=" * 100)
def safe_read(path, max_chars=2500):
path = Path(path)
if not path.exists():
return ""
text = path.read_text(encoding="utf-8", errors="ignore")
return text[:max_chars] + ("\n... [truncated]" if len(text) > max_chars else "")
def clear_loaded_modules(prefixes):
for name in list(sys.modules):
if any(name == prefix or name.startswith(prefix + ".") for prefix in prefixes):
del sys.modules[name]
def get_colab_secret(names):
try:
from google.colab import userdata
for name in names:
try:
value = userdata.get(name)
if value:
return value
except Exception:
pass
except Exception:
pass
return None
def collect_api_key(provider):
env_candidates = [
"AUTOFIGURE_API_KEY",
"OPENROUTER_API_KEY",
"GOOGLE_API_KEY",
"GEMINI_API_KEY",
"BIANXIE_API_KEY",
]
for key_name in env_candidates:
value = os.environ.get(key_name)
if value:
print(f"Using API key from environment variable: {key_name}")
return value
secret_candidates = {
"openrouter": ["AUTOFIGURE_API_KEY", "OPENROUTER_API_KEY"],
"gemini": ["AUTOFIGURE_API_KEY", "GOOGLE_API_KEY", "GEMINI_API_KEY"],
"bianxie": ["AUTOFIGURE_API_KEY", "BIANXIE_API_KEY"],
}.get(provider, ["AUTOFIGURE_API_KEY"])
value = get_colab_secret(secret_candidates)
if value:
print("Using API key from Colab Secrets.")
return value
value = getpass(f"Paste your {provider} API key, or press Enter to skip cloud generation: ").strip()
return value
We begin by importing and defining the main paths, provider settings, model configuration, and tutorial options. We also prepare the detailed figure description and sample paper content that we use later for AutoFigure generation. We then create helper functions to run commands, print section headings, read files safely, clear loaded modules, and securely collect API keys.
Copy CodeCopiedUse a different Browser
def display_file_if_possible(path, title=None):
path = Path(path) if path else None
if not path or not path.exists():
print(f"Missing file: {path}")
return
try:
from IPython.display import display, Image as IPImage, SVG, Markdown
if title:
display(Markdown(f"### {title}"))
suffix = path.suffix.lower()
if suffix == ".png":
display(IPImage(filename=str(path)))
elif suffix == ".svg":
display(SVG(filename=str(path)))
elif suffix in [".json", ".md", ".txt", ".drawio"]:
print(safe_read(path, max_chars=5000))
else:
print(path)
except Exception as exc:
print(f"Could not display {path}: {exc}")
def make_output_gallery(output_dir):
output_dir = Path(output_dir)
gallery_path = output_dir / "gallery.html"
blocks = []
for p in sorted(output_dir.rglob("*.png")):
rel = p.relative_to(output_dir)
blocks.append(f"""
{rel}
""")
for p in sorted(output_dir.rglob("*.svg")):
rel = p.relative_to(output_dir)
svg_text = p.read_text(encoding="utf-8", errors="ignore")
blocks.append(f"""
{rel}
{svg_text}
""")
for p in sorted(output_dir.rglob("*.drawio")):
rel = p.relative_to(output_dir)
code = p.read_text(encoding="utf-8", errors="ignore")[:4000]
blocks.append(f"""
{rel}
Editable draw.io mxGraph XML file.
{code}""")
for p in sorted(output_dir.rglob("generation_report.json")):
rel = p.relative_to(output_dir)
try:
report_text = json.dumps(json.loads(p.read_text(encoding="utf-8")), indent=2)[:7000]
except Exception:
report_text = p.read_text(encoding="utf-8", errors="ignore")[:7000]
blocks.append(f"""
{rel}
{report_text}""")
html = f"""
AutoFigure Colab Gallery
AutoFigure Colab Gallery
{''.join(blocks)}
"""
gallery_path.write_text(html, encoding="utf-8")
return gallery_path
def summarize_generation_result(result, label):
print("\n" + "-" * 100)
print(label)
print("-" * 100)
print(f"Success: {result.success}")
print(f"Final score: {result.final_score}")
print(f"Iterations used: {result.iterations_used}")
print(f"SVG path: {result.svg_path}")
print(f"mxGraph path: {result.mxgraph_path}")
print(f"Preview path: {result.preview_path}")
print(f"Enhanced path: {result.enhanced_path}")
print(f"Enhanced paths: {result.enhanced_paths}")
print(f"Error: {result.error}")
if result.logs:
print("\nRecent logs:")
for log in result.logs[-20:]:
print(f"- {log}")
display_file_if_possible(result.preview_path, f"{label}: PNG Preview")
if result.svg_path:
display_file_if_possible(result.svg_path, f"{label}: SVG")
if result.mxgraph_path:
display_file_if_possible(result.mxgraph_path, f"{label}: mxGraph XML")
report_candidates = []
for candidate in [result.svg_path, result.mxgraph_path, result.preview_path]:
if candidate:
report_candidates.append(Path(candidate).parent / "generation_report.json")
for report_path in report_candidates:
if report_path.exists():
print("\nGeneration report preview:")
print(safe_read(report_path, max_chars=6000))
try:
import pandas as pd
from IPython.display import display
report = json.loads(report_path.read_text(encoding="utf-8"))
rows = []
for row in report.get("iteration_history", []):
rows.append({
"iteration": row.get("iteration"),
"quality_score": row.get("quality_score"),
"improvement": row.get("improvement"),
"has_critique": row.get("critique") is not None,
})
if rows:
display(pd.DataFrame(rows))
except Exception as exc:
print(f"Could not tabulate report: {exc}")
break
We define utility functions that help us display generated files directly inside Colab, including PNG, SVG, JSON, Markdown, text, and draw.io outputs. We also build an HTML gallery generator so that all AutoFigure outputs can be reviewed on a single, organized page. We then add a result-summary function that prints generation metadata, displays previews, and shows the iteration report in a readable format.
Copy CodeCopiedUse a different Browser
heading("1. Installing AutoFigure and Colab dependencies")
OUTPUT_ROOT.mkdir(parents=True, exist_ok=True)
run("apt-get update -qq", quiet=True)
run(
"apt-get install -y -qq "
"libcairo2 libpango-1.0-0 libpangocairo-1.0-0 "
"libgdk-pixbuf-2.0-0 libffi-dev shared-mime-info",
quiet=True,
)
clear_loaded_modules(["PIL", "autofigure"])
run(f"{sys.executable} -m pip install -q -U pip 'setuptools Restart runtime, then rerun this full cell.")
raise exc
if RUN_MXGRAPH_DEMO:
run(f"{sys.executable} -m playwright install chromium", quiet=True)
sys.path.insert(0, str(REPO_DIR))
heading("2. Importing AutoFigure SDK")
from autofigure import AutoFigureAgent, Config
from autofigure.generator import (
validate_code_syntax,
code_to_png,
get_initial_prompt_template,
)
from autofigure.extractor import MethodologyExtractor
print("AutoFigure imported successfully.")
print(f"Repository directory: {REPO_DIR}")
print(f"Output root: {OUTPUT_ROOT}")
heading("3. Offline SVG preflight: validation and rendering")
preflight_dir = OUTPUT_ROOT / "00_offline_preflight"
preflight_dir.mkdir(parents=True, exist_ok=True)
sample_svg = """
AutoFigure Offline Rendering Check
Text Prompt
method description
AutoFigure
generate → evaluate → refine
Figure
SVG + PNG output
""".strip()
is_valid, validation_message = validate_code_syntax(sample_svg, "svg")
print(f"SVG syntax valid: {is_valid}")
print(f"Validation message: {validation_message}")
sample_svg_path = preflight_dir / "offline_preflight.svg"
sample_png_path = preflight_dir / "offline_preflight.png"
sample_svg_path.write_text(sample_svg, encoding="utf-8")
render_ok, processed_svg = code_to_png(
sample_svg,
str(sample_png_path),
attempt_repair=False,
output_format="svg",
)
print(f"Rendered PNG: {render_ok} -> {sample_png_path}")
display_file_if_possible(sample_png_path, "Offline preflight PNG")
We install the required system packages, resolve Pillow compatibility issues, clone the AutoFigure repository, and install the SDK along with its PDF and web dependencies. We then import AutoFigure’s main classes and generator utilities after confirming that the environment is ready. We also run offline SVG validation and PNG rendering tests to ensure the rendering pipeline works before making any API-based generation calls.
Copy CodeCopiedUse a different Browser
heading("4. Creating a custom reference figure")
reference_dir = OUTPUT_ROOT / "01_custom_references"
reference_dir.mkdir(parents=True, exist_ok=True)
reference_path = reference_dir / "reference_architecture_style.png"
W, H = 1333, 750
img = Image.new("RGB", (W, H), "white")
draw = ImageDraw.Draw(img)
try:
title_font = ImageFont.truetype("DejaVuSans-Bold.ttf", 36)
box_font = ImageFont.truetype("DejaVuSans-Bold.ttf", 24)
small_font = ImageFont.truetype("DejaVuSans.ttf", 18)
except Exception:
title_font = None
box_font = None
small_font = None
draw.text(
(W // 2, 55),
"Reference Layout: Modular Scientific Pipeline",
anchor="mm",
fill="black",
font=title_font,
)
boxes = [
(90, 215, 290, 120, "Input", "documents"),
(365, 215, 290, 120, "Planner", "route by task"),
(640, 215, 290, 120, "Experts", "summary / table / vision"),
(915, 215, 290, 120, "Verifier", "grounded output"),
]
for i, (x, y, bw, bh, title, subtitle) in enumerate(boxes):
draw.rounded_rectangle(
[x, y, x + bw, y + bh],
radius=22,
fill=(245, 245, 245),
outline=(20, 20, 20),
width=3,
)
draw.text(
(x + bw / 2, y + 45),
title,
anchor="mm",
fill="black",
font=box_font,
)
draw.text(
(x + bw / 2, y + 82),
subtitle,
anchor="mm",
fill=(70, 70, 70),
font=small_font,
)
if i
ax = x + bw + 20
ay = y + bh / 2
bx
今日のまとめ
AIデイリーブリーフで今日の重要ニュースをまとめ読み