---
sidebar_position: 1
---

# Python API Reference

This page provides detailed documentation of CaDaR's Python API.

## Core Functions

### ara2bizi(text, darija="Ma")

Convert Arabic script to Latin (Bizi) script.

**Parameters:**
- `text` (str): Input text in Arabic script
- `darija` (str, optional): Dialect code. Defaults to "Ma" (Moroccan)

**Returns:**
- str: Text in Latin (Bizi) script

**Raises:**
- ValueError: If invalid input or unsupported dialect

**Example:**
```python
import cadar

result = cadar.ara2bizi("سلام عليكم", darija="Ma")
print(result)  # Output: "salam 3likom"
```

### bizi2ara(text, darija="Ma")

Convert Latin (Bizi) script to Arabic script.

**Parameters:**
- `text` (str): Input text in Latin (Bizi) script
- `darija` (str, optional): Dialect code. Defaults to "Ma" (Moroccan)

**Returns:**
- str: Text in Arabic script

**Raises:**
- ValueError: If invalid input or unsupported dialect

**Example:**
```python
import cadar

result = cadar.bizi2ara("kifash dayer?", darija="Ma")
print(result)  # Output: "كيفاش داير؟"
```

### ara2ara(text, darija="Ma")

Standardize Arabic text by removing diacritics and normalizing characters.

**Parameters:**
- `text` (str): Input text in Arabic script
- `darija` (str, optional): Dialect code. Defaults to "Ma" (Moroccan)

**Returns:**
- str: Standardized Arabic text

**Raises:**
- ValueError: If invalid input or unsupported dialect

**Example:**
```python
import cadar

result = cadar.ara2ara("أنَا مِنْ المَغْرِب", darija="Ma")
print(result)  # Output: "انا من المغرب"
```

### bizi2bizi(text, darija="Ma")

Standardize Latin (Bizi) text by removing duplicate characters and normalizing spacing.

**Parameters:**
- `text` (str): Input text in Latin (Bizi) script
- `darija` (str, optional): Dialect code. Defaults to "Ma" (Moroccan)

**Returns:**
- str: Standardized Latin text

**Raises:**
- ValueError: If invalid input or unsupported dialect

**Example:**
```python
import cadar

result = cadar.bizi2bizi("salaaaam bzaaaaf", darija="Ma")
print(result)  # Output: "salam bzaf"
```

## Convenience Functions

### transliterate(text, target, darija="Ma")

Transliterate text with automatic script detection.

**Parameters:**
- `text` (str): Input text in either Arabic or Latin script
- `target` (str): Target script ('latin' or 'arabic')
- `darija` (str, optional): Dialect code. Defaults to "Ma" (Moroccan)

**Returns:**
- str: Text in target script

**Raises:**
- ValueError: If invalid input, unsupported dialect, or invalid target

**Example:**
```python
import cadar

# Auto-detect Arabic and convert to Latin
result1 = cadar.transliterate("سلام", target="latin", darija="Ma")
print(result1)  # Output: "salam"

# Auto-detect Latin and convert to Arabic
result2 = cadar.transliterate("salam", target="arabic", darija="Ma")
print(result2)  # Output: "سلام"
```

### standardize(text, script, darija="Ma")

Standardize text with automatic script detection.

**Parameters:**
- `text` (str): Input text in either Arabic or Latin script
- `script` (str): Target script ('auto', 'arabic', or 'latin')
- `darija` (str, optional): Dialect code. Defaults to "Ma" (Moroccan)

**Returns:**
- str: Standardized text

**Raises:**
- ValueError: If invalid input, unsupported dialect, or invalid script

**Example:**
```python
import cadar

# Auto-detect script and standardize
result1 = cadar.standardize("salaaaam", script="auto", darija="Ma")
print(result1)  # Output: "salam"

# Auto-detect Arabic and standardize
result2 = cadar.standardize("أنَا", script="auto", darija="Ma")
print(result2)  # Output: "انا"
```

## CaDaR Class

### class CaDaR

A reusable processor for multiple transliteration operations.

#### __init__(darija="Ma")

Create a new CaDaR processor.

**Parameters:**
- `darija` (str, optional): Dialect code. Defaults to "Ma" (Moroccan)

**Raises:**
- ValueError: If unsupported dialect

#### Methods

##### ara2bizi(text)

Convert Arabic script to Latin script.

**Parameters:**
- `text` (str): Input text in Arabic script

