tagmaster-python 1.0.7
A comprehensive Python client for the Tagmaster classification API with project management, category management, AI classification, and analytics
License: MIT
Requires Python: >=3.7
Keywords: tagmaster, classification, api, client, text-analysis, nlp, project-management, category-management, analytics, csv-import-export

# Tagmaster Python Client

A comprehensive Python client library for the Tagmaster classification API. This client provides easy access to all API Key Protected endpoints for project management, category management, classification, and analytics.

## 🚀 Features

- **🔑 API Key Authentication**: Simple authentication using project-specific API keys
- **📁 Project Management**: Full CRUD operations for projects
- **🏷️ Category Management**: Create, update, delete, and manage classification categories
- **🤖 AI Classification**: Text and image classification with confidence scoring
- **📊 Analytics & History**: Comprehensive classification history and statistics
- **📁 CSV Import/Export**: Bulk operations for categories and classification data
- **🔧 Utility Functions**: Health checks, connection testing, and configuration

## 📦 Installation

```bash
pip install tagmaster-python
```

Or install from source:

```bash
git clone https://github.com/tagmaster/tagmaster-python.git
cd tagmaster-python
pip install -e .
```

## 🔑 Quick Start

```python
from tagmaster import TagmasterClassificationClient

# Initialize client with your API key
client = TagmasterClassificationClient(api_key="your-project-api-key")

# Classify text
result = client.classify_text("Customer needs help with password reset")
print(f"Top match: {result['classifications'][0]['category']}")

# Get all projects
projects = client.get_projects()
print(f"Found {len(projects)} projects")
```

## 📚 API Reference

### Initialization

```python
client = TagmasterClassificationClient(
    api_key="your-api-key",
    base_url="https://api.tagmaster.com"  # Optional, defaults to localhost:3001
)
```

### Project Management

#### Get All Projects
```python
projects = client.get_projects()
# Returns: List of project dictionaries
```

#### Get Specific Project
```python
project = client.get_project(project_uuid)
# Returns: Project dictionary or None if not found
```

#### Create Project
```python
project = client.create_project(
    name="My Project",
    description="Project description"
)
# Returns: Created project dictionary
```

#### Update Project
```python
updated_project = client.update_project(
    project_uuid="uuid-here",
    name="New Name",  # Optional
    description="New description"  # Optional
)
# Returns: Updated project dictionary
```

#### Delete Project
```python
success = client.delete_project(project_uuid)
# Returns: True if successful
```

### Category Management

#### Get Categories for Project
```python
categories = client.get_categories(project_uuid)
# Returns: List of category dictionaries
```

#### Get Specific Category
```python
category = client.get_category(project_uuid, category_uuid)
# Returns: Category dictionary or None if not found
```

#### Create Category
```python
category = client.create_category(
    project_uuid="uuid-here",
    name="Category Name",
    description="Category description"  # Optional
)
# Returns: Created category dictionary
```

#### Update Category
```python
updated_category = client.update_category(
    project_uuid="uuid-here",
    category_uuid="uuid-here",
    name="New Name",  # Optional
    description="New description"  # Optional
)
# Returns: Updated category dictionary
```

#### Delete Category
```python
success = client.delete_category(category_uuid)
# Returns: True if successful
```

#### Bulk Delete Categories
```python
result = client.bulk_delete_categories([
    "category-uuid-1",
    "category-uuid-2"
])
# Returns: Response dictionary with deletion results
```

#### Import Categories from CSV
```python
result = client.import_categories_csv(
    project_uuid="uuid-here",
    csv_file_path="categories.csv"
)
# Returns: Response dictionary with import results
```

#### Export Categories to CSV
```python
csv_file = client.export_categories_csv(
    project_uuid="uuid-here",
    output_file_path="exported_categories.csv"  # Optional
)
# Returns: Path to exported CSV file
```

### Classification

#### Text Classification
```python
result = client.classify_text("Text to classify")
# Returns: Dictionary with classification results
```

#### Image Classification
```python
result = client.classify_image("https://example.com/image.jpg")
# Returns: Dictionary with classification results
```

### Classification History & Analytics

#### Get Classification History
```python
history = client.get_classification_history(
    limit=50,                    # Number of records (max 100)
    offset=0,                    # Number of records to skip
    classification_type='text',  # 'text' or 'image'
    success=True,                # Filter by success status
    start_date='2024-01-01',    # Start date filter
    end_date='2024-12-31'       # End date filter
)
# Returns: Dictionary with history and pagination info
```

#### Get Specific Classification Request
```python
request = client.get_classification_request(request_uuid)
# Returns: Classification request details
```

#### Get Classification Statistics
```python
stats = client.get_classification_stats(
    start_date='2024-01-01',  # Optional start date
    end_date='2024-12-31'     # Optional end date
)
# Returns: Dictionary with classification statistics
```

#### Export Classification History to CSV
```python
csv_file = client.export_classification_history_csv(
    output_file_path="history.csv",  # Optional
    start_date='2024-01-01',        # Optional start date
    end_date='2024-12-31'           # Optional end date
)
# Returns: Path to exported CSV file
```

### Utility Methods

#### Health Check
```python
health = client.get_health_status()
# Returns: Health status information
```

#### Check Remaining Requests
```python
remaining = client.get_remaining_requests()
# Returns: Number of remaining requests or "Unlimited"
```

#### Update Base URL
```python
client.set_base_url("https://api.tagmaster.com")
# Updates the base URL and tests connection
```

## 📋 Response Format Examples

