17 Commits
v34 ... v46

Author SHA1 Message Date
Andrew Stein
c5706317aa Updated build name. 2023-06-11 19:36:05 -04:00
Andrew Stein
0a2f6d1869 Reorganized files. 2023-06-11 19:35:13 -04:00
Andrew Stein
b753769a53 Updated POM version. 2023-06-11 19:33:09 -04:00
Andrew Stein
8162cada71 Reorganized directories 2023-06-11 19:32:49 -04:00
Andrew Stein
fdcc12ee41 Updated README 2023-06-11 19:07:28 -04:00
Andrew Stein
8c526a1539 Updated README and added new functions for parity. 2023-06-11 19:02:16 -04:00
Andrew Stein
95cf38c620 Updated action 2023-06-11 18:48:53 -04:00
Andrew Stein
6968219c55 Updated action 2023-06-11 18:28:05 -04:00
Andrew Stein
e6279b689f Updated action 2023-06-11 18:26:50 -04:00
Andrew Stein
3462385f3d Updated models to include static retrieval & action functions. 2023-06-11 18:19:25 -04:00
Andrew Stein
0bca63fd50 Updated POM. 2023-06-11 18:00:51 -04:00
Andrew Stein
f7998ee0f9 Merge branch 'main' of https://github.com/AndrewCPU/elevenlabs-api 2023-06-11 18:00:18 -04:00
Andrew Stein
22cdc7146c Updated POM version. 2023-06-11 17:59:56 -04:00
Andrew Stein
e746eeaea9 Update build.yml 2023-06-11 17:55:03 -04:00
Andrew Stein
36eac79a9c Merge pull request #6 from AndrewCPU/REWRITE
Rewrite
2023-06-11 17:50:37 -04:00
Andrew Stein
810c264ac6 Rewrite 2023-06-11 17:49:07 -04:00
Andrew Stein
6a2256d4ca Setup 2023-06-11 17:48:39 -04:00
125 changed files with 2874 additions and 2436 deletions

View File

@@ -1,4 +1,4 @@
name: Dev Build
name: Build
on:
push:
@@ -17,11 +17,11 @@ jobs:
- name: Set up Java
uses: actions/setup-java@v2
with:
java-version: '17'
java-version: '11'
distribution: 'zulu'
- name: Build with Maven
run: mvn clean package
run: mvn clean package -Dmaven.test.skip
- name: Read version from POM file
id: version

114
README.md
View File

@@ -4,6 +4,10 @@
## Getting Started
So you wanna make custom voices, huh? Well you've come to the right place.
### Note: This repo is undergoing an upgrade to v2.0
If any of the documentation is out of place or issues occur, please submit a PR or create an issue.
I downgraded the repo from JDK 17 to JDK 11 as well.
### Installation
**Maven**
@@ -12,7 +16,7 @@ To add `elevenlabs-api` to your Maven project, use:
<dependency>
<groupId>net.andrewcpu.elevenlabs</groupId>
<artifactId>elevenlabs-api</artifactId>
<version>1.0-SNAPSHOT</version>
<version>2.0-SNAPSHOT</version>
</dependency>
```
The most up-to date package information can be found on the [Packages tab](https://github.com/AndrewCPU/elevenlabs-api/packages/)
@@ -27,11 +31,10 @@ Compiled JARs are available via the [Releases tab](https://github.com/AndrewCPU/
To access your ElevenLabs API key, head to the [official website](https://elevenlabs.io/), you can view your `xi-api-key` using the 'Profile' tab on the website.
To set up your ElevenLabs API key, you must register it with the ElevenLabsAPI Java API like below:
```java
ElevenLabsAPI.getInstance().setAPIKey("YOUR_API_KEY_HERE");
ElevenLabs.setApiKey("YOUR_API_KEY_HERE");
```
*For any public repository security, you should store your API key in an environment variable, or external from your source code.*
Once you've injected your API Key, you can safely assume that you will not receive a `ElevenLabsAPINotInitiatedException`.
- - -
<!-- TOC -->
@@ -66,9 +69,6 @@ Once you've injected your API Key, you can safely assume that you will not recei
* [Exceptions](#exceptions)
* [*ElevenLabsAPINotInitiatedException*](#elevenlabsapinotinitiatedexception)
* [*ElevenLabsValidationException*](#elevenlabsvalidationexception)
* [Built in Types](#built-in-types)
* [`Voice` Related Types](#voice-related-types)
* [`User` Related Types](#user-related-types)
* [Misc](#misc)
* [Links to ElevenLabs](#links-to-elevenlabs)
@@ -168,8 +168,15 @@ To generate an audio file with a given `Voice`, you can utilize the `Voice#gener
Depending on how you access your `Voice`, (with or without settings), will decide whether you can use the implicit `voiceSettings` or if you have to specify the `VoiceSettings` object to use. Unless explicitly requesting the `Voice` without settings, every `Voice` object SHOULD contain its default `VoiceSettings`.
```java
Voice voice;
File outputFile = voice.generate(String text, VoiceSettings voiceSettings, File output);
File outputFile = voice.generate(String text, File output); // Uses default voice settings
File file = voice.generate(String text);
File file = voice.generate(String text, VoiceSettings settings);
File file = voice.generate(String text, String model, VoiceSettings settings);
File file = voice.generate(String text, String model);
InputStream inputStream = voice.generateStream(String text);
InputStream inputStream = voice.generateStream(String text, VoiceSettings settings);
InputStream inputStream = voice.generateStream(String text, String model, VoiceSettings settings);
InputStream inputStream = voice.generateStream(String text, String model);
```
- - -
@@ -186,7 +193,7 @@ You can download a `Sample` via the `Sample#downloadAudio(File outputFile)` func
The `File` parameter of `downloadAudio()` is the location of where you want to locally download the sample.
```java
Voice voice;
File file = voice.getSamples().get(0).downloadAudio(File outputFile);
File file = voice.getSamples().get(0).downloadAudio();
```
### Deleting a Sample
@@ -214,11 +221,11 @@ HistoryItem item = history.getHistoryItem("itemId");
### Downloading History
The official API of ElevenLabs provides an endpoint for downloading multiple `HistoryItem`'s as a ZIP file. To download such items, you can pass a `String[]` containing the `HistoryItem` IDs, OR you can provide a `List<HistoryItem>` parameter.
The second parameter is the path in which you would like to save the ZIP file.
```java
History history;
File download = history.downloadHistory(new String[]{"item-id1", "item-id2"}, new File("outputFile.zip"));
File download = history.downloadHistory(List<HistoryItem> historyItems, File outputFile);
File download = history.downloadHistory(new String[]{"item-id1", "item-id2"});
File download = history.downloadHistory(List<HistoryItem> historyItems);
```
### Deleting a HistoryItem
@@ -236,10 +243,10 @@ Voice voice = item.getVoice();
```
### Downloading a HistoryItem Audio
A `HistoryItem` is a previous TTS generation. You can download the generation as an MP3 file by providing the `downloadAudio(File file)` function with the target location for the downloaded file. The return value is the same `File` provided as a parameter.
A `HistoryItem` is a previous TTS generation. You can download the generation as an MP3 file by executing the `downloadAudio()` function. The return value is the tmp `File` location of your download.
```java
HistoryItem item;
File file = item.downloadAudio(File outputFile);
File file = item.downloadAudio();
```
- - -
@@ -259,77 +266,8 @@ User user = User.get();
- - -
## Exceptions
You'll find most actions that make network requests also will throw `IOException`, `ElevenLabsAPINotInitiatedException`, and `ElevenLabsValidationException`.
*The only function that will make a network request **without throwing an exception is*** `HistoryItem#getVoice()`.
### *ElevenLabsAPINotInitiatedException*
This exception will be thrown if you attempt to use the library without setting an API key.
### *ElevenLabsValidationException*
This error indicates a malformed request to the ElevenLabs API. The exception should provide the location of any syntactically incorrect parameters within the request.
- - -
# Built in Types
There are a few objects and enums defined for this API.
## `Voice` Related Types
```java
Voice(String voiceId, String name, List<Sample> samples, String category,
Map<String, String> labels, String previewUrl, List<String> availableForTiers,
VoiceSettings settings)
```
```java
VoiceSettings(double stability, double similarityBoost)
```
```java
Sample(String sampleId, String fileName, String mimeType, long sizeBytes, String hash)
```
```java
History(List<HistoryItem> history)
```
```java
History.HistoryItem(String historyItemId, String voiceId, String voiceName, String text,
long dateUnix, int characterCountChangeFrom, int characterCountChangeTo,
String contentType, GenerationState state)
```
```java
public enum GenerationState {
CREATED,
DELETED,
PROCESSING;
}
```
- - -
## `User` Related Types
```java
User(Subscription subscription, boolean isNewUser, String xiApiKey)
```
```java
Subscription(String tier, int characterCount, int characterLimit, boolean canExtendCharacterLimit,
boolean allowedToExtendCharacterLimit, long nextCharacterCountResetUnix, int voiceLimit,
boolean canExtendVoiceLimit, boolean canUseInstantVoiceCloning, List<AvailableModel> availableModels,
AccountStatus status, NextInvoice nextInvoice)
```
```java
AvailableModel(String modelId, String displayName, List<SupportedLanguage> supportedLanguages)
```
```java
SupportedLanguage(String isoCode, String displayName)
```
```java
NextInvoice(int amountDueCents, long nextPaymentAttemptUnix)
```
```java
public enum AccountStatus {
TRIALING,
ACTIVE,
INCOMPLETE,
INCOMPLETE_EXPIRED,
PAST_DUE,
CANCELED,
UNPAID,
FREE;
}
```
- - -
@@ -341,7 +279,15 @@ If you like what you see, give it a star! :)
- - -
#### Unit Testing
*Todo*
Unit tests have been created, these endpoints are destructive and not included in the testing:
* deleteHistoryItem - WONT TEST
* deleteSample - WONT TEST
* deleteVoice - WONT TEST
* editVoiceSettings - WONT TEST
* createVoice - WONT TEST
* editVoice - WONT TEST
To run the unit tests yourself, you have to clone this repo and update the ElevenLabsTest.java file with your API key and your voice to test on.
Thanks to ElevenLabs for making an awesome tool 🥂

45
pom.xml
View File

@@ -34,11 +34,11 @@
<groupId>net.andrewcpu</groupId>
<artifactId>elevenlabs-api</artifactId>
<version>1.1-SNAPSHOT</version>
<version>2.1-SNAPSHOT</version>
<properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
@@ -52,9 +52,42 @@
<dependencies>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.4.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.13.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.13.4</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>2.0.7</version>
<type>pom</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>2.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>
</dependencies>

View File

@@ -0,0 +1,126 @@
package net.andrewcpu.elevenlabs;
import net.andrewcpu.elevenlabs.model.history.History;
import net.andrewcpu.elevenlabs.model.history.HistoryItem;
import net.andrewcpu.elevenlabs.model.request.TextToSpeechRequest;
import net.andrewcpu.elevenlabs.model.response.CreateVoiceResponse;
import net.andrewcpu.elevenlabs.model.response.GenerationTypeModel;
import net.andrewcpu.elevenlabs.model.user.Subscription;
import net.andrewcpu.elevenlabs.model.user.User;
import net.andrewcpu.elevenlabs.model.voice.Voice;
import net.andrewcpu.elevenlabs.model.voice.VoiceSettings;
import net.andrewcpu.elevenlabs.requests.ElevenLabsRequest;
import net.andrewcpu.elevenlabs.requests.history.*;
import net.andrewcpu.elevenlabs.requests.models.GetModelsRequest;
import net.andrewcpu.elevenlabs.requests.samples.DeleteSampleRequest;
import net.andrewcpu.elevenlabs.requests.samples.GetSampleRequest;
import net.andrewcpu.elevenlabs.requests.tts.PostTextToSpeechRequest;
import net.andrewcpu.elevenlabs.requests.tts.PostTextToSpeechStreamedRequest;
import net.andrewcpu.elevenlabs.requests.user.GetSubscriptionRequest;
import net.andrewcpu.elevenlabs.requests.user.GetUserRequest;
import net.andrewcpu.elevenlabs.requests.voices.*;
import net.andrewcpu.elevenlabs.util.ElevenNetworkUtil;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
public class ElevenLabs {
private static String API_KEY = null;
public static String getApiKey() {
return API_KEY;
}
public static void setApiKey(String apiKey) {
API_KEY = apiKey;
}
private static <T> T sendRequest(ElevenLabsRequest<T> request) {
return ElevenNetworkUtil.sendRequest(request.getType(),request.getEndpoint(), request.getPayload(),request.getResponseClass());
}
public static History getHistory() {
return sendRequest(new GetHistoryRequest());
}
public static User getUser() {
return sendRequest(new GetUserRequest());
}
public static Subscription getSubscription() {
return sendRequest(new GetSubscriptionRequest());
}
public static HistoryItem getHistoryItem(String historyItemId) {
return sendRequest(new GetHistoryItemByIdRequest(historyItemId));
}
public static String deleteHistoryItem(String historyItemId) {
return sendRequest(new DeleteHistoryItemRequest(historyItemId));
}
public static File getHistoryItemAudio(String historyItemId) {
return sendRequest(new GetHistoryItemAudioRequest(historyItemId));
}
public static File getHistoryItemAudio(String... historyItemIds) {
return sendRequest(new PostDownloadHistoryItemsRequest(historyItemIds));
}
public static String deleteSample(String voiceId, String sampleId) {
return sendRequest(new DeleteSampleRequest(voiceId, sampleId));
}
public static File getAudioSample(String voiceId, String sampleId) {
return sendRequest(new GetSampleRequest(voiceId, sampleId));
}
public static List<Voice> getVoices() {
return sendRequest(new GetVoicesRequest()).getVoices();
}
public static VoiceSettings getDefaultVoiceSettings() {
return sendRequest(new GetDefaultVoiceSettingsRequest());
}
public static VoiceSettings getVoiceSettings(String voiceId) {
return sendRequest(new GetVoiceSettingsRequest(voiceId));
}
public static Voice getVoice(String voiceId) {
return sendRequest(new GetVoiceRequest(voiceId));
}
public static Voice getVoice(String voiceId, boolean withSettings) {
return sendRequest(new GetVoiceRequest(voiceId, withSettings));
}
public static String deleteVoice(String voiceId) {
return sendRequest(new DeleteVoiceRequest(voiceId));
}
public static String editVoiceSettings(String voiceId, VoiceSettings settings) {
return sendRequest(new PostEditVoiceSettingsRequest(voiceId, settings));
}
public static CreateVoiceResponse createVoice(String name, File[] files, String description, Map<String, String> labels) {
return sendRequest(new PostAddVoiceRequest(name, files, description, labels));
}
public static String editVoice(String voiceId, String name, File[] files, String description, Map<String, String> labels) {
return sendRequest(new PostEditVoiceRequest(voiceId, name, files, description, labels));
}
public static GenerationTypeModel[] getAvailableModels() {
return sendRequest(new GetModelsRequest());
}
public static File generateTextToSpeech(String voiceId, String text, String modelId, VoiceSettings voiceSettings) {
return sendRequest(new PostTextToSpeechRequest(voiceId, new TextToSpeechRequest(text, modelId, voiceSettings)));
}
public static InputStream generateTextToSpeechStreamed(String voiceId, String text, String modelId, VoiceSettings voiceSettings) {
return sendRequest(new PostTextToSpeechStreamedRequest(voiceId, new TextToSpeechRequest(text, modelId, voiceSettings)));
}
}

View File

