Python-Notebooks

Integration von Jupyter-Notebooks

Integrieren Sie Jupyter-Notebooks für benutzerdefinierte Anreicherungen, Datenanalysen und Workflows für maschinelles Lernen.

Notebook-Details abrufen

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

Ruft umfassende Informationen über ein Jupyter-Notebook ab, einschließlich seiner Zellen, Ausführungsstatus und Integrationsparameter.

Parameter

Parameter Typ Ort Beschreibung
tenantId GUID Pfad Die Mandantenkennung
projectId GUID Pfad Die Projektkennung
notebookId GUID Pfad Die Notebookkennung

Antwort

{
  "notebookId": "aa0e8400-e29b-41d4-a716-446655440000",
  "projectId": "660e8400-e29b-41d4-a716-446655440000",
  "notebookName": "Process Mining Analysis",
  "notebookDescription": "Benutzerdefinierte Analyse zur Optimierung der Customer Journey",
  "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
}

Alle Notebooks auflisten

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

Ruft eine Liste aller Jupyter-Notebooks im Projekt mit grundlegenden Metadaten und Ausführungsstatus ab.

Abfrageparameter

Parameter Typ Beschreibung
status string Nach Status filtern: Ready, Running, Error, Kernel_Dead
kernelType string Nach Kernel-Typ filtern: python3, r, scala
enrichmentMode boolean Filter für Notebooks, die für Datenanreicherung konfiguriert sind
page integer Seitennummer für die Paginierung (Standard: 1)
pageSize integer Anzahl der Elemente pro Seite (Standard: 20, max.: 100)

Antwort

{
  "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
}

Neues Notebook erstellen

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

Erstellt ein neues Jupyter-Notebook mit spezifizierter Konfiguration und optionaler Vorlage. Das Notebook wird automatisch für die mindzie-Datenintegration konfiguriert.

Anfragetext

{
  "notebookName": "Advanced Customer Analytics",
  "notebookDescription": "Machine-Learning-Modelle zur Vorhersage des Kundenverhaltens",
  "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\nDieses Notebook analysiert Daten zur Customer Journey mit Prozess-Mining-Techniken."
    },
    {
      "cellType": "code",
      "content": "import pandas as pd\nimport numpy as np\nfrom mindzie_sdk import ProcessMiningClient\n\n# Initialisiere mindzie client\nclient = ProcessMiningClient()"
    }
  ]
}

Antwort

Gibt 201 Created zurück mit dem vollständigen Notebook-Objekt inklusive generierter Notebook-ID und initialer Sitzungsinformationen.

Notebook ausführen

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

Führt alle Zellen im Notebook oder einen angegebenen Zellbereich aus. Die Ausführung läuft asynchron und die Ergebnisse werden zur Abfrage gespeichert.

Anfragetext

{
  "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"
}

Antwort

{
  "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
  }
}

Ausführungsstatus abrufen

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

Ruft den aktuellen Status und Fortschritt einer Notebook-Ausführung ab, einschließlich zellenspezifischer Ausführungsdetails und Fehler.

Antwort

{
  "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' Spalte wurde im Datensatz nicht gefunden"
    }
  ],
  "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"
  }
}

Ausführungsergebnisse abrufen

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

Ruft die Ausgaben und Ergebnisse einer abgeschlossenen Notebook-Ausführung ab, inklusive generierter Daten, Diagramme und angereicherter Datensätze.

Abfrageparameter

Parameter Typ Beschreibung
outputType string Nach Ausgabetyp filtern: all, data, plots, models, reports
format string Antwortformat: summary, detailed, download
cellId string Ergebnisse nur von bestimmter Zelle abrufen

Antwort

{
  "executionId": "bb0e8400-e29b-41d4-a716-446655440000",
  "status": "Completed",
  "outputs": [
    {
      "cellId": "cell-002",
      "outputType": "display_data",
      "contentType": "text/html",
      "title": "Datensatzübersicht",
      "content": "<div>Datensatz enthält 15.420 Einträge...</div>",
      "downloadUrl": "https://api.mindzie.com/downloads/cell-002-bb0e8400.html"
    },
    {
      "cellId": "cell-005",
      "outputType": "image/png",
      "title": "Customer Journey Flussdiagramm",
      "dimensions": {"width": 800, "height": 600},
      "downloadUrl": "https://api.mindzie.com/downloads/cell-005-bb0e8400.png"
    },
    {
      "cellId": "cell-008",
      "outputType": "application/json",
      "title": "Process Mining Metriken",
      "content": {
        "avgCycleTime": "4.2 Stunden",
        "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"
    }
  ]
}

Notebook aktualisieren

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

Aktualisiert Notebook-Konfiguration, Zellen oder Integrationseinstellungen. Änderungen an Zellen lösen eine neue Notebook-Version aus.

Anfragetext

{
  "notebookName": "Advanced Customer Analytics v2",
  "notebookDescription": "Verbesserte ML-Modelle mit Echtzeit-Vorhersagefunktionen",
  "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"]
  }
}

Antwort

Gibt das aktualisierte Notebook-Objekt mit inkrementierter Versionsnummer und Änderungszeitstempeln zurück.

Notebook löschen

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

Entfernt dauerhaft ein Notebook und dessen gesamte Ausführungshistorie. Dieser Vorgang kann nicht rückgängig gemacht werden und stoppt laufende Ausführungen.

Antwortcodes

  • 204 No Content - Notebook erfolgreich gelöscht
  • 404 Not Found - Notebook nicht gefunden oder Zugriff verweigert
  • 409 Conflict - Notebook wird derzeit ausgeführt und kann nicht gelöscht werden

