mono/packages/media/docs/cli-background-remove-bria.md
2025-08-11 12:25:45 +02:00

606 lines
14 KiB
Markdown

# Bria AI Background Remove CLI Documentation
The `pm-media background:remove:bria` command uses [Bria AI's professional-grade background removal service](https://docs.bria.ai/image-editing/endpoints/background-remove) for enterprise-quality results. Bria AI offers advanced features including content moderation, alpha channel preservation, and high-precision edge detection.
## Table of Contents
- [Installation](#installation)
- [Setup](#setup)
- [Basic Usage](#basic-usage)
- [Command Line Options](#command-line-options)
- [API Usage](#api-usage)
- [Examples](#examples)
- [Bria AI vs Replicate](#bria-ai-vs-replicate)
- [Advanced Features](#advanced-features)
- [Performance Tips](#performance-tips)
- [Troubleshooting](#troubleshooting)
## Installation
```bash
npm install @polymech/media
```
## Setup
### 1. Get Bria AI API Key
1. Visit [Bria AI API Documentation](https://docs.bria.ai/)
2. Register for an account
3. Get your API token from the dashboard
4. Copy your API token
### 2. Set API Key
You can provide your API key in multiple ways:
**Option A: Configuration File (Recommended)**
```javascript
// In your config
{
bria: {
key: "your_bria_api_token_here"
}
}
```
**Option B: Environment Variable**
```bash
export BRIA_API_TOKEN="your_bria_api_token_here"
```
**Option C: Command Line Argument**
```bash
pm-media background:remove:bria --src input.jpg --apiKey "your_bria_api_token_here"
```
## Basic Usage
```bash
pm-media background:remove:bria --src <input> --dst <output> [options]
```
### Required Parameters
- `--src`: Source files (FILE|FOLDER|GLOB pattern)
### Optional Parameters
- `--dst`: Destination path (defaults to source location with modified name)
- `--apiKey`: Bria API key (if not set via config or environment variable)
## Command Line Options
### Core Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--src` | string | required | Source files (FILE\|FOLDER\|GLOB) |
| `--dst` | string | - | Destination path |
| `--apiKey` | string | - | Bria API key |
### Bria AI Specific Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--sync` | boolean | true | Use synchronous processing |
| `--contentModeration` | boolean | false | Enable content moderation |
| `--preserveAlpha` | boolean | true | Preserve alpha channel from input |
### Utility Options
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--dry` | boolean | false | Preview mode (no API calls) |
| `--verbose` | boolean | false | Show detailed processing info |
| `--debug` | boolean | false | Enable debug messages |
| `--logLevel` | string | "info" | Log level (warn\|info\|debug\|error) |
## API Usage
### Import the Library
```typescript
import {
briaBackgroundRemove,
removeBriaBackground,
BriaBackgroundRemoveOptions
} from '@polymech/media';
```
### Single File Background Removal
```typescript
import { removeBriaBackground } from '@polymech/media';
await removeBriaBackground(
'input.jpg',
'output.png',
{
apiKey: 'your_bria_api_token',
sync: true,
contentModeration: false,
preserveAlpha: true
}
);
```
### Batch Processing API
```typescript
import { briaBackgroundRemove } from '@polymech/media';
const options: BriaBackgroundRemoveOptions = {
src: 'photos/*.jpg',
dst: 'no-bg/',
apiKey: process.env.BRIA_API_TOKEN,
sync: true,
contentModeration: true,
preserveAlpha: true,
// ... other IOptions
};
await briaBackgroundRemove(options);
```
### Advanced Configuration
```typescript
const enterpriseOptions: BriaBackgroundRemoveOptions = {
src: 'professional/*.jpg',
dst: 'processed/',
apiKey: 'your_token',
sync: true,
contentModeration: true, // Enterprise content filtering
preserveAlpha: true, // Maintain transparency
verbose: true
};
await briaBackgroundRemove(enterpriseOptions);
```
## Examples
### Example 1: Basic Background Removal
```bash
# Remove background from a single image
pm-media background:remove:bria \
--src "photo.jpg" \
--dst "no-background.png"
```
### Example 2: Professional Batch Processing
```bash
# Process multiple images with content moderation
pm-media background:remove:bria \
--src "photos/*.jpg" \
--dst "processed/" \
--contentModeration \
--verbose
```
### Example 3: E-commerce Product Images
```bash
# Professional product photography processing
pm-media background:remove:bria \
--src "products/*.jpg" \
--dst "catalog/" \
--preserveAlpha \
--sync
```
### Example 4: Studio Photography Workflow
```bash
# High-quality portrait processing
pm-media background:remove:bria \
--src "studio-photos/*.jpg" \
--dst "final/" \
--contentModeration \
--preserveAlpha \
--verbose
```
### Example 5: Safe Content Processing
```bash
# Process with content moderation enabled
pm-media background:remove:bria \
--src "user-uploads/*.jpg" \
--dst "moderated/" \
--contentModeration \
--sync
```
### Example 6: Dry Run Preview
```bash
# Preview what would be processed
pm-media background:remove:bria \
--src "batch/*.jpg" \
--dst "output/" \
--dry \
--verbose
```
### Example 7: Alpha Channel Preservation
```bash
# Maintain original transparency
pm-media background:remove:bria \
--src "images-with-alpha/*.png" \
--dst "processed/" \
--preserveAlpha
```
## Bria AI vs Replicate
### When to Use Bria AI
**Choose Bria AI for:**
- **Enterprise/Commercial Use**: Professional-grade service
- **Content Moderation**: Built-in safety features
- **Alpha Channel Preservation**: Advanced transparency handling
- **Consistent Quality**: Enterprise-level reliability
- **Compliance**: Content safety for business applications
### When to Use Replicate
**Choose Replicate for:**
- **Experimentation**: Multiple model options
- **Custom Models**: Access to specialized models
- **Alpha Matting**: Fine-tuned edge refinement
- **Cost Optimization**: Various pricing models
- **Flexibility**: Different AI models for different use cases
### Feature Comparison
| Feature | Bria AI | Replicate |
|---------|---------|-----------|
| **Quality** | Enterprise-grade | High quality |
| **Content Moderation** | ✅ Built-in | ❌ Not available |
| **Alpha Preservation** | ✅ Advanced | ✅ Basic |
| **Model Selection** | ❌ Single model | ✅ Multiple models |
| **Alpha Matting** | ❌ Not available | ✅ Available |
| **Enterprise Support** | ✅ Yes | ❌ Community |
| **Compliance** | ✅ Enterprise | ❌ Basic |
## Advanced Features
### Content Moderation
Bria AI includes built-in content moderation to ensure safe processing:
```bash
# Enable content moderation for user-generated content
pm-media background:remove:bria \
--src "user-uploads/*.jpg" \
--dst "safe-processed/" \
--contentModeration \
--verbose
```
**Benefits:**
- Prevents processing of inappropriate content
- Returns detailed error messages for failed moderation
- Suitable for public-facing applications
- Compliant with enterprise content policies
### Alpha Channel Preservation
Advanced transparency handling for professional workflows:
```bash
# Preserve original alpha channel information
pm-media background:remove:bria \
--src "complex-transparency/*.png" \
--dst "processed/" \
--preserveAlpha
```
**Features:**
- Maintains partial transparency values
- Preserves original alpha channel data
- Professional-quality edge handling
- Perfect for layered compositions
### Synchronous vs Asynchronous Processing
```bash
# Synchronous (immediate results)
pm-media background:remove:bria --src input.jpg --dst output.png --sync
# Asynchronous (for large batches)
pm-media background:remove:bria --src "batch/*.jpg" --dst "output/" --sync false
```
## File Format Support
### Supported Input Formats
- JPEG (.jpg, .jpeg)
- PNG (.png)
- WebP (.webp)
### Output Format
- **PNG with transparency** (recommended)
- High-quality background removal
- Preserves original image quality
### Quality Guidelines
```bash
# Best quality settings
pm-media background:remove:bria \
--src "high-res/*.jpg" \
--dst "premium/" \
--preserveAlpha \
--sync \
--verbose
```
## Performance Tips
### 1. Use Synchronous Processing
```bash
# Recommended for most use cases
--sync true
```
### 2. Batch Processing Strategy
```bash
# Process in reasonable batches
pm-media background:remove:bria --src "batch1/*.jpg" --dst "output1/"
pm-media background:remove:bria --src "batch2/*.jpg" --dst "output2/"
```
### 3. Content Moderation for Safety
```bash
# Enable for user-generated content
--contentModeration
```
### 4. Alpha Channel Optimization
```bash
# Only when needed (slightly slower)
--preserveAlpha
```
## Cost Considerations
### Bria AI Pricing
Background removal costs per API call. Check current pricing at [Bria AI Pricing](https://docs.bria.ai/).
### Cost Optimization
```bash
# Test with dry run first
pm-media background:remove:bria --src "*.jpg" --dst "output/" --dry
# Use content moderation to avoid processing inappropriate content
--contentModeration
```
## Troubleshooting
### Common Issues
#### "Bria API key is required"
```bash
# Check configuration
echo $BRIA_API_TOKEN
# Or use command line
pm-media background:remove:bria --src input.jpg --apiKey "your_token"
```
#### "API error: 422"
- Content moderation failed
- Image contains inappropriate content
- Check image content and try again
#### "API error: 403"
- Invalid API token
- Insufficient permissions
- Check your Bria AI account status
#### Poor edge quality
- Bria AI automatically optimizes edges
- Use `--preserveAlpha` for complex transparency
- Ensure high-quality input images
### Debug Mode
Enable detailed logging:
```bash
pm-media background:remove:bria \
--src "input/*" \
--dst "output/" \
--debug \
--verbose
```
### API Rate Limits
- Monitor your API usage in Bria dashboard
- Use appropriate batch sizes
- Consider asynchronous processing for large batches
## Integration Examples
### E-commerce Workflow
```bash
#!/bin/bash
# Professional product photography pipeline
INPUT_DIR="$1"
OUTPUT_DIR="$2"
# Remove backgrounds with content moderation
pm-media background:remove:bria \
--src "$INPUT_DIR/*.jpg" \
--dst "$OUTPUT_DIR/no-bg/" \
--contentModeration \
--preserveAlpha \
--verbose
# Create thumbnails
pm-media resize \
--src "$OUTPUT_DIR/no-bg/*.png" \
--dst "$OUTPUT_DIR/thumbs/" \
--width 300 \
--height 300 \
--fit contain \
--background white
```
### Safe Content Processing
```bash
#!/bin/bash
# User-generated content processing with safety
pm-media background:remove:bria \
--src "user-uploads/*.jpg" \
--dst "processed/" \
--contentModeration \
--preserveAlpha \
--verbose
echo "Safe processing complete"
```
### Enterprise Batch Processing
```bash
#!/bin/bash
# Enterprise-grade batch processing
for dir in */; do
if [ -d "$dir" ]; then
echo "Processing directory: $dir"
pm-media background:remove:bria \
--src "$dir*.jpg" \
--dst "enterprise-processed/$dir" \
--contentModeration \
--preserveAlpha \
--sync \
--verbose
fi
done
```
## Advanced Usage
### Environment Configuration
```bash
# .env file
BRIA_API_TOKEN=your_token_here
CONTENT_MODERATION=true
PRESERVE_ALPHA=true
# Use in scripts
pm-media background:remove:bria \
--src "*.jpg" \
--dst "output/" \
--contentModeration \
--preserveAlpha
```
### Quality Control Pipeline
```bash
#!/bin/bash
# Multi-stage quality control
INPUT="$1"
BASE_NAME=$(basename "$INPUT" .jpg)
# Process with Bria AI
pm-media background:remove:bria \
--src "$INPUT" \
--dst "bria-processed/${BASE_NAME}_bria.png" \
--contentModeration \
--preserveAlpha \
--verbose
```
### Conditional Processing
```bash
#!/bin/bash
# Smart processing based on content type
for image in *.jpg; do
echo "Processing $image with Bria AI..."
pm-media background:remove:bria \
--src "$image" \
--dst "processed/" \
--contentModeration \
--preserveAlpha
done
```
## TypeScript Definitions
```typescript
interface BriaBackgroundRemoveOptions extends IOptions {
apiKey?: string;
sync?: boolean;
contentModeration?: boolean;
preserveAlpha?: boolean;
}
declare function removeBriaBackground(
inputPath: string,
outputPath: string,
options: BriaBackgroundRemoveOptions
): Promise<void>;
declare function briaBackgroundRemove(
options: BriaBackgroundRemoveOptions
): Promise<any>;
```
## Security & Compliance
### API Key Security
- Store API keys in configuration files or environment variables
- Never commit API keys to version control
- Use environment-specific configurations
- Monitor API usage in Bria dashboard
### Content Safety
- Enable content moderation for user-generated content
- Review failed moderation results
- Implement appropriate content policies
- Use Bria's enterprise compliance features
## Contributing
For bug reports, feature requests, or contributions, please visit the project repository.
## References
- [Bria AI API Documentation](https://docs.bria.ai/image-editing/endpoints/background-remove)
- [Bria AI Enterprise Features](https://docs.bria.ai/)
- [Content Moderation Guidelines](https://docs.bria.ai/)
## License
This tool is part of the @polymech/media package. Please refer to the package license for usage terms.