@@ -1,140 +0,0 @@
package net.andrewcpu.elevenlabs;
import net.andrewcpu.elevenlabs.api.net.ElevenLabsRequest;
import net.andrewcpu.elevenlabs.api.net.ElevenLabsResponse;
import net.andrewcpu.elevenlabs.enums.ContentType;
import net.andrewcpu.elevenlabs.enums.ResponseType;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsAPINotInitiatedException;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsException;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsValidationException;
import net.andrewcpu.elevenlabs.util.DebugLogger;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import static net.andrewcpu.elevenlabs.util.MultipartUtil.*;
@SuppressWarnings({"unchecked", "UnusedReturnValue"})
public class ElevenLabsAPI {
private static ElevenLabsAPI instance;
private static final String baseURL = "https://api.elevenlabs.io/v1/";
private static boolean debugMode = false;
public static boolean isDebugMode() {
return debugMode;
}
public static <T> T getRequestResult(ElevenLabsRequest<T> request) throws ElevenLabsException {
return ElevenLabsAPI.getInstance().getResult(request);
}
public static void setDebugMode(boolean enabled) {
debugMode = enabled;
}
public static ElevenLabsAPI getInstance() {
if (instance == null) {
instance = new ElevenLabsAPI();
}
return instance;
}
private boolean instantiated;
private String apiKey;
public ElevenLabsAPI() {
instantiated = false;
}
public void setAPIKey(String apiKey) {
instantiated = true;
this.apiKey = apiKey;
}
private void checkOrThrow(ElevenLabsResponse<?> response) throws ElevenLabsException {
if (response == null) {
throw new ElevenLabsValidationException("An error has occurred.");
}
if (!response.isSuccessful()) {
throw response.getException();
}
}
public <T> T getResult(ElevenLabsRequest<T> request) throws ElevenLabsException {
ElevenLabsResponse<T> response = sendRequest(request);
checkOrThrow(response);
return response.getResult();
}
private <T> ElevenLabsResponse<T> sendRequest(ElevenLabsRequest<T> request) throws ElevenLabsException {
if (!instantiated) {
throw new ElevenLabsAPINotInitiatedException();
}
String formattedEndpoint = request.getFormattedEndpoint();
URL url;
int responseCode;
InputStream successStream = null, errorStream = null;
try {
String boundary = "---------------------------" + System.currentTimeMillis();
DebugLogger.log(ElevenLabsAPI.class,"Request to " + baseURL + ", " + formattedEndpoint);
url = new URL(baseURL + formattedEndpoint);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
setupConnection(request, boundary, connection);
if (request.getContentType() == ContentType.JSON) {
handleJSON(request, connection);
} else if (request.getContentType() == ContentType.MULTIPART) {
handleMultipart(request, connection, boundary);
connection.getOutputStream().flush();
connection.getOutputStream().close();
}
if(request.getResponseType() == ResponseType.FILE_STREAM) {
request.getStreamedResponseCallback().handleStreamedResponse(connection.getInputStream(), connection.getErrorStream());
}
responseCode = connection.getResponseCode();
if (responseCode >= 200 && responseCode < 300) {
successStream = connection.getInputStream();
} else {
errorStream = connection.getErrorStream();
}
} catch (IOException e) {
throw new ElevenLabsException(e);
}
return new ElevenLabsResponse<>(responseCode, errorStream, successStream, request);
}
private void setupConnection(ElevenLabsRequest<?> request, String boundary, HttpURLConnection connection) throws ProtocolException {
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.setRequestMethod(request.getMethod().name());
String contType = request.getContentType().getType();
if (request.getContentType() == ContentType.MULTIPART) {
contType += "; boundary=" + boundary;
}
connection.setRequestProperty("xi-api-key", apiKey);
connection.setRequestProperty("Content-Type", contType); // this can be done better.
connection.setDoOutput(true);
}
private static void handleJSON(ElevenLabsRequest<?> request, HttpURLConnection connection) throws IOException {
if (request.getBody() != null) {
connection.getOutputStream().write(request.getBody().toJSONString().getBytes(StandardCharsets.UTF_8));
}
}
private static void handleMultipart(ElevenLabsRequest<?> request, HttpURLConnection connection, String boundary) throws IOException {
writeFormValues(request, connection, boundary);
String footer = "--" + boundary + "--\r\n";
connection.getOutputStream().write(footer.getBytes(StandardCharsets.UTF_8));
}
}

View File

@@ -1,31 +0,0 @@
package net.andrewcpu.elevenlabs.api;
import net.andrewcpu.elevenlabs.api.net.requests.history.DeleteHistoryItemRequest;
import net.andrewcpu.elevenlabs.api.net.requests.history.DownloadHistoryRequest;
import net.andrewcpu.elevenlabs.api.net.requests.history.GetHistoryAudioRequest;
import net.andrewcpu.elevenlabs.api.net.requests.history.GetHistoryRequest;
import net.andrewcpu.elevenlabs.elements.voice.History;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsException;
import java.io.File;
import java.util.List;
import static net.andrewcpu.elevenlabs.ElevenLabsAPI.getRequestResult;
public class HistoryAPI {
public static History getHistory() throws ElevenLabsException {
return getRequestResult(new GetHistoryRequest());
}
public static File downloadHistory(List<String> historyIds, File outputFile) throws ElevenLabsException {
return getRequestResult(new DownloadHistoryRequest(historyIds, outputFile));
}
public static File getHistoryItemAudio(History.HistoryItem historyItem, File outputFile) throws ElevenLabsException {
return getRequestResult(new GetHistoryAudioRequest(historyItem.getHistoryItemId(), outputFile));
}
public static String deleteHistoryItem(History.HistoryItem historyItem) throws ElevenLabsException {
return getRequestResult(new DeleteHistoryItemRequest(historyItem.getHistoryItemId()));
}
}

View File

@@ -1,36 +0,0 @@
package net.andrewcpu.elevenlabs.api;
import net.andrewcpu.elevenlabs.api.net.requests.samples.DeleteSampleRequest;
import net.andrewcpu.elevenlabs.api.net.requests.samples.GetAudioSampleRequest;
import net.andrewcpu.elevenlabs.elements.voice.Sample;
import net.andrewcpu.elevenlabs.elements.voice.Voice;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsException;
import org.json.simple.JSONObject;
import java.io.File;
import static net.andrewcpu.elevenlabs.ElevenLabsAPI.getRequestResult;
public class SampleAPI {
public static JSONObject deleteSample(String voiceId, String sampleId) throws ElevenLabsException {
return getRequestResult(new DeleteSampleRequest(voiceId, sampleId));
}
public static JSONObject deleteSample(Voice voice, String sampleId) throws ElevenLabsException {
return deleteSample(voice.getVoiceId(), sampleId);
}
public static JSONObject deleteSample(String voiceId, Sample sample) throws ElevenLabsException {
return deleteSample(voiceId, sample.getSampleId());
}
public static JSONObject deleteSample(Voice voice, Sample sample) throws ElevenLabsException {
return deleteSample(voice.getVoiceId(), sample.getSampleId());
}
public static File getSampleAudio(String voiceId, String sampleId, File file) throws ElevenLabsException {
return getRequestResult(new GetAudioSampleRequest(voiceId, sampleId, file));
}
public static File getSampleAudio(Voice voice, Sample sample, File file) throws ElevenLabsException {
return getSampleAudio(voice.getVoiceId(), sample.getSampleId(), file);
}
}

View File

@@ -1,20 +0,0 @@
package net.andrewcpu.elevenlabs.api;
import net.andrewcpu.elevenlabs.api.net.requests.user.GetSubscriptionInfoRequest;
import net.andrewcpu.elevenlabs.api.net.requests.user.GetUserRequest;
import net.andrewcpu.elevenlabs.elements.user.Subscription;
import net.andrewcpu.elevenlabs.elements.user.User;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsException;
import static net.andrewcpu.elevenlabs.ElevenLabsAPI.getRequestResult;
public class UserAPI {
public static Subscription getSubscription() throws ElevenLabsException {
return getRequestResult(new GetSubscriptionInfoRequest());
}
public static User getUser() throws ElevenLabsException {
return getRequestResult(new GetUserRequest());
}
}

View File

@@ -1,85 +0,0 @@
package net.andrewcpu.elevenlabs.api;
import net.andrewcpu.elevenlabs.api.net.requests.voices.*;
import net.andrewcpu.elevenlabs.api.net.requests.voices.settings.GetDefaultVoiceSettingsRequest;
import net.andrewcpu.elevenlabs.api.net.requests.voices.settings.GetVoiceSettingsRequest;
import net.andrewcpu.elevenlabs.api.net.requests.voices.settings.UpdateVoiceSettingsRequest;
import net.andrewcpu.elevenlabs.api.net.requests.voices.tts.GenerateTextToSpeechRequest;
import net.andrewcpu.elevenlabs.api.net.requests.voices.tts.GenerateTextToSpeechStreamRequest;
import net.andrewcpu.elevenlabs.elements.voice.Voice;
import net.andrewcpu.elevenlabs.elements.voice.VoiceSettings;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsException;
import net.andrewcpu.elevenlabs.util.StreamedResponseCallback;
import org.json.simple.JSONObject;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import static net.andrewcpu.elevenlabs.ElevenLabsAPI.getRequestResult;
public class VoiceAPI {
public static VoiceSettings getDefaultVoiceSettings() throws ElevenLabsException {
return getRequestResult(new GetDefaultVoiceSettingsRequest());
}
public static File getTextToSpeech(String text, Voice voice, VoiceSettings settings, File outputFile) throws ElevenLabsException {
return getRequestResult(new GenerateTextToSpeechRequest(voice, settings, text, outputFile));
}
public static InputStream getTextToSpeechStreamed(String text, Voice voice, VoiceSettings settings, StreamedResponseCallback callback, File file) throws ElevenLabsException{
return getRequestResult(new GenerateTextToSpeechStreamRequest(voice, settings, text, callback, file));
}
public static List<Voice> getVoices() throws ElevenLabsException {
return getRequestResult(new GetVoicesRequest());
}
public static Voice getVoice(String voiceId, boolean withSettings) throws ElevenLabsException {
return getRequestResult(new GetVoiceRequest(voiceId, withSettings));
}
public static Voice getVoice(String voiceId) throws ElevenLabsException {
return getVoice(voiceId, true);
}
public static VoiceSettings getVoiceSettings(String voiceId) throws ElevenLabsException {
return getRequestResult(new GetVoiceSettingsRequest(voiceId));
}
public static VoiceSettings getVoiceSettings(Voice voice) throws ElevenLabsException {
return getVoiceSettings(voice.getVoiceId());
}
public static boolean deleteVoice(Voice voice) throws ElevenLabsException {
return deleteVoice(voice.getVoiceId());
}
public static boolean deleteVoice(String voiceId) throws ElevenLabsException {
JSONObject result = getRequestResult(new DeleteVoiceRequest(voiceId));
if(result.containsKey("status") && result.get("status").equals("ok")){
return true;
}
return false;
}
public static JSONObject editVoice(Voice voice, VoiceSettings voiceSettings) throws ElevenLabsException {
return editVoice(voice.getVoiceId(), voiceSettings);
}
public static JSONObject editVoice(String voiceId, VoiceSettings settings) throws ElevenLabsException {
return getRequestResult(new UpdateVoiceSettingsRequest(voiceId, settings));
}
public static String createVoice(String name, Map<String, String> labels, List<File> files) throws ElevenLabsException {
CreateVoiceRequest request = new CreateVoiceRequest(name, files, labels);
return getRequestResult(request);
}
public static JSONObject editVoice(String voiceId, String name, Map<String, String> labels, List<File> files) throws ElevenLabsException {
EditVoiceRequest editVoiceRequest = new EditVoiceRequest(voiceId, name, files, labels);
return getRequestResult(editVoiceRequest);
}
}

View File

@@ -1,113 +0,0 @@
package net.andrewcpu.elevenlabs.api.net;
import net.andrewcpu.elevenlabs.api.net.multipart.MultipartForm;
import net.andrewcpu.elevenlabs.api.net.transformers.ResultTransformer;
import net.andrewcpu.elevenlabs.enums.ContentType;
import net.andrewcpu.elevenlabs.enums.HTTPMethod;
import net.andrewcpu.elevenlabs.enums.ResponseType;
import net.andrewcpu.elevenlabs.util.StreamedResponseCallback;
import org.json.simple.JSONObject;
import java.io.File;
import java.util.List;
public abstract class ElevenLabsRequest<T> {
protected ContentType contentType = ContentType.JSON;
protected ResponseType responseType = ResponseType.JSON;
protected final HTTPMethod method;
protected List<String> parameters;
protected ResultTransformer<T> resultTransformer;
protected JSONObject body;
protected File outputFilePath;
protected MultipartForm multipartForm;
protected StreamedResponseCallback streamedResponseCallback;
public ElevenLabsRequest(List<String> parameters, JSONObject body, HTTPMethod method, ResultTransformer<T> resultTransformer) {
this.method = method;
this.parameters = parameters;
this.body = body;
this.resultTransformer = resultTransformer;
}
public ElevenLabsRequest(JSONObject body, HTTPMethod method) {
this.body = body;
this.method = method;
}
public ElevenLabsRequest(List<String> parameters, HTTPMethod method) {
this.parameters = parameters;
this.method = method;
}
public ElevenLabsRequest(List<String> parameters, HTTPMethod method, ResultTransformer<T> resultTransformer) {
this.parameters = parameters;
this.method = method;
this.resultTransformer = resultTransformer;
}
public ElevenLabsRequest(HTTPMethod method) {
this.method = method;
}
public ElevenLabsRequest(HTTPMethod method, ResultTransformer<T> resultTransformer) {
this.method = method;
this.resultTransformer = resultTransformer;
}
public ElevenLabsRequest(JSONObject body, HTTPMethod method, ResultTransformer<T> resultTransformer) {
this.resultTransformer = resultTransformer;
this.method = method;
this.body = body;
}
public abstract String getEndpoint();
public MultipartForm getMultipartForm() {
return multipartForm;
}
public ContentType getContentType() {
return contentType;
}
public HTTPMethod getMethod() {
return method;
}
public File getOutputFilePath() {
return outputFilePath;
}
public StreamedResponseCallback getStreamedResponseCallback() {
return streamedResponseCallback;
}
public ResultTransformer<T> getResultTransformer() {
return resultTransformer;
}
public String getFormattedEndpoint(){
String endpoint = getEndpoint();
if(endpoint.startsWith("/")){
endpoint = endpoint.substring(1);
}
if(parameters != null && !parameters.isEmpty()){
for(int i = 0; i<parameters.size(); i++){
endpoint = endpoint.replaceFirst("\\{.*?}", parameters.get(i));
}
}
return endpoint;
}
public JSONObject getBody() {
return body;
}
public ResponseType getResponseType() {
return responseType;
}
}

View File

