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.2.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.2-py3-none-any.whl (10.6 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: tagmaster_python-1.0.2.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.2.tar.gz
Algorithm Hash digest
SHA256 f3a830569204a4162d0107bc43a78abd72333993cc789b140f3538019141cf2e
MD5 479bde89d07b28c9c9b4829c0042f2aa
BLAKE2b-256 463689ce72eb0e4a1d209445db49bec8de4d0ed634ae4f0b0f7b284bd0da8a42

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for tagmaster_python-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 5c415020054959aac20a34b57f0aba6f98e100d2eb35e753db3c393fe95fa8ac
MD5 658d9b4902b359737ab393e0b52b3e6d
BLAKE2b-256 69c62947bc54864a5ccae5c4deb5d764755d242ef85069eba15ba3aa7cc92257

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