> ## Documentation Index
> Fetch the complete documentation index at: https://ekacare-consent-url-fix.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

# Eka Care Ekascribe Python SDK Integration

This guide explains how to integrate the Eka Care Ekascribe Python SDK.

## Overview

Eka Care provides an Ekascribe service that allows you to transcribe audio files into structured medical data. The Python SDK simplifies this integration process.

## Quick Start

The integration process follows these main steps:

1. Set up webhook registration (one-time setup)
2. Install the SDK
3. Implement authentication
4. Upload audio files
5. Process the webhook callback
6. Retrieve and parse the Ekascribe results

## Prerequisites

* Python 3.6 or higher
* pip for dependency management
* Client credentials (client ID and secret) from Eka Care

## Installation

You can add the Eka Care Python SDK to your project using pip:

```bash theme={null}
pip install ekacare
```

## Available Template IDs

Eka Care supports multiple output templates for different medical documentation needs. Choose the appropriate template ID based on your requirements:

| Template ID               | Description                                                      | Use Case                                              |
| ------------------------- | ---------------------------------------------------------------- | ----------------------------------------------------- |
| `clinical_notes_template` | Comprehensive clinical notes with structured medical information | General clinical documentation, patient consultations |
| `eka_emr_template`        | EMR-compatible format for electronic medical records             | Integration with EMR systems                          |
| `transcript_template`     | Basic transcription with minimal structuring                     | Simple audio-to-text conversion                       |

## Available model types

| Model Type | Description                             |
| ---------- | --------------------------------------- |
| pro        | Our most accurate model                 |
| lite       | More performant model for lower latency |

## Supported Input Languages

Eka Care supports transcription in multiple languages. Specify the appropriate language ID in the `input_language` parameter:

| Language ID | Language Name           |
| ----------- | ----------------------- |
| `en-IN`     | English (India)         |
| `en-US`     | English (United States) |
| `hi`        | Hindi                   |
| `gu`        | Gujarati                |
| `kn`        | Kannada                 |
| `ml`        | Malayalam               |
| `ta`        | Tamil                   |
| `te`        | Telugu                  |
| `bn`        | Bengali                 |
| `mr`        | Marathi                 |
| `pa`        | Punjabi                 |

## Step 1: Register Webhook (One-time Setup)

Before using the Ekascribe service, register a webhook to receive notifications when transcription is complete:

```bash theme={null}
curl --request POST \
  --url https://api.eka.care/notification/v1/connect/webhook/subscriptions \
  --header 'Authorization: Bearer <auth_token>' \
  --header 'Content-Type: application/json' \
  --data '{
    "event_names": [
      "v2rx.completed"
    ],
    "endpoint": "your-endpoint-url",
    "signing_key": "supersecretkey",
    "protocol": "https"
  }'
```

## Step 2: Authentication

Initialize the client with your credentials and obtain access tokens:

```python theme={null}
from ekacare import EkaCareClient

# Initialize the client
client = EkaCareClient(
    client_id="your_client_id",
    client_secret="your_client_secret"
)

# Login to get tokens
token_response = client.auth.login()
access_token = token_response["access_token"]
refresh_token = token_response["refresh_token"]

# Set access token manually if needed
client.set_access_token(access_token)

# Refresh token when needed
refreshed_tokens = client.auth.refresh_token(refresh_token)
new_access_token = refreshed_tokens["access_token"]
```

## Step 3: Upload Audio Files

Upload audio files for transcription:

```python theme={null}
# Prepare files and metadata
audio_files = [
    "path/to/audio_file1.mp3",
    "path/to/audio_file2.mp3"
]
# Optional fields transaction_id, extra_data, action
transaction_id = "unique_transaction_id"  
extra_data = {
    "mode": "dictation",
    "model_type": "lite"
}
action = "ekascribe-v2"

# Upload files
responses = client.v2rx.upload(
    file_paths=audio_files, 
    txn_id=transaction_id, 
    action=action, 
    extra_data=extra_data,
    output_format = {
        "input_language": ["en-IN"],
        "output_template": [
            {
                "template_id": "clinical_notes_template",
                "codification_needed": True
            }]
    }
)

# Process responses
for response in responses:
    # Handle response data as needed
    print(response)
```

## Step 4: Handle Webhook Callback

When the transcription is complete, Eka Care will send a webhook notification to your registered endpoint. Here's a sample of what you'll receive:

