Download Paper Figures with Sciverse
MultimodalRetrievalBeginner

Download Paper Figures with Sciverse

Extract figure paths from full-text Markdown and fetch binary assets through the resource endpoint

Scenario
Users need to extract figures, tables, experiment plots, or workflow diagrams from papers for reports, presentations, or multimodal RAG.
Estimated calls
~3-10 API calls
Tools
contentresource
Pipeline
content→ Markdown 中 ![](path)→ resource(file_name=path)→ 图片二进制

Input example

Input:
doc_id="paper_xxx"
Need: find figure paths in the full text and download the binary files.

Output example

Downloaded files:
- figures/fig1.png
- figures/fig2.jpg

Each file is fetched through GET /resource?file_name=...

Agent Prompt example

You are a paper asset extraction assistant. Read the paper content, detect figure or table resource paths, then call resource to download each asset. Return local filenames with source metadata.

Implementation steps

Step 1: Set up the environment

Configure token and HTTP client

!pip install httpx
import os
os.environ["SCIVERSE_API_TOKEN"] = "sv-your-token-here"  # 替换为你的真实值

Step 2: Extract figure paths from full text

Read content and parse Markdown image or resource references

import os
import re
import asyncio
import httpx
from pathlib import Path

BASE = "https://api.sciverse.space"
TOKEN = os.environ["SCIVERSE_API_TOKEN"]
HEADERS = {"Authorization": f"Bearer {TOKEN}"}

async def get_content(doc_id: str, offset: int = 0, limit: int = 4000):
    async with httpx.AsyncClient(timeout=30) as client:
        resp = await client.get(
            f"{BASE}/content", headers=HEADERS,
            params={"doc_id": doc_id, "offset": offset, "limit": limit}
        )
        resp.raise_for_status()
        return resp.json()

async def find_doc_id(query: str) -> str:
    """Use agentic-search to get a real doc_id for the figure example."""
    async with httpx.AsyncClient(timeout=30) as client:
        resp = await client.post(
            f"{BASE}/agentic-search",
            headers=HEADERS,
            json={"query": query, "top_k": 3},
        )
        resp.raise_for_status()
        hits = (resp.json().get("hits") or [])
        if not hits:
            raise ValueError(f"No papers found for query: {query}")
        return hits[0]["doc_id"]

async def main():
    # 先通过 agentic-search 获取真实 doc_id
    doc_id = await find_doc_id("AlphaFold2 protein structure")
    result = await get_content(doc_id, offset=0, limit=4000)
    # 注意:响应字段是 text
    markdown_text = result["text"]
    # 提取所有图片路径
    figure_paths = re.findall(r'!\\[.*?\\]\\((.*?)\\)', markdown_text)
    print(f"Found {len(figure_paths)} figures:")
    for p in figure_paths:
        print(f"  {p}")
    return figure_paths

figure_paths = await main()

Step 3: Download figures through resource

Call the resource endpoint for each file_name and save binary output

async def download_resource(file_name: str, save_dir: str = "./figures"):
    """下载资源文件。参数 file_name 为 content 中提取的相对路径"""
    Path(save_dir).mkdir(exist_ok=True)
    async with httpx.AsyncClient(timeout=60) as client:
        resp = await client.get(
            f"{BASE}/resource",
            headers=HEADERS,
            params={"file_name": file_name}  # 注意:参数是 file_name
        )
        resp.raise_for_status()
        local_name = file_name.split("/")[-1]
        save_path = f"{save_dir}/{local_name}"
        Path(save_path).write_bytes(resp.content)
        print(f"  Saved: {save_path} ({len(resp.content)} bytes)")
        return save_path

async def download_all(paths: list):
    results = []
    for p in paths:
        try:
            saved = await download_resource(p)
            results.append(saved)
        except httpx.HTTPStatusError as e:
            print(f"  Failed: {p} ({e.response.status_code})")
    return results

saved_files = await download_all(figure_paths)

Notes

  • Do not guess file_name; use paths returned in content.
  • Cache downloaded assets to avoid repeated binary fetches.
  • Some papers may not expose figures as separate resources.
  • Keep doc_id and figure path together for traceability.
  • For multimodal analysis, pass the downloaded asset to a vision model separately.

FAQ

如何获取论文图表?

先用 content 读取 Markdown 中的图表路径,再用 resource 获取资源文件。

resource API 是否负责图像理解?

不负责,resource 只返回资源,图像理解由上层多模态模型完成。

适合哪些资源?

适合论文中的 Figure、Table、实验图、流程图和补充图表资源。

找不到图表怎么办?

需要先确认论文全文中是否包含可解析的资源路径,再决定是否回退到文本证据。

Next steps

Need an API key?

Create one in Console > Tokens.The same API key works for enabled Sciverse, DianShi, and Skills capabilities, with starter quota available according to account permissions.

Open console