2Slides Logo
Pythonでプレゼンテーションを自動生成:2Slides APIチュートリアル
2Slides Team
3 min read

Pythonでプレゼンテーション生成を自動化: 2Slides APIチュートリアル

Pythonは、自動化、データパイプライン、AIワークフローにおいて最もよく使われる言語です。このチュートリアルでは、Pythonから2Slides REST APIを使用して、シンプルな単発のスライドから複雑な自動化パイプラインまで、プレゼンテーションを自動的に生成する方法を紹介します。

前提条件

pip install requests python-dotenv

.env
ファイルを作成します。

TWOSLIDES_API_KEY=sk-2slides-your-api-key

クイックスタート: 最初のスライドを生成する

import os import time import requests from dotenv import load_dotenv load_dotenv() API_KEY = os.getenv('TWOSLIDES_API_KEY') BASE_URL = 'https://2slides.com/api/v1' HEADERS = { 'Authorization': f'Bearer {API_KEY}', 'Content-Type': 'application/json' } def generate_slides(topic, theme_id=None, mode='async'): """テキストのトピックからプレゼンテーションを生成します。""" payload = { 'userInput': topic, 'mode': mode, 'responseLanguage': 'en', 'resolution': '2K', } if theme_id: payload['themeId'] = theme_id response = requests.post( f'{BASE_URL}/slides/generate', headers=HEADERS, json=payload ) response.raise_for_status() return response.json() def wait_for_job(job_id, timeout=300, interval=3): """ジョブが完了するまでポーリングします。""" start = time.time() while time.time() - start < timeout: response = requests.get( f'{BASE_URL}/jobs/{job_id}', headers=HEADERS ) data = response.json() status = data.get('status') print(f' Job {job_id}: {status}') if status == 'success': return data if status == 'failed': raise Exception(f'Job failed: {data}') time.sleep(interval) raise TimeoutError(f'Job {job_id} timed out after {timeout}s') # プレゼンテーションを生成 job = generate_slides('Top 10 AI Trends for 2026') print(f'ジョブID: {job["jobId"]}') result = wait_for_job(job['jobId']) print(f'ダウンロード: {result["downloadUrl"]}')

ドキュメントをスライドに変換する

def convert_file_to_slides(file_url, prompt='', theme_id=None): """PDF、DOCX、XLSX、その他のファイルをスライドに変換します。""" payload = { 'fileUrl': file_url, 'userInput': prompt, 'mode': 'async' } if theme_id: payload['themeId'] = theme_id response = requests.post( f'{BASE_URL}/slides/create-pdf-slides', headers=HEADERS, json=payload ) response.raise_for_status() job = response.json() return wait_for_job(job['jobId']) # 四半期レポートのPDFを変換 result = convert_file_to_slides( file_url='https://your-storage.com/q1-report.pdf', prompt='Executive summary for the board, 10 slides max' ) print(f'ダウンロード: {result["downloadUrl"]}')

デザインを合わせたスライド (Create Like This)

def create_like_this(topic, reference_image_url, resolution='2K'): """参照デザインに合わせたスライドを生成します。""" payload = { 'userInput': topic, 'designStyle': { 'global': { 'referenceImageUrl': reference_image_url } }, 'resolution': resolution, 'mode': 'async' } response = requests.post( f'{BASE_URL}/slides/create-like-this', headers=HEADERS, json=payload ) response.raise_for_status() job = response.json() return wait_for_job(job['jobId']) # ブランドテンプレートに合わせる result = create_like_this( topic='Monthly Team Update — March 2026', reference_image_url='https://your-brand.com/slide-template.png' )

音声ナレーションを追加する

def add_narration(job_id, mode='single', voice='Charon', content_mode='concise'): """既存のスライドにAI音声ナレーションを追加します。""" payload = { 'jobId': job_id, 'mode': mode, 'voice': voice, 'contentMode': content_mode } response = requests.post( f'{BASE_URL}/slides/generate-narration', headers=HEADERS, json=payload ) response.raise_for_status() return response.json() def download_with_audio(job_id): """音声ファイル付きのスライドをダウンロードします。""" response = requests.post( f'{BASE_URL}/slides/download-slides-pages-voices', headers=HEADERS, json={'jobId': job_id} ) response.raise_for_status() return response.json()

テーマを閲覧する

def search_themes(query=''): """利用可能なスライドテーマを検索します。""" params = {'query': query} if query else {} response = requests.get( f'{BASE_URL}/themes', headers=HEADERS, params=params ) response.raise_for_status() return response.json() themes = search_themes('corporate') for theme in themes.get('themes', []): print(f"{theme['id']}: {theme['name']}")

本番パイプラインの例

""" 自動化された週次レポートパイプライン。 cronで実行: 0 9 * * MON python weekly_report.py """ import json from datetime import datetime def weekly_report_pipeline(): print(f'週次レポートを生成中: {datetime.now().isoformat()}') # 1. スライドを生成 job = generate_slides( topic='''Weekly Engineering Update — Week of March 23, 2026: - Deployed v2.4 to production (99.9% uptime) - 3 new API endpoints shipped - Performance: p99 latency down 40% - Sprint velocity: 42 story points (target: 40) - Next week: database migration, new auth system''', theme_id='corporate-standard-id' ) result = wait_for_job(job['jobId']) print(f'スライド準備完了: {result["downloadUrl"]}') # 2. ナレーションを追加 add_narration(job['jobId'], mode='single', voice='Kore') print('ナレーションを追加しました') # 3. パッケージをダウンロード package = download_with_audio(job['jobId']) print(f'完全なパッケージ: {json.dumps(package, indent=2)}') return result['downloadUrl'] if __name__ == '__main__': url = weekly_report_pipeline() print(f'\nレポートURL: {url}')

エラーハンドリングのベストプラクティス

from requests.exceptions import HTTPError, Timeout, ConnectionError def safe_generate(topic, retries=3): """リトライロジック付きでスライドを生成します。""" for attempt in range(retries): try: job = generate_slides(topic) return wait_for_job(job['jobId']) except HTTPError as e: if e.response.status_code == 429: wait = 2 ** attempt * 5 # Exponential backoff print(f'レート制限されました。{wait}秒待機します...') time.sleep(wait) elif e.response.status_code == 402: raise Exception('クレジットが不足しています') else: raise except (Timeout, ConnectionError) as e: print(f'ネットワークエラー (試行 {attempt + 1}): {e}') time.sleep(5) raise Exception(f'{retries}回の再試行後に失敗しました')

よくある質問

必要なPythonのバージョンは?

f-stringsと

requests
の互換性のためにPython 3.7以降が必要です。

async Python (asyncio/aiohttp)は使えますか?

はい、非同期HTTP呼び出しには

requests
aiohttp
に置き換えてください。ポーリングパターンは同じように機能します。

大量のバッチジョブを処理するには?

asyncio
を使用して、レート制限 (60 req/min) を守りながら複数の生成を並行して実行してください。


自動化を始めましょう — 2Slides APIキーを取得して、Pythonからプレゼンテーションを生成しましょう。

About 2Slides

Create stunning AI-powered presentations in seconds. Transform your ideas into professional slides with 2slides AI Agent.

Try For Free