```json theme={null}
{
  "event": "v2rx.completed",
  "data": {
    "transaction_id": "unique_transaction_id",
    "status": "completed",
    "session_id": "unique_transaction_id"
  },
  "timestamp": "2023-07-20T10:30:00Z"
}
```

## Step 5: Retrieve Ekascribe Results

After receiving the webhook notification, retrieve the transcription results:

```python theme={null}
import base64

# Get the session ID from the webhook callback
session_id = "unique_transaction_id"  # This comes from the webhook payload which equals to transaction_id of Step 3: Upload Audio files 

# Fetch session status and results
action = "ekascribe-v2"
session_data = client.v2rx.get_session_status(session_id, action)


#{
#  "data": {
#    "output": [
#      {
#        "template_id": "clinical_notes_template",
#        "value": "<base 64 encoded value>",
#        "name": "Clinical Notes Template",
#        "status": "success",
#        "errors": [],
#        "warnings": []
#      }
#    ]
#  }
#}

# Extract and decode the Template value
for template_data in session_status.get("data", {}).get("output", []):
    template_id, template_value = template_data.get("template_id"), template_data.get("value")
    decoded_bytes = base64.b64decode(template_value)
    template_json = decoded_bytes.decode('utf-8')
    print(template_json)
```

## Complete Example

Here's a complete example integrating all the above steps:

```python theme={null}
from ekacare import EkaCareClient
import base64
import time

def ekascribe_integration_example():
    try:
        # Initialize the client
        client = EkaCareClient(
            client_id="your_client_id",
            client_secret="your_client_secret"
        )
        
        # Authenticate
        authenticate_client(client)
        
        # Upload audio files
        transaction_id = "unique_transaction_id"
        upload_audio_files(client, transaction_id)
        
        # NOTE: At this point, wait for the webhook callback
        # This would typically be handled by your web server
        
        # Once webhook is received, fetch results
        # The session_id would come from the webhook payload
        session_id = transaction_id         # "session_id_from_webhook"
        get_transcription_results(client, session_id)
        
    except Exception as e:
        print(f"Error: {str(e)}")

def authenticate_client(client):
    token_response = client.auth.login()
    client.set_access_token(token_response["access_token"])

def upload_audio_files(client, transaction_id):
    audio_files = [
        "path/to/audio1.mp3",
        "path/to/audio2.mp3"
    ]
    
    extra_data = {
        "mode": "dictation",
        "model_type": "lite"
    }

    action = "ekascribe-v2"

    
    
    responses = client.v2rx.upload(
    file_paths=audio_files, 
    txn_id=transaction_id, 
    action=action, 
    extra_data=extra_data,
    output_format = {
        "input_language": ["en-IN"],
        "output_template": [
            {
                "template_id": "clinical_notes_template",
                "codification_needed": True
            }]
    }
)
    
    return responses

def get_transcription_results(client, session_id):
    action = "ekascribe-v2"
    session_status = client.v2rx.get_session_status(session_id, action)
    
    if "data" in session_status and "output" in session_status["data"] and "fhir" in session_status["data"]["output"]:
        encoded_fhir = session_status["data"]["output"]["fhir"]
        decoded_bytes = base64.b64decode(encoded_fhir)
        fhir_json = decoded_bytes.decode('utf-8')
        return fhir_json
    else:
        # Handle non-completed status
        return None

if __name__ == "__main__":
    ekascribe_integration_example()
```

The uploader automatically:

* Determines appropriate upload method based on file size
* Uses multipart upload for large files (>100MB)
* Detects content types from file extensions
* Groups related files with transaction IDs

## Additional Resources

* [Eka Care Python SDK Examples Repository](https://github.com/eka-care/ekapython-sdk-example)
* [Eka Care Python Webhook Documentation](https://github.com/eka-care/ekapython-webhook-sdk)
* [Eka Care Developer Documentation](https://developer.eka.care/)
* [API Reference for Webhooks](https://developer.eka.care/api-reference/connect/webhooks/register-webhook)
* [API Reference for Ekascribe](https://developer.eka.care/api-reference/health-ai/ekascribe/retrieve-transcribe)

## Troubleshooting

### Common Errors

1. **Authentication Failed**: Verify your client ID and secret are correct
2. **File Upload Failed**: Ensure file paths are valid and files are readable
3. **Webhook Not Received**: Check your endpoint is publicly accessible and correctly registered
4. **Import Errors**: Make sure you've installed all necessary dependencies

### Support

For additional support, contact the Eka Care developer support team at [support@eka.care](mailto:support@eka.care).
