Metadata-Version: 2.4
Name: superb-ai-onprem
Version: 2.0.3
Summary: Python SDK for Superb AI On-premise
Home-page: https://github.com/Superb-AI-Suite/superb-ai-onprem-python
Author: Superb AI
Author-email: support@superb-ai.com
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.22.0
Requires-Dist: urllib3>=1.21.1
Requires-Dist: pydantic>=1.8.0
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# 🚀 Superb AI On-premise Python SDK

![Python](https://img.shields.io/badge/python-3.7+-blue.svg)
![License](https://img.shields.io/badge/license-MIT-green.svg)
![Version](https://img.shields.io/pypi/v/superb-ai-onprem.svg)

**Superb AI On-premise Python SDK** is a comprehensive Python library that provides a simple and intuitive interface to interact with your on-premise Superb AI installation. Build powerful data management, annotation, and machine learning workflows with ease.

## 🌟 Key Features

- **🗂️ Dataset Management**: Create, organize, and manage your datasets
- **📊 Data Operations**: Upload, annotate, and manipulate your data with powerful filtering
- **🔍 Advanced Filtering**: Sophisticated filtering system for precise data queries  
- **🏷️ Annotation Management**: Handle annotations and versions seamlessly
- **📁 Content Management**: Upload and manage file content
- **⚡ Activity Tracking**: Monitor and manage long-running tasks
- **🔧 Slice Management**: Organize data into logical groups
- **🤖 Model Tracking**: Register and monitor ML model performance
- **📈 Analytics Reports**: Generate and visualize dataset analytics

모델 생성·수정과 조회 필터에는 `ModelTaskType`을 사용합니다. `VLM`은 시각·언어 이해 모델을, `VISION_GENERATION`은 이미지·영상 생성 모델을 나타냅니다. 생성 모델 타입으로 API를 호출하려면 서버에도 해당 타입 지원이 반영되어 있어야 합니다.

## 🔧 Installation

### Step 1: Install the SDK

Install the SDK using pip:

```bash
pip install superb-ai-onprem
```

**Requirements:**
- Python 3.7 or higher
- Active Superb AI On-premise installation

> ⚠️ **Important**: The SDK will not work without this configuration file. Make sure to replace the values with your actual credentials from your Superb AI administrator.

## 🚀 Quick Start

Get up and running with Superb AI SDK in minutes:

### Step 1: Authentication Setup

First, set up your authentication credentials:

**Option A: Config file (Recommended for local development)**
```bash
# Create config directory
mkdir -p ~/.spb

# Create config file
cat > ~/.spb/onprem-config << EOF
[default]
host=https://your-superb-ai-host.com
access_key=your-access-key
access_key_secret=your-access-key-secret
EOF
```

### Step 2: Your First Workflow

```python
from spb_onprem import DatasetService, DataService, ModelService, ReportService

# Initialize services
dataset_service = DatasetService()
data_service = DataService()
model_service = ModelService()
report_service = ReportService()

# 1. Find existing datasets
datasets, cursor, total = dataset_service.get_datasets(length=10)
print(f"📂 Found {total} datasets")

if datasets:
    # Use the first available dataset
    dataset = datasets[0]
    print(f"✅ Using dataset: {dataset.name} (ID: {dataset.id})")
    
    # 2. Get data list from the dataset
    data_list, cursor, total = data_service.get_data_list(
        dataset_id=dataset.id,
        length=10
    )
    
    print(f"📊 Dataset contains {total} data items")
    
    # 3. Display data information
    for i, data in enumerate(data_list, 1):
        print(f"  {i}. Key: {data.key}, Type: {data.type}, ID: {data.id}")
        
    if total > len(data_list):
        print(f"  ... and {total - len(data_list)} more items")
    
    # 4. Check models in the dataset
    models, _, model_count = model_service.get_models(
        dataset_id=dataset.id,
        length=5
    )
    
    if model_count > 0:
        print(f"\n🤖 Found {model_count} models")
        for model in models:
            print(f"  - {model.name} ({model.baseline_model})")
    
    # 5. Check analytics reports
    reports, _, report_count = report_service.get_analytics_reports(
        dataset_id=dataset.id,
        length=5
    )
    
    if report_count > 0:
        print(f"\n📈 Found {report_count} analytics reports")
        for report in reports:
            print(f"  - {report.title}")
else:
    print("❌ No datasets found. Please create a dataset first.")
```

**🎉 Congratulations!** You've successfully:
- ✅ Connected to your Superb AI instance
- ✅ Found existing datasets
- ✅ Retrieved and displayed data information
- ✅ Explored models and reports

Ready for more? Check out our [comprehensive documentation](#-documentation) below!

## 🗑️ Deleting (changed in 2.0.0)

Deleting no longer removes rows at once. Each call starts **one** activity
(`DELETE_MODEL`, `DELETE_DIAGNOSIS`, `DELETE_ANALYTICS_REPORT`, `DELETE_SLICE`,
`DELETE_DATA`, `REMOVE_DATA_FROM_SLICE`, `DELETE_DATASET`, `DELETE_MODEL_DEPLOYMENT`) and returns its
`ActivityHistory` instead of `bool` (or `Data` for `remove_data_from_slice`). The
delete activities also delete the files in storage; `REMOVE_DATA_FROM_SLICE` only
takes data out of a slice and deletes no files.

| Function | Targets (exactly one) |
| --- | --- |
| `ModelService.delete_models(dataset_id, ...)` | `model_ids=[...]` or `model_filter=ModelFilter(...)` |
| `DiagnosisService.delete_diagnoses(dataset_id, ...)` | `diagnosis_ids=[...]` or `diagnosis_filter=DiagnosisFilter(...)` |
| `ReportService.delete_analytics_reports(dataset_id, ...)` | `report_ids=[...]` or `report_filter=AnalyticsReportsFilter(...)` |
| `SliceService.delete_slices(dataset_id, ...)` | `slice_ids=[...]` or `slice_filter=SlicesFilter(...)` |
| `DataService.delete_data(dataset_id, ...)` | `data_id`, `data_ids=[...]` or `data_filter=DataListFilter(...)` |
| `DataService.remove_data_from_slice(dataset_id, ..., slice_id=...)` | `data_id`, `data_ids=[...]` or `data_filter=...` |
| `DatasetService.delete_dataset(dataset_id)` | the dataset |
| `ModelDeploymentService.delete_model_deployments(dataset_id, ...)` (new, `DELETE_MODEL_DEPLOYMENT`) | `deployment_ids=[...]` or `deployment_filter=ModelDeploymentFilter(...)` |

Empty lists and filters without a condition (`{}`, `{"must": {}}`, `must: null`,
`must.idIn: []`) are refused with `BadDeletionTargetError` (a `ValueError`).

**Deprecated:** `delete_model`, `delete_diagnosis`, `delete_analytics_report` and
`delete_slice` still work but warn with `DeprecationWarning` and will be removed in the
next major version. Each call starts one activity, so calling them in a loop starts one
activity per target; pass all the IDs to the plural function instead.

- The history is always truthy, so `if service.delete_x(...)` keeps running, but `bool(...)` no
  longer tells whether anything was deleted (and `== True` is False). Use
  `ActivityService().wait_for_activity(history.id)` and check its `status`.
- The deletion functions never return `False` any more. The SDK refuses malformed targets
  before sending (`BadDeletionTargetError`: empty lists or filters, an empty `idIn`, a non-list
  `idIn`, an unknown `statusIn` value, ...). The platform checks only keys, types and required
  values when the request is made (`InvalidInputError`) and the rest when the activity runs. The targets
  are found when the activity runs: if none match or they are already deleted, the activity
  succeeds without deleting anything; a target that cannot be deleted then (still running, a
  model used by a deployment) is not refused at request time but makes the activity `FAILED`
  (see its `status` and `meta`).
- `ActivityStatus.CANCELLED` is now an alias of `CANCELED`; its value is `"CANCELED"`, so
  comparing a status with the string `"CANCELLED"` is False.
- Progress and errors show in the Activity log. A non-admin of the dataset submits the
  activity as `AWAITING_APPROVAL`; an admin (Owner, WorkspaceAdmin, DATASET-ADMIN) starts it at once.
- To block until the deletion ends, call `ActivityService().wait_for_activity(history.id)`.
- `ContentService.delete_content` is unchanged (a content is a file, not an entity), but it
  raises when storage fails instead of returning `False`.

The server must have the deletion activities (job definitions and base DAGs).
See the "Deletion Activities" section of [Activities](spb_onprem/activities/README.md).

## 📚 Module Documentation

### 🏗️ Core Modules

Comprehensive guides for each SDK module with detailed examples and best practices:

| Module | Purpose | Key Features | Documentation |
|--------|---------|--------------|---------------|
| **📁 Datasets** | Dataset lifecycle management | Create, organize, manage data collections | [📂 Dataset Guide](spb_onprem/datasets/README.md) |
| **📊 Data** | Individual data management | CRUD operations, advanced filtering, annotations | [📊 Data Guide](spb_onprem/data/README.md) |
| **🔪 Slices** | Data organization & filtering | Create filtered views, team collaboration | [🔪 Slice Guide](spb_onprem/slices/README.md) |
| **⚡ Activities** | Workflow & task management | Process automation, progress tracking | [⚡ Activity Guide](spb_onprem/activities/README.md) |
| **🤖 Models** | ML model management | Track models, training configs, performance metrics | [🤖 Model Guide](spb_onprem/models/README.md) |
| **📈 Reports** | Analytics & visualization | Create reports, charts, dashboards | [📈 Report Guide](spb_onprem/reports/README.md) |
| **📊 Charts** | Chart data factory | Generate training metrics visualizations (9 chart types) | [📊 Chart Guide](spb_onprem/charts/README.md) |
| **❓ VLM Settings** | VLM question sets | Dataset and slice question sets, optimistic locking | [❓ VLM Settings Guide](spb_onprem/vlm_settings/README.md) |
| **🚀 Model Deployments** | Serve models on GPUs | Deploy, wait, invoke, stop, start, delete; deployment definitions | [🚀 Model Deployment Guide](spb_onprem/model_deployments/README.md) |

### 🎯 Getting Started Paths

Choose your learning path based on your use case:

#### **📊 Data Management Workflow**
1. Start with [📁 Datasets](spb_onprem/datasets/README.md) - Create and organize your data collections
2. Then explore [📊 Data](spb_onprem/data/README.md) - Manage individual items and annotations  
3. Use [🔪 Slices](spb_onprem/slices/README.md) - Organize data into logical groups

#### **🚀 ML Pipeline Integration**
1. Begin with [📊 Data](spb_onprem/data/README.md) - Understand data structure and filtering
2. Configure [⚡ Activities](spb_onprem/activities/README.md) - Automate labeling and review workflows
3. Track with [🤖 Models](spb_onprem/models/README.md) - Register and monitor model performance
4. Create visualizations with [📊 Charts](spb_onprem/charts/README.md) - Generate training metrics charts
5. Build dashboards with [📈 Reports](spb_onprem/reports/README.md) - Compile analytics reports

#### **👥 Team Collaboration**
1. Setup [📁 Datasets](spb_onprem/datasets/README.md) - Organize team projects  
2. Create [🔪 Slices](spb_onprem/slices/README.md) - Assign work to team members
3. Implement [⚡ Activities](spb_onprem/activities/README.md) - Track progress and quality

### 🔧 Advanced Features

Each module includes:
- **🎯 Quick Start Examples** - Get running immediately
- **📋 Detailed Entity Documentation** - Pydantic models with comprehensive field descriptions  
- **🔍 Advanced Usage Patterns** - Best practices and complex workflows
- **🔗 Cross-Module Integration** - How modules work together
- **⚡ Performance Tips** - Optimization recommendations

### 🌐 Module Relationships

```
📁 Datasets (containers)
├── 📊 Data (individual items) 
│   ├── 🔪 Slices (filtered views)
│   │   └── 🤖 Models (training configs)
│   └── ⚡ Activities (processing workflows)
└── 📈 Reports (analytics & visualizations)
```

### 🆕 New Modules (v2.0+)

| Module | Added | Status | Description |
|--------|-------|--------|-------------|
| **🤖 Models** | v2.0 | ✅ Stable | ML model lifecycle management and performance tracking |
| **📈 Reports** | v2.0 | ✅ Stable | Analytics reports and visualization dashboards |
| **📊 Charts** | v2.0 | ✅ Stable | Chart data factory with 9 chart types for training metrics visualization |

### ⚠️ Deprecated Modules

| Module | Status | Migration Path |
|--------|--------|----------------|
| **InferService** | 🚫 Deprecated | Use [🤖 Models](spb_onprem/models/README.md) for model management and [⚡ Activities](spb_onprem/activities/README.md) for inference workflows |





## ⚠️ Error Handling

The SDK provides specific error types for different scenarios:

```python
from spb_onprem.exceptions import (
    BadParameterError,
    NotFoundError,
    UnknownError
)

try:
    dataset = dataset_service.get_dataset(dataset_id="non-existent-id")
except NotFoundError:
    print("Dataset not found")
except BadParameterError as e:
    print(f"Invalid parameter: {e}")
except UnknownError as e:
    print(f"An unexpected error occurred: {e}")
```


## 🔐 Security notes

- Platform credentials (`Authorization`, or `x-user-email` in system mode) are sent only to the
  platform API host, never to presigned storage URLs, and are dropped when a redirect leaves the host.
  **Exception:** the deprecated `InferService` sends them to `MODEL_ENDPOINT_URL`, whatever its host.
- Platform API requests (GraphQL, model deployment invoke) do not follow redirects, so the credentials
  are never resent to another URL. Write `host` with `https://`: if an `http://` host is redirected
  to `https://`, the SDK raises a `BadResponseError` that says so (following the redirect would turn
  the POST into a GET and fail with an unclear Apollo CSRF 400). Reading a config whose `host` uses
  `http://` (other than a loopback host) gives an `InsecureHostWarning` once. If the server serves
  plain HTTP only, turn it off with
  `warnings.filterwarnings("ignore", category=spb_onprem.exceptions.InsecureHostWarning)`.
- SDK error messages, SDK logs, `SDK_DEBUG_GQL` output and SDK exceptions hide credentials and
  presigned URL signatures (URL query strings).
- On import, the SDK adds a filter to the `urllib3.connectionpool` and `urllib3.util.retry` loggers
  that replaces URL query strings with `<redacted>` in their records, at every level (for example
  the WARNING urllib3 writes when it retries). Other output that shows raw requests, such as
  `http.client` debug printing (`HTTPConnection.debuglevel`), is not covered.

## 🧪 Requirements

- Python >= 3.7
- requests >= 2.22.0
- urllib3 >= 1.21.1
- pydantic >= 1.8.0

## 🤝 Contributing

We welcome contributions to the Superb AI On-premise SDK! Here's how you can help:

### Development Setup

1. **Clone the repository:**
```bash
git clone https://github.com/Superb-AI-Suite/superb-ai-onprem-python.git
cd superb-ai-onprem-python
```

2. **Install development dependencies:**
```bash
pip install -e ".[dev]"
```

### Contribution Guidelines

- **Code Style:** Follow PEP 8 guidelines
- **Testing:** Add tests for new features
- **Documentation:** Update docstrings and README
- **Pull Requests:** Use descriptive titles and include test results

### Reporting Issues

When reporting issues, please include:
- SDK version (`spb_onprem.__version__`)
- Python version
- Error messages and stack traces
- Minimal reproduction example
- Expected vs actual behavior

## 📞 Support

### Community Support
- **GitHub Issues:** [Report bugs and request features](https://github.com/Superb-AI-Suite/superb-ai-onprem-python/issues)
- **Documentation:** [Official API documentation](https://docs.superb-ai.com)

### Enterprise Support
- **Technical Support:** Contact your Superb AI representative
- **Custom Integration:** Professional services available
- **Training:** SDK workshops and onboarding sessions

### Quick Help

**Common Issues:**
- **Authentication errors:** Check config file format and credentials
- **Connection issues:** Verify host URL and network connectivity  
- **Import errors:** Ensure SDK is properly installed (`pip install superb-ai-onprem`)
- **Performance issues:** Use appropriate pagination and filtering

**Need immediate help?** Check our [FAQ section](https://docs.superb-ai.com/faq) or contact support.

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

---

**🚀 Ready to build something amazing?** Start with our [Quick Start Guide](#-quick-start) and explore the powerful features of Superb AI On-premise SDK!

<div align="center">
  <sub>Built with ❤️ by the <a href="https://superb-ai.com">Superb AI</a> team</sub>
</div>