### Classification Response
```json
{
  "success": true,
  "classifications": [
    {
      "category": "Login Issues",
      "confidence": 95.2,
      "description": "Problems with user authentication and login"
    },
    {
      "category": "Password Reset",
      "confidence": 87.1,
      "description": "Password recovery and reset requests"
    }
  ],
  "projectName": "Customer Support",
  "totalCategories": 5,
  "provider": "openai",
  "model": "gpt-4",
  "responseTime": 1250
}
```

### Project Response
```json
{
  "id": 1,
  "uuid": "550e8400-e29b-41d4-a716-446655440000",
  "name": "My Project",
  "description": "Project description",
  "userId": 1,
  "createdAt": "2024-01-01T00:00:00.000Z",
  "updatedAt": "2024-01-01T00:00:00.000Z"
}
```

### Category Response
```json
{
  "id": 1,
  "uuid": "550e8400-e29b-41d4-a716-446655440001",
  "name": "Category Name",
  "description": "Category description",
  "projectId": 1,
  "createdAt": "2024-01-01T00:00:00.000Z"
}
```

## 🔧 Configuration

### Environment Variables
```bash
export TAGMASTER_API_KEY="your-api-key"
export TAGMASTER_BASE_URL="https://api.tagmaster.com"
```

### Custom Base URL
```python
# Initialize with custom base URL
client = TagmasterClassificationClient(
    api_key="your-key",
    base_url="https://api.tagmaster.com"
)

# Or change after initialization
client.set_base_url("https://api.tagmaster.com")
```

## 📁 CSV Import/Export

### Categories CSV Format
```csv
name,description
Login Issues,Problems with user authentication and login
Password Reset,Password recovery and reset requests
Technical Support,Technical issues and troubleshooting
```

### Classification History CSV Format
```csv
id,uuid,type,success,inputData,outputData,responseTime,createdAt
1,uuid-1,text,true,"Customer needs help",{"category":"Login Issues"},1250,2024-01-01T00:00:00.000Z
```

## 🚨 Error Handling

The client provides comprehensive error handling:

```python
try:
    result = client.classify_text("Text to classify")
    print("Success:", result)
except requests.RequestException as e:
    print(f"API Error: {e}")
except ValueError as e:
    print(f"Validation Error: {e}")
except ConnectionError as e:
    print(f"Connection Error: {e}")
except Exception as e:
    print(f"Unexpected Error: {e}")
```

### Common Error Codes
- **401**: Invalid or missing API key
- **403**: No active subscription or request limit exceeded
- **404**: Resource not found
- **429**: Rate limit exceeded
- **500**: Internal server error

## 📊 Usage Examples

### Complete Workflow Example
```python
from tagmaster import TagmasterClassificationClient

# Initialize client
client = TagmasterClassificationClient(api_key="your-key")

# Create a new project
project = client.create_project(
    name="Customer Support",
    description="Customer support ticket classification"
)

# Create categories
categories = [
    ("Login Issues", "Authentication problems"),
    ("Billing", "Payment and billing questions"),
    ("Technical", "Technical support requests")
]

for name, description in categories:
    client.create_category(project['uuid'], name, description)

# Classify some text
result = client.classify_text("User can't log in to account")
print(f"Classified as: {result['classifications'][0]['category']}")

# Export categories
csv_file = client.export_categories_csv(project['uuid'])
print(f"Categories exported to: {csv_file}")
```

### Batch Classification Example
```python
texts = [
    "Customer needs password reset",
    "Payment was charged twice",
    "App is crashing on startup"
]

results = []
for text in texts:
    try:
        result = client.classify_text(text)
        results.append({
            'input': text,
            'classification': result['classifications'][0]['category'],
            'confidence': result['classifications'][0]['confidence']
        })
    except Exception as e:
        results.append({
            'input': text,
            'error': str(e)
        })

# Export results
import pandas as pd
df = pd.DataFrame(results)
df.to_csv('batch_classifications.csv', index=False)
```

### Analytics Dashboard Example
```python
# Get statistics for the current month
from datetime import date
start_date = date.today().replace(day=1)
end_date = date.today()

stats = client.get_classification_stats(start_date, end_date)
history = client.get_classification_history(
    limit=100,
    start_date=start_date,
    end_date=end_date
)

print(f"Monthly Statistics:")
print(f"  Total Requests: {stats['statistics']['totalRequests']}")
print(f"  Success Rate: {stats['statistics']['successfulRequests'] / stats['statistics']['totalRequests'] * 100:.1f}%")
print(f"  Avg Response Time: {stats['statistics']['averageResponseTime']}ms")

# Export detailed history
csv_file = client.export_classification_history_csv(
    start_date=start_date,
    end_date=end_date
)
print(f"Detailed history exported to: {csv_file}")
```

## 🧪 Testing

Run the comprehensive example:

```bash
python example_usage.py
```

Run tests:

```bash
pytest
```

## 📖 Documentation

- **API Reference**: This README
- **Backend API**: [API_KEY_ENDPOINTS.md](../saas-backend/API_KEY_ENDPOINTS.md)
- **Swagger Organization**: [SWAGGER_ORGANIZATION.md](../saas-backend/SWAGGER_ORGANIZATION.md)

## 🤝 Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Add tests if applicable
5. Submit a pull request

## 📄 License

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

## 🆘 Support

- **Documentation**: [GitHub Wiki](https://github.com/tagmaster/tagmaster-python/wiki)
- **Issues**: [GitHub Issues](https://github.com/tagmaster/tagmaster-python/issues)
- **Email**: support@tagmaster.com

## 🔄 Changelog

### v1.0.0
- Initial release with comprehensive API coverage
- Project management (CRUD operations)
- Category management (CRUD operations, import/export)
- Text and image classification
- Classification history and analytics
- CSV import/export functionality
- Utility methods and error handling