Bestehendes Notebook hochladen

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

Lädt eine bestehende Jupyter-Notebook-Datei (.ipynb) hoch und konfiguriert sie für mindzie-Integration. Das Notebook wird geparst und Zellen werden validiert.

Anfrage (Multipart Form Data)

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"

Customer Journey Analysis
--boundary
Content-Disposition: form-data; name="enrichmentMode"

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

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

Antwort

Gibt 201 Created zurück mit dem hochgeladenen Notebook-Objekt einschließlich Parsergebnissen und Validierungswarnungen.

Beispiel: Komplett-Workflow mit Notebook

Dieses Beispiel zeigt, wie man ein Jupyter-Notebook erstellt, ausführt und Ergebnisse abruft:

// 1. Neues Notebook erstellen
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: 'Erweiterte Analysen zur Prozessoptimierung',
      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\nAnalyse der Prozesseffizienz und Engpässe.'
        },
        {
          cellType: 'code',
          content: 'import pandas as pd\nfrom mindzie_sdk import ProcessMiningClient\n\nclient = ProcessMiningClient()'
        }
      ]
    })
  });

  return await response.json();
};

// 2. Notebook ausführen
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. Ausführungsfortschritt überwachen
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(`Status: ${execution.status}, Fortschritt: ${execution.progress.percentComplete}%`);

    if (execution.status === 'Running') {
      setTimeout(() => checkStatus(), 15000);
    } else if (execution.status === 'Completed') {
      console.log('Notebook-Ausführung abgeschlossen!');
      await getNotebookResults(notebookId, executionId);
    } else if (execution.status === 'Error') {
      console.log('Ausführung fehlgeschlagen:', execution.cellResults.filter(c => c.status === 'Error'));
    }
  };

  await checkStatus();
};

// 4. Ausführungsergebnisse abrufen
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('Ausführungsergebnisse:', results);
  console.log('Angereicherte Datensätze:', results.enrichedDatasets);
  console.log('Generierte Modelle:', results.models);

  return results;
};

// Workflow ausführen
createNotebook()
  .then(notebook => {
    console.log(`Notebook erstellt: ${notebook.notebookId}`);
    return executeNotebook(notebook.notebookId);
  })
  .then(execution => {
    console.log(`Ausführung gestartet: ${execution.executionId}`);
    return monitorNotebookExecution(execution.notebookId, execution.executionId);
  })
  .catch(error => console.error('Notebook-Workflow fehlgeschlagen:', error));

Python-Beispiel

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):
        """Erstellt ein neues Jupyter-Notebook"""
        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):
        """Lädt eine bestehende Notebook-Datei hoch"""
        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 ''
            }
            # Entferne Content-Type Header für Multipart-Upload
            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):
        """Führt alle Zellen in einem Notebook aus"""
        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):
        """Ruft den Ausführungsstatus eines Notebooks ab"""
        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):
        """Wartet, bis die Notebook-Ausführung abgeschlossen ist"""
        start_time = time.time()

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

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

            time.sleep(poll_interval)

        raise TimeoutError(f"Notebook-Ausführung {execution_id} wurde nicht innerhalb von {timeout} Sekunden abgeschlossen")

    def get_execution_results(self, notebook_id, execution_id, output_type="all", format_type="detailed"):
        """Ruft Ausführungsergebnisse eines Notebooks ab"""
        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):
        """Listet alle Notebooks mit optionalen Filtern auf"""
        url = f"{self.base_url}/api/{self.tenant_id}/{self.project_id}/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()

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

try:
    # Erstellt ein Process Mining Notebook
    notebook = manager.create_notebook(
        'Advanced Process Analytics',
        'Machine Learning basierte Prozessanalyse mit Anomalieerkennung',
        'python3',
        'process_mining_starter',
        {
            'enrichmentMode': True,
            'datasetBinding': 'dataset-guid',
            'outputFormat': 'enriched_dataframe',
            'autoExecution': False
        }
    )

    print(f"Notebook erstellt: {notebook['notebookId']}")

    # Ausführung mit benutzerdefinierten Parametern
    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 Minuten
    )

    print(f"Ausführung gestartet: {execution['executionId']}")
    print(f"Geschätzte Dauer: {execution['estimatedDuration']}")

    # Auf Abschluss warten
    final_status = manager.wait_for_completion(
        notebook['notebookId'],
        execution['executionId']
    )

    if final_status['status'] == 'Completed':
        # Detaillierte Ergebnisse abrufen
        results = manager.get_execution_results(
            notebook['notebookId'],
            execution['executionId'],
            'all',
            'detailed'
        )

        print("Notebook-Ausführung erfolgreich abgeschlossen!")
        print(f"Generierte Ausgaben: {len(results['outputs'])}")
        print(f"Angereicherte Datensätze: {len(results['enrichedDatasets'])}")
        print(f"Erstellte ML-Modelle: {len(results['models'])}")

        # Angereicherte Daten herunterladen
        for dataset in results['enrichedDatasets']:
            print(f"Angereicherte Daten herunterladen: {dataset['downloadUrl']}")

        # Modelle herunterladen
        for model in results['models']:
            print(f"Modell '{model['name']}' herunterladen: {model['downloadUrl']}")

    else:
        print(f"Notebook-Ausführung fehlgeschlagen mit Status: {final_status['status']}")
        failed_cells = [cell for cell in final_status['cellResults'] if cell['status'] == 'Error']
        for cell in failed_cells:
            print(f"Zelle {cell['cellId']} fehlgeschlagen: {cell['errorMessage']}")

except Exception as e:
    print(f"Fehler im Notebook-Workflow: {e}")