**Returns:**
- str: Text in Latin script

##### bizi2ara(text)

Convert Latin script to Arabic script.

**Parameters:**
- `text` (str): Input text in Latin script

**Returns:**
- str: Text in Arabic script

##### ara2ara(text)

Standardize Arabic text.

**Parameters:**
- `text` (str): Input text in Arabic script

**Returns:**
- str: Standardized Arabic text

##### bizi2bizi(text)

Standardize Latin text.

**Parameters:**
- `text` (str): Input text in Latin script

**Returns:**
- str: Standardized Latin text

##### get_dialect()

Get the current dialect.

**Returns:**
- str: Dialect name

**Example:**
```python
import cadar

# Create a processor
processor = cadar.CaDaR(darija="Ma")
print(f"Using dialect: {processor.get_dialect()}")  # Output: "Moroccan"

# Use for multiple operations
texts = ["سلام", "كيفاش", "بزاف"]
for text in texts:
    latin = processor.ara2bizi(text)
    print(f"{text} → {latin}")
```

## Error Handling

CaDaR raises `ValueError` for various error conditions:

### Common Errors

1. **Empty Input**
```python
cadar.ara2bizi("")  # Raises ValueError: Empty input
```

2. **Unsupported Dialect**
```python
cadar.ara2bizi("سلام", darija="EG")  # Raises ValueError: Unsupported dialect
```

3. **Invalid Target**
```python
cadar.transliterate("salam", target="hebrew")  # Raises ValueError: Target must be 'latin' or 'arabic'
```

4. **Invalid Script**
```python
cadar.standardize("salam", script="cyrillic")  # Raises ValueError: Script must be 'auto', 'arabic', or 'latin'
```

### Best Practices

```python
import cadar

def safe_transliterate(text, target="latin"):
    """Safely transliterate with error handling"""
    try:
        return cadar.transliterate(text, target=target, darija="Ma")
    except ValueError as e:
        print(f"Error: {e}")
        return text  # Return original on error

# Usage
result = safe_transliterate("سلام", target="latin")
```

## Module Attributes

### __version__

Get the installed CaDaR version.

```python
import cadar
print(cadar.__version__)  # e.g., "0.1.11"
```

### __author__

Get the author of CaDaR.

```python
import cadar
print(cadar.__author__)  # "Ouail LAAMIRI"
```

## Performance Considerations

### Batch Processing

For processing multiple texts, reuse the CaDaR class:

```python
import cadar

# Inefficient: Creates new processor each time
results = [cadar.ara2bizi(text, darija="Ma") for text in texts]

# Efficient: Reuses processor
processor = cadar.CaDaR(darija="Ma")
results = [processor.ara2bizi(text) for text in texts]
```

### Memory Usage

CaDaR is memory-efficient but for very large texts:

```python
def process_large_text(text):
    """Process large text in chunks"""
    processor = cadar.CaDaR(darija="Ma")
    chunk_size = 1000
    
    for i in range(0, len(text), chunk_size):
        chunk = text[i:i+chunk_size]
        yield processor.ara2bizi(chunk)
```

## Integration Examples

### Flask Web App

```python
from flask import Flask, request, jsonify
import cadar

app = Flask(__name__)
processor = cadar.CaDaR(darija="Ma")

@app.route('/transliterate', methods=['POST'])
def api_transliterate():
    data = request.json
    text = data.get('text', '')
    target = data.get('target', 'latin')
    
    try:
        result = cadar.transliterate(text, target, darija="Ma")
        return jsonify({'result': result})
    except ValueError as e:
        return jsonify({'error': str(e)}), 400

if __name__ == '__main__':
    app.run()
```

### Django Integration

```python
from django.http import JsonResponse
import cadar

class TransliterationView:
    def __init__(self):
        self.processor = cadar.CaDaR(darija="Ma")
    
    def post(self, request):
        text = request.POST.get('text', '')
        direction = request.POST.get('direction', 'ara2bizi')
        
        try:
            if direction == 'ara2bizi':
                result = self.processor.ara2bizi(text)
            else:
                result = self.processor.bizi2ara(text)
            
            return JsonResponse({'result': result})
        except ValueError as e:
            return JsonResponse({'error': str(e)}, status=400)
```

## Full API Reference

For a complete list of all functions and their parameters, see the [source code documentation](https://github.com/Oit-Technologies/CaDaR/blob/main/src/python_bindings.rs).