@@ -1,89 +0,0 @@
package net.andrewcpu.elevenlabs.api.net;
import net.andrewcpu.elevenlabs.enums.ResponseType;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsExceptionBuilder;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsValidationException;
import net.andrewcpu.elevenlabs.util.DebugLogger;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
public class ElevenLabsResponse<T> {
private final InputStream errorStream;
private JSONObject error;
public final InputStream successStream;
private JSONObject successful;
private final ElevenLabsRequest<T> request;
private final int responseCode;
private T resultingObject;
public ElevenLabsResponse(int responseCode, InputStream errorStream, InputStream successStream, ElevenLabsRequest<T> request) {
this.responseCode = responseCode;
this.errorStream = errorStream;
this.successStream = successStream;
this.request = request;
try {
_buildObjects();
} catch (IOException | ParseException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private void _buildObjects() throws IOException, ParseException {
if (isSuccessful()) {
if (request.getResponseType() == ResponseType.JSON) {
String responseBody = new String(successStream.readAllBytes(), StandardCharsets.UTF_8);
DebugLogger.log(getClass(), responseBody);
JSONObject object = ((JSONObject) new JSONParser().parse(responseBody));
this.successful = object;
resultingObject = request.getResultTransformer().transform(object);
} else if (request.getResponseType() == ResponseType.FILE_STREAM) {
InputStream inputStream = successStream;
byte[] buffer = new byte[4096];
int bytesRead;
OutputStream outputStream = new FileOutputStream(request.getOutputFilePath());
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
try {
resultingObject = request.getResultTransformer().transform();
} catch (Exception e) {
throw new RuntimeException(e);
}
} else if (request.getResponseType() == ResponseType.STRING) {
String responseBody = new String(successStream.readAllBytes(), StandardCharsets.UTF_8);
DebugLogger.log(getClass(), responseBody);
resultingObject = request.getResultTransformer().transform(responseBody);
}
} else {
String responseBody = new String(errorStream.readAllBytes(), StandardCharsets.UTF_8);
DebugLogger.log(getClass(), responseBody);
this.error = ((JSONObject) new JSONParser().parse(responseBody));
}
}
public ElevenLabsValidationException getException() {
return ElevenLabsExceptionBuilder.build(this.error);
}
public T getResult() {
return resultingObject;
}
public JSONObject getResultJSON() {
return successful;
}
public boolean isSuccessful() {
return responseCode >= 200 && responseCode < 300;
}
}

View File

@@ -1,15 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.multipart;
import java.io.File;
public class MultipartFile extends MultipartFormContent {
private final File file;
public MultipartFile(String name, File file) {
super(name, file);
this.file = file;
}
public File getFile() {
return file;
}
}

View File

@@ -1,21 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.multipart;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MultipartForm {
private final List<MultipartFormContent> items;
public MultipartForm() {
items = new ArrayList<>();
}
public List<MultipartFormContent> getItems() {
return items;
}
public void push(MultipartFormContent... formContent) {
items.addAll(Arrays.asList(formContent));
}
}

View File

@@ -1,35 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.multipart;
import java.io.File;
public class MultipartFormContent {
private final String name;
private final String filename;
private final String value;
public MultipartFormContent(String name, File file) {
this.name = name;
this.filename = file.getName();
this.value = null;
}
public MultipartFormContent(String name, String value) {
this.name = name;
this.value = value;
this.filename = null;
}
public String getName() {
return name;
}
public String getFilename() {
return filename;
}
public String getValue() {
return value;
}
}

View File

@@ -1,39 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests;
import net.andrewcpu.elevenlabs.api.net.ElevenLabsRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.ResultTransformer;
import net.andrewcpu.elevenlabs.enums.HTTPMethod;
import org.json.simple.JSONObject;
import java.util.List;
public abstract class ElevenLabsDeleteRequest<T> extends ElevenLabsRequest<T> {
public ElevenLabsDeleteRequest(List<String> parameters, JSONObject body, ResultTransformer<T> resultTransformer) {
super(parameters, body, HTTPMethod.DELETE, resultTransformer);
}
public ElevenLabsDeleteRequest(JSONObject body, ResultTransformer<T> resultTransformer) {
super(body, HTTPMethod.DELETE, resultTransformer);
}
public ElevenLabsDeleteRequest(JSONObject body) {
super(body, HTTPMethod.DELETE);
}
public ElevenLabsDeleteRequest(List<String> parameters) {
super(parameters, HTTPMethod.DELETE);
}
public ElevenLabsDeleteRequest(List<String> parameters, ResultTransformer<T> resultTransformer) {
super(parameters, HTTPMethod.DELETE, resultTransformer);
}
public ElevenLabsDeleteRequest() {
super(HTTPMethod.DELETE);
}
public ElevenLabsDeleteRequest(ResultTransformer<T> resultTransformer) {
super(HTTPMethod.DELETE, resultTransformer);
}
}

View File

@@ -1,37 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests;
import net.andrewcpu.elevenlabs.api.net.ElevenLabsRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.ResultTransformer;
import net.andrewcpu.elevenlabs.enums.HTTPMethod;
import org.json.simple.JSONObject;
import java.util.List;
public abstract class ElevenLabsGetRequest<T> extends ElevenLabsRequest<T> {
public ElevenLabsGetRequest(List<String> parameters, JSONObject body, ResultTransformer<T> resultTransformer) {
super(parameters, body, HTTPMethod.GET, resultTransformer);
}
public ElevenLabsGetRequest(JSONObject body, ResultTransformer<T> resultTransformer) {
super(body, HTTPMethod.GET, resultTransformer);
}
public ElevenLabsGetRequest(JSONObject body) {
super(body, HTTPMethod.GET);
}
public ElevenLabsGetRequest(List<String> parameters) {
super(parameters, HTTPMethod.GET);
}
public ElevenLabsGetRequest(List<String> parameters, ResultTransformer<T> resultTransformer) {
super(parameters, HTTPMethod.GET, resultTransformer);
}
public ElevenLabsGetRequest() {
super(HTTPMethod.GET);
}
public ElevenLabsGetRequest( ResultTransformer<T> resultTransformer) {
super(HTTPMethod.GET, resultTransformer);
}
}

View File

@@ -1,38 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests;
import net.andrewcpu.elevenlabs.api.net.ElevenLabsRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.ResultTransformer;
import net.andrewcpu.elevenlabs.enums.HTTPMethod;
import org.json.simple.JSONObject;
import java.util.List;
public abstract class ElevenLabsPostRequest<T> extends ElevenLabsRequest<T> {
public ElevenLabsPostRequest(List<String> parameters, JSONObject body, ResultTransformer<T> resultTransformer) {
super(parameters, body, HTTPMethod.POST, resultTransformer);
}
public ElevenLabsPostRequest(JSONObject body) {
super(body, HTTPMethod.POST);
}
public ElevenLabsPostRequest(JSONObject body, ResultTransformer<T> resultTransformer) {
super(body, HTTPMethod.POST, resultTransformer);
}
public ElevenLabsPostRequest(List<String> parameters) {
super(parameters, HTTPMethod.POST);
}
public ElevenLabsPostRequest(List<String> parameters, ResultTransformer<T> resultTransformer) {
super(parameters, HTTPMethod.POST, resultTransformer);
}
public ElevenLabsPostRequest() {
super(HTTPMethod.POST);
}
public ElevenLabsPostRequest(ResultTransformer<T> resultTransformer) {
super(HTTPMethod.POST, resultTransformer);
}
}

View File

@@ -1,19 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.history;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsDeleteRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestTransformer;
import net.andrewcpu.elevenlabs.enums.ResponseType;
import java.util.List;
public class DeleteHistoryItemRequest extends ElevenLabsDeleteRequest<String> {
public DeleteHistoryItemRequest(String historyId) {
super(List.of(historyId), RequestTransformer.STRING_RESULT_TRANSFORMER);
responseType = (ResponseType.STRING);
}
@Override
public String getEndpoint() {
return "history/{historyItemId}";
}
}

View File

@@ -1,31 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.history;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsPostRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.FilePingPongTransformer;
import net.andrewcpu.elevenlabs.enums.ResponseType;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.File;
import java.util.List;
@SuppressWarnings("unchecked")
public class DownloadHistoryRequest extends ElevenLabsPostRequest<File> {
private static JSONObject getBody(List<String> historyIds) {
JSONObject object = new JSONObject();
JSONArray array = new JSONArray();
array.addAll(historyIds);
object.put("history_item_ids", array);
return object;
}
public DownloadHistoryRequest(List<String> historyIds, File outputFile) {
super(null, getBody(historyIds), new FilePingPongTransformer(outputFile));
responseType = (ResponseType.FILE_STREAM);
outputFilePath = (outputFile);
}
@Override
public String getEndpoint() {
return "history/download";
}
}

View File

@@ -1,21 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.history;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsGetRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.FilePingPongTransformer;
import net.andrewcpu.elevenlabs.enums.ResponseType;
import java.io.File;
import java.util.List;
public class GetHistoryAudioRequest extends ElevenLabsGetRequest<File> {
public GetHistoryAudioRequest(String historyId, File outputFile) {
super(List.of(historyId), new FilePingPongTransformer(outputFile));
responseType = (ResponseType.FILE_STREAM);
outputFilePath = (outputFile);
}
@Override
public String getEndpoint() {
return "history/{historyItemId}/audio";
}
}

View File

@@ -1,16 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.history;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsGetRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestTransformer;
import net.andrewcpu.elevenlabs.elements.voice.History;
public class GetHistoryRequest extends ElevenLabsGetRequest<History> {
public GetHistoryRequest() {
super(RequestTransformer.HISTORY_TRANSFORMER);
}
@Override
public String getEndpoint() {
return "history";
}
}

View File

@@ -1,20 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.samples;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsDeleteRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestTransformer;
import net.andrewcpu.elevenlabs.enums.ResponseType;
import org.json.simple.JSONObject;
import java.util.List;
public class DeleteSampleRequest extends ElevenLabsDeleteRequest<JSONObject> {
public DeleteSampleRequest(String voiceId, String sampleId) {
super(List.of(voiceId, sampleId), RequestTransformer.IN_OUT_TRANSFORMER);
responseType = (ResponseType.JSON);
}
@Override
public String getEndpoint() {
return "voices/{voiceId}/samples/{sampleId}";
}
}

View File

@@ -1,21 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.samples;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsGetRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.FilePingPongTransformer;
import net.andrewcpu.elevenlabs.enums.ResponseType;
import java.io.File;
import java.util.List;
public class GetAudioSampleRequest extends ElevenLabsGetRequest<File> {
public GetAudioSampleRequest(String voiceId, String sampleId, File outputFile) {
super(List.of(voiceId, sampleId), new FilePingPongTransformer(outputFile));
responseType = ResponseType.FILE_STREAM;
outputFilePath = outputFile;
}
@Override
public String getEndpoint() {
return "voices/{voiceId}/samples/{sampleId}/audio";
}
}

View File

@@ -1,16 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.user;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsGetRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestTransformer;
import net.andrewcpu.elevenlabs.elements.user.Subscription;
public class GetSubscriptionInfoRequest extends ElevenLabsGetRequest<Subscription> {
public GetSubscriptionInfoRequest() {
super(RequestTransformer.SUBSCRIPTION_TRANSFORMER);
}
@Override
public String getEndpoint() {
return "user/subscription";
}
}

View File

@@ -1,16 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.user;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsGetRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestTransformer;
import net.andrewcpu.elevenlabs.elements.user.User;
public class GetUserRequest extends ElevenLabsGetRequest<User> {
public GetUserRequest() {
super(RequestTransformer.USER_TRANSFORMER);
}
@Override
public String getEndpoint() {
return "user";
}
}

View File

@@ -1,43 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.voices;
import net.andrewcpu.elevenlabs.api.net.multipart.MultipartFile;
import net.andrewcpu.elevenlabs.api.net.multipart.MultipartForm;
import net.andrewcpu.elevenlabs.api.net.multipart.MultipartFormContent;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsPostRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestTransformer;
import net.andrewcpu.elevenlabs.enums.ContentType;
import org.json.simple.JSONObject;
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
@SuppressWarnings("unchecked")
public class CreateVoiceRequest extends ElevenLabsPostRequest<String> {
public CreateVoiceRequest(String name, List<File> files, Map<String, String> labels) {
super(RequestTransformer.VOICE_ID_TRANSFORMER);
this.contentType = ContentType.MULTIPART;
this.multipartForm = new MultipartForm();
buildBody(name, files, labels);
}
@Override
public String getEndpoint() {
return "voices/add";
}
private void buildBody(String name, List<File> files, Map<String, String> labels) {
JSONObject val = new JSONObject();
if (labels != null && labels.size() != 0) {
labels.keySet().forEach(key -> val.put(key, labels.get(key)));
}
MultipartFormContent nameMultipart = new MultipartFormContent("name", URLEncoder.encode(name, StandardCharsets.UTF_8));
MultipartFormContent labelsMultipart = new MultipartFormContent("labels", val.toJSONString());
this.multipartForm.push(nameMultipart, labelsMultipart);
this.multipartForm.push(files.stream()
.map(file -> new MultipartFile("files", file))
.toArray(MultipartFile[]::new));
}
}

View File

@@ -1,18 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.voices;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsDeleteRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestTransformer;
import org.json.simple.JSONObject;
import java.util.List;
public class DeleteVoiceRequest extends ElevenLabsDeleteRequest<JSONObject> {
public DeleteVoiceRequest(String voiceId) {
super(List.of(voiceId), RequestTransformer.IN_OUT_TRANSFORMER);
}
@Override
public String getEndpoint() {
return "voices/{voiceId}";
}
}

View File

@@ -1,45 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.voices;
import net.andrewcpu.elevenlabs.api.net.multipart.MultipartFile;
import net.andrewcpu.elevenlabs.api.net.multipart.MultipartForm;
import net.andrewcpu.elevenlabs.api.net.multipart.MultipartFormContent;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsPostRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestTransformer;
import net.andrewcpu.elevenlabs.enums.ContentType;
import net.andrewcpu.elevenlabs.enums.ResponseType;
import org.json.simple.JSONObject;
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
public class EditVoiceRequest extends ElevenLabsPostRequest<JSONObject> {
public EditVoiceRequest(String voiceId, String name, List<File> files, Map<String, String> labels) {
super(List.of(voiceId), RequestTransformer.IN_OUT_TRANSFORMER);
this.contentType = ContentType.MULTIPART;
this.multipartForm = new MultipartForm();
buildBody(name, files, labels);
}
@Override
public String getEndpoint() {
return "voices/{voiceId}/edit";
}
private void buildBody(String name, List<File> files, Map<String, String> labels) {
JSONObject val = new JSONObject();
if (labels != null && labels.size() != 0) {
labels.keySet().forEach(key -> val.put(key, labels.get(key)));
}
MultipartFormContent nameMultipart = new MultipartFormContent("name", URLEncoder.encode(name, StandardCharsets.UTF_8));
MultipartFormContent labelsMultipart = new MultipartFormContent("labels", val.toJSONString());
this.multipartForm.push(nameMultipart, labelsMultipart);
this.multipartForm.push(files.stream()
.map(file -> new MultipartFile("files", file))
.toArray(MultipartFile[]::new));
}
}

View File

@@ -1,18 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.voices;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsGetRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestTransformer;
import net.andrewcpu.elevenlabs.elements.voice.Voice;
import java.util.List;
public class GetVoiceRequest extends ElevenLabsGetRequest<Voice> {
public GetVoiceRequest(String voiceId, boolean withSettings) {
super(List.of(voiceId, String.valueOf(withSettings)), RequestTransformer.VOICE_TRANSFORMER);
}
@Override
public String getEndpoint() {
return "voices/{voiceId}?with_settings={withSettings}";
}
}

View File

@@ -1,18 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.voices;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsGetRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestTransformer;
import net.andrewcpu.elevenlabs.elements.voice.Voice;
import java.util.List;
public class GetVoicesRequest extends ElevenLabsGetRequest<List<Voice>> {
public GetVoicesRequest() {
super(RequestTransformer.VOICE_LIST_TRANSFORMER);
}
@Override
public String getEndpoint() {
return "voices";
}
}

View File

@@ -1,16 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.voices.settings;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsGetRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestTransformer;
import net.andrewcpu.elevenlabs.elements.voice.VoiceSettings;
public class GetDefaultVoiceSettingsRequest extends ElevenLabsGetRequest<VoiceSettings> {
public GetDefaultVoiceSettingsRequest() {
super(RequestTransformer.VOICE_SETTINGS_TRANSFORMER);
}
@Override
public String getEndpoint() {
return "voices/settings/default";
}
}

View File

@@ -1,18 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.voices.settings;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsGetRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestTransformer;
import net.andrewcpu.elevenlabs.elements.voice.VoiceSettings;
import java.util.List;
public class GetVoiceSettingsRequest extends ElevenLabsGetRequest<VoiceSettings> {
public GetVoiceSettingsRequest(String voiceId) {
super(List.of(voiceId), RequestTransformer.VOICE_SETTINGS_TRANSFORMER);
}
@Override
public String getEndpoint() {
return "voices/{voiceId}/settings";
}
}

View File

@@ -1,20 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.voices.settings;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsPostRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestTransformer;
import net.andrewcpu.elevenlabs.api.net.transformers.ResultTransformer;
import net.andrewcpu.elevenlabs.elements.voice.VoiceSettings;
import org.json.simple.JSONObject;
import java.util.List;
public class UpdateVoiceSettingsRequest extends ElevenLabsPostRequest<JSONObject> {
public UpdateVoiceSettingsRequest(String voiceId, VoiceSettings settings){
super(List.of(voiceId), settings.toJSON(), RequestTransformer.IN_OUT_TRANSFORMER);
}
@Override
public String getEndpoint() {
return "voices/{voiceId}/settings/edit";
}
}

View File

@@ -1,34 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.voices.tts;
import net.andrewcpu.elevenlabs.api.net.ElevenLabsRequest;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsPostRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.FilePingPongTransformer;
import net.andrewcpu.elevenlabs.elements.voice.Voice;
import net.andrewcpu.elevenlabs.elements.voice.VoiceSettings;
import net.andrewcpu.elevenlabs.enums.HTTPMethod;
import net.andrewcpu.elevenlabs.enums.ResponseType;
import org.json.simple.JSONObject;
import java.io.File;
import java.util.List;
@SuppressWarnings("unchecked")
public class GenerateTextToSpeechRequest extends ElevenLabsPostRequest<File> {
private static JSONObject buildBody(VoiceSettings settings, String text){
JSONObject object = new JSONObject();
object.put("text", text);
object.put("voice_settings", settings.toJSON());
return object;
}
public GenerateTextToSpeechRequest(Voice voice, VoiceSettings settings, String text, File outputFile){
super(List.of(voice.getVoiceId()), buildBody(settings, text), new FilePingPongTransformer(outputFile));
responseType = (ResponseType.FILE_STREAM);
outputFilePath = (outputFile);
}
@Override
public String getEndpoint() {
return "text-to-speech/{voiceId}";
}
}

View File

@@ -1,35 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.requests.voices.tts;
import net.andrewcpu.elevenlabs.api.net.requests.ElevenLabsPostRequest;
import net.andrewcpu.elevenlabs.api.net.transformers.RequestInputStreamTransformer;
import net.andrewcpu.elevenlabs.elements.voice.Voice;
import net.andrewcpu.elevenlabs.elements.voice.VoiceSettings;
import net.andrewcpu.elevenlabs.enums.ResponseType;
import net.andrewcpu.elevenlabs.util.StreamedResponseCallback;
import org.json.simple.JSONObject;
import java.io.File;
import java.io.InputStream;
import java.util.List;
public class GenerateTextToSpeechStreamRequest extends ElevenLabsPostRequest<InputStream> {
private static JSONObject buildBody(VoiceSettings settings, String text){
JSONObject object = new JSONObject();
object.put("text", text);
object.put("voice_settings", settings.toJSON());
return object;
}
public GenerateTextToSpeechStreamRequest(Voice voice, VoiceSettings settings, String text, StreamedResponseCallback callback, File outputFile){
super(List.of(voice.getVoiceId()), buildBody(settings, text), new RequestInputStreamTransformer());
responseType = (ResponseType.FILE_STREAM);
this.streamedResponseCallback = callback;
this.outputFilePath = outputFile;
if(outputFilePath.exists()) outputFilePath.delete();
}
@Override
public String getEndpoint() {
return "text-to-speech/{voiceId}/stream";
}
}

View File

@@ -1,19 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.transformers;
import net.andrewcpu.elevenlabs.util.DebugLogger;
import java.io.File;
public class FilePingPongTransformer extends ResultTransformerAdapter<File> {
private final File file;
public FilePingPongTransformer(File file) {
this.file = file;
}
@Override
public File transform() {
DebugLogger.log(getClass(), file.getAbsolutePath());
return file;
}
}

View File

@@ -1,18 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.transformers;
import net.andrewcpu.elevenlabs.api.net.ElevenLabsResponse;
import java.io.InputStream;
public class RequestInputStreamTransformer extends ResultTransformerAdapter<InputStream> {
@Override
public InputStream transform(ElevenLabsResponse<InputStream> response) {
return response.successStream;
}
@Override
public InputStream transform() {
return null;
}
}

View File

@@ -1,29 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.transformers;
import net.andrewcpu.elevenlabs.api.net.transformers.obj.*;
import net.andrewcpu.elevenlabs.elements.user.Subscription;
import net.andrewcpu.elevenlabs.elements.user.User;
import net.andrewcpu.elevenlabs.elements.voice.History;
import net.andrewcpu.elevenlabs.elements.voice.Voice;
import net.andrewcpu.elevenlabs.elements.voice.VoiceSettings;
import org.json.simple.JSONObject;
import java.util.List;
public class RequestTransformer {
public static final ResultTransformer<Voice> VOICE_TRANSFORMER = new VoiceTransformer();
public static final ResultTransformer<VoiceSettings> VOICE_SETTINGS_TRANSFORMER = new VoiceSettingTransformer();
public static final ResultTransformer<History> HISTORY_TRANSFORMER = new HistoryTransformer();
public static final ResultTransformer<User> USER_TRANSFORMER = new UserTransformer();
public static final ResultTransformer<Subscription> SUBSCRIPTION_TRANSFORMER = new SubscriptionTransformer();
public static final ResultTransformer<List<Voice>> VOICE_LIST_TRANSFORMER = new VoiceListTransformer();
public static final ResultTransformer<String> STRING_RESULT_TRANSFORMER = new StringPingPongTransformer();
public static final ResultTransformer<String> VOICE_ID_TRANSFORMER = new VoiceIDTransformer();
public static final ResultTransformer<JSONObject> IN_OUT_TRANSFORMER = new ResultTransformerAdapter<JSONObject>(){
@Override
public JSONObject transform(JSONObject object) {
return object;
}
};
}

View File

@@ -1,11 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.transformers;
import net.andrewcpu.elevenlabs.api.net.ElevenLabsResponse;
import org.json.simple.JSONObject;
public abstract class ResultTransformer<T> {
public abstract T transform(JSONObject object);
public abstract T transform(String object);
public abstract T transform();
public abstract T transform(ElevenLabsResponse<T> response);
}

View File

@@ -1,27 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.transformers;
import net.andrewcpu.elevenlabs.api.net.ElevenLabsResponse;
import org.json.simple.JSONObject;
public class ResultTransformerAdapter<T> extends ResultTransformer<T> {
@Override
public T transform(JSONObject object) {
throw new UnsupportedOperationException("transform(JSONObject object) is not defined.");
}
@Override
public T transform(String object) {
throw new UnsupportedOperationException("transform(String object) is not defined.");
}
@Override
public T transform() {
throw new UnsupportedOperationException("transform() is not defined.");
}
@Override
public T transform(ElevenLabsResponse<T> response) {
throw new UnsupportedOperationException("transform(Response response) is not defined.");
}
}

View File

@@ -1,11 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.transformers;
import net.andrewcpu.elevenlabs.util.DebugLogger;
public class StringPingPongTransformer extends ResultTransformerAdapter<String> {
@Override
public String transform(String object) {
DebugLogger.log(getClass(),object);
return object;
}
}

View File

@@ -1,12 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.transformers.obj;
import net.andrewcpu.elevenlabs.api.net.transformers.ResultTransformerAdapter;
import net.andrewcpu.elevenlabs.elements.voice.History;
import org.json.simple.JSONObject;
public class HistoryTransformer extends ResultTransformerAdapter<History> {
@Override
public History transform(JSONObject object) {
return History.fromJSON(object);
}
}

View File

@@ -1,12 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.transformers.obj;
import net.andrewcpu.elevenlabs.api.net.transformers.ResultTransformerAdapter;
import net.andrewcpu.elevenlabs.elements.user.Subscription;
import org.json.simple.JSONObject;
public class SubscriptionTransformer extends ResultTransformerAdapter<Subscription> {
@Override
public Subscription transform(JSONObject object) {
return Subscription.fromJSON(object);
}
}

View File

@@ -1,12 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.transformers.obj;
import net.andrewcpu.elevenlabs.api.net.transformers.ResultTransformerAdapter;
import net.andrewcpu.elevenlabs.elements.user.User;
import org.json.simple.JSONObject;
public class UserTransformer extends ResultTransformerAdapter<User> {
@Override
public User transform(JSONObject object) {
return User.fromJSON(object);
}
}

View File

@@ -1,12 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.transformers.obj;
import net.andrewcpu.elevenlabs.api.net.transformers.ResultTransformerAdapter;
import org.json.simple.JSONObject;
public class VoiceIDTransformer extends ResultTransformerAdapter<String> {
@Override
public String transform(JSONObject object) {
return object.get("voice_id").toString();
}
}

View File

@@ -1,24 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.transformers.obj;
import net.andrewcpu.elevenlabs.api.net.transformers.ResultTransformerAdapter;
import net.andrewcpu.elevenlabs.elements.voice.Voice;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class VoiceListTransformer extends ResultTransformerAdapter<List<Voice>> {
@Override
public List<Voice> transform(JSONObject object) {
JSONArray voiceArray = (JSONArray) object.get("voices");
List<Voice> voices = new ArrayList<>();
for (Object o : voiceArray) {
JSONObject voiceJson = (JSONObject) o;
voices.add(Voice.fromJSON(voiceJson));
}
return voices;
}
}

View File

@@ -1,12 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.transformers.obj;
import net.andrewcpu.elevenlabs.api.net.transformers.ResultTransformerAdapter;
import net.andrewcpu.elevenlabs.elements.voice.VoiceSettings;
import org.json.simple.JSONObject;
public class VoiceSettingTransformer extends ResultTransformerAdapter<VoiceSettings> {
@Override
public VoiceSettings transform(JSONObject object) {
return VoiceSettings.fromJSON(object);
}
}

View File

@@ -1,12 +0,0 @@
package net.andrewcpu.elevenlabs.api.net.transformers.obj;
import net.andrewcpu.elevenlabs.api.net.transformers.ResultTransformerAdapter;
import net.andrewcpu.elevenlabs.elements.voice.Voice;
import org.json.simple.JSONObject;
public class VoiceTransformer extends ResultTransformerAdapter<Voice> {
@Override
public Voice transform(JSONObject object) {
return Voice.fromJSON(object);
}
}

View File

@@ -1,80 +0,0 @@
package net.andrewcpu.elevenlabs.elements;
import net.andrewcpu.elevenlabs.ElevenLabsAPI;
import net.andrewcpu.elevenlabs.api.VoiceAPI;
import net.andrewcpu.elevenlabs.elements.voice.Voice;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsException;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsValidationException;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("UnusedReturnValue")
public class VoiceBuilder {
private String name = null;
private final Map<String, String> labels;
private final List<File> files;
private String voiceId;
public static VoiceBuilder fromVoice(Voice voice){
VoiceBuilder voiceBuilder = new VoiceBuilder();
voiceBuilder.withName(voice.getName());
voiceBuilder.withVoiceID(voice.getVoiceId());
for(String key : voice.getLabels().keySet()){
voiceBuilder.withLabel(key, voice.getLabels().get(key));
}
return voiceBuilder;
}
public VoiceBuilder() {
labels = new HashMap<>();
files = new ArrayList<>();
voiceId = null;
}
public VoiceBuilder withName(String name){
this.name = name;
return this;
}
public VoiceBuilder withFile(File file){
files.add(file);
return this;
}
public VoiceBuilder withLabel(String key, String value){
labels.put(key, value);
return this;
}
public VoiceBuilder removeLabel(String key){
labels.remove(key);
return this;
}
public VoiceBuilder removeFile(File file){
files.remove(file);
return this;
}
public VoiceBuilder withVoiceID(String id){
this.voiceId = id;
return this;
}
public Voice edit() throws ElevenLabsException {
VoiceAPI.editVoice(voiceId, name, labels, files);
return VoiceAPI.getVoice(voiceId, true);
}
public Voice create() throws ElevenLabsException {
if(files.isEmpty()){
throw new ElevenLabsValidationException("Cannot build a voice without any files.");
}
String voiceId = VoiceAPI.createVoice(name, labels, files);
return VoiceAPI.getVoice(voiceId, true);
}
}

View File

@@ -1,190 +0,0 @@
package net.andrewcpu.elevenlabs.elements.user;
import net.andrewcpu.elevenlabs.api.UserAPI;
import net.andrewcpu.elevenlabs.enums.AccountStatus;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
public class Subscription {
private final String tier;
private final int characterCount;
private final int characterLimit;
private final boolean canExtendCharacterLimit;
private final boolean allowedToExtendCharacterLimit;
private final long nextCharacterCountResetUnix;
private final int voiceLimit;
private final boolean canExtendVoiceLimit;
private final boolean canUseInstantVoiceCloning;
private final List<AvailableModel> availableModels;
private final AccountStatus status;
private final NextInvoice nextInvoice;
public static Subscription fromJSON(JSONObject object) {
String tier = (String) object.get("tier");
int characterCount = ((Long) object.get("character_count")).intValue();
int characterLimit = ((Long) object.get("character_limit")).intValue();
boolean canExtendCharacterLimit = (Boolean) object.get("can_extend_character_limit");
boolean allowedToExtendCharacterLimit = (Boolean) object.get("allowed_to_extend_character_limit");
long nextCharacterCountResetUnix = (Long) object.get("next_character_count_reset_unix");
int voiceLimit = ((Long) object.get("voice_limit")).intValue();
boolean canExtendVoiceLimit = (Boolean) object.get("can_extend_voice_limit");
boolean canUseInstantVoiceCloning = (Boolean) object.get("can_use_instant_voice_cloning");
List<AvailableModel> availableModels = new ArrayList<>();
JSONArray availableModelsJson = (JSONArray) object.get("available_models");
for (Object model : availableModelsJson) {
JSONObject modelJson = (JSONObject) model;
String modelId = (String) modelJson.get("model_id");
String displayName = (String) modelJson.get("display_name");
List<SupportedLanguage> supportedLanguages = new ArrayList<>();
JSONArray supportedLanguagesJson = (JSONArray) modelJson.get("supported_languages");
for (Object language : supportedLanguagesJson) {
JSONObject languageJson = (JSONObject) language;
String isoCode = (String) languageJson.get("iso_code");
String languageDisplayName = (String) languageJson.get("display_name");
supportedLanguages.add(new SupportedLanguage(isoCode, languageDisplayName));
}
availableModels.add(new AvailableModel(modelId, displayName, supportedLanguages));
}
String status = (String) object.get("status");
NextInvoice invoice = null;
if(object.containsKey("next_invoice")){
JSONObject nextInvoiceJson = (JSONObject) object.get("next_invoice");
invoice = new NextInvoice(
((Long) nextInvoiceJson.get("amount_due_cents")).intValue(),
(Long) nextInvoiceJson.get("next_payment_attempt_unix")
);
}
return new Subscription(tier, characterCount, characterLimit, canExtendCharacterLimit, allowedToExtendCharacterLimit, nextCharacterCountResetUnix, voiceLimit, canExtendVoiceLimit, canUseInstantVoiceCloning, availableModels, status, invoice);
}
public static Subscription get() throws ElevenLabsException {
return UserAPI.getSubscription();
}
private Subscription(String tier, int characterCount, int characterLimit, boolean canExtendCharacterLimit, boolean allowedToExtendCharacterLimit,
long nextCharacterCountResetUnix, int voiceLimit, boolean canExtendVoiceLimit, boolean canUseInstantVoiceCloning, List<AvailableModel> availableModels,
String status, NextInvoice nextInvoice) {
this.tier = tier;
this.characterCount = characterCount;
this.characterLimit = characterLimit;
this.canExtendCharacterLimit = canExtendCharacterLimit;
this.allowedToExtendCharacterLimit = allowedToExtendCharacterLimit;
this.nextCharacterCountResetUnix = nextCharacterCountResetUnix;
this.voiceLimit = voiceLimit;
this.canExtendVoiceLimit = canExtendVoiceLimit;
this.canUseInstantVoiceCloning = canUseInstantVoiceCloning;
this.availableModels = availableModels;
this.status = AccountStatus.valueOf(status.toUpperCase());
this.nextInvoice = nextInvoice;
}
public String getTier() {
return tier;
}
public int getCharacterCount() {
return characterCount;
}
public int getCharacterLimit() {
return characterLimit;
}
public boolean isCanExtendCharacterLimit() {
return canExtendCharacterLimit;
}
public boolean isAllowedToExtendCharacterLimit() {
return allowedToExtendCharacterLimit;
}
public long getNextCharacterCountResetUnix() {
return nextCharacterCountResetUnix;
}
public int getVoiceLimit() {
return voiceLimit;
}
public boolean isCanExtendVoiceLimit() {
return canExtendVoiceLimit;
}
public boolean isCanUseInstantVoiceCloning() {
return canUseInstantVoiceCloning;
}
public List<AvailableModel> getAvailableModels() {
return availableModels;
}
public AccountStatus getStatus() {
return status;
}
public NextInvoice getNextInvoice() {
return nextInvoice;
}
@Override
public String toString() {
return "Subscription{" +
"tier='" + tier + '\'' +
", characterCount=" + characterCount +
", characterLimit=" + characterLimit +
", canExtendCharacterLimit=" + canExtendCharacterLimit +
", allowedToExtendCharacterLimit=" + allowedToExtendCharacterLimit +
", nextCharacterCountResetUnix=" + nextCharacterCountResetUnix +
", voiceLimit=" + voiceLimit +
", canExtendVoiceLimit=" + canExtendVoiceLimit +
", canUseInstantVoiceCloning=" + canUseInstantVoiceCloning +
", availableModels=" + availableModels +
", status='" + status + '\'' +
", nextInvoice=" + nextInvoice +
'}';
}
public record AvailableModel(String modelId, String displayName, List<SupportedLanguage> supportedLanguages) {
@Override
public String toString() {
return "AvailableModel{" +
"modelId='" + modelId + '\'' +
", displayName='" + displayName + '\'' +
", supportedLanguages=" + supportedLanguages +
'}';
}
}
public record SupportedLanguage(String isoCode, String displayName) {
@Override
public String toString() {
return "SupportedLanguage{" +
"isoCode='" + isoCode + '\'' +
", displayName='" + displayName + '\'' +
'}';
}
}
public record NextInvoice(int amountDueCents, long nextPaymentAttemptUnix) {
public Date getNextPaymentAttempt() {
return new Date(nextPaymentAttemptUnix);
}
@Override
public String toString() {
return "NextInvoice{" +
"amountDueCents=" + amountDueCents +
", nextPaymentAttemptUnix=" + nextPaymentAttemptUnix +
'}';
}
}
}

View File

@@ -1,57 +0,0 @@
package net.andrewcpu.elevenlabs.elements.user;
import net.andrewcpu.elevenlabs.ElevenLabsAPI;
import net.andrewcpu.elevenlabs.api.HistoryAPI;
import net.andrewcpu.elevenlabs.api.UserAPI;
import net.andrewcpu.elevenlabs.elements.voice.History;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsException;
import org.json.simple.JSONObject;
public class User {
private final Subscription subscription;
private final boolean isNewUser;
private final String apiKey;
public static User get() throws ElevenLabsException {
return UserAPI.getUser();
}
public User(Subscription subscription, boolean isNewUser, String xiApiKey) {
this.subscription = subscription;
this.isNewUser = isNewUser;
this.apiKey = xiApiKey;
}
public Subscription getSubscription() {
return subscription;
}
public boolean isNewUser() {
return isNewUser;
}
public String getAPIKey() {
return apiKey;
}
public History getHistory() throws ElevenLabsException {
return HistoryAPI.getHistory();
}
public static User fromJSON(JSONObject object) {
JSONObject subscriptionJson = (JSONObject) object.get("subscription");
Subscription subscription = Subscription.fromJSON(subscriptionJson);
boolean isNewUser = (boolean) object.get("is_new_user");
String xiApiKey = (String) object.get("xi_api_key");
return new User(subscription, isNewUser, xiApiKey);
}
@Override
public String toString() {
return "User{" +
"subscription=" + subscription +
", isNewUser=" + isNewUser +
", apiKey='" + apiKey + '\'' +
'}';
}
}

View File

@@ -1,173 +0,0 @@
package net.andrewcpu.elevenlabs.elements.voice;
import net.andrewcpu.elevenlabs.api.HistoryAPI;
import net.andrewcpu.elevenlabs.api.VoiceAPI;
import net.andrewcpu.elevenlabs.enums.GenerationState;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
public record History(List<HistoryItem> history) {
public static History fromJSON(JSONObject object) {
List<HistoryItem> historyItems = new ArrayList<>();
JSONArray historyArray = (JSONArray) object.get("history");
History history = new History(new ArrayList<>());
for (Object item : historyArray) {
JSONObject itemJson = (JSONObject) item;
String historyItemId = (String) itemJson.get("history_item_id");
String voiceId = (String) itemJson.get("voice_id");
String voiceName = (String) itemJson.get("voice_name");
String text = (String) itemJson.get("text");
long dateUnix = (Long) itemJson.get("date_unix");
int characterCountChangeFrom = ((Long) itemJson.get("character_count_change_from")).intValue();
int characterCountChangeTo = ((Long) itemJson.get("character_count_change_to")).intValue();
String contentType = (String) itemJson.get("content_type");
String state = (String) itemJson.get("state");
HistoryItem historyItem = new HistoryItem(historyItemId, voiceId, voiceName, text, dateUnix, characterCountChangeFrom, characterCountChangeTo, contentType, state, history);
historyItems.add(historyItem);
}
history.history.addAll(historyItems);
return history;
}
public static History get() throws ElevenLabsException {
return HistoryAPI.getHistory();
}
public HistoryItem getHistoryItem(String id) {
for (HistoryItem item : history) {
if (item.getHistoryItemId().equals(id)) {
return item;
}
}
return null;
}
public File downloadHistory(String[] ids, File file) throws ElevenLabsException {
return HistoryAPI.downloadHistory(Arrays.stream(ids).toList(), file);
}
public File downloadHistory(List<HistoryItem> historyItems, File file) throws ElevenLabsException {
return HistoryAPI.downloadHistory(historyItems.stream().map(HistoryItem::getHistoryItemId).collect(Collectors.toList()), file);
}
@Override
public String toString() {
return "History{" +
"history=" + history +
'}';
}
public static class HistoryItem {
private final String historyItemId;
private final String voiceId;
private final String voiceName;
private final String text;
private final long dateUnix;
private final int characterCountChangeFrom;
private final int characterCountChangeTo;
private final String contentType;
private final GenerationState state;
private Voice voice;
private final History history;
HistoryItem(String historyItemId, String voiceId, String voiceName, String text, long dateUnix, int characterCountChangeFrom, int characterCountChangeTo, String contentType, String state, History history) {
this.historyItemId = historyItemId;
this.voiceId = voiceId;
this.voiceName = voiceName;
this.text = text;
this.dateUnix = dateUnix;
this.characterCountChangeFrom = characterCountChangeFrom;
this.characterCountChangeTo = characterCountChangeTo;
this.contentType = contentType;
this.state = GenerationState.valueOf(state.toUpperCase());
this.history = history;
this.voice = null;
}
public Voice getVoice() {
if (voice == null) {
try {
voice = VoiceAPI.getVoice(voiceId);
} catch (ElevenLabsException e) {
throw new RuntimeException(e);
}
}
return voice;
}
public String getHistoryItemId() {
return historyItemId;
}
public String getVoiceId() {
return voiceId;
}
public String getVoiceName() {
return voiceName;
}
public String getText() {
return text;
}
public long getDateUnix() {
return dateUnix;
}
public Date getDate() {
return new Date(dateUnix);
}
public int getCharacterCountChangeFrom() {
return characterCountChangeFrom;
}
public int getCharacterCountChangeTo() {
return characterCountChangeTo;
}
public String getContentType() {
return contentType;
}
public GenerationState getState() {
return state;
}
public String delete() throws ElevenLabsException {
String output = HistoryAPI.deleteHistoryItem(this);
history.history.remove(this);
return output;
}
public File downloadAudio(File outputFile) throws ElevenLabsException {
return HistoryAPI.getHistoryItemAudio(this, outputFile);
}
@Override
public String toString() {
return "HistoryItem{" +
"historyItemId='" + historyItemId + '\'' +
", voiceId='" + voiceId + '\'' +
", voiceName='" + voiceName + '\'' +
", text='" + text + '\'' +
", dateUnix=" + dateUnix +
", characterCountChangeFrom=" + characterCountChangeFrom +
", characterCountChangeTo=" + characterCountChangeTo +
", contentType='" + contentType + '\'' +
", state='" + state + '\'' +
", voice=" + voice +
'}';
}
}
}

View File

@@ -1,91 +0,0 @@
package net.andrewcpu.elevenlabs.elements.voice;
import net.andrewcpu.elevenlabs.ElevenLabsAPI;
import net.andrewcpu.elevenlabs.api.SampleAPI;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsException;
import org.json.simple.JSONObject;
import java.io.File;
public class Sample {
private final String sampleId;
private final String fileName;
private final String mimeType;
private final long sizeBytes;
private final String hash;
private Voice voice;
static Sample fromJSON(JSONObject object) {
String sampleId = (String) object.get("sample_id");
String fileName = (String) object.get("file_name");
String mimeType = (String) object.get("mime_type");
int sizeBytes = ((Long) object.get("size_bytes")).intValue();
String hash = (String) object.get("hash");
return new Sample(sampleId, fileName, mimeType, sizeBytes, hash);
}
private Sample(String sampleId, String fileName, String mimeType, long sizeBytes, String hash) {
this.sampleId = sampleId;
this.fileName = fileName;
this.mimeType = mimeType;
this.sizeBytes = sizeBytes;
this.hash = hash;
}
public Voice getVoice() {
return voice;
}
public void setVoice(Voice voice) {
this.voice = voice;
}
public String getSampleId() {
return sampleId;
}
public String getFileName() {
return fileName;
}
public String getMimeType() {
return mimeType;
}
public long getSizeBytes() {
return sizeBytes;
}
public String getHash() {
return hash;
}
public boolean delete() throws ElevenLabsException {
JSONObject result = SampleAPI.deleteSample(voice,this);
if(result.containsKey("status")){
if(result.get("status").equals("ok")){
return true;
}
}
return false;
}
public File downloadAudio(File outputFile) throws ElevenLabsException {
return SampleAPI.getSampleAudio(voice, this, outputFile);
}
@Override
public String toString() {
return "Sample{" +
"sampleId='" + sampleId + '\'' +
", fileName='" + fileName + '\'' +
", mimeType='" + mimeType + '\'' +
", sizeBytes=" + sizeBytes +
", hash='" + hash + '\'' +
", voice=" + voice.getVoiceId() +
'}';
}
}

View File

@@ -1,193 +0,0 @@
package net.andrewcpu.elevenlabs.elements.voice;
import net.andrewcpu.elevenlabs.ElevenLabsAPI;
import net.andrewcpu.elevenlabs.api.VoiceAPI;
import net.andrewcpu.elevenlabs.elements.VoiceBuilder;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsException;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsValidationException;
import net.andrewcpu.elevenlabs.util.StreamedResponseCallback;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import java.io.File;
import java.io.InputStream;
import java.util.*;
public class Voice {
private final String voiceId;
private final String name;
private final List<Sample> samples;
private final String category;
private final Map<String, String> labels;
private final String previewUrl;
private final List<String> availableForTiers;
private VoiceSettings voiceSettings;
private boolean hasSettings;
public static Voice fromJSON(JSONObject object) {
String voiceId = (String) object.get("voice_id");
String name = (String) object.get("name");
List<Sample> samples = new ArrayList<>();
if(object.containsKey("samples") && object.get("samples") != null){
JSONArray samplesJson = (JSONArray) object.get("samples");
for (Object sampleObj : samplesJson) {
JSONObject sampleJson = (JSONObject) sampleObj;
samples.add(Sample.fromJSON(sampleJson));
}
}
String category = (String) object.get("category");
JSONObject labelsJson = (JSONObject) object.get("labels");
Map<String, String> labels = new HashMap<>();
for (Object key : labelsJson.keySet()) {
String labelName = (String) key;
String labelValue = (String) labelsJson.get(labelName);
labels.put(labelName, labelValue);
}
String previewUrl = (String) object.get("preview_url");
JSONArray availableForTiersJson = (JSONArray) object.get("available_for_tiers");
List<String> availableForTiers = new ArrayList<>();
for (Object tier : availableForTiersJson) {
availableForTiers.add((String) tier);
}
double stab = -1;
double sim = -1;
if(object.containsKey("settings") && object.get("settings") != null){
JSONObject settingsJson = (JSONObject) object.get("settings");
VoiceSettings settings = new VoiceSettings(((Double) settingsJson.get("stability")),
((Double) settingsJson.get("similarity_boost")));
stab = settings.getStability();
sim = settings.getSimilarityBoost();
}
Voice voice = new Voice(voiceId, name, samples, category, labels, previewUrl, availableForTiers, stab, sim);
voice.hasSettings = stab != -1;
voice.getSamples().forEach(s -> s.setVoice(voice));
return voice;
}
public static List<Voice> getVoices() throws ElevenLabsException {
return VoiceAPI.getVoices();
}
public static Voice get(String voiceId) throws ElevenLabsException {
Voice voice = VoiceAPI.getVoice(voiceId);
voice.hasSettings = true;
return voice;
}
public static Voice get(String voiceId, boolean withSettings) throws ElevenLabsException {
Voice voice = VoiceAPI.getVoice(voiceId, withSettings);
voice.hasSettings = withSettings;
return voice;
}
private Voice(String voiceId, String name, List<Sample> samples, String category, Map<String, String> labels, String previewUrl, List<String> availableForTiers, double stability, double similarityBoost) {
this.voiceId = voiceId;
this.name = name;
this.samples = samples;
this.category = category;
this.labels = labels;
this.previewUrl = previewUrl;
this.availableForTiers = availableForTiers;
this.voiceSettings = new VoiceSettings(stability, similarityBoost);
}
public String getVoiceId() {
return voiceId;
}
public String getName() {
return name;
}
public List<Sample> getSamples() {
return samples;
}
public String getCategory() {
return category;
}
public Map<String, String> getLabels() {
return labels;
}
public String getPreviewUrl() {
return previewUrl;
}
public List<String> getAvailableForTiers() {
return availableForTiers;
}
public VoiceSettings getVoiceSettings() {
return voiceSettings;
}
public boolean delete() throws ElevenLabsException {
return VoiceAPI.deleteVoice(getVoiceId());
}
public void fetchSettings() throws ElevenLabsException {
this.voiceSettings = VoiceAPI.getVoiceSettings(getVoiceId());
hasSettings = true;
}
public VoiceBuilder editor() {
return VoiceBuilder.fromVoice(this);
}
public void updateVoiceSettings(VoiceSettings settings) throws ElevenLabsException {
JSONObject response = VoiceAPI.editVoice(this, settings);
if(response != null){
this.voiceSettings = settings;
hasSettings = true;
return;
}
}
public File generate(String text, VoiceSettings voiceSettings, File output) throws ElevenLabsException {
return VoiceAPI.getTextToSpeech(text, this, voiceSettings,output);
}
public File generate(String text, File output) throws ElevenLabsException {
if(!hasSettings){
throw new ElevenLabsValidationException("Cannot use default voice settings for " + voiceId + " because this object does not have VoiceSettings");
}
return generate(text, voiceSettings, output);
}
public InputStream generateStream(String text, VoiceSettings voiceSettings, StreamedResponseCallback streamedResponseCallback, File file) throws ElevenLabsException {
return VoiceAPI.getTextToSpeechStreamed(text, this, voiceSettings, streamedResponseCallback, file);
}
public InputStream generateStream(String text, StreamedResponseCallback callback, File file) throws ElevenLabsException {
return generateStream(text, voiceSettings, callback, file);
}
public String getLabel(String label) {
return labels.get(label);
}
public boolean hasLabel(String label){
return labels.containsKey(label);
}
@Override
public String toString() {
return "Voice{" +
"voiceId='" + voiceId + '\'' +
", name='" + name + '\'' +
", samples=" + samples +
", category='" + category + '\'' +
", labels=" + labels +
", previewUrl='" + previewUrl + '\'' +
", availableForTiers=" + availableForTiers +
", voiceSettings=" + voiceSettings +
'}';
}
}

View File

@@ -1,55 +0,0 @@
package net.andrewcpu.elevenlabs.elements.voice;
import net.andrewcpu.elevenlabs.api.VoiceAPI;
import net.andrewcpu.elevenlabs.exceptions.ElevenLabsException;
import org.json.simple.JSONObject;
@SuppressWarnings("unchecked")
public class VoiceSettings {
private double stability;
private double similarityBoost;
public static VoiceSettings fromJSON(JSONObject object){
return new VoiceSettings((double)object.get("stability"), (double)object.get("similarity_boost"));
}
public static VoiceSettings getDefaultVoiceSettings() throws ElevenLabsException {
return VoiceAPI.getDefaultVoiceSettings();
}
public VoiceSettings(double stability, double similarityBoost) {
this.stability = stability;
this.similarityBoost = similarityBoost;
}
public double getStability() {
return stability;
}
public void setStability(double stability) {
this.stability = stability;
}
public double getSimilarityBoost() {
return similarityBoost;
}
public void setSimilarityBoost(double similarityBoost) {
this.similarityBoost = similarityBoost;
}
public JSONObject toJSON() {
JSONObject object = new JSONObject();
object.put("stability", stability);
object.put("similarity_boost", similarityBoost);
return object;
}
@Override
public String toString() {
return "VoiceSettings{" +
"stability=" + stability +
", similarityBoost=" + similarityBoost +
'}';
}
}

View File

@@ -1,12 +0,0 @@
package net.andrewcpu.elevenlabs.enums;
public enum AccountStatus {
TRIALING,
ACTIVE,
INCOMPLETE,
INCOMPLETE_EXPIRED,
PAST_DUE,
CANCELED,
UNPAID,
FREE
}

View File

@@ -1,14 +0,0 @@
package net.andrewcpu.elevenlabs.enums;
public enum ContentType {
JSON("application/json"), MULTIPART("multipart/form-data");
private final String type;
ContentType(String type) {
this.type = type;
}
public String getType() {
return type;
}
}

View File

@@ -1,7 +0,0 @@
package net.andrewcpu.elevenlabs.enums;
public enum GenerationState {
CREATED,
DELETED,
PROCESSING
}

View File

@@ -1,8 +0,0 @@
package net.andrewcpu.elevenlabs.enums;
public enum HTTPMethod {
POST,
GET,
PUT,
DELETE
}

View File

@@ -0,0 +1,5 @@
package net.andrewcpu.elevenlabs.enums;
public enum HttpRequestType {
POST, GET, PUT, DELETE;
}

View File

@@ -1,7 +0,0 @@
package net.andrewcpu.elevenlabs.enums;
public enum ResponseType {
JSON,
FILE_STREAM,
STRING
}

View File

@@ -1,7 +0,0 @@
package net.andrewcpu.elevenlabs.exceptions;
public class ElevenLabsAPINotInitiatedException extends ElevenLabsException{
public ElevenLabsAPINotInitiatedException() {
super("ElevenLabs API has not been initiated.");
}
}

View File

@@ -1,13 +0,0 @@
package net.andrewcpu.elevenlabs.exceptions;
import java.io.IOException;
public class ElevenLabsException extends Exception{
public ElevenLabsException(String message) {
super(message);
}
public ElevenLabsException(IOException ioException) {
super(ioException);
}
}

View File

@@ -1,26 +0,0 @@
package net.andrewcpu.elevenlabs.exceptions;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class ElevenLabsExceptionBuilder {
public static ElevenLabsValidationException build(JSONObject errorResponse) {
StringBuilder message = new StringBuilder();
if(errorResponse.get("detail") instanceof JSONObject detail) {
message.append(detail.get("status")).append(" ").append(detail.get("message"));
}
else if(errorResponse.get("detail") instanceof JSONArray details){
for(Object detailObject : details){
JSONObject detail = (JSONObject)detailObject;
String locStr = ((JSONArray)detail.get("loc")).get(0).toString();
int locInt = (int)(((JSONArray)detail.get("loc")).get(1));
message.append(detail.get("type").toString())
.append(": ")
.append(detail.get("msg").toString()).append(" at ").append(locStr).append(":").append(locInt)
.append("\n");
}
}
return new ElevenLabsValidationException(message.toString().trim());
}
}

View File

@@ -1,7 +0,0 @@
package net.andrewcpu.elevenlabs.exceptions;
public class ElevenLabsValidationException extends ElevenLabsException{
public ElevenLabsValidationException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,7 @@
package net.andrewcpu.elevenlabs.exceptions;
public class RequestException extends Exception {
public RequestException(String message) {
super(message);
}
}

View File

@@ -0,0 +1,9 @@
package net.andrewcpu.elevenlabs.exceptions;
import net.andrewcpu.elevenlabs.model.error.ValidationError;
public class ValidationException extends RequestException{
public ValidationException(ValidationError validationError) {
super(validationError.toString());
}
}

View File

@@ -0,0 +1,8 @@
package net.andrewcpu.elevenlabs.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class ElevenModel {
}

View File

@@ -0,0 +1,39 @@
package net.andrewcpu.elevenlabs.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Language {
@JsonProperty("language_id")
private String languageId;
@JsonProperty("name")
private String name;
public Language(String languageId, String name) {
this.languageId = languageId;
this.name = name;
}
public Language() {
}
@JsonIgnore
public String getLanguageId() {
return languageId;
}
@JsonIgnore
public String getName() {
return name;
}
@Override
@JsonIgnore
public String toString() {
return "Language{" +
"languageId='" + languageId + '\'' +
", name='" + name + '\'' +
'}';
}
}

View File

@@ -0,0 +1,32 @@
package net.andrewcpu.elevenlabs.model.error;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.model.ElevenModel;
import java.util.List;
public class ValidationError extends ElevenModel {
@JsonProperty("detail")
private List<ValidationErrorDetail> details;
public ValidationError(List<ValidationErrorDetail> details) {
this.details = details;
}
public ValidationError() {
}
@JsonIgnore
public List<ValidationErrorDetail> getDetails() {
return details;
}
@Override
@JsonIgnore
public String toString() {
return "ValidationError{" +
"details=" + details +
'}';
}
}

View File

@@ -0,0 +1,52 @@
package net.andrewcpu.elevenlabs.model.error;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.model.ElevenModel;
import java.util.List;
public class ValidationErrorDetail extends ElevenModel {
@JsonProperty("loc")
private List locations;
@JsonProperty("msg")
private String message;
@JsonProperty("type")
private String type;
public ValidationErrorDetail(List locations, String message, String type) {
this.locations = locations;
this.message = message;
this.type = type;
}
public ValidationErrorDetail() {
}
@JsonIgnore
public List getLocations() {
return locations;
}
@JsonIgnore
public String getMessage() {
return message;
}
@JsonIgnore
public String getType() {
return type;
}
@JsonIgnore
@Override
public String toString() {
return "ValidationErrorDetail{" +
"locations=" + locations +
", message='" + message + '\'' +
", type='" + type + '\'' +
'}';
}
}

View File

@@ -0,0 +1,101 @@
package net.andrewcpu.elevenlabs.model.history;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.model.ElevenModel;
public class Feedback extends ElevenModel {
@JsonProperty("thumbs_up")
private boolean thumbsUp;
@JsonProperty("feedback")
private String feedback;
@JsonProperty("emotions")
private boolean emotions;
@JsonProperty("inaccurate_clone")
private boolean inaccurateClone;
@JsonProperty("glitches")
private boolean glitches;
@JsonProperty("audio_quality")
private boolean audioQuality;
@JsonProperty("other")
private boolean other;
@JsonProperty("review_status")
private String reviewStatus;
public Feedback(boolean thumbsUp, String feedback, boolean emotions, boolean inaccurateClone, boolean glitches, boolean audioQuality, boolean other, String reviewStatus) {
this.thumbsUp = thumbsUp;
this.feedback = feedback;
this.emotions = emotions;
this.inaccurateClone = inaccurateClone;
this.glitches = glitches;
this.audioQuality = audioQuality;
this.other = other;
this.reviewStatus = reviewStatus;
}
public Feedback() {
}
@JsonIgnore
public boolean isThumbsUp() {
return thumbsUp;
}
@JsonIgnore
public String getFeedback() {
return feedback;
}
@JsonIgnore
public boolean isEmotions() {
return emotions;
}
@JsonIgnore
public boolean isInaccurateClone() {
return inaccurateClone;
}
@JsonIgnore
public boolean isGlitches() {
return glitches;
}
@JsonIgnore
public boolean isAudioQuality() {
return audioQuality;
}
@JsonIgnore
public boolean isOther() {
return other;
}
@JsonIgnore
public String getReviewStatus() {
return reviewStatus;
}
@JsonIgnore
@Override
public String toString() {
return "Feedback{" +
"thumbsUp=" + thumbsUp +
", feedback='" + feedback + '\'' +
", emotions=" + emotions +
", inaccurateClone=" + inaccurateClone +
", glitches=" + glitches +
", audioQuality=" + audioQuality +
", other=" + other +
", reviewStatus='" + reviewStatus + '\'' +
'}';
}
}

View File

@@ -0,0 +1,76 @@
package net.andrewcpu.elevenlabs.model.history;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.ElevenLabs;
import net.andrewcpu.elevenlabs.model.ElevenModel;
import java.io.File;
import java.util.Arrays;
import java.util.List;
public class History extends ElevenModel {
public static History get() {
return ElevenLabs.getHistory();
}
@JsonProperty("history")
private List<HistoryItem> historyItems;
@JsonProperty("last_history_item_id")
private String lastHistoryItemId;
@JsonProperty("has_more")
private boolean hasMore;
public History(List<HistoryItem> historyItems) {
this.historyItems = historyItems;
}
public History() {
}
@JsonIgnore
public HistoryItem getHistoryItem(String id) {
for (HistoryItem item : historyItems) {
if (item.getHistoryItemId().equals(id)) {
return item;
}
}
return null;
}
@JsonIgnore
public List<HistoryItem> getHistoryItems() {
return historyItems;
}
@JsonIgnore
public String getLastHistoryItemId() {
return lastHistoryItemId;
}
@JsonIgnore
public boolean isHasMore() {
return hasMore;
}
public File downloadHistory(String... historyIds) {
return ElevenLabs.getHistoryItemAudio(historyIds);
}
public File downloadHistory(HistoryItem... items) {
return ElevenLabs.getHistoryItemAudio(Arrays.stream(items).map(HistoryItem::getHistoryItemId).toArray(String[]::new));
}
@JsonIgnore
@Override
public String toString() {
return "History{" +
"historyItems=" + historyItems +
", lastHistoryItemId='" + lastHistoryItemId + '\'' +
", hasMore=" + hasMore +
'}';
}
}

View File

@@ -0,0 +1,152 @@
package net.andrewcpu.elevenlabs.model.history;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.ElevenLabs;
import net.andrewcpu.elevenlabs.model.ElevenModel;
import java.io.File;
import java.util.Map;
public class HistoryItem extends ElevenModel {
@JsonProperty("history_item_id")
private String historyItemId;
@JsonProperty("request_id")
private String requestId;
@JsonProperty("voice_id")
private String voiceId;
@JsonProperty("voice_name")
private String voiceName;
@JsonProperty("text")
private String text;
@JsonProperty("date_unix")
private long dateUnix;
@JsonProperty("character_count_change_from")
private int characterCountChangeFrom;
@JsonProperty("character_count_change_to")
private int characterCountChangeTo;
@JsonProperty("content_type")
private String contentType;
@JsonProperty("state")
private String state;
@JsonProperty("settings")
private Map<String, Object> settings;
@JsonProperty("feedback")
private Feedback feedback;
public HistoryItem(String historyItemId, String requestId, String voiceId, String voiceName, String text, long dateUnix, int characterCountChangeFrom, int characterCountChangeTo, String contentType, String state, Map<String, Object> settings, Feedback feedback) {
this.historyItemId = historyItemId;
this.requestId = requestId;
this.voiceId = voiceId;
this.voiceName = voiceName;
this.text = text;
this.dateUnix = dateUnix;
this.characterCountChangeFrom = characterCountChangeFrom;
this.characterCountChangeTo = characterCountChangeTo;
this.contentType = contentType;
this.state = state;
this.settings = settings;
this.feedback = feedback;
}
public HistoryItem() {
}
@JsonIgnore
public String getHistoryItemId() {
return historyItemId;
}
@JsonIgnore
public String getRequestId() {
return requestId;
}
@JsonIgnore
public String getVoiceId() {
return voiceId;
}
@JsonIgnore
public String getVoiceName() {
return voiceName;
}
@JsonIgnore
public String getText() {
return text;
}
@JsonIgnore
public long getDateUnix() {
return dateUnix;
}
@JsonIgnore
public int getCharacterCountChangeFrom() {
return characterCountChangeFrom;
}
@JsonIgnore
public int getCharacterCountChangeTo() {
return characterCountChangeTo;
}
@JsonIgnore
public String getContentType() {
return contentType;
}
@JsonIgnore
public String getState() {
return state;
}
@JsonIgnore
public Map<String, Object> getSettings() {
return settings;
}
@JsonIgnore
public Feedback getFeedback() {
return feedback;
}
public String delete() {
return ElevenLabs.deleteHistoryItem(historyItemId);
}
public File downloadAudio() {
return ElevenLabs.getHistoryItemAudio(historyItemId);
}
@JsonIgnore
@Override
public String toString() {
return "HistoryItem{" +
"historyItemId='" + historyItemId + '\'' +
", requestId='" + requestId + '\'' +
", voiceId='" + voiceId + '\'' +
", voiceName='" + voiceName + '\'' +
", text='" + text + '\'' +
", dateUnix=" + dateUnix +
", characterCountChangeFrom=" + characterCountChangeFrom +
", characterCountChangeTo=" + characterCountChangeTo +
", contentType='" + contentType + '\'' +
", state='" + state + '\'' +
", settings=" + settings +
", feedback=" + feedback +
'}';
}
}

View File

@@ -0,0 +1,32 @@
package net.andrewcpu.elevenlabs.model.history;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.model.ElevenModel;
import java.util.List;
public class HistoryItemList extends ElevenModel {
@JsonProperty("history_item_ids")
private List<String> historyIds;
public HistoryItemList(List<String> historyIds) {
this.historyIds = historyIds;
}
public HistoryItemList() {
}
@JsonIgnore
public List<String> getHistoryIds() {
return historyIds;
}
@JsonIgnore
@Override
public String toString() {
return "HistoryItemList{" +
"historyIds=" + historyIds +
'}';
}
}

View File

@@ -0,0 +1,51 @@
package net.andrewcpu.elevenlabs.model.request;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.model.ElevenModel;
import net.andrewcpu.elevenlabs.model.voice.VoiceSettings;
public class TextToSpeechRequest extends ElevenModel {
@JsonProperty("text")
private String text;
@JsonProperty("model_id")
private String modelId;
@JsonProperty("voice_settings")
private VoiceSettings voiceSettings;
public TextToSpeechRequest(String text, String modelId, VoiceSettings voiceSettings) {
this.text = text;
this.modelId = modelId;
this.voiceSettings = voiceSettings;
}
public TextToSpeechRequest() {
}
@JsonIgnore
public String getText() {
return text;
}
@JsonIgnore
public String getModelId() {
return modelId;
}
@JsonIgnore
public VoiceSettings getVoiceSettings() {
return voiceSettings;
}
@JsonIgnore
@Override
public String toString() {
return "TextToSpeechRequest{" +
"text='" + text + '\'' +
", modelId='" + modelId + '\'' +
", voiceSettings=" + voiceSettings +
'}';
}
}

View File

@@ -0,0 +1,30 @@
package net.andrewcpu.elevenlabs.model.response;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.model.ElevenModel;
public class CreateVoiceResponse extends ElevenModel {
@JsonProperty("voice_id")
private String voiceId;
public CreateVoiceResponse(String voiceId) {
this.voiceId = voiceId;
}
public CreateVoiceResponse() {
}
@JsonIgnore
public String getVoiceId() {
return voiceId;
}
@JsonIgnore
@Override
public String toString() {
return "CreateVoiceResponse{" +
"voiceId='" + voiceId + '\'' +
'}';
}
}

View File

@@ -0,0 +1,104 @@
package net.andrewcpu.elevenlabs.model.response;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.model.ElevenModel;
import net.andrewcpu.elevenlabs.model.Language;
import java.util.List;
public class GenerationTypeModel extends ElevenModel {
@JsonProperty("model_id")
private String modelId;
@JsonProperty("name")
private String name;
@JsonProperty("can_be_finetuned")
private boolean canBeFinetuned;
@JsonProperty("can_do_text_to_speech")
private boolean canDoTextToSpeech;
@JsonProperty("can_do_voice_conversion")
private boolean canDoVoiceConversion;
@JsonProperty("token_cost_factor")
private int tokenCostFactor;
@JsonProperty("description")
private String description;
@JsonProperty("languages")
private List<Language> languages;
public GenerationTypeModel(String modelId, String name, boolean canBeFinetuned, boolean canDoTextToSpeech, boolean canDoVoiceConversion, int tokenCostFactor, String description, List<Language> languages) {
this.modelId = modelId;
this.name = name;
this.canBeFinetuned = canBeFinetuned;
this.canDoTextToSpeech = canDoTextToSpeech;
this.canDoVoiceConversion = canDoVoiceConversion;
this.tokenCostFactor = tokenCostFactor;
this.description = description;
this.languages = languages;
}
public GenerationTypeModel() {
}
@JsonIgnore
public String getModelId() {
return modelId;
}
@JsonIgnore
public String getName() {
return name;
}
@JsonIgnore
public boolean isCanBeFinetuned() {
return canBeFinetuned;
}
@JsonIgnore
public boolean isCanDoTextToSpeech() {
return canDoTextToSpeech;
}
@JsonIgnore
public boolean isCanDoVoiceConversion() {
return canDoVoiceConversion;
}
@JsonIgnore
public int getTokenCostFactor() {
return tokenCostFactor;
}
@JsonIgnore
public String getDescription() {
return description;
}
@JsonIgnore
public List<Language> getLanguages() {
return languages;
}
@JsonIgnore
@Override
public String toString() {
return "ModelResponse{" +
"modelId='" + modelId + '\'' +
", name='" + name + '\'' +
", canBeFinetuned=" + canBeFinetuned +
", canDoTextToSpeech=" + canDoTextToSpeech +
", canDoVoiceConversion=" + canDoVoiceConversion +
", tokenCostFactor=" + tokenCostFactor +
", description='" + description + '\'' +
", languages=" + languages +
'}';
}
}

View File

@@ -0,0 +1,33 @@
package net.andrewcpu.elevenlabs.model.response;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.model.ElevenModel;
import net.andrewcpu.elevenlabs.model.voice.Voice;
import java.util.List;
public class VoiceModelResponse extends ElevenModel {
@JsonProperty("voices")
private List<Voice> voices;
public VoiceModelResponse(List<Voice> voices) {
this.voices = voices;
}
public VoiceModelResponse() {
}
@JsonIgnore
public List<Voice> getVoices() {
return voices;
}
@JsonIgnore
@Override
public String toString() {
return "VoiceModelResponse{" +
"voices=" + voices +
'}';
}
}

View File

@@ -0,0 +1,113 @@
package net.andrewcpu.elevenlabs.model.tuning;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.model.ElevenModel;
import java.util.List;
public class FineTuning extends ElevenModel {
@JsonProperty("model_id")
private String modelId;
@JsonProperty("language")
private String language;
@JsonProperty("is_allowed_to_fine_tune")
private boolean isAllowedToFineTune;
@JsonProperty("fine_tuning_requested")
private boolean fineTuningRequested;
@JsonProperty("finetuning_state")
private String finetuningState;
@JsonProperty("verification_attempts")
private List<VerificationAttempt> verificationAttempts;
@JsonProperty("verification_failures")
private List<String> verificationFailures;
@JsonProperty("verification_attempts_count")
private int verificationAttemptsCount;
@JsonProperty("slice_ids")
private List<String> sliceIds;
public FineTuning(String modelId, String language, boolean isAllowedToFineTune, boolean fineTuningRequested, String finetuningState, List<VerificationAttempt> verificationAttempts, List<String> verificationFailures, int verificationAttemptsCount, List<String> sliceIds) {
this.modelId = modelId;
this.language = language;
this.isAllowedToFineTune = isAllowedToFineTune;
this.fineTuningRequested = fineTuningRequested;
this.finetuningState = finetuningState;
this.verificationAttempts = verificationAttempts;
this.verificationFailures = verificationFailures;
this.verificationAttemptsCount = verificationAttemptsCount;
this.sliceIds = sliceIds;
}
public FineTuning() {
}
@JsonIgnore
public String getModelId() {
return modelId;
}
@JsonIgnore
public String getLanguage() {
return language;
}
@JsonIgnore
public boolean isAllowedToFineTune() {
return isAllowedToFineTune;
}
@JsonIgnore
public boolean isFineTuningRequested() {
return fineTuningRequested;
}
@JsonIgnore
public String getFinetuningState() {
return finetuningState;
}
@JsonIgnore
public List<VerificationAttempt> getVerificationAttempts() {
return verificationAttempts;
}
@JsonIgnore
public List<String> getVerificationFailures() {
return verificationFailures;
}
@JsonIgnore
public int getVerificationAttemptsCount() {
return verificationAttemptsCount;
}
@JsonIgnore
public List<String> getSliceIds() {
return sliceIds;
}
@Override
@JsonIgnore
public String toString() {
return "FineTuning{" +
"modelId='" + modelId + '\'' +
", language='" + language + '\'' +
", isAllowedToFineTune=" + isAllowedToFineTune +
", fineTuningRequested=" + fineTuningRequested +
", finetuningState='" + finetuningState + '\'' +
", verificationAttempts=" + verificationAttempts +
", verificationFailures=" + verificationFailures +
", verificationAttemptsCount=" + verificationAttemptsCount +
", sliceIds=" + sliceIds +
'}';
}
}

View File

@@ -0,0 +1,70 @@
package net.andrewcpu.elevenlabs.model.tuning;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.model.ElevenModel;
public class Recording extends ElevenModel {
@JsonProperty("recording_id")
private String recordingId;
@JsonProperty("mime_type")
private String mimeType;
@JsonProperty("size_bytes")
private long sizeBytes;
@JsonProperty("upload_date_unix")
private long uploadDateUnix;
@JsonProperty("transcription")
private String transcription;
public Recording(String recordingId, String mimeType, long sizeBytes, long uploadDateUnix, String transcription) {
this.recordingId = recordingId;
this.mimeType = mimeType;
this.sizeBytes = sizeBytes;
this.uploadDateUnix = uploadDateUnix;
this.transcription = transcription;
}
public Recording() {
}
@JsonIgnore
public String getRecordingId() {
return recordingId;
}
@JsonIgnore
public String getMimeType() {
return mimeType;
}
@JsonIgnore
public long getSizeBytes() {
return sizeBytes;
}
@JsonIgnore
public long getUploadDateUnix() {
return uploadDateUnix;
}
@JsonIgnore
public String getTranscription() {
return transcription;
}
@JsonIgnore
@Override
public String toString() {
return "Recording{" +
"recordingId='" + recordingId + '\'' +
", mimeType='" + mimeType + '\'' +
", sizeBytes=" + sizeBytes +
", uploadDateUnix=" + uploadDateUnix +
", transcription='" + transcription + '\'' +
'}';
}
}

View File

@@ -0,0 +1,80 @@
package net.andrewcpu.elevenlabs.model.tuning;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.model.ElevenModel;
public class VerificationAttempt extends ElevenModel {
@JsonProperty("text")
private String text;
@JsonProperty("date_unix")
private long dateUnix;
@JsonProperty("accepted")
private boolean accepted;
@JsonProperty("similarity")
private double similarity;
@JsonProperty("levenshtein_distance")
private double levenshteinDistance;
@JsonProperty("recording")
private Recording recording;
public VerificationAttempt(String text, long dateUnix, boolean accepted, double similarity, double levenshteinDistance, Recording recording) {
this.text = text;
this.dateUnix = dateUnix;
this.accepted = accepted;
this.similarity = similarity;
this.levenshteinDistance = levenshteinDistance;
this.recording = recording;
}
public VerificationAttempt() {
}
@JsonIgnore
public String getText() {
return text;
}
@JsonIgnore
public long getDateUnix() {
return dateUnix;
}
@JsonIgnore
public boolean isAccepted() {
return accepted;
}
@JsonIgnore
public double getSimilarity() {
return similarity;
}
@JsonIgnore
public double getLevenshteinDistance() {
return levenshteinDistance;
}
@JsonIgnore
public Recording getRecording() {
return recording;
}
@JsonIgnore
@Override
public String toString() {
return "VerificationAttempt{" +
"text='" + text + '\'' +
", dateUnix=" + dateUnix +
", accepted=" + accepted +
", similarity=" + similarity +
", levenshteinDistance=" + levenshteinDistance +
", recording=" + recording +
'}';
}
}

View File

@@ -0,0 +1,156 @@
package net.andrewcpu.elevenlabs.model.user;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.ElevenLabs;
import net.andrewcpu.elevenlabs.model.ElevenModel;
public class Subscription extends ElevenModel {
@JsonIgnore
public static Subscription get() {
return ElevenLabs.getSubscription();
}
@JsonProperty("tier")
private String tier;
@JsonProperty("character_count")
private int characterCount;
@JsonProperty("character_limit")
private int characterLimit;
@JsonProperty("can_extend_character_limit")
private boolean canExtendCharacterLimit;
@JsonProperty("allowed_to_extend_character_limit")
private boolean allowedToExtendCharacterLimit;
@JsonProperty("next_character_count_reset_unix")
private long nextCharacterCountResetUnix;
@JsonProperty("voice_limit")
private int voiceLimit;
@JsonProperty("professional_voice_limit")
private int professionalVoiceLimit;
@JsonProperty("can_extend_voice_limit")
private boolean canExtendVoiceLimit;
@JsonProperty("can_use_instant_voice_cloning")
private boolean canUseInstantVoiceCloning;
@JsonProperty("can_use_professional_voice_cloning")
private boolean canUseProfessionalVoiceCloning;
@JsonProperty("currency")
private String currency;
@JsonProperty("status")
private String status;
public Subscription(String tier, int characterCount, int characterLimit, boolean canExtendCharacterLimit, boolean allowedToExtendCharacterLimit, long nextCharacterCountResetUnix, int voiceLimit, int professionalVoiceLimit, boolean canExtendVoiceLimit, boolean canUseInstantVoiceCloning, boolean canUseProfessionalVoiceCloning, String currency, String status) {
this.tier = tier;
this.characterCount = characterCount;
this.characterLimit = characterLimit;
this.canExtendCharacterLimit = canExtendCharacterLimit;
this.allowedToExtendCharacterLimit = allowedToExtendCharacterLimit;
this.nextCharacterCountResetUnix = nextCharacterCountResetUnix;
this.voiceLimit = voiceLimit;
this.professionalVoiceLimit = professionalVoiceLimit;
this.canExtendVoiceLimit = canExtendVoiceLimit;
this.canUseInstantVoiceCloning = canUseInstantVoiceCloning;
this.canUseProfessionalVoiceCloning = canUseProfessionalVoiceCloning;
this.currency = currency;
this.status = status;
}
public Subscription() {
}
@JsonIgnore
public String getTier() {
return tier;
}
@JsonIgnore
public int getCharacterCount() {
return characterCount;
}
@JsonIgnore
public int getCharacterLimit() {
return characterLimit;
}
@JsonIgnore
public boolean isCanExtendCharacterLimit() {
return canExtendCharacterLimit;
}
@JsonIgnore
public boolean isAllowedToExtendCharacterLimit() {
return allowedToExtendCharacterLimit;
}
@JsonIgnore
public long getNextCharacterCountResetUnix() {
return nextCharacterCountResetUnix;
}
@JsonIgnore
public int getVoiceLimit() {
return voiceLimit;
}
@JsonIgnore
public int getProfessionalVoiceLimit() {
return professionalVoiceLimit;
}
@JsonIgnore
public boolean isCanExtendVoiceLimit() {
return canExtendVoiceLimit;
}
@JsonIgnore
public boolean isCanUseInstantVoiceCloning() {
return canUseInstantVoiceCloning;
}
@JsonIgnore
public boolean isCanUseProfessionalVoiceCloning() {
return canUseProfessionalVoiceCloning;
}
@JsonIgnore
public String getCurrency() {
return currency;
}
@JsonIgnore
public String getStatus() {
return status;
}
@JsonIgnore
@Override
public String toString() {
return "Subscription{" +
"tier='" + tier + '\'' +
", characterCount=" + characterCount +
", characterLimit=" + characterLimit +
", canExtendCharacterLimit=" + canExtendCharacterLimit +
", allowedToExtendCharacterLimit=" + allowedToExtendCharacterLimit +
", nextCharacterCountResetUnix=" + nextCharacterCountResetUnix +
", voiceLimit=" + voiceLimit +
", professionalVoiceLimit=" + professionalVoiceLimit +
", canExtendVoiceLimit=" + canExtendVoiceLimit +
", canUseInstantVoiceCloning=" + canUseInstantVoiceCloning +
", canUseProfessionalVoiceCloning=" + canUseProfessionalVoiceCloning +
", currency='" + currency + '\'' +
", status='" + status + '\'' +
'}';
}
}

View File

@@ -0,0 +1,66 @@
package net.andrewcpu.elevenlabs.model.user;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.ElevenLabs;
import net.andrewcpu.elevenlabs.model.ElevenModel;
public class User extends ElevenModel {
public static User get() {
return ElevenLabs.getUser();
}
@JsonProperty("subscription")
private Subscription subscription;
@JsonProperty("is_new_user")
private boolean isNewUser;
@JsonProperty("xi_api_key")
private String xiApiKey;
@JsonProperty("can_use_delayed_payment_methods")
private boolean canUseDelayedPaymentMethods;
public User(Subscription subscription, boolean isNewUser, String xiApiKey, boolean canUseDelayedPaymentMethods) {
this.subscription = subscription;
this.isNewUser = isNewUser;
this.xiApiKey = xiApiKey;
this.canUseDelayedPaymentMethods = canUseDelayedPaymentMethods;
}
public User() {
}
@JsonIgnore
public Subscription getSubscription() {
return subscription;
}
@JsonIgnore
public boolean isNewUser() {
return isNewUser;
}
@JsonIgnore
public String getXiApiKey() {
return xiApiKey;
}
@JsonIgnore
public boolean isCanUseDelayedPaymentMethods() {
return canUseDelayedPaymentMethods;
}
@JsonIgnore
@Override
public String toString() {
return "User{" +
"subscription=" + subscription +
", isNewUser=" + isNewUser +
", xiApiKey='" + xiApiKey + '\'' +
", canUseDelayedPaymentMethods=" + canUseDelayedPaymentMethods +
'}';
}
}

View File

@@ -0,0 +1,87 @@
package net.andrewcpu.elevenlabs.model.voice;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.ElevenLabs;
import net.andrewcpu.elevenlabs.model.ElevenModel;
import java.io.File;
public class Sample extends ElevenModel {
@JsonProperty("sample_id")
private String sampleId;
@JsonProperty("file_name")
private String fileName;
@JsonProperty("mime_type")
private String mimeType;
@JsonProperty("size_bytes")
private long sizeBytes;
@JsonProperty("hash")
private String hash;
@JsonIgnore
public Voice voice;
public Sample(String sampleId, String fileName, String mimeType, long sizeBytes, String hash) {
this.sampleId = sampleId;
this.fileName = fileName;
this.mimeType = mimeType;
this.sizeBytes = sizeBytes;
this.hash = hash;
}
public Sample() {
}
@JsonIgnore
public String getSampleId() {
return sampleId;
}
@JsonIgnore
public String getFileName() {
return fileName;
}
@JsonIgnore
public String getMimeType() {
return mimeType;
}
@JsonIgnore
public long getSizeBytes() {
return sizeBytes;
}
@JsonIgnore
public String getHash() {
return hash;
}
public File downloadAudio() {
return ElevenLabs.getAudioSample(voice.getVoiceId(), sampleId);
}
/**
* Warning! This will delete the sample.
*/
public String delete() {
return ElevenLabs.deleteSample(voice.getVoiceId(), sampleId);
}
@Override
@JsonIgnore
public String toString() {
return "Sample{" +
"sampleId='" + sampleId + '\'' +
", fileName='" + fileName + '\'' +
", mimeType='" + mimeType + '\'' +
", sizeBytes=" + sizeBytes +
", hash='" + hash + '\'' +
'}';
}
}

View File

@@ -0,0 +1,80 @@
package net.andrewcpu.elevenlabs.model.voice;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.model.ElevenModel;
public class Sharing extends ElevenModel {
@JsonProperty("status")
private String status;
@JsonProperty("history_item_sample_id")
private String historyItemSampleId;
@JsonProperty("original_voice_id")
private String originalVoiceId;
@JsonProperty("public_owner_id")
private String publicOwnerId;
@JsonProperty("liked_by_count")
private int likedByCount;
@JsonProperty("cloned_by_count")
private int clonedByCount;
public Sharing(String status, String historyItemSampleId, String originalVoiceId, String publicOwnerId, int likedByCount, int clonedByCount) {
this.status = status;
this.historyItemSampleId = historyItemSampleId;
this.originalVoiceId = originalVoiceId;
this.publicOwnerId = publicOwnerId;
this.likedByCount = likedByCount;
this.clonedByCount = clonedByCount;
}
public Sharing() {
}
@JsonIgnore
public String getStatus() {
return status;
}
@JsonIgnore
public String getHistoryItemSampleId() {
return historyItemSampleId;
}
@JsonIgnore
public String getOriginalVoiceId() {
return originalVoiceId;
}
@JsonIgnore
public String getPublicOwnerId() {
return publicOwnerId;
}
@JsonIgnore
public int getLikedByCount() {
return likedByCount;
}
@JsonIgnore
public int getClonedByCount() {
return clonedByCount;
}
@Override
@JsonIgnore
public String toString() {
return "Sharing{" +
"status='" + status + '\'' +
", historyItemSampleId='" + historyItemSampleId + '\'' +
", originalVoiceId='" + originalVoiceId + '\'' +
", publicOwnerId='" + publicOwnerId + '\'' +
", likedByCount=" + likedByCount +
", clonedByCount=" + clonedByCount +
'}';
}
}

View File

@@ -0,0 +1,199 @@
package net.andrewcpu.elevenlabs.model.voice;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.ElevenLabs;
import net.andrewcpu.elevenlabs.model.ElevenModel;
import net.andrewcpu.elevenlabs.model.tuning.FineTuning;
import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Voice extends ElevenModel {
public static List<Voice> getVoices() {
return ElevenLabs.getVoices();
}
public static Voice getVoice(String voiceId) {
return ElevenLabs.getVoice(voiceId);
}
public static Voice getVoice(String voiceId, boolean withSettings) {
return ElevenLabs.getVoice(voiceId, withSettings);
}
@JsonProperty("voice_id")
private String voiceId;
@JsonProperty("name")
private String name;
@JsonProperty("samples")
private List<Sample> samples;
@JsonProperty("category")
private String category;
@JsonProperty("fine_tuning")
private FineTuning fineTuning;
@JsonProperty("labels")
private Map<String, String> labels;
@JsonProperty("description")
private String description;
@JsonProperty("preview_url")
private String previewUrl;
@JsonProperty("available_for_tiers")
private List<String> availableForTiers;
@JsonProperty("settings")
private VoiceSettings settings;
@JsonProperty("sharing")
private Sharing sharing;
@JsonIgnore
public String getVoiceId() {
return voiceId;
}
@JsonIgnore
public String getName() {
return name;
}
@JsonIgnore
public List<Sample> getSamples() {
return samples.stream().peek(s -> s.voice = this).collect(Collectors.toList());
}
@JsonIgnore
public String getCategory() {
return category;
}
@JsonIgnore
public FineTuning getFineTuning() {
return fineTuning;
}
@JsonIgnore
public Map<String, String> getLabels() {
return labels;
}
@JsonIgnore
public String getDescription() {
return description;
}
@JsonIgnore
public String getPreviewUrl() {
return previewUrl;
}
@JsonIgnore
public List<String> getAvailableForTiers() {
return availableForTiers;
}
@JsonIgnore
public VoiceSettings getSettings() {
return settings;
}
@JsonIgnore
public Sharing getSharing() {
return sharing;
}
/**
* Warning! This will delete the voice.
*/
public String delete() {
return ElevenLabs.deleteVoice(voiceId);
}
public VoiceSettings fetchSettings() {
this.settings = ElevenLabs.getVoiceSettings(voiceId);
return settings;
}
public VoiceSettings updateVoiceSettings(VoiceSettings voiceSettings) {
ElevenLabs.editVoiceSettings(voiceId, voiceSettings);
this.settings = voiceSettings;
return settings;
}
public Voice refresh() {
Voice refreshedData = Voice.getVoice(voiceId, true);
this.name = refreshedData.name;
this.settings = refreshedData.settings;
this.voiceId = refreshedData.voiceId;
this.labels = refreshedData.labels;
this.description = refreshedData.description;
this.samples = refreshedData.samples;
this.fineTuning = refreshedData.fineTuning;
this.availableForTiers = refreshedData.availableForTiers;
this.sharing = refreshedData.sharing;
this.previewUrl = refreshedData.previewUrl;
this.category = refreshedData.category;
return this;
}
public File generate(String text, String model) {
return ElevenLabs.generateTextToSpeech(voiceId, text, model, settings);
}
public File generate(String text, String model, VoiceSettings settings) {
return ElevenLabs.generateTextToSpeech(voiceId, text, model, settings);
}
public File generate(String text, VoiceSettings settings) {
return ElevenLabs.generateTextToSpeech(voiceId, text, "eleven_monolingual_v1", settings);
}
public File generate(String text) {
return ElevenLabs.generateTextToSpeech(voiceId, text, "eleven_monolingual_v1", settings);
}
public InputStream generateStream(String text, String model) {
return ElevenLabs.generateTextToSpeechStreamed(voiceId, text, model, settings);
}
public InputStream generateStream(String text, String model, VoiceSettings settings) {
return ElevenLabs.generateTextToSpeechStreamed(voiceId, text, model, settings);
}
public InputStream generateStream(String text, VoiceSettings settings) {
return ElevenLabs.generateTextToSpeechStreamed(voiceId, text, "eleven_monolingual_v1", settings);
}
public InputStream generateStream(String text) {
return ElevenLabs.generateTextToSpeechStreamed(voiceId, text, "eleven_monolingual_v1", settings);
}
@JsonIgnore
@Override
public String toString() {
return "Voice{" +
"voiceId='" + voiceId + '\'' +
", name='" + name + '\'' +
", samples=" + samples +
", category='" + category + '\'' +
", fineTuning=" + fineTuning +
", labels=" + labels +
", description='" + description + '\'' +
", previewUrl='" + previewUrl + '\'' +
", availableForTiers=" + availableForTiers +
", settings=" + settings +
", sharing=" + sharing +
'}';
}
}

View File

@@ -0,0 +1,93 @@
package net.andrewcpu.elevenlabs.model.voice;
import net.andrewcpu.elevenlabs.ElevenLabs;
import net.andrewcpu.elevenlabs.model.response.CreateVoiceResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class VoiceBuilder {
public static VoiceBuilder fromVoice(Voice voice) {
VoiceBuilder voiceBuilder = new VoiceBuilder(voice);
return voiceBuilder;
}
private Voice voice;
private String name;
private String description;
private Map<String, String> labels;
private List<File> files;
public VoiceBuilder() {
this.labels = new HashMap<>();
this.files = new ArrayList<>();
}
public VoiceBuilder(Voice voice) {
this();
this.voice = voice;
this.name = voice.getName();
this.description = voice.getDescription();
this.labels = voice.getLabels();
}
public String getName() {
return name;
}
public VoiceBuilder withName(String name) {
this.name = name;
return this;
}
public String getDescription() {
return description;
}
public VoiceBuilder withDescription(String description) {
this.description = description;
return this;
}
public Map<String, String> getLabels() {
return labels;
}
public VoiceBuilder withLabels(Map<String, String> labels) {
this.labels = labels;
return this;
}
public VoiceBuilder withLabel(String key, String value) {
this.labels.put(key, value);
return this;
}
public List<File> getFiles() {
return files;
}
public VoiceBuilder withFile(File file) {
this.files.add(file);
return this;
}
public VoiceBuilder withFiles(List<File> files) {
this.files = files;
return this;
}
public Voice create() {
CreateVoiceResponse createVoiceResponse = ElevenLabs.createVoice(name, files.toArray(File[]::new), description, labels);
return Voice.getVoice(createVoiceResponse.getVoiceId(), true);
}
public Voice edit() {
ElevenLabs.editVoice(voice.getVoiceId(), name, files.toArray(File[]::new), description, labels);
voice = voice.refresh();
return voice;
}
}

View File

@@ -0,0 +1,44 @@
package net.andrewcpu.elevenlabs.model.voice;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import net.andrewcpu.elevenlabs.ElevenLabs;
import net.andrewcpu.elevenlabs.model.ElevenModel;
public class VoiceSettings extends ElevenModel {
public static VoiceSettings getDefaultVoiceSettings() {
return ElevenLabs.getDefaultVoiceSettings();
}
@JsonProperty("stability")
private double stability;
@JsonProperty("similarity_boost")
private double similarityBoost;
public VoiceSettings(double stability, double similarityBoost) {
this.stability = stability;
this.similarityBoost = similarityBoost;
}
public VoiceSettings() {
}
@JsonIgnore
public double getStability() {
return stability;
}
@JsonIgnore
public double getSimilarityBoost() {
return similarityBoost;
}
@JsonIgnore
@Override
public String toString() {
return "VoiceSettings{" +
"stability=" + stability +
", similarityBoost=" + similarityBoost +
'}';
}
}

View File

@@ -0,0 +1,9 @@
package net.andrewcpu.elevenlabs.requests;
import net.andrewcpu.elevenlabs.enums.HttpRequestType;
public abstract class DeleteRequest<T> extends ElevenLabsRequest<T> {
public DeleteRequest(String endpoint, Class<T> clazz) {
super(HttpRequestType.DELETE, endpoint, clazz);
}
}

View File

@@ -0,0 +1,31 @@
package net.andrewcpu.elevenlabs.requests;
import net.andrewcpu.elevenlabs.enums.HttpRequestType;
public abstract class ElevenLabsRequest<T> {
private HttpRequestType type;
private String endpoint;
private Class<T> responseClass;
public ElevenLabsRequest(HttpRequestType type, String endpoint, Class<T> clazz) {
this.type = type;
this.endpoint = endpoint;
this.responseClass = clazz;
}
public HttpRequestType getType() {
return type;
}
public String getEndpoint() {
return endpoint;
}
public Class<T> getResponseClass() {
return responseClass;
}
public abstract Object getPayload();
}

View File

@@ -0,0 +1,9 @@
package net.andrewcpu.elevenlabs.requests;
import net.andrewcpu.elevenlabs.enums.HttpRequestType;
public abstract class GetRequest<T> extends ElevenLabsRequest<T> {
public GetRequest(String endpoint, Class<T> clazz) {
super(HttpRequestType.GET, endpoint, clazz);
}
}

View File

@@ -0,0 +1,9 @@
package net.andrewcpu.elevenlabs.requests;
import net.andrewcpu.elevenlabs.enums.HttpRequestType;
public abstract class PostRequest<T> extends ElevenLabsRequest<T> {
public PostRequest(String endpoint, Class<T> clazz) {
super(HttpRequestType.POST, endpoint, clazz);
}
}

View File

@@ -0,0 +1,9 @@
package net.andrewcpu.elevenlabs.requests;
import net.andrewcpu.elevenlabs.enums.HttpRequestType;
public abstract class PutRequest<T> extends ElevenLabsRequest<T> {
public PutRequest(String endpoint, Class<T> clazz) {
super(HttpRequestType.PUT, endpoint, clazz);
}
}

View File

@@ -0,0 +1,14 @@
package net.andrewcpu.elevenlabs.requests.history;
import net.andrewcpu.elevenlabs.requests.DeleteRequest;
public class DeleteHistoryItemRequest extends DeleteRequest<String> {
public DeleteHistoryItemRequest(String historyItemId) {
super("v1/history/" + historyItemId, String.class);
}
@Override
public Object getPayload() {
return null;
}
}

View File

@@ -0,0 +1,16 @@
package net.andrewcpu.elevenlabs.requests.history;
import net.andrewcpu.elevenlabs.requests.GetRequest;
import java.io.File;
public class GetHistoryItemAudioRequest extends GetRequest<File> {
public GetHistoryItemAudioRequest(String historyItemId) {
super("v1/history/" + historyItemId + "/audio", File.class);
}
@Override
public Object getPayload() {
return null;
}
}

View File

@@ -0,0 +1,15 @@
package net.andrewcpu.elevenlabs.requests.history;
import net.andrewcpu.elevenlabs.model.history.HistoryItem;
import net.andrewcpu.elevenlabs.requests.GetRequest;
public class GetHistoryItemByIdRequest extends GetRequest<HistoryItem> {
public GetHistoryItemByIdRequest(String historyId) {
super("v1/history/" + historyId, HistoryItem.class);
}
@Override
public Object getPayload() {
return null;
}
}

View File

@@ -0,0 +1,15 @@
package net.andrewcpu.elevenlabs.requests.history;
import net.andrewcpu.elevenlabs.model.history.History;
import net.andrewcpu.elevenlabs.requests.GetRequest;
public class GetHistoryRequest extends GetRequest<History> {
public GetHistoryRequest() {
super("v1/history", History.class);
}
@Override
public Object getPayload() {
return null;
}
}

View File

@@ -0,0 +1,21 @@
package net.andrewcpu.elevenlabs.requests.history;
import net.andrewcpu.elevenlabs.model.history.HistoryItemList;
import net.andrewcpu.elevenlabs.requests.PostRequest;
import java.io.File;
import java.util.Arrays;
import java.util.stream.Collectors;
public class PostDownloadHistoryItemsRequest extends PostRequest<File> {
private String[] historyItemIds;
public PostDownloadHistoryItemsRequest(String... historyItemIds) {
super("v1/history/download", File.class);
this.historyItemIds = historyItemIds;
}
@Override
public Object getPayload() {
return new HistoryItemList(Arrays.stream(this.historyItemIds).collect(Collectors.toList()));
}
}

View File

@@ -0,0 +1,15 @@
package net.andrewcpu.elevenlabs.requests.models;
import net.andrewcpu.elevenlabs.model.response.GenerationTypeModel;
import net.andrewcpu.elevenlabs.requests.GetRequest;
public class GetModelsRequest extends GetRequest<GenerationTypeModel[]> {
public GetModelsRequest() {
super("v1/models", GenerationTypeModel[].class);
}
@Override
public Object getPayload() {
return null;
}
}

Some files were not shown because too many files have changed in this diff Show More