Metadata-Version: 2.4
Name: privabase
Version: 1.0.0
Summary: Python SDK for the PrivaBase privacy and compliance API
Home-page: https://github.com/privabase/privabase-python-sdk
Author: PrivaBase
Author-email: PrivaBase <support@privabase.com>
License: MIT
Project-URL: Homepage, https://privabase.com
Project-URL: Documentation, https://privabase.com/docs
Project-URL: Repository, https://github.com/privabase/privabase-python-sdk
Project-URL: Bug Tracker, https://github.com/privabase/privabase-python-sdk/issues
Keywords: privacy,compliance,gdpr,ccpa,data-protection,compliance-management
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: requests>=2.28.0
Provides-Extra: async
Requires-Dist: httpx>=0.23.0; extra == "async"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=3.0.0; extra == "dev"
Requires-Dist: responses>=0.20.0; extra == "dev"
Requires-Dist: black>=22.0.0; extra == "dev"
Requires-Dist: flake8>=4.0.0; extra == "dev"
Requires-Dist: mypy>=0.950; extra == "dev"
Dynamic: author
Dynamic: home-page
Dynamic: license-file
Dynamic: requires-python

# PrivaBase Python SDK

A comprehensive Python SDK for the PrivaBase privacy and compliance API. Build, manage, and maintain compliance across multiple frameworks (GDPR, CCPA, and more) with ease.

