Pythonノートブック

Jupyterノートブック統合

カスタムの強化、データ分析、機械学習ワークフローのためにJupyterノートブックを統合します。

ノートブック詳細の取得

GET /api/{tenantId}/{projectId}/notebook/{notebookId}

Jupyterノートブックのセル、実行状態、統合パラメータを含む包括的な情報を取得します。

パラメータ

パラメータ 場所 説明
tenantId GUID パス テナント識別子
projectId GUID パス プロジェクト識別子
notebookId GUID パス ノートブック識別子

レスポンス

{
  "notebookId": "aa0e8400-e29b-41d4-a716-446655440000",
  "projectId": "660e8400-e29b-41d4-a716-446655440000",
  "notebookName": "Process Mining Analysis",
  "notebookDescription": "カスタマー ジャーニー最適化のためのカスタム分析",
  "notebookVersion": "1.3.2",
  "kernelType": "python3",
  "status": "Ready",
  "integration": {
    "enrichmentMode": true,
    "datasetBinding": "880e8400-e29b-41d4-a716-446655440000",
    "outputFormat": "enriched_dataframe",
    "autoExecution": false
  },
  "cells": [
    {
      "cellId": "cell-001",
      "cellType": "code",
      "executionCount": 15,
      "hasOutput": true,
      "lastExecuted": "2024-01-20T10:30:00Z",
      "executionStatus": "Success"
    },
    {
      "cellId": "cell-002",
      "cellType": "markdown",
      "lastModified": "2024-01-19T14:20:00Z"
    }
  ],
  "environment": {
    "pythonVersion": "3.9.18",
    "packages": ["pandas", "numpy", "scikit-learn", "mindzie-sdk"],
    "customLibraries": ["process_mining_utils", "customer_analytics"]
  },
  "dateCreated": "2024-01-15T10:30:00Z",
  "dateModified": "2024-01-20T10:30:00Z",
  "createdBy": "user123",
  "lastExecutionDate": "2024-01-20T10:30:00Z",
  "executionCount": 47
}

すべてのノートブック一覧

GET /api/{tenantId}/{projectId}/notebooks

プロジェクト内のすべてのJupyterノートブックの基本メタデータおよび実行状態のリストを取得します。

クエリパラメータ

パラメータ 説明
status string ステータスでフィルター: Ready, Running, Error, Kernel_Dead
kernelType string カーネルタイプでフィルター: python3, r, scala
enrichmentMode boolean データ強化設定されたノートブックでフィルター
page integer ページ番号(デフォルト: 1)
pageSize integer 1ページあたりの項目数(デフォルト: 20、最大: 100)

レスポンス

{
  "notebooks": [
    {
      "notebookId": "aa0e8400-e29b-41d4-a716-446655440000",
      "notebookName": "Process Mining Analysis",
      "kernelType": "python3",
      "status": "Ready",
      "enrichmentMode": true,
      "cellCount": 12,
      "lastExecutionDate": "2024-01-20T10:30:00Z",
      "dateCreated": "2024-01-15T10:30:00Z"
    }
  ],
  "totalCount": 8,
  "page": 1,
  "pageSize": 20,
  "hasNextPage": false
}

新しいノートブックの作成

POST /api/{tenantId}/{projectId}/notebook

指定された設定およびオプションのテンプレートで新しいJupyterノートブックを作成します。ノートブックは自動的にmindzieデータ統合用に設定されます。

リクエストボディ

{
  "notebookName": "Advanced Customer Analytics",
  "notebookDescription": "顧客行動予測のための機械学習モデル",
  "kernelType": "python3",
  "template": "process_mining_starter",
  "integration": {
    "enrichmentMode": true,
    "datasetBinding": "880e8400-e29b-41d4-a716-446655440000",
    "outputFormat": "enriched_dataframe",
    "autoExecution": false
  },
  "environment": {
    "packages": ["pandas", "numpy", "scikit-learn", "matplotlib", "seaborn"],
    "customLibraries": ["process_mining_utils"]
  },
  "initialCells": [
    {
      "cellType": "markdown",
      "content": "# Customer Analytics Notebook\n\nこのノートブックはプロセスマイニング技術を使用して顧客ジャーニーデータを分析します。"
    },
    {
      "cellType": "code",
      "content": "import pandas as pd\nimport numpy as np\nfrom mindzie_sdk import ProcessMiningClient\n\n# mindzieクライアントの初期化\nclient = ProcessMiningClient()"
    }
  ]
}

レスポンス

