# JavaScript Installation
Source: https://docs.getvalenceai.com/SDK/javascript
Get our SDK up and running in your Javascript environment
### Requirements
As best practice, it is recommended to set up your environment variables. Create a `.env` file in your project root and add the following:
```bash theme={null}
VALENCE_API_KEY=your_api_key # Required: Your Valence API key
VALENCE_DISCRETE_URL=https://discrete-api-url # Optional: Discrete audio endpoint
VALENCE_ASYNCH_URL=https://asynch-api-url # Optional: Asynch audio endpoint
VALENCE_LOG_LEVEL=info # Optional: debug, info, warn, error
```
Your Valence API Key is required, while while all other fields are optional.
### Usage
Install the package via `npm`.
```bash theme={null}
npm install valenceai
```
You can validate the package configuration using the following code:
```javascript theme={null}
import { validateConfig } from 'valenceai';
try {
validateConfig();
console.log('Configuration is valid!');
} catch (error) {
console.error('Configuration error:', error.message);
}
```
**Client Constructor:**
```javascript theme={null}
import { ValenceClient } from 'valenceai';
client = new ValenceClient(
None, // API key (or use VALENCE_API_KEY env var)
5*1024*1024, // Size of each upload chunk for asynch audio
5 // Number of retry attempts
)
```
**DiscreteAPI:**
```javascript theme={null}
import { ValenceClient } from 'valenceai';
try {
const client = new ValenceClient();
const result = await client.discrete.emotions('YOUR_FILE.wav');
console.log('Emotion detected:', result);
} catch (error) {
console.error('Error:', error.message);
}
```
**AsynchAPI:**
```javascript theme={null}
import { ValenceClient } from 'valenceai';
try {
const client = new ValenceClient();
// Upload the audio file
const requestId = await client.asynch.upload('YOUR_FILE.wav');
console.log('Upload complete. Request ID:', requestId);
// Get emotions from uploaded audio
const emotions = await client.asynch.emotions(requestId);
console.log('Emotions detected:', emotions);
} catch (error) {
console.error('Error:', error.message);
}
```
**Advanced AsynchAPI Usage:**
This usage is only recommended if you receive errors during file uploads or require smaller upload segments during the upload of a large file.
```javascript theme={null}
import { ValenceClient } from 'valenceai';
// Custom client configuration
const client = new ValenceClient(
2 * 1024 * 1024, // 2MB parts
5 // 5 retry attempts
);
// Upload with custom configuration
const requestId = await client.asynch.upload('huge_file.wav');
// Custom polling with more attempts and shorter intervals
const emotions = await client.asynch.emotions(
requestId,
50, // 50 polling attempts
3 // 3 second intervals
);
```
More information about additional parameters and expected values can be found in the [API Reference](/api-reference/introduction).
Check out the Valence package on NPM →
# Python Installation
Source: https://docs.getvalenceai.com/SDK/python
Get our SDK up and running in your Python environment
### Requirements
Python 3.8+ is required to ensure proper functionality of all necessary libraries.
As best practice, it is recommended to set up your environment variables as such:
```bash theme={null}
export VALENCE_API_KEY= "api_key_here"
export VALENCE_DISCRETE_URL= "https://discrete-api-url" # Optional: custom Discrete audio endpoint
export VALENCE_ASYNCH_URL= "https://asynch-api-url" # Optional: custom Asynch audio endpoint
export VALENCE_LOG_LEVEL= "DEBUG" # Optional: INFO, DEBUG, ERROR
```
Your Valence API Key is required, while while all other fields are optional.
### Usage
Install the package via `pip`.
```bash theme={null}
pip install valenceai
```
**Client Constructor:**
```python theme={null}
from valenceai import ValenceClient
client = ValenceClient(
api_key=None, # API key (or use VALENCE_API_KEY env var)
part_size=5*1024*1024, # Size of each upload chunk for asynch audio
show_progress=True, # Show progress bar for asynch uploads
max_threads=3 # Number of concurrent threads for asynch uploads
)
```
**DiscreteAPI:**
```python theme={null}
from valenceai import ValenceClient
client = ValenceClient()
result = client.discrete.emotions("YOUR_FILE.wav")
print(result)
```
**AsynchAPI:**
```python theme={null}
from valenceai import ValenceClient
client = ValenceClient(show_progress=True)
request_id = client.asynch.upload("YOUR_FILE.wav")
# Get emotions from uploaded audio
result = client.asynch.emotions(request_id)
print(result)
```
More information about additional parameters and expected values can be found in the [API Reference](/api-reference/introduction).
Check out the Valence package on PyPI →
# Upload a short file and receive the classified emotion
Source: https://docs.getvalenceai.com/api-reference/api/post
POST /v1/discrete/emotion
For real-time emotion classification of short files, the file's singular classified emotion is returned.
### Parameters
* `file_path` (string): Path to the audio file
### Response
**Returns:** `prediction [string]` - Emotion prediction results
**Throws:** Error if file doesn't exist, API key missing, or request fails
# Introduction
Source: https://docs.getvalenceai.com/api-reference/introduction
This section outlines the required inputs and expected outputs of each endpoint, along with describing all optional parameters. API usage examples are also included.
## Authentication
All API endpoints are authenticated using API Keys. These can either be passed directly to the URL or they can be defined in an environment file.
**Passing Directly:**
```json theme={null}
"headers": [
{
x-api-key: "YOUR_KEY"
}
]
```
**Environment Variables:**
```bash Python theme={null}
export VALENCE_API_KEY= "api_key_here"
export VALENCE_DISCRETE_URL= "https://discrete-api-url" # Optional: custom Discrete audio endpoint
export VALENCE_ASYNCH_URL= "https://asynch-api-url" # Optional: custom Asynch audio endpoint
export VALENCE_LOG_LEVEL= "DEBUG" # Optional: INFO, DEBUG, ERROR
```
```bash Javascript theme={null}
VALENCE_API_KEY= your_api_key # Required: Your Valence API key
VALENCE_DISCRETE_URL= https://discrete-api-url # Optional: Discrete audio endpoint
VALENCE_ASYNCH_URL= https://asynch-api-url # Optional: Asynch audio endpoint
VALENCE_LOG_LEVEL= info # Optional: debug, info, warn, error
```
# Get emotions (Discrete)
Source: https://docs.getvalenceai.com/api-reference/sdk/discrete
For real-time emotion classification of short files, the file's singular classified emotion is returned, along with confidences of other emotions in the model.
### Parameters
* `file_path` (string): Path to the audio file
### Response
**Returns:** `prediction [string]` - Emotion prediction results
**Throws:** Error if file doesn't exist, API key missing, or request fails
API Keys are included in the client constructor. Find more information on the client constructor [***here.***](/api-reference/introduction)
### Usage
```python Python theme={null}
from valenceai import ValenceClient
client = ValenceClient()
result = client.discrete.emotions("YOUR_FILE.wav")
print(result)
```
```javascript JavaScript theme={null}
import { ValenceClient } from 'valenceai';
try {
const client = new ValenceClient();
const result = await client.discrete.emotions('YOUR_FILE.wav');
console.log('Emotion detected:', result);
}
catch (error) {
console.error('Error:', error.message);
}
```
# Get emotions (Asynch)
Source: https://docs.getvalenceai.com/api-reference/sdk/get_emotions
After uploading your audio file via upload_file, get the results of your file's emotion classification.
### Parameters
* `request_id` (string): Request ID from `client.asynch.upload`
* `max_tries` (number, optional): Maximum polling attempts (default: 20, range: 1-100)
* `interval` (number, optional): Polling interval in milliseconds (default: 5000, range: 1000-60000)
### Response
**Returns:** `results [string]` - Emotion prediction results
**Throws:** Error if request\_id is invalid or prediction times out
### Usage
```python Python theme={null}
from valenceai import ValenceClient
client = ValenceClient(show_progress=True)
# Upload the audio file
request_id = client.asynch.upload("YOUR_FILE.wav")
# Get emotions from uploaded audio
result = client.asynch.emotions(request_id)
print(result)
```
```javascript Javascript theme={null}
import { ValenceClient } from 'valenceai';
try {
const client = new ValenceClient();
// Upload the audio file
const requestId = await client.asynch.upload('YOUR_FILE.wav');
console.log('Upload complete. Request ID:', requestId);
// Get emotions from uploaded audio
const emotions = await client.asynch.emotions(requestId);
console.log('Emotions detected:', emotions);
} catch (error) {
console.error('Error:', error.message);
}
```
# Upload file (Asynch)
Source: https://docs.getvalenceai.com/api-reference/sdk/upload_file
Send a file to Valence's system for emotional classification.
### Parameters
* `file_path` (string): Path to the audio file
* `partSize` (number, optional): Size of each part in bytes (default: 5MB, range: 1MB-100MB)
* `maxRetries` (number, optional): Maximum retry attempts (default: 3)
### Response
**Returns:** `RequestID [string]` - Request ID for tracking the upload
**Throws:** Error if file doesn't exist, API key missing, or upload fails
API Keys are included in the client constructor. Find more information on the client constructor [***here.***](/api-reference/introduction)
### Usage
```python Python theme={null}
from valenceai import ValenceClient
client = ValenceClient(show_progress=True)
# Upload the audio file
request_id = client.asynch.upload("YOUR_FILE.wav")
```
```javascript Javascript theme={null}
import { ValenceClient } from 'valence-sdk';
try {
const client = new ValenceClient();
// Upload the audio file
const requestId = await client.asynch.upload('YOUR_FILE.wav');
console.log('Upload complete. Request ID:', requestId);
```
# Introduction
Source: https://docs.getvalenceai.com/introduction
Valence’s Pulse API offers real-time emotion classification of audio data using our proprietary machine learning models. Below are additional details of capabilities and data specifications.
### Feature Overview
The emotional classification model used in our APIs is optimized for North American English conversational data.
The API includes a baseline model of 4 basic emotions. The emotions included by default are angry, happy, neutral, and sad. Our other model offerings include different subsets of the following emotions: happy, sad, angry, neutral, surprised, disgusted, nervous, irritated, excited, sleepy.
*Coming soon* – The API will include a model choice parameter, allowing users to choose between models of 4, 5, and 7 emotions.
The number of emotions, emotional buckets, and language support can be customized. If you are interested in a custom model, please [contact us](https://www.valencevibrations.com/contact).
### Choosing an API
While our APIs include the same model offerings in the backend, they are best suited for different purposes.
| | DiscreteAPI | AsynchAPI |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| Inputs | A short audio file, 4-10s in length. | A long audio file, at least 5s in length. Inputs can be up to 1 GB large. |
| Outputs | A JSON that includes the primary emotion detected in the file, along with its confidence. The confidence scores of all other emotions in the model are also returned. | A time-stamped JSON that includes the classified emotion and its confidence at a rate of 1 classification per 5 seconds of audio. |
| Response Time | 100-500 ms | Dependent upon file size |
| Accessible outside SDK | ✅ Yes | ❌ No |
The **DiscreteAPI** is built for real-time analysis of emotions in audio data. Small snippets of audio are sent to the API to receive feedback in real-time of what emotions are detected based on tone of voice. This API operates on an approximate per-sentence basis, and audio must be cut to the appropriate size.
The **AsynchAPI** is built for emotion analysis of pre-recorded audio files. Files of any length, up to 1 GB in size, can be sent to the API to receive a summary of emotions throughout the file. Similar to the DiscreteAPI, this API operates on an approximate per-sentence basis, but the AsynchAPI provides timestamps to show the change in emotions over time.
*Coming soon* – StreamingAPI via WebSockets for real-time analysis of an audio stream.
### Ideal Inputs
The APIs expect mono audio in the .wav format. An ideal audio file is recorded at 44100 Hz (44.1 kHz), though sampling rates as low as 8 kHz can still be used with high accuracy. For custom use cases, microphone specifications can be customized based on audio environment, including optimizations for mono/stereo audio, single microphone applications, noisy environments, etc.
For the **DiscreteAPI**, there are two input data formatting options:
* raw audio file `[multipart/form-data] `
* processed audio file `[application/json]`
Requests sent using the raw audio file will have reduced latencies. JSON input can only be sent from Python environments, as there are specific data processing requirements. These requirements are outlined in Quickstart and the API Reference.
For the **AsynchAPI**, the only input data option is an audio file, in the .wav format.
### Outputs
Outputs are returned as JSONs in the following formats:
**DiscreteAPI:**
```json theme={null}
{
"main_emotion": "happy",
"confidence": 0.777777777,
"all_predictions": {
"angry": 0.123456789,
"happy": 0.777777777,
"neutral": 0.23456789,
"sad": 0.098765432
}
}
```
The emotion returned in `main_emotion` is the highest confidence emotion returned from the model. Within `all_predictions`, each emotion is followed by its level of confidence. Some may use the top two highest confidence emotions to generate more nuanced states. We recommend dropping a `main_emotion` with confidence under 0.38, but that is at the user's discretion.
**AsynchAPI:**
```json theme={null}
{
"request_id": "27a33189-bdd7-47ca-9817-abacfb7bdaf3",
"status": "completed",
"emotions": [
{
"t": "00:00",
"emotion": "neutral",
"confidence": 0.82791723
},
{
"t": "00:05",
"emotion": "neutral",
"confidence": 0.719817432
},
{
"t": "00:10",
"emotion": "happy",
"confidence": 0.917309381
},
{
"t": "00:15",
"emotion": "neutral",
"confidence": 0.414097846
}
"..."
]
}
```
The emotions returned in `emotions` are the highest confidence emotion returned from the model, alongside the timestamp and confidence. The number of values in `emotions` correlates directly to the length of the input file. We recommend dropping `emotions` with confidence under 0.38, but that is at the user's discretion.
Looking for a different interval of timestamps? The customizability of audio length is in beta and will be released soon.
# Quickstart
Source: https://docs.getvalenceai.com/quickstart
Get to testing the API quickly! This guide will walk you through direct usage of our DiscreteAPI for real-time emotion analysis and our AsynchAPI for emotion analysis of pre-recorded files.
### Prerequisites
* A valid [API key](https://calendly.com/chloe-duckworth/demo)
* Endpoint URL for Pulse API
* Python 3.7+ OR JavaScript
Valence provides Python and JavaScript SDKs, though you can also make direct HTTPS requests to the DiscreteAPI. The AsynchAPI can only be accessed through the SDK.
### DiscreteAPI Examples
Below are two examples of direct usage of our DiscreteAPI. There are two data input options: `[multipart/form-data]` and `[application/json]` . `[multipart/form-data]` allows a user to directly upload an audio file and `[application/json]` allows a user to process their data before sending it to the API.
**File upload**
```python Python [expandable] theme={null}
import requests
# Define the API endpoint and the API key
API_LINK = 'https://api.getvalenceai.com//v1/discrete/emotion'
API_KEY = 'YOUR_API_KEY'
# Define the file path to upload
file_path = "YOUR_FILE"
# Open the file in binary mode
with open(file_path, 'rb') as file:
# Prepare the files parameter with the file object
files = {
'file': file
}
# Prepare the headers with the API key
headers = {
'x-api-key': API_KEY
}
# Make the POST request to upload the file
response = requests.post(API_LINK, files=files, headers=headers)
# Check the response status
if response.status_code == 200:
print("Response:", response.json())
else:
print(f"Failed to upload file, {response.status_code}, {response.text}")
```
```javascript JavaScript [expandable] theme={null}
const axios = require('axios');
const fs = require('fs');
// Define the API endpoint and the API key
const API_LINK = 'https://api.getvalenceai.com/v1/discrete/emotion';
const API_KEY = 'YOUR_API_KEY';
// Define the file path to upload
const filePath = "YOUR_FILE";
// Open the file and prepare the request
const file = fs.createReadStream(filePath);
const formData = new FormData();
formData.append('file', file);
// Prepare the headers with the API key
const headers = {
'x-api-key': API_KEY,
...formData.getHeaders()
};
// Make the POST request to upload the file
axios.post(API_LINK, formData, { headers })
.then(response => {
console.log("Response:", response.data);
})
.catch(error => {
console.error(`Failed to upload file, ${error.response.status}, ${error.response.data}`);
});
```
```bash cURL theme={null}
#!/bin/sh
export API_LINK='https://api.getvalenceai.com/v1/discrete/emotion'
export API_KEY='YOUR_API_KEY'
curl -X POST "$API_LINK" \
-H "x-api-key: $API_KEY" \
-H "Content-Type: multipart/form-data" \
-F "file=@YOUR_FILE.wav"
```
**Send processed data**
```python [expandable] theme={null}
import requests
import librosa
import json
import numpy as np
API_LINK = 'https://api.getvalenceai.com/v1/discrete/emotion'
API_KEY = 'YOUR_API_KEY'
headers = {
'Content-Type': 'application/json',
'x-api-key': API_KEY
}
fp = 'YOUR_FILE.wav'
X, sample_rate = librosa.load(fp, sr=44100, duration=4.5, offset=0.5)
event = {'payload': [X[:198450].tolist()]}
jevent = json.dumps(event)
response = requests.post(API_LINK, json=jevent, headers=headers)
print(response.status_code)
print(response.headers)
print(response.json())
```
All data sent to the DiscreteAPI is data-in-transit. It is not stored on Valence's systems.
### AsynchAPI Examples
Below are examples of usage for our AsynchAPI. This API has to be used in conjunction with the SDK and requires direct file upload. In these examples, the API key is included as an environment variable.
```python Python SDK theme={null}
from valenceai import ValenceClient
client = ValenceClient(show_progress=True)
# Upload the audio file
request_id = client.asynch.upload("YOUR_FILE.wav")
# Get emotions from uploaded audio
result = client.asynch.emotions(request_id)
print(result)
```
```javascript JavaScript SDK theme={null}
import { ValenceClient } from 'valenceai';
try {
const client = new ValenceClient();
// Upload the audio file
const requestId = await client.asynch.upload('YOUR_FILE.wav');
console.log('Upload complete. Request ID:', requestId);
// Get emotions from uploaded audio
const emotions = await client.asynch.emotions(requestId);
console.log('Emotions detected:', emotions);
} catch (error) {
console.error('Error:', error.message);
}
```
All files sent to the AsynchAPI are briefly saved on Valence's systems while being processed. Our database is cleared every 24 hours. More information on data privacy can be found [here](https://getvalenceai.com/legal/data-processing).
# Welcome to Valence's Docs
Source: https://docs.getvalenceai.com/welcome
These docs are your starting point for building emotion detection and understanding into your application. Valence’s APIs allow for real-time and asynchronous processing of voice data for emotion analysis, allowing you to create rich, emotionally-intelligent user experiences. We offer REST interfaces alongside simple integration examples so you can get our emotion AI up and running easily.
## Learn
Get some more information about our products and their main use cases and capabilities.
Learn about our emotion models and their usage. Understand which APIs best suit your needs.
Get started with our models. Quick tutorials for both our standalone APIs and SDKs.
Need help getting started? Have a question that's not answered in the docs? Send us an email!
## Getting Started
Browse our the technical details for both API and SDK integrations.
Directly integrate our emotion APIs into your project with our detailed usage guide.
Looking for more resources? Check out our SDK and learn how to get started with emotion AI.