semanticpen 1.0.0
AI Article Writer & SEO Blog Generator SDK - Professional Python library for automated content creation, AI-powered article generation, and SEO blog writing with SemanticPen
License: MIT
Requires Python: >=3.8
Keywords: ai article writer, seo blog writer, ai content generator, automated article writing, ai blog generator, seo content creation, ai writing assistant, article generation api, content automation, ai copywriting, blog writing ai, seo article generator, ai content writer, automated blogging, ai text generator, content writing ai, seo blog automation, ai article creation, blog content generator, ai seo writer, semanticpen, ai, article, generation, content, writing, api, sdk, python, seo, blog, automated-writing, content-creation, ai-writer

# SemanticPen Python SDK

[![PyPI version](https://badge.fury.io/py/semanticpen.svg)](https://badge.fury.io/py/semanticpen)
[![Python versions](https://img.shields.io/pypi/pyversions/semanticpen.svg)](https://pypi.org/project/semanticpen/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

**AI Article Writer & SEO Blog Generator SDK** - Professional Python library for automated content creation, AI-powered article generation, and SEO blog writing with [SemanticPen](https://www.semanticpen.com).

## 🚀 Features

- **AI-Powered Article Generation**: Generate high-quality articles from keywords
- **SEO Optimization**: Built-in SEO best practices and optimization
- **Bulk Operations**: Generate multiple articles simultaneously
- **Real-time Status Tracking**: Monitor article generation progress
- **Type Safety**: Full typing support with dataclasses and type hints
- **Error Handling**: Comprehensive error handling and retry mechanisms
- **Async Support**: Built for high-performance applications
- **Flexible Configuration**: Customizable settings for different use cases

## 📦 Installation

```bash
pip install semanticpen
```

## 🔑 Quick Start

### Basic Usage

```python
from semanticpen import SemanticPenClient

# Initialize client
client = SemanticPenClient.create("your-api-key")

# Generate a single article
result = client.generate_article("Python programming best practices")
print(f"Article ID: {result['articleId']}")
print(f"Project ID: {result['projectId']}")
print(f"Message: {result['message']}")

# Check article status
status = client.get_article_status(result['articleId'])
print(f"Status: {status['status']}")
print(f"Complete: {status['isComplete']}")
```

### Advanced Configuration

```python
from semanticpen import SemanticPenClient, SemanticPenConfig

# Custom configuration
config = SemanticPenConfig(
    api_key="your-api-key",
    base_url="https://www.semanticpen.com",
    timeout=60000,  # 60 seconds
    debug=True
)

client = SemanticPenClient.create_with_config(config)
```

## 📝 Core Features

### 1. Article Generation

#### Single Article
```python
# Simple generation
result = client.generate_article("AI in healthcare")

# With options
result = client.generate_article(
    "Machine learning algorithms",
    gpt_version="gpt-4",
    project_name="AI Blog Series",
    preset_id="seo-optimized"
)
```

#### Bulk Generation
```python
keywords = [
    "Python web development",
    "Django best practices", 
    "FastAPI tutorial"
]

results = client.generate_articles(keywords)
print(f"Successfully generated: {results.success_count}")
print(f"Failed: {results.failure_count}")
```

### 2. Article Retrieval

```python
# Get complete article
article = client.get_article("article-id")
print(f"Title: {article.title}")
print(f"Content: {article.article_html}")
print(f"Status: {article.status}")

# Get multiple articles
article_ids = ["id1", "id2", "id3"]
results = client.get_articles(article_ids)

for article in results.successful:
    print(f"Article: {article.title}")
```

### 3. Status Monitoring

```python
# Quick completion check
is_complete = client.is_article_complete("article-id")

# Detailed status
status = client.get_article_status("article-id")
print(f"Status: {status['status']}")
print(f"Complete: {status['isComplete']}")
print(f"Has Error: {status['hasError']}")
```

### 4. Waiting for Completion

```python
from semanticpen import PollingConfig

# Generate and wait for completion
article = client.generate_and_wait(
    "Content marketing strategies",
    polling_config=PollingConfig(
        interval=5000,  # Check every 5 seconds
        max_attempts=60  # Max 5 minutes
    )
)

print(f"Completed article: {article.title}")
print(f"Content length: {len(article.article_html)}")
```

### 5. Bulk Operations with Progress Tracking

```python
def progress_callback(completed, total, new_articles):
    print(f"Progress: {completed}/{total} articles completed")
    for article in new_articles:
        print(f"  ✓ {article.title}")

# Generate multiple articles and wait
result = client.generate_bulk_and_wait(
    ["Topic 1", "Topic 2", "Topic 3"],
    on_progress=progress_callback
)

print(f"Successful: {len(result['successful'])}")
print(f"Failed: {len(result['failed'])}")
print(f"Total time: {result['total_time']:.2f} seconds")
```

## 🏗️ Advanced Usage

### Request Builder Pattern

```python
# Complex article generation with builder pattern
builder = client.create_request_builder()

articles = (builder
    .keyword(["AI ethics", "Machine learning bias"])
    .gpt_version("gpt-4")
    .project_name("AI Ethics Series")
    .preset("academic")
    .parameter("tone", "professional")
    .parameter("target_audience", "researchers")
    .generate_and_wait())

print(f"Generated {len(articles)} articles")
```

### Error Handling

```python
from semanticpen import (
    AuthenticationError,
    ValidationError, 
    RateLimitError,
    NetworkError,
    TimeoutError
)

try:
    result = client.generate_article("Python tutorials")
except AuthenticationError:
    print("Invalid API key")
except ValidationError as e:
    print(f"Invalid input: {e}")
except RateLimitError as e:
    print(f"Rate limit exceeded. Retry after: {e.retry_after}s")
except NetworkError:
    print("Network connection failed")
except TimeoutError:
    print("Request timed out")
```

### Custom Polling Configuration

```python
from semanticpen import PollingConfig

# Custom polling behavior
custom_polling = PollingConfig(
    interval=3000,        # Poll every 3 seconds
    max_attempts=100,     # Try for up to 100 times
    backoff_multiplier=1.2  # Increase interval by 20% each time
)

article = client.wait_for_article(
    "article-id",
    polling_config=custom_polling
)
```

## 🔧 Configuration Options

### SemanticPenConfig

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `api_key` | `str` | Required | Your SemanticPen API key |
| `base_url` | `str` | `"https://www.semanticpen.com"` | API base URL |
| `timeout` | `int` | `30000` | Request timeout in milliseconds |
| `debug` | `bool` | `False` | Enable debug logging |

### PollingConfig

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `interval` | `int` | `5000` | Polling interval in milliseconds |
| `max_attempts` | `int` | `60` | Maximum polling attempts |
| `backoff_multiplier` | `float` | `1.0` | Exponential backoff multiplier |

## 📊 Response Types

### Article
```python
@dataclass
class Article:
    id: str
    organization_id: str
    user_id: str
    project_id: str
    target_keyword: str
    status: ArticleStatusEnum
    created_at: str
    updated_at: str
    article_html: Optional[str] = None
    content: Optional[str] = None
    title: Optional[str] = None
    metadata: Optional[Dict[str, Any]] = None
    completed_at: Optional[str] = None
    error_message: Optional[str] = None
```

### BulkOperationResult
```python
@dataclass
class BulkOperationResult:
    successful: List[Any]
    failed: List[Dict[str, Any]]
    total: int
    success_count: int
    failure_count: int
```

## 🧪 Testing

```python
# Test API connection
if client.test_connection():
    print("✓ Connected to SemanticPen API")
else:
    print("✗ Connection failed")

# Validate keywords
validation = SemanticPenClient.validate_keywords([
    "Valid keyword",
    "",  # Invalid
    "Another valid keyword"
])

if validation["valid"]:
    print("All keywords are valid")
else:
    print(f"Validation errors: {validation['errors']}")
```

## 📚 API Reference

### SemanticPenClient Methods

| Method | Description |
|--------|-------------|
| `create(api_key, **options)` | Create client with API key |
| `test_connection()` | Test API connectivity |
| `generate_article(keyword, **options)` | Generate single article |
| `generate_articles(keywords, **options)` | Generate multiple articles |
| `get_article(article_id)` | Retrieve article by ID |
| `get_articles(article_ids)` | Retrieve multiple articles |
| `is_article_complete(article_id)` | Check if article is complete |
| `get_article_status(article_id)` | Get article status |
| `wait_for_article(article_id, **options)` | Wait for article completion |
| `generate_and_wait(keyword, **options)` | Generate and wait workflow |

## 🌟 Examples

See the [`examples/`](./examples) directory for complete examples:

- [`basic_usage.py`](./examples/basic_usage.py) - Simple article generation
- [`bulk_generation.py`](./examples/bulk_generation.py) - Multiple article generation
- [`async_monitoring.py`](./examples/async_monitoring.py) - Real-time status monitoring
- [`error_handling.py`](./examples/error_handling.py) - Comprehensive error handling

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

## 📄 License

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

## 🔗 Links

- **Website**: [https://www.semanticpen.com](https://www.semanticpen.com)
- **API Documentation**: [https://www.semanticpen.com/api-documentation](https://www.semanticpen.com/api-documentation)
- **Python SDK Documentation**: [https://www.semanticpen.com/api-documentation](https://www.semanticpen.com/api-documentation)
- **Support**: [contact@semanticpen.com](mailto:contact@semanticpen.com)
- **Issues**: [GitHub Issues](https://github.com/semanticpen/python-sdk/issues)

## 💡 Need Help?

- 📖 Check our [documentation](https://www.semanticpen.com/api-documentation)
- 💬 Join our [community forum](https://community.semanticpen.com) 
- 📧 Email us at [support@semanticpen.com](mailto:support@semanticpen.com)
- 🐛 Report bugs on [GitHub](https://github.com/semanticpen/python-sdk/issues)

---

**Made with ❤️ by the SemanticPen team**