作成されたノートブックIDおよび初期セッション情報を含む完全なノートブックオブジェクトと共に201 Createdを返します。

ノートブックの実行

POST /api/{tenantId}/{projectId}/notebook/{notebookId}/execute

ノートブック内のすべてのセルまたは指定されたセル範囲を実行します。実行は非同期で行われ、結果は取得のため保存されます。

リクエストボディ

{
  "executionMode": "all",
  "cellRange": {
    "startCell": "cell-001",
    "endCell": "cell-010"
  },
  "parameters": {
    "dataset_id": "880e8400-e29b-41d4-a716-446655440000",
    "analysis_period": "2024-01",
    "include_weekends": false
  },
  "outputOptions": {
    "captureOutputs": true,
    "saveIntermediateResults": true,
    "generateReport": true
  },
  "timeout": 1800,
  "priority": "Normal"
}

レスポンス

{
  "executionId": "bb0e8400-e29b-41d4-a716-446655440000",
  "notebookId": "aa0e8400-e29b-41d4-a716-446655440000",
  "status": "Running",
  "startTime": "2024-01-20T10:30:00Z",
  "estimatedDuration": "15-20 minutes",
  "currentCell": "cell-003",
  "progress": {
    "totalCells": 12,
    "completedCells": 2,
    "currentCellIndex": 3,
    "percentComplete": 17
  },
  "parameters": {
    "dataset_id": "880e8400-e29b-41d4-a716-446655440000",
    "analysis_period": "2024-01",
    "include_weekends": false
  }
}

実行状態の取得

GET /api/{tenantId}/{projectId}/notebook/{notebookId}/execution/{executionId}

ノートブック実行の現在の状態および進捗を、セルごとの実行詳細とエラー情報とともに取得します。

レスポンス

{
  "executionId": "bb0e8400-e29b-41d4-a716-446655440000",
  "notebookId": "aa0e8400-e29b-41d4-a716-446655440000",
  "status": "Completed",
  "startTime": "2024-01-20T10:30:00Z",
  "endTime": "2024-01-20T10:47:00Z",
  "totalDuration": "17 minutes",
  "progress": {
    "totalCells": 12,
    "completedCells": 12,
    "successfulCells": 11,
    "failedCells": 1,
    "percentComplete": 100
  },
  "cellResults": [
    {
      "cellId": "cell-001",
      "status": "Success",
      "executionTime": "0.5 seconds",
      "hasOutput": false
    },
    {
      "cellId": "cell-002",
      "status": "Success",
      "executionTime": "3.2 seconds",
      "hasOutput": true,
      "outputType": "display_data"
    },
    {
      "cellId": "cell-003",
      "status": "Error",
      "executionTime": "1.1 seconds",
      "errorType": "KeyError",
      "errorMessage": "'customer_id' 列がデータセットに存在しません"
    }
  ],
  "outputs": {
    "dataFrames": 3,
    "plots": 5,
    "models": 2,
    "enrichedData": {
      "recordCount": 15420,
      "newColumns": ["customer_segment", "journey_score", "anomaly_flag"]
    }
  },
  "resources": {
    "peakMemoryUsage": "2.3 GB",
    "cpuTime": "8.5 minutes",
    "diskUsage": "450 MB"
  }
}

実行結果の取得

GET /api/{tenantId}/{projectId}/notebook/{notebookId}/execution/{executionId}/results

完了したノートブック実行の出力および結果を、生成されたデータ、プロット、強化されたデータセットを含めて取得します。

クエリパラメータ

パラメータ 説明
outputType string 出力タイプでフィルター: all, data, plots, models, reports
format string レスポンス形式: summary, detailed, download
cellId string 特定のセルの結果のみ取得

レスポンス

