Skip to main content

A comprehensive Python client for the Tagmaster classification API with project management, category management, AI classification, and analytics

Project description

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

pip install tagmaster-python

Or install from source:

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

🔑 Quick Start

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

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

Project Management

Get All Projects

projects = client.get_projects()
# Returns: List of project dictionaries

Get Specific Project

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

Create Project

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

Update Project

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

Delete Project

success = client.delete_project(project_uuid)
# Returns: True if successful

Category Management

Get Categories for Project

categories = client.get_categories(project_uuid)
# Returns: List of category dictionaries

Get Specific Category

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

Create Category

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

Update Category

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

success = client.delete_category(category_uuid)
# Returns: True if successful

Bulk Delete Categories

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

Import Categories from CSV

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

Export Categories to CSV

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

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

Image Classification

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

Classification History & Analytics

Get Classification History

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

request = client.get_classification_request(request_uuid)
# Returns: Classification request details

Get Classification Statistics

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

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

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

Check Remaining Requests

remaining = client.get_remaining_requests()
# Returns: Number of remaining requests or "Unlimited"

Update Base URL

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

📋 Response Format Examples

Classification Response

{
  "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

{
  "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

{
  "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

export TAGMASTER_API_KEY="your-api-key"
export TAGMASTER_BASE_URL="https://api.tagmaster.com"

Custom Base URL

# 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

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

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:

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

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

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

# 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:

python example_usage.py

Run tests:

pytest

📖 Documentation

🤝 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 file for details.

🆘 Support

🔄 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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

tagmaster_python-1.0.6.tar.gz (17.2 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

tagmaster_python-1.0.6-py3-none-any.whl (10.6 kB view details)

Uploaded Python 3

File details

Details for the file tagmaster_python-1.0.6.tar.gz.

File metadata

  • Download URL: tagmaster_python-1.0.6.tar.gz
  • Upload date:
  • Size: 17.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.10.0

File hashes

Hashes for tagmaster_python-1.0.6.tar.gz
Algorithm Hash digest
SHA256 3a6204655586d1c3104b0c075e03818901f1303cfc3cd1f5f459d458b7fec3cd
MD5 29d8dd85ffe38f982f468a66940640ea
BLAKE2b-256 1215af43cf6e3b97889b525c468d1e9561fcc258ee26ad5d1480dd16b49dc5de

See more details on using hashes here.

File details

Details for the file tagmaster_python-1.0.6-py3-none-any.whl.

File metadata

File hashes

Hashes for tagmaster_python-1.0.6-py3-none-any.whl
Algorithm Hash digest
SHA256 5889287159c4844aa63bdbc8e6b79b5285470a18629916c5002ebfdad8c2ddbf
MD5 84811ab107c37da6a3dd976b65ce10f7
BLAKE2b-256 86b4262ee716a9ae34d4a7b29936b61e57e037283409725506b227864302f336

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page