Metadata-Version: 2.4
Name: privacypal-sdk
Version: 1.0.1
Summary: Official Python SDK for the PrivacyPal Data Twins API — encode and decode PII with synthetic privacy twins.
Author: PrivacyPal
License: MIT
Project-URL: Homepage, https://github.com/PrivacyPal/privacypal-cloud
Project-URL: Documentation, https://docs.privacypal.com
Project-URL: Repository, https://github.com/PrivacyPal/privacypal-cloud
Project-URL: Issues, https://github.com/PrivacyPal/privacypal-cloud/issues
Keywords: privacypal,privacy,data-twins,pii,encryption,sdk
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.28.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: responses>=0.25.0; extra == "dev"

# PrivacyPal SDK

Official Python SDK for the PrivacyPal Data Twins API.

## Overview

PrivacyPal SDK provides a simple interface for encoding sensitive data into synthetic "privacy twins" and decoding them back to original values with proper authorization. This enables safe handling of PII (Personally Identifiable Information) in your agents and applications.

## Features

- **Secure PII Handling** - Automatically detects and replaces sensitive data with synthetic twins
- **Bidirectional Flow** - Encode sensitive data and decode it back when authorized
- **Batch Processing** - Process multiple records efficiently
- **File Upload Support** - Encode PII in PDFs, DOCX, CSV, images, and more
- **Easy Integration** - Simple, intuitive Pythonic API

## Installation

```bash
pip install privacypal-sdk
```

## Quick Start

### Natural Language Prompts

PrivacyPal works seamlessly with **natural language prompts and instructions**:

```python
from privacypal_sdk import PrivacyPalClient

# Initialize the client
client = PrivacyPalClient(
    api_url="https://api.privacypal.ai",
    api_key="your-jwt-token",
)

# Your natural language prompt with embedded PII
prompt = (
    "I want to analyze the average credit debt that John Doe would experience "
    "being that his credit is poor even though his income is high. When completed "
    "draft an email to john@email.com so we can send this report to him."
)

# Encode: Automatically detects and protects PII
result = client.encode(
    data=prompt,
    source_container="ai_prompts.credit_analysis",
)

print("Protected:", result["encodedData"])
# "...analyze the average credit debt that Jane Smith would experience..."
# "...draft an email to jane.smith@example.com..."

print("Continuation ID:", result["continuationId"])
print("PII Protected:", len(result["transformations"]), "entities")

# Decode back to original (with authorization)
decoded = client.decode(
    continuation_id=result["continuationId"],
    data=result["encodedData"],
    sensitive_hashes=[t["originalHash"] for t in result["transformations"]],
    authorization={
        "token": "your-jwt-token",
        "purpose": "Credit analysis report generation",
    },
)

print("Original:", decoded["decodedData"])
# Exact original prompt perfectly restored
```

### Simple PII List

You can also encode simple lists of sensitive data:

```python
result = client.encode(
    data="John Doe, SSN: 123-45-6789, email: john@company.com",
    source_container="customer_db.users",
    metadata={"rowId": "1001"},
)
```

## API Reference

### Client Initialization

```python
client = PrivacyPalClient(
    api_url="https://api.privacypal.ai",  # PrivacyPal API base URL
    api_key="your-jwt-token",              # JWT access token
    timeout=30,                            # Request timeout in seconds (default: 30)
)
```

### Encoding

#### `client.encode(...)`

Encode a single data item containing sensitive information.

**Parameters:**
- `data` — Input text containing potential PII
- `source_container` — Source identifier (e.g. `"customer_db.users"`)
- `source_element` — Element identifier (e.g. `"personal_info"`)
- `metadata` — Additional metadata dict (`rowId`, `sourceTable`, etc.)
- `score_threshold` — PII detection threshold (default: `0.35`)
- `language` — Language code (default: `"en"`)
- `continuation_id` — Optional ID for correlation

**Returns** a dict:
- `encodedData` — Data with PII replaced by synthetic twins
- `continuationId` — ID for later decoding
- `transformations` — List of transformations applied
- `statistics` — Processing statistics

**Example:**
```python
result = client.encode(
    data="Patient: Alice Johnson, DOB: 03/15/1985, SSN: 987-65-4321",
    source_container="medical_db.patients",
    metadata={"rowId": "P12345", "recordType": "patient_intake"},
)
```

#### `client.encode_batch(items)`

Encode multiple data items in a single request. All items share the same `continuationId`.

**Example:**
```python
result = client.encode_batch([
    {
        "data": "Employee: Bob Williams, SSN: 111-22-3333",
        "source_container": "hr_db.employees",
        "metadata": {"rowId": "E001"},
    },
    {
        "data": "Employee: Carol Davis, SSN: 444-55-6666",
        "source_container": "hr_db.employees",
        "metadata": {"rowId": "E002"},
    },
])
```

#### `client.encode_file(file_content, file_name, ...)`

Encode a file by uploading it for server-side PII detection. Supports PDF, DOCX, CSV, images, and more.

**Example:**
```python
with open("report.pdf", "rb") as f:
    result = client.encode_file(f.read(), "report.pdf")
```

### Decoding

#### `client.decode(...)`

Decode synthetic twins back to original sensitive data (requires authorization).

**Parameters:**
- `continuation_id` — ID from the encoding response
- `data` — Data containing synthetic twins
- `sensitive_hashes` — List of original value hashes to decode
- `authorization` — Dict with `token` and `purpose` keys

**Returns** a dict:
- `decodedData` — Data with twins replaced by originals
- `transformations` — List of decoded transformations
- `auditLog` — Audit information
- `statistics` — Processing statistics

**Example:**
```python
result = client.decode(
    continuation_id="abc-123-def",
    data=encode_result["encodedData"],
    sensitive_hashes=[t["originalHash"] for t in encode_result["transformations"]],
    authorization={
        "token": "jwt-token",
        "purpose": "Medical records review for patient care",
    },
)
```

### Dataset Management

#### `client.get_dataset_twins(continuation_id)`

Retrieve all data twins for a specific dataset.

**Example:**
```python
result = client.get_dataset_twins("abc-123-def")
print(f"Found {result['count']} twins")
for twin in result["twins"]:
    print(twin["entityType"], twin["catalogItemId"])
```

### Configuration Methods

#### `client.update_api_key(new_api_key)`

Update the API key for authentication.

#### `client.update_api_url(new_api_url)`

Update the API base URL.

#### `client.get_config()`

Get the current configuration as a dict.

## Entity Types

The SDK detects and handles various PII entity types:

- `PERSON` — Person names
- `EMAIL_ADDRESS` — Email addresses
- `PHONE_NUMBER` — Phone numbers
- `US_SSN` — US Social Security Numbers
- `CREDIT_CARD` — Credit card numbers
- `LOCATION` — Addresses and locations
- `DATE_TIME` — Dates and timestamps
- `IP_ADDRESS` — IP addresses
- And more...

## Error Handling

The SDK provides a structured exception hierarchy:

```python
from privacypal_sdk import (
    PrivacyPalError,
    AuthenticationError,
    TrialExpiredError,
    NetworkError,
    RequestError,
)

try:
    result = client.encode(data="...")
except AuthenticationError:
    print("Invalid or expired token")
except TrialExpiredError:
    print("Subscription required")
except NetworkError:
    print("Cannot reach the API")
except PrivacyPalError as e:
    print(f"API error: {e}")
```

## Best Practices

1. **Store Continuation IDs** — Always save the `continuationId` for later decoding
2. **Store Hashes** — Keep track of `originalHash` values from transformations for selective decoding
3. **Authorization Purpose** — Provide clear, specific purposes for audit trails
4. **Batch Processing** — Use `encode_batch` for multiple records to improve performance
5. **Error Handling** — Always wrap API calls in try/except blocks

## Performance

Typical latencies:
- **Encoding**: 70–280ms per record
- **Decoding**: 20–65ms per record
- **Batch Encoding**: 50–200ms average per record
- **Get Dataset Twins**: 10–30ms

## License

MIT

## Support

For issues and questions:
- GitHub: [PrivacyPal/privacypal-cloud](https://github.com/PrivacyPal/privacypal-cloud)
- Documentation: [docs.privacypal.com](https://docs.privacypal.com)