{
  "executionId": "bb0e8400-e29b-41d4-a716-446655440000",
  "status": "Completed",
  "outputs": [
    {
      "cellId": "cell-002",
      "outputType": "display_data",
      "contentType": "text/html",
      "title": "データセット概要",
      "content": "<div>データセットは15,420件のレコードを含みます...</div>",
      "downloadUrl": "https://api.mindzie.com/downloads/cell-002-bb0e8400.html"
    },
    {
      "cellId": "cell-005",
      "outputType": "image/png",
      "title": "カスタマー ジャーニーフローチャート",
      "dimensions": {"width": 800, "height": 600},
      "downloadUrl": "https://api.mindzie.com/downloads/cell-005-bb0e8400.png"
    },
    {
      "cellId": "cell-008",
      "outputType": "application/json",
      "title": "プロセスマイニング指標",
      "content": {
        "avgCycleTime": "4.2 hours",
        "bottleneckActivities": ["Review Application", "Manager Approval"],
        "processEfficiency": 78.5,
        "customerSatisfactionScore": 8.2
      },
      "downloadUrl": "https://api.mindzie.com/downloads/cell-008-bb0e8400.json"
    }
  ],
  "enrichedDatasets": [
    {
      "name": "customer_journey_enhanced",
      "recordCount": 15420,
      "newColumns": ["customer_segment", "journey_score", "anomaly_flag"],
      "format": "pandas_dataframe",
      "downloadUrl": "https://api.mindzie.com/downloads/enriched-bb0e8400.csv"
    }
  ],
  "models": [
    {
      "name": "customer_churn_predictor",
      "modelType": "RandomForestClassifier",
      "accuracy": 0.87,
      "features": ["journey_score", "cycle_time", "touchpoint_count"],
      "downloadUrl": "https://api.mindzie.com/downloads/model-bb0e8400.pkl"
    }
  ],
  "reports": [
    {
      "name": "Customer Analytics Summary",
      "format": "html",
      "downloadUrl": "https://api.mindzie.com/downloads/report-bb0e8400.html"
    }
  ]
}

ノートブックの更新

PUT /api/{tenantId}/{projectId}/notebook/{notebookId}

ノートブックの設定、セル、統合設定を更新します。セルの変更は新しいノートブックバージョンをトリガーします。

リクエストボディ

{
  "notebookName": "Advanced Customer Analytics v2",
  "notebookDescription": "リアルタイム予測機能を備えた強化されたMLモデル",
  "integration": {
    "enrichmentMode": true,
    "datasetBinding": "880e8400-e29b-41d4-a716-446655440000",
    "outputFormat": "enriched_dataframe",
    "autoExecution": true,
    "scheduleExecution": "0 2 * * *"
  },
  "environment": {
    "packages": ["pandas", "numpy", "scikit-learn", "tensorflow", "matplotlib"],
    "customLibraries": ["process_mining_utils", "ml_models"]
  }
}

レスポンス

バージョン番号のインクリメントと修正日時を含む更新されたノートブックオブジェクトを返します。

ノートブックの削除

DELETE /api/{tenantId}/{projectId}/notebook/{notebookId}

ノートブックとそのすべての実行履歴を完全に削除します。この操作は元に戻せず、実行中の処理は停止します。

レスポンスコード

  • 204 No Content - ノートブックを正常に削除しました
  • 404 Not Found - ノートブックが見つからないかアクセス権がありません
  • 409 Conflict - ノートブックは実行中のため削除できません

既存ノートブックのアップロード

POST /api/{tenantId}/{projectId}/notebook/upload

既存のJupyterノートブック(.ipynbファイル)をアップロードし、mindzie統合用に設定します。ノートブックは解析され、セルが検証されます。

リクエスト(マルチパートフォームデータ)

Content-Type: multipart/form-data

--boundary
Content-Disposition: form-data; name="file"; filename="analysis.ipynb"
Content-Type: application/json

{notebook content}
--boundary
Content-Disposition: form-data; name="notebookName"

カスタマージャーニー分析
--boundary
Content-Disposition: form-data; name="enrichmentMode"

true
--boundary
Content-Disposition: form-data; name="datasetBinding"

880e8400-e29b-41d4-a716-446655440000
--boundary--

レスポンス

解析結果と検証警告を含むアップロードされたノートブックオブジェクトと共に201 Createdを返します。

例:ノートブックの完全なワークフロー

この例はJupyterノートブックの作成、実行、結果取得を示します:

// 1. 新規ノートブック作成
const createNotebook = async () => {
  const response = await fetch('/api/{tenantId}/{projectId}/notebook', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      notebookName: 'Process Mining Analysis',
      notebookDescription: 'プロセス最適化のための高度な分析',
      kernelType: 'python3',
      template: 'process_mining_starter',
      integration: {
        enrichmentMode: true,
        datasetBinding: '880e8400-e29b-41d4-a716-446655440000',
        outputFormat: 'enriched_dataframe',
        autoExecution: false
      },
      environment: {
        packages: ['pandas', 'numpy', 'scikit-learn', 'matplotlib'],
        customLibraries: ['process_mining_utils']
      },
      initialCells: [
        {
          cellType: 'markdown',
          content: '# Process Mining Analysis\n\nプロセス効率とボトルネックを分析します。'
        },
        {
          cellType: 'code',
          content: 'import pandas as pd\nfrom mindzie_sdk import ProcessMiningClient\n\nclient = ProcessMiningClient()'
        }
      ]
    })
  });

  return await response.json();
};

