Python Defterleri
Jupyter Defteri Entegrasyonu
Özel zenginleştirmeler, veri analizi ve makine öğrenimi iş akışları için Jupyter defterlerini entegre edin.
Defter Detaylarını Al
GET /api/{tenantId}/{projectId}/notebook/{notebookId}
Bir Jupyter defterinin hücreleri, yürütme durumu ve entegrasyon parametreleri dahil olmak üzere kapsamlı bilgilerini alır.
Parametreler
| Parametre | Tür | Konum | Açıklama |
|---|---|---|---|
tenantId |
GUID | Yol | Kiracı kimliği |
projectId |
GUID | Yol | Proje kimliği |
notebookId |
GUID | Yol | Defter kimliği |
Yanıt
{
"notebookId": "aa0e8400-e29b-41d4-a716-446655440000",
"projectId": "660e8400-e29b-41d4-a716-446655440000",
"notebookName": "Süreç Madenciliği Analizi",
"notebookDescription": "Müşteri yolculuğunu optimize etmek için özel analiz",
"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
}
Tüm Defterleri Listele
GET /api/{tenantId}/{projectId}/notebooks
Projede bulunan tüm Jupyter defterlerinin temel meta verileri ve yürütme durumlarını alır.
Sorgu Parametreleri
| Parametre | Tür | Açıklama |
|---|---|---|
status |
string | Duruma göre filtrele: Ready, Running, Error, Kernel_Dead |
kernelType |
string | Kernel türüne göre filtrele: python3, r, scala |
enrichmentMode |
boolean | Veri zenginleştirme için yapılandırılmış defterleri filtrele |
page |
integer | Sayfa numarası (varsayılan: 1) |
pageSize |
integer | Sayfa başına öğe sayısı (varsayılan: 20, maksimum: 100) |
Yanıt
{
"notebooks": [
{
"notebookId": "aa0e8400-e29b-41d4-a716-446655440000",
"notebookName": "Süreç Madenciliği Analizi",
"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
}
Yeni Defter Oluştur
POST /api/{tenantId}/{projectId}/notebook
Belirtilen yapılandırma ve isteğe bağlı şablonla yeni bir Jupyter defteri oluşturur. Defter otomatik olarak mindzie veri entegrasyonu için yapılandırılır.
İstek Gövdesi
{
"notebookName": "Gelişmiş Müşteri Analitiği",
"notebookDescription": "Müşteri davranışı tahmini için makine öğrenimi modelleri",
"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": "# Müşteri Analitiği Defteri\n\nBu defter, süreç madenciliği teknikleri kullanarak müşteri yolculuğu verilerini analiz eder."
},
{
"cellType": "code",
"content": "import pandas as pd\nimport numpy as np\nfrom mindzie_sdk import ProcessMiningClient\n\n# mindzie istemcisini başlat\nclient = ProcessMiningClient()"
}
]
}
Yanıt
Oluşturulan defterin tam nesnesi, üretildiği notebook ID ve başlangıç oturumu bilgileri ile birlikte 201 Created döner.
Defteri Çalıştır
POST /api/{tenantId}/{projectId}/notebook/{notebookId}/execute
Defterdeki tüm hücreleri veya belirtilen hücre aralığını çalıştırır. Çalıştırma asenkron olarak yürütülür ve sonuçlar alınmak üzere saklanır.
İstek Gövdesi
{
"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"
}
Yanıt
{
"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
}
}
Yürütme Durumunu Al
GET /api/{tenantId}/{projectId}/notebook/{notebookId}/execution/{executionId}
Defter yürütmesinin mevcut durumunu ve ilerlemesini, hücre bazında yürütme detayları ve varsa hata bilgileriyle birlikte alır.
Yanıt
{
"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' sütunu veri setinde bulunamadı"
}
],
"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"
}
}
Yürütme Sonuçlarını Al
GET /api/{tenantId}/{projectId}/notebook/{notebookId}/execution/{executionId}/results
Tamamlanmış defter yürütmesinden çıktıları ve sonuçları, oluşturulan verileri, çizimleri ve zenginleştirilmiş veri setlerini alır.
Sorgu Parametreleri
| Parametre | Tür | Açıklama |
|---|---|---|
outputType |
string | Çıktı türüne göre filtrele: all, data, plots, models, reports |
format |
string | Yanıt biçimi: summary, detailed, download |
cellId |
string | Sadece belirli hücrenin sonuçlarını al |
Yanıt
{
"executionId": "bb0e8400-e29b-41d4-a716-446655440000",
"status": "Completed",
"outputs": [
{
"cellId": "cell-002",
"outputType": "display_data",
"contentType": "text/html",
"title": "Veri Seti Genel Bakışı",
"content": "<div>Veri seti 15,420 kayıt içermektedir...</div>",
"downloadUrl": "https://api.mindzie.com/downloads/cell-002-bb0e8400.html"
},
{
"cellId": "cell-005",
"outputType": "image/png",
"title": "Müşteri Yolculuğu Akış Şeması",
"dimensions": {"width": 800, "height": 600},
"downloadUrl": "https://api.mindzie.com/downloads/cell-005-bb0e8400.png"
},
{
"cellId": "cell-008",
"outputType": "application/json",
"title": "Süreç Madenciliği Ölçütleri",
"content": {
"avgCycleTime": "4.2 saat",
"bottleneckActivities": ["Başvuruyu İnceleme", "Yönetici Onayı"],
"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": "Müşteri Analitiği Özeti",
"format": "html",
"downloadUrl": "https://api.mindzie.com/downloads/report-bb0e8400.html"
}
]
}
Defteri Güncelle
PUT /api/{tenantId}/{projectId}/notebook/{notebookId}
Defter yapılandırmasını, hücreleri veya entegrasyon ayarlarını günceller. Hücrelerde yapılan değişiklikler yeni defter sürümü oluşturur.
İstek Gövdesi
{
"notebookName": "Gelişmiş Müşteri Analitiği v2",
"notebookDescription": "Gerçek zamanlı tahmin özellikli geliştirilmiş ML modelleri",
"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"]
}
}
Yanıt
Güncellenmiş defter nesnesi, sürüm numarası artırılmış ve değişiklik zaman damgalarıyla geri döner.
Defteri Sil
DELETE /api/{tenantId}/{projectId}/notebook/{notebookId}
Bir defteri ve tüm yürütme geçmişini kalıcı olarak siler. Bu işlem geri alınamaz ve halihazırda çalışan yürütmeleri durdurur.
Yanıt Kodları
204 No Content- Defter başarıyla silindi404 Not Found- Defter bulunamadı veya erişim reddedildi409 Conflict- Defter şu anda çalışıyor ve silinemez
Mevcut Defteri Yükle
POST /api/{tenantId}/{projectId}/notebook/upload
Mevcut bir Jupyter defteri (.ipynb dosyası) yükler ve mindzie entegrasyonu için yapılandırır. Defter ayrıştırılır ve hücreler doğrulanır.
İstek (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"
Müşteri Yolculuğu Analizi
--boundary
Content-Disposition: form-data; name="enrichmentMode"
true
--boundary
Content-Disposition: form-data; name="datasetBinding"
880e8400-e29b-41d4-a716-446655440000
--boundary--
Yanıt
Yüklenen defter nesnesi, ayrıştırma sonuçları ve varsa doğrulama uyarıları dahil olmak üzere 201 Created döner.
Örnek: Tam Defter İş Akışı
Bu örnek, bir Jupyter defteri oluşturmayı, çalıştırmayı ve sonuçlarını almayı gösterir:
// 1. Yeni bir defter oluştur
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: 'Süreç Madenciliği Analizi',
notebookDescription: 'Süreç optimizasyonu için gelişmiş analizler',
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: '# Süreç Madenciliği Analizi\n\nSüreç verimliliği ve darboğazların analizi.'
},
{
cellType: 'code',
content: 'import pandas as pd\nfrom mindzie_sdk import ProcessMiningClient\n\nclient = ProcessMiningClient()'
}
]
})
});
return await response.json();
};
// 2. Defteri çalıştır
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. Yürütme ilerlemesini izle
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(`Durum: ${execution.status}, İlerleme: ${execution.progress.percentComplete}%`);
if (execution.status === 'Running') {
setTimeout(() => checkStatus(), 15000);
} else if (execution.status === 'Completed') {
console.log('Defter yürütmesi tamamlandı!');
await getNotebookResults(notebookId, executionId);
} else if (execution.status === 'Error') {
console.log('Yürütme başarısız:', execution.cellResults.filter(c => c.status === 'Error'));
}
};
await checkStatus();
};
// 4. Yürütme sonuçlarını al
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('Yürütme Sonuçları:', results);
console.log('Zenginleştirilmiş Veri Setleri:', results.enrichedDatasets);
console.log('Oluşturulan Modeller:', results.models);
return results;
};
// İş akışını çalıştır
createNotebook()
.then(notebook => {
console.log(`Oluşturulan defter: ${notebook.notebookId}`);
return executeNotebook(notebook.notebookId);
})
.then(execution => {
console.log(`Yürütme başlatıldı: ${execution.executionId}`);
return monitorNotebookExecution(execution.notebookId, execution.executionId);
})
.catch(error => console.error('Defter iş akışı başarısız:', error));
Python Örneği
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):
"""Yeni bir Jupyter defteri oluşturur"""
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):
"""Mevcut bir defter dosyasını yükler"""
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 ''
}
# Multipart yükleme için Content-Type başlığını kaldır
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):
"""Defterdeki tüm hücreleri çalıştırır"""
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):
"""Defter yürütme durumunu alır"""
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):
"""Defter yürütmesinin tamamlanmasını bekler"""
start_time = time.time()
while time.time() - start_time < timeout:
status = self.get_execution_status(notebook_id, execution_id)
print(f"Defter {notebook_id}: {status['status']} ({status['progress']['percentComplete']}%)")
if status['status'] in ['Completed', 'Error', 'Cancelled']:
return status
time.sleep(poll_interval)
raise TimeoutError(f"Defter yürütmesi {execution_id} {timeout} saniye içinde tamamlanmadı")
def get_execution_results(self, notebook_id, execution_id, output_type="all", format_type="detailed"):
"""Defter yürütme sonuçlarını alır"""
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):
"""Tüm defterleri isteğe bağlı filtreyle listeler"""
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()
# Kullanım örneği
manager = NotebookManager(
'https://your-mindzie-instance.com',
'tenant-guid',
'project-guid',
'your-auth-token'
)
try:
# Süreç madenciliği defteri oluştur
notebook = manager.create_notebook(
'Gelişmiş Süreç Analitiği',
'Anomali tespiti ile makine öğrenimi tabanlı süreç analizi',
'python3',
'process_mining_starter',
{
'enrichmentMode': True,
'datasetBinding': 'dataset-guid',
'outputFormat': 'enriched_dataframe',
'autoExecution': False
}
)
print(f"Oluşturulan defter: {notebook['notebookId']}")
# Özel parametrelerle çalıştır
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 dakika
)
print(f"Yürütme başlatıldı: {execution['executionId']}")
print(f"Tahmini süre: {execution['estimatedDuration']}")
# Tamamlanmasını bekle
final_status = manager.wait_for_completion(
notebook['notebookId'],
execution['executionId']
)
if final_status['status'] == 'Completed':
# Ayrıntılı sonuçları al
results = manager.get_execution_results(
notebook['notebookId'],
execution['executionId'],
'all',
'detailed'
)
print("Defter yürütmesi başarıyla tamamlandı!")
print(f"Oluşturulan çıktı sayısı: {len(results['outputs'])}")
print(f"Zenginleştirilmiş veri seti sayısı: {len(results['enrichedDatasets'])}")
print(f"Oluşturulan ML modeli sayısı: {len(results['models'])}")
# Zenginleştirilmiş verileri indir
for dataset in results['enrichedDatasets']:
print(f"Zenginleştirilmiş veriyi indir: {dataset['downloadUrl']}")
# Modelleri indir
for model in results['models']:
print(f"'{model['name']}' modeli indir: {model['downloadUrl']}")
else:
print(f"Defter yürütmesi {final_status['status']} durumuyla başarısız oldu")
failed_cells = [cell for cell in final_status['cellResults'] if cell['status'] == 'Error']
for cell in failed_cells:
print(f"{cell['cellId']} hücresi başarısız oldu: {cell['errorMessage']}")
except Exception as e:
print(f"Defter iş akışında hata: {e}")