[![Python Version](https://img.shields.io/badge/python-3.8+-blue)](https://www.python.org/downloads/)
[![License](https://img.shields.io/badge/license-MIT-green)](LICENSE)

## Features

- 🔐 **Type-safe**: Full type hints throughout (Python 3.8+)
- ⚡ **Automatic Retries**: Exponential backoff with rate limit handling
- 📊 **Comprehensive**: Covers compliance, documents, frameworks, DSR, monitoring, vendors, and trust center
- 🔄 **Context Manager**: Proper resource management with `with` statement
- 📝 **Well Documented**: Detailed docstrings and examples
- 🧪 **Fully Tested**: Comprehensive test suite with mocked HTTP

## Installation

```bash
pip install privabase
```

### Optional Dependencies

For async support:
```bash
pip install privabase[async]
```

For development:
```bash
pip install privabase[dev]
```

## Quick Start

```python
from privabase import PrivaBase

# Initialize the client
client = PrivaBase(api_key="pk_your_api_key")

# Check compliance
result = client.compliance.check(
    framework="gdpr",
    data_practices={
        "collects_personal_data": True,
        "has_privacy_policy": True,
        "data_retention_defined": False
    }
)

print(f"Compliant: {result.compliant}")
print(f"Score: {result.score}")
print(f"Recommendations: {result.recommendations}")
```

## API Reference

### Client Initialization

```python
client = PrivaBase(
    api_key="pk_xxx",  # Required
    base_url="https://privacy-compliance-api.vercel.app",  # Optional
    timeout=30,  # Optional, seconds
    max_retries=3  # Optional, automatic retries
)
```

### Compliance Module

#### Check Compliance

```python
result = client.compliance.check(
    framework="gdpr",
    data_practices={
        "collects_personal_data": True,
        "has_privacy_policy": True,
        "data_retention_defined": False
    }
)

# Returns ComplianceResult
print(result.compliant)  # bool
print(result.score)  # float (0-1)
print(result.issues)  # List of issues
print(result.recommendations)  # List of recommendations
```

#### Scan Privacy Policy

```python
scan = client.compliance.scan_policy("https://example.com/privacy")

print(scan.found)  # bool
print(scan.content)  # str or None
print(scan.issues)  # List of issues found
print(scan.score)  # float
```

#### Get Compliance Report

```python
report = client.compliance.get_report("gdpr")
print(report)
```

### Documents Module

#### Generate Document

```python
doc = client.documents.generate(
    template="gdpr-privacy-policy",
    data={
        "company_name": "Acme Inc",
        "website": "https://acme.com",
        "contact_email": "privacy@acme.com"
    },
    format="pdf"  # or "docx", "markdown"
)

print(doc.id)  # Document ID
print(doc.url)  # Download URL
print(doc.content)  # Document content
```

#### List Templates

```python
templates = client.documents.list_templates()
for template in templates:
    print(f"{template['id']}: {template['name']}")
```

#### Get Template Details

```python
template = client.documents.get_template("gdpr-privacy-policy")
print(template['required_fields'])
print(template['description'])
```

#### Regenerate Document

```python
doc = client.documents.regenerate(
    document_id="doc_123",
    data={"company_name": "New Name"}
)
```

#### Delete Document

```python
success = client.documents.delete("doc_123")
```

### Frameworks Module

#### List All Frameworks

```python
frameworks = client.frameworks.list()
for fw in frameworks:
    print(f"{fw.name} (v{fw.version})")
    print(f"  Regions: {', '.join(fw.regions)}")
    print(f"  Categories: {', '.join(fw.categories)}")
```

#### Get Framework Details

```python
framework = client.frameworks.get("gdpr")
print(framework.description)
print(framework.regions)  # List of applicable regions
```

#### List by Region

```python
eu_frameworks = client.frameworks.list_by_region("EU")
```

#### Search Frameworks

```python
results = client.frameworks.search("data protection")
```

### DSR (Data Subject Request) Module

#### Create DSR

```python
dsr = client.dsr.create(
    type="access",  # or "deletion", "portability", "rectification"
    email="user@example.com",
    framework="gdpr",
    metadata={"reason": "user initiated"}
)

print(dsr.id)
print(dsr.status)  # "pending", "in_progress", "completed", "denied"
```

#### Get DSR

```python
dsr = client.dsr.get("dsr_123")
print(dsr.status)
print(dsr.updated_at)
```

#### List DSRs

```python
pending_requests = client.dsr.list(
    framework="gdpr",
    status="pending"
)
```

#### Update DSR Status

```python
dsr = client.dsr.update_status("dsr_123", "completed")
```

#### Delete DSR

```python
success = client.dsr.delete("dsr_123")
```

### Monitoring Module

#### Create Monitoring Schedule

```python
schedule = client.monitoring.create_schedule(
    framework="gdpr",
    frequency="weekly",  # or "daily", "monthly"
    enabled=True
)

print(schedule.id)
print(schedule.next_check)
```

#### Get Schedule

```python
schedule = client.monitoring.get_schedule("sched_123")
```

#### List Schedules

```python
schedules = client.monitoring.list_schedules(
    framework="gdpr",
    enabled=True
)
```

#### Update Schedule

```python
schedule = client.monitoring.update_schedule(
    "sched_123",
    frequency="daily",
    enabled=False
)
```

#### Delete Schedule

```python
success = client.monitoring.delete_schedule("sched_123")
```

#### Run Manual Check

```python
result = client.monitoring.run_check("sched_123")
```

### Vendors Module

#### Assess Vendor

```python
risk = client.vendors.assess_vendor(
    vendor_name="Cloud Storage Provider",
    categories=["data_security", "compliance"]
)

print(risk.risk_level)  # "low", "medium", "high", "critical"
print(risk.score)  # 0-1
print(risk.recommendations)
```

#### Get Vendor Assessment

```python
risk = client.vendors.get_vendor("vendor_123")
```

#### List Vendors

```python
risky_vendors = client.vendors.list_vendors(risk_level="high")
```

#### Reassess Vendor

```python
risk = client.vendors.reassess_vendor("vendor_123")
```

#### Delete Vendor

```python
success = client.vendors.delete_vendor("vendor_123")
```

### Trust Center Module

#### Get Trust Center Info

```python
info = client.trust_center.get_info()

print(info.certifications)  # List of certifications
print(info.compliance_frameworks)  # Supported frameworks
print(info.security_practices)  # List of practices
print(info.data_centers)  # Data center information
```

#### Get Certifications

```python
certs = client.trust_center.get_certifications()
```

#### Get Compliance Status

```python
status = client.trust_center.get_compliance_status()
```

#### Get Security Practices

```python
practices = client.trust_center.get_security_practices()
```

#### Get Data Center Info

```python
dc_info = client.trust_center.get_data_center_info()
```

## Error Handling

The SDK provides specific exception classes for different error scenarios:

```python
from privabase import (
    PrivaBaseError,
    AuthenticationError,
    RateLimitError,
    ValidationError,
    NotFoundError,
    ServerError,
)

try:
    result = client.compliance.check(...)
except AuthenticationError:
    print("Invalid API key")
except RateLimitError as e:
    print(f"Rate limited. Retry after {e.retry_after} seconds")
except ValidationError as e:
    print(f"Invalid request: {e.message}")
except NotFoundError:
    print("Resource not found")
except ServerError:
    print("Server error, please try again")
except PrivaBaseError as e:
    print(f"API error: {e.message}")
```

## Context Manager

Use the client as a context manager for proper resource cleanup:

```python
with PrivaBase(api_key="pk_xxx") as client:
    result = client.compliance.check(...)
    # Resources are automatically cleaned up
```

## Automatic Retries

The SDK automatically retries failed requests with exponential backoff:

- **Rate limit errors (429)**: Always retried
- **Other errors**: Retried up to `max_retries` times
- **Exponential backoff**: Delay = 1s × 2^(attempt-1), up to `Retry-After` header

```python
client = PrivaBase(
    api_key="pk_xxx",
    max_retries=3  # Default
)
```

## Type Hints

All responses include proper type hints:

```python
from privabase import (
    ComplianceResult,
    Framework,
    Document,
    DSRRequest,
    MonitoringSchedule,
    VendorRisk,
    TrustCenterInfo,
    PolicyScan,
)

# IDE autocomplete and type checking work seamlessly
result: ComplianceResult = client.compliance.check(...)
frameworks: List[Framework] = client.frameworks.list()
```

## Testing

Run the test suite:

```bash
pytest tests/
```

With coverage:

```bash
pytest tests/ --cov=privabase --cov-report=html
```

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add amazing feature'`)
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## License

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

## Support

- **Documentation**: https://privabase.com/docs
- **GitHub Issues**: https://github.com/privabase/privabase-python-sdk/issues
- **Email**: support@privabase.com

## Changelog

### 1.0.0 (2024-02-10)
- Initial release
- Compliance checking
- Document generation
- Framework listing
- DSR management
- Monitoring schedules
- Vendor risk assessment
- Trust center information