// 2. ノートブック実行
const executeNotebook = async (notebookId) => {
  const response = await fetch(`/api/{tenantId}/{projectId}/notebook/${notebookId}/execute`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      executionMode: 'all',
      parameters: {
        dataset_id: '880e8400-e29b-41d4-a716-446655440000',
        analysis_period: '2024-01',
        include_weekends: false
      },
      outputOptions: {
        captureOutputs: true,
        saveIntermediateResults: true,
        generateReport: true
      },
      timeout: 1800,
      priority: 'High'
    })
  });

  return await response.json();
};

// 3. 実行進捗の監視
const monitorNotebookExecution = async (notebookId, executionId) => {
  const checkStatus = async () => {
    const response = await fetch(`/api/{tenantId}/{projectId}/notebook/${notebookId}/execution/${executionId}`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    const execution = await response.json();
    console.log(`ステータス: ${execution.status}, 進捗: ${execution.progress.percentComplete}%`);

    if (execution.status === 'Running') {
      setTimeout(() => checkStatus(), 15000);
    } else if (execution.status === 'Completed') {
      console.log('ノートブックの実行が完了しました!');
      await getNotebookResults(notebookId, executionId);
    } else if (execution.status === 'Error') {
      console.log('実行失敗:', execution.cellResults.filter(c => c.status === 'Error'));
    }
  };

  await checkStatus();
};

// 4. 実行結果の取得
const getNotebookResults = async (notebookId, executionId) => {
  const response = await fetch(`/api/{tenantId}/{projectId}/notebook/${notebookId}/execution/${executionId}/results?format=detailed`, {
    headers: {
      'Authorization': `Bearer ${token}`
    }
  });

  const results = await response.json();
  console.log('実行結果:', results);
  console.log('強化データセット:', results.enrichedDatasets);
  console.log('生成されたモデル:', results.models);

  return results;
};

// ワークフローの実行
createNotebook()
  .then(notebook => {
    console.log(`作成されたノートブック: ${notebook.notebookId}`);
    return executeNotebook(notebook.notebookId);
  })
  .then(execution => {
    console.log(`実行開始: ${execution.executionId}`);
    return monitorNotebookExecution(execution.notebookId, execution.executionId);
  })
  .catch(error => console.error('ノートブックワークフロー失敗:', error));

Python例

import requests
import time
import json
from pathlib import Path

class NotebookManager:
    def __init__(self, base_url, tenant_id, project_id, token):
        self.base_url = base_url
        self.tenant_id = tenant_id
        self.project_id = project_id
        self.headers = {
            'Authorization': f'Bearer {token}',
            'Content-Type': 'application/json'
        }

    def create_notebook(self, name, description, kernel_type="python3", template=None, integration=None):
        """新しいJupyterノートブックを作成"""
        url = f"{self.base_url}/api/{self.tenant_id}/{self.project_id}/notebook"
        payload = {
            'notebookName': name,
            'notebookDescription': description,
            'kernelType': kernel_type,
            'template': template,
            'integration': integration or {
                'enrichmentMode': True,
                'outputFormat': 'enriched_dataframe',
                'autoExecution': False
            }
        }
        response = requests.post(url, json=payload, headers=self.headers)
        return response.json()

    def upload_notebook(self, file_path, name, dataset_binding=None):
        """既存ノートブックファイルをアップロード"""
        url = f"{self.base_url}/api/{self.tenant_id}/{self.project_id}/notebook/upload"

        with open(file_path, 'rb') as file:
            files = {'file': (Path(file_path).name, file, 'application/json')}
            data = {
                'notebookName': name,
                'enrichmentMode': 'true',
                'datasetBinding': dataset_binding or ''
            }
            # マルチパートアップロードのためContent-Typeヘッダーを除去
            headers = {k: v for k, v in self.headers.items() if k != 'Content-Type'}
            response = requests.post(url, files=files, data=data, headers=headers)

        return response.json()

    def execute_notebook(self, notebook_id, parameters=None, timeout=1800):
        """ノートブックのすべてのセルを実行"""
        url = f"{self.base_url}/api/{self.tenant_id}/{self.project_id}/notebook/{notebook_id}/execute"
        payload = {
            'executionMode': 'all',
            'parameters': parameters or {},
            'outputOptions': {
                'captureOutputs': True,
                'saveIntermediateResults': True,
                'generateReport': True
            },
            'timeout': timeout,
            'priority': 'Normal'
        }
        response = requests.post(url, json=payload, headers=self.headers)
        return response.json()

    def get_execution_status(self, notebook_id, execution_id):
        """ノートブック実行のステータスを取得"""
        url = f"{self.base_url}/api/{self.tenant_id}/{self.project_id}/notebook/{notebook_id}/execution/{execution_id}"
        response = requests.get(url, headers=self.headers)
        return response.json()

    def wait_for_completion(self, notebook_id, execution_id, poll_interval=15, timeout=3600):
        """ノートブック実行完了まで待機"""
        start_time = time.time()

        while time.time() - start_time < timeout:
            status = self.get_execution_status(notebook_id, execution_id)
            print(f"ノートブック {notebook_id}: {status['status']} ({status['progress']['percentComplete']}%)")

            if status['status'] in ['Completed', 'Error', 'Cancelled']:
                return status

            time.sleep(poll_interval)

        raise TimeoutError(f"ノートブック実行 {execution_id} は {timeout} 秒以内に完了しませんでした")

    def get_execution_results(self, notebook_id, execution_id, output_type="all", format_type="detailed"):
        """ノートブック実行結果を取得"""
        url = f"{self.base_url}/api/{self.tenant_id}/{self.project_id}/notebook/{notebook_id}/execution/{execution_id}/results"
        params = {
            'outputType': output_type,
            'format': format_type
        }
        response = requests.get(url, params=params, headers=self.headers)
        return response.json()

    def list_notebooks(self, status=None, enrichment_mode=None, page=1, page_size=20):
        """オプションでフィルタリングしながらノートブックの一覧を取得"""
        url = f"{self.base_url}/api/{self.tenantId}/{self.projectId}/notebooks"
        params = {'page': page, 'pageSize': page_size}

        if status:
            params['status'] = status
        if enrichment_mode is not None:
            params['enrichmentMode'] = str(enrichment_mode).lower()

        response = requests.get(url, params=params, headers=self.headers)
        return response.json()

# 使用例
manager = NotebookManager(
    'https://your-mindzie-instance.com',
    'tenant-guid',
    'project-guid',
    'your-auth-token'
)

try:
    # プロセスマイニング用ノートブックを作成
    notebook = manager.create_notebook(
        'Advanced Process Analytics',
        '異常検知を含む機械学習ベースのプロセス分析',
        'python3',
        'process_mining_starter',
        {
            'enrichmentMode': True,
            'datasetBinding': 'dataset-guid',
            'outputFormat': 'enriched_dataframe',
            'autoExecution': False
        }
    )

    print(f"作成されたノートブック: {notebook['notebookId']}")

    # カスタムパラメータで実行
    execution_params = {
        'dataset_id': 'dataset-guid',
        'analysis_type': 'full_analysis',
        'time_window': '30_days',
        'ml_models': ['anomaly_detection', 'process_prediction'],
        'generate_visualizations': True
    }

    execution = manager.execute_notebook(
        notebook['notebookId'],
        execution_params,
        timeout=2400  # 40分
    )

    print(f"実行開始: {execution['executionId']}")
    print(f"推定所要時間: {execution['estimatedDuration']}")

    # 完了まで待機
    final_status = manager.wait_for_completion(
        notebook['notebookId'],
        execution['executionId']
    )

    if final_status['status'] == 'Completed':
        # 詳細結果を取得
        results = manager.get_execution_results(
            notebook['notebookId'],
            execution['executionId'],
            'all',
            'detailed'
        )

        print("ノートブック実行は正常に完了しました!")
        print(f"生成された出力数: {len(results['outputs'])}")
        print(f"強化データセット数: {len(results['enrichedDatasets'])}")
        print(f"作成されたMLモデル数: {len(results['models'])}")

        # 強化データのダウンロード
        for dataset in results['enrichedDatasets']:
            print(f"強化データダウンロード: {dataset['downloadUrl']}")

        # モデルのダウンロード
        for model in results['models']:
            print(f"モデル '{model['name']}' のダウンロード: {model['downloadUrl']}")

    else:
        print(f"ノートブック実行は失敗しました。ステータス: {final_status['status']}")
        failed_cells = [cell for cell in final_status['cellResults'] if cell['status'] == 'Error']
        for cell in failed_cells:
            print(f"セル {cell['cellId']} が失敗: {cell['errorMessage']}")

except Exception as e:
    print(f"ノートブックワークフローでエラー発生: {e}")