Skip to content

Commit

Permalink
Merge pull request #134 from jptrsn/token-grant
Browse files Browse the repository at this point in the history
Token grant
  • Loading branch information
jptrsn authored Feb 17, 2025
2 parents 4750c03 + 3b2bea9 commit c0cdfef
Show file tree
Hide file tree
Showing 19 changed files with 229 additions and 83 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,20 @@
</select>
</label>

<ng-container *ngIf="provider() as p">
<div class="text-md mt-3">{{'SETTINGS.PROVIDER.' + p + '.label' | translate}}</div>
<p class="text-sm mb-3">{{'SETTINGS.PROVIDER.' + p + '.description' | translate }}</p>
<div class="flex flex-row flex-wrap justify-between">
<div class="text-sm">{{'SETTINGS.PROVIDER.' + p + '.cost' | translate }}</div>
<div class="text-sm" [ngClass]="{'text-error': group.hasError('credits')}" *ngIf="p !== 'web'"><span translate>SETTINGS.PROVIDER.balance</span>: {{balance()}}</div>
</div>
</ng-container>

<ng-container *ngIf="selectedOption() as so">
<a [href]="so.url" target="_blank">
<div class="text-md mt-3">{{'SETTINGS.PROVIDER.' + so.value + '.label' | translate}}</div>
</a>
<p class="text-sm mb-3">{{'SETTINGS.PROVIDER.' + so.value + '.description' | translate }}</p>
<div class="flex flex-row flex-wrap justify-between">
<div class="text-sm">{{'SETTINGS.PROVIDER.' + so.value + '.cost' | translate }}</div>
<div class="text-sm" [ngClass]="{'text-error': group.hasError('credits')}" *ngIf="so.value !== 'web'">
<span translate>SETTINGS.PROVIDER.balance</span>: {{balance() | hoursminutes }}
</div>
</div>
</ng-container>


<ng-container *ngIf="provider() === 'azure'">
<div *ngIf="dialect() === 'unspecified'" class="text-md text-warn"><span translate>SETTINGS.PROVIDER.dialectRequired</span> {{fallbackDialect()}}</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Component, computed, effect, signal, Signal, WritableSignal } from '@an
import { toSignal } from '@angular/core/rxjs-interop';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
import { select, Store } from '@ngrx/store';
import { map } from 'rxjs';
import { map, startWith } from 'rxjs';
import { RecognitionActions } from '../../../../actions/recogntion.actions';
import { AppState } from '../../../../models/app.model';
import { RecognitionEngineState } from '../../../../models/recognition.model';
Expand All @@ -13,6 +13,13 @@ import { selectUserBalance } from '../../../../selectors/user.selector';
import { DefaultDialects, InterfaceLanguage, RecognitionDialect, SettingsActions } from '../../models/settings.model';
import { slideInUpOnEnterAnimation, fadeOutOnLeaveAnimation } from 'angular-animations';

interface ProviderOption {
value: string;
paid: boolean;
url: string;
tokensPerMinute: number;
}

@Component({
selector: 'app-recognition-engine',
templateUrl: './recognition-engine.component.html',
Expand All @@ -30,13 +37,14 @@ export class RecognitionEngineComponent {
public balance: Signal<number | undefined>;
public isLoggedIn: Signal<boolean | undefined>;
public patreonUrl = 'https://patreon.com/zipcaptions';
public selectedOption: Signal<ProviderOption | undefined>;
public group: FormGroup<{
provider: FormControl<RecognitionEngineState['provider'] | null | undefined>,
dialect: FormControl<RecognitionDialect | null | undefined>,
}>;
public providers: { value: RecognitionEngineState['provider'], paid: boolean }[] = [
{ value: 'web', paid: false },
{ value: 'azure', paid: true}
public providers: ProviderOption[] = [
{ value: 'web', paid: false, url: "https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition", tokensPerMinute: 0 },
{ value: 'azure', paid: true, url: "https://learn.microsoft.com/en-us/javascript/api/overview/azure/microsoft-cognitiveservices-speech-sdk-readme?view=azure-node-latest", tokensPerMinute: 60 }
]
public showToast: WritableSignal<boolean> = signal(false);
public errorMessage: WritableSignal<string | undefined> = signal(undefined);
Expand Down Expand Up @@ -76,6 +84,15 @@ export class RecognitionEngineComponent {
return formProvider() || provider()
})

this.selectedOption = computed(() => {
const opt = formProvider();
if (opt) {
console.log('selected option', opt);
return this.providers.find((p) => p.value === opt)
}
return undefined;
})

// Handle state change after saving the form, so as to show success/error message
effect(() => {
if (this.formProviderToSave !== null) {
Expand All @@ -90,7 +107,23 @@ export class RecognitionEngineComponent {

this.isLoggedIn = toSignal(this.store.select(selectUserLoggedIn));
const balance = toSignal(this.store.select(selectUserBalance));
this.balance = computed(() => this.isLoggedIn() ? balance() : undefined);
this.balance = computed(() => {
if (this.isLoggedIn()) {
const so = this.selectedOption();
const b = balance();
if (so?.tokensPerMinute && b) {
return (b/so.tokensPerMinute) * 60000;
}
}
return undefined;
});

effect(() => {
const p = provider();
if (p && p !== this.group.controls['provider'].value) {
this.group.controls['provider'].setValue(p, {emitEvent: true})
}
}, { allowSignalWrites: true })
}

setProvider(): void {
Expand Down
10 changes: 4 additions & 6 deletions packages/client/src/assets/i18n/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -351,22 +351,20 @@
"PROVIDER": {
"title": "Anerkennung API Provider",
"description": "Wählen Sie aus, welcher Dienstleister Sie verwenden möchten, um sichere Audio- und Rückgabeergebnisse zu verarbeiten. Verschiedene Motoren werden in Geschwindigkeit, Qualität und Kosten unterschiedlich sein. Wir tun unser Bestes, um Ihnen so viel Wahl wie möglich zu bringen, während die Dinge so frei wie wir können.",
"balance": "Ihre Token",
"acquire": "Um Tokens zu erhalten, können Sie uns auf Patreon unterstützen oder einige von der Community Pool anfordern (kommt bald)",
"web": {
"label": "Browser (Chrome und Safari)",
"description": "Mit dem Browser-Anbieter sendet Zip Captions Audio-Daten von Ihrem Gerät direkt an Ihren Browser-Anbieter über die Web Speech API.",
"cost": "Rate: immer kostenlos",
"link": "https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition"
"cost": "Rate: immer kostenlos"
},
"azure": {
"label": "Microsoft Azure kognitive Dienstleistungen",
"description": "Mit dem Azure Cognitive Services-Anbieter sendet Zip Captions Audio-Daten von Ihrem Gerät direkt an die Microsoft-API mit einem sicheren Web-Socket.",
"cost": "Rate: 60 Tokens pro Minute",
"link": "https://learn.microsoft.com/en-us/javascript/api/overview/azure/microsoft-cognitiveservices-speech-sdk-readme?view=azure-node-latest"
"cost": "Rate: 60 Tokens pro Minute"
},
"dialectRequired": "WARNING! Dieser Anbieter erfordert einen ausgewählten Dialekt. Mit Ihren aktuellen Einstellungen werden Sie den Standarddialekt",
"setSuccess": "Der Anbieter hat sich erfolgreich geändert"
"setSuccess": "Der Anbieter hat sich erfolgreich geändert",
"balance": "Dein Gleichgewicht"
}
},
"STREAM": {
Expand Down
8 changes: 3 additions & 5 deletions packages/client/src/assets/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -351,21 +351,19 @@
"PROVIDER": {
"title": "Recognition API Provider",
"description": "Select which service providder you would like use to securely process audio and return results. Different engines will vary in speed, quality, and cost. We do our best to bring you as much choice as possible while keeping things as free as we can.",
"balance": "Your tokens",
"balance": "Your balance",
"dialectRequired": "WARNING! This provider requires a selected dialect. With your current settings, you will use the default dialect of",
"acquire": "To get tokens, you can support us on Patreon, or request some from the Community Pool (coming soon)",
"setSuccess": "Provider changed successfully",
"web": {
"label": "Browser (Chrome/Safari)",
"description": "Using the browser provider, Zip Captions will send audio data from your device directly to your browser provider using the Web Speech API.",
"cost": "Rate: always free",
"link": "https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition"
"cost": "Rate: always free"
},
"azure": {
"label": "Microsoft Azure Cognitive Services",
"description": "Using the Azure Cognitive Services provider, Zip Captions will send audio data from your device directly to Microsoft's API using a secure web socket. This provider requires a specified dialect, please ensure the setting is correct.",
"cost": "Rate: 60 tokens per minute",
"link": "https://learn.microsoft.com/en-us/javascript/api/overview/azure/microsoft-cognitiveservices-speech-sdk-readme?view=azure-node-latest"
"cost": "Rate: 60 tokens per minute"
}
}
},
Expand Down
10 changes: 4 additions & 6 deletions packages/client/src/assets/i18n/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -351,22 +351,20 @@
"PROVIDER": {
"title": "Proveedor de API",
"description": "Seleccione cuál proveedor de servicios le gustaría utilizar para procesar de forma segura los resultados de audio y devolución. Los diferentes motores varían en velocidad, calidad y coste. Nosotros hacemos lo mejor posible para traerle la mayor cantidad de opciones posible mientras mantendremos las cosas tan libres como podemos.",
"balance": "tus tokens",
"acquire": "Para obtener tokens, puede apoyarnos en Patreon, o solicitar algunos de la piscina de la comunidad (venga pronto)",
"web": {
"label": "El navegador (Chrome y Safari)",
"description": "Con el proveedor de navegador, Zip Captions enviará datos de audio desde su dispositivo directamente a su proveedor de navegador utilizando la API de habla web.",
"cost": "Tamaño: siempre libre",
"link": "https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition"
"cost": "Tamaño: siempre libre"
},
"azure": {
"label": "Microsoft Azure Servicios Cognitivos",
"description": "Con el proveedor de Servicios Cognitivos de Azure, Zip Captions enviará datos de audio desde su dispositivo directamente a la API de Microsoft utilizando un socket web seguro.",
"cost": "Rate: 60 tokens por minuto",
"link": "https://learn.microsoft.com/en-us/javascript/api/overview/azure/microsoft-cognitiveservices-speech-sdk-readme?view=azure-node-latest"
"cost": "Rate: 60 tokens por minuto"
},
"dialectRequired": "NOTA: Este proveedor requiere un dialecto seleccionado. con sus configuraciones actuales, usará el dialecto de",
"setSuccess": "El proveedor cambió con éxito"
"setSuccess": "El proveedor cambió con éxito",
"balance": "tu equilibrio"
}
},
"STREAM": {
Expand Down
10 changes: 4 additions & 6 deletions packages/client/src/assets/i18n/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -351,22 +351,20 @@
"PROVIDER": {
"title": "Le fournisseur d’API",
"description": "Choisissez quel fournisseur de services vous aimeriez utiliser pour traiter en toute sécurité les résultats audio et de retour. Différents moteurs varieront en vitesse, qualité et coût. Nous faisons notre mieux pour vous apporter autant de choix que possible tout en gardant les choses aussi libres que nous pouvons.",
"balance": "Vos tokens",
"acquire": "Pour obtenir des tokens, vous pouvez nous soutenir sur Patreon, ou demander quelques-uns de la piscine communautaire (vint bientôt)",
"web": {
"label": "Le navigateur (Chrome et Safari)",
"description": "En utilisant le fournisseur de navigateur, Zip Captions enverra des données audio de votre appareil directement à votre fournisseur de navigateur en utilisant l’API Web Speech.",
"cost": "Résultat : toujours gratuit",
"link": "https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition"
"cost": "Résultat : toujours gratuit"
},
"azure": {
"label": "Microsoft Azure Cognitive Services",
"description": "Grâce au fournisseur Azure Cognitive Services, Zip Captions envoie des données audio de votre appareil directement à l’API de Microsoft en utilisant un socket web sécurisé.",
"cost": "Résultat : 60 tokens par minute",
"link": "https://learn.microsoft.com/en-us/javascript/api/overview/azure/microsoft-cognitiveservices-speech-sdk-readme?view=azure-node-latest"
"cost": "Résultat : 60 tokens par minute"
},
"dialectRequired": "ATTENTION: Ce fournisseur nécessite un dialecte sélectionné. Avec vos paramètres actuels, vous utiliserez le dialecte par défaut de",
"setSuccess": "Le fournisseur a changé avec succès"
"setSuccess": "Le fournisseur a changé avec succès",
"balance": "Votre équilibre"
}
},
"STREAM": {
Expand Down
10 changes: 4 additions & 6 deletions packages/client/src/assets/i18n/id.json
Original file line number Diff line number Diff line change
Expand Up @@ -351,22 +351,20 @@
"PROVIDER": {
"title": "Penyedia API",
"description": "Pilih mana penyedia layanan yang ingin Anda gunakan untuk memproses audio dengan aman dan mengembalikan hasil. mesin yang berbeda akan bervariasi dalam kecepatan, kualitas, dan biaya. kami melakukan yang terbaik untuk membawa Anda sebanyak pilihan yang mungkin sambil menjaga hal-hal gratis sebanyak yang kita bisa.",
"balance": "Token Anda",
"acquire": "Untuk mendapatkan token, Anda dapat mendukung kami di Patreon, atau meminta beberapa dari Community Pool (menerima segera)",
"web": {
"label": "Penggunaan Browser (Chrome dan Safari)",
"description": "Dengan menggunakan penyedia browser, Zip Captions akan mengirim data audio dari perangkat Anda langsung ke penyedia browser Anda menggunakan Web Speech API.",
"cost": "Harga : Selalu Gratis",
"link": "https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition"
"cost": "Harga : Selalu Gratis"
},
"azure": {
"label": "Aplikasi Microsoft Azure Cognitive",
"description": "Menggunakan penyedia layanan kognitif Azure, Zip Captions akan mengirim data audio dari perangkat Anda langsung ke API Microsoft menggunakan soket web yang aman.",
"cost": "Kadar: 60 token per menit",
"link": "https://learn.microsoft.com/en-us/javascript/api/overview/azure/microsoft-cognitiveservices-speech-sdk-readme?view=azure-node-latest"
"cost": "Kadar: 60 token per menit"
},
"dialectRequired": "PERINGATAN!Penyedia ini membutuhkan dialek yang dipilih.Dengan pengaturan Anda saat ini, Anda akan menggunakan dialek default dari",
"setSuccess": "Pembekal Berubah Sukses"
"setSuccess": "Pembekal Berubah Sukses",
"balance": "Keseimbangan Anda"
}
},
"STREAM": {
Expand Down
10 changes: 4 additions & 6 deletions packages/client/src/assets/i18n/it.json
Original file line number Diff line number Diff line change
Expand Up @@ -351,22 +351,20 @@
"PROVIDER": {
"title": "Fornitore di API",
"description": "Selezionare quale fornitore di servizi si desidera utilizzare per elaborare in modo sicuro i risultati audio e di ritorno. diversi motori variano in velocità, qualità e costo. facciamo del nostro meglio per portare il maggior numero possibile di scelte, mantenendo le cose il più libero possibile.",
"balance": "I tuoi token",
"acquire": "Per ottenere i token, puoi supportarci su Patreon, o richiedere alcuni dal Community Pool (l'arrivo presto)",
"web": {
"label": "Il tuo browser (Chrome e Safari)",
"description": "Utilizzando il fornitore del browser, Zip Captions invierà dati audio dal tuo dispositivo direttamente al tuo fornitore del browser utilizzando l'API Web Speech.",
"cost": "Tasso: sempre libero",
"link": "https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition"
"cost": "Tasso: sempre libero"
},
"azure": {
"label": "Servizi Microsoft Azure Cognitive",
"description": "Utilizzando il fornitore di servizi Azure Cognitive, Zip Captions trasmetterà dati audio dal tuo dispositivo direttamente all'API di Microsoft utilizzando un socket web sicuro.",
"cost": "Tasso: 60 tokens al minuto",
"link": "https://learn.microsoft.com/en-us/javascript/api/overview/azure/microsoft-cognitiveservices-speech-sdk-readme?view=azure-node-latest"
"cost": "Tasso: 60 tokens al minuto"
},
"dialectRequired": "ATTENZIONE: Questo fornitore richiede un dialetto selezionato. con le tue impostazioni attuali, utilizzerai il dialetto predefinito di",
"setSuccess": "Il fornitore è cambiato con successo"
"setSuccess": "Il fornitore è cambiato con successo",
"balance": "Il tuo equilibrio"
}
},
"STREAM": {
Expand Down
10 changes: 4 additions & 6 deletions packages/client/src/assets/i18n/pl.json
Original file line number Diff line number Diff line change
Expand Up @@ -351,22 +351,20 @@
"PROVIDER": {
"title": "Rozpoznawanie dostawcy API",
"description": "Wybierz, który dostawca usług chciałbyś użyć do bezpiecznego przetwarzania dźwięku i zwrotu wyników. Różne silniki będą się różnić w prędkości, jakości i kosztu. robimy wszystko, co w naszej mocy, aby przynieść Ci jak najwięcej wyboru, a jednocześnie utrzymywać rzeczy tak wolne, jak możemy.",
"balance": "Twoje tokeny",
"acquire": "Aby uzyskać tokeny, możesz wspierać nas na Patreon, lub poprosić o niektóre z Community Pool (przyjdzie wkrótce)",
"web": {
"label": "Przeglądarka (Chrome / Safari)",
"description": "Korzystając z dostawcy przeglądarki, Zip Captions wysyła dane audio z urządzenia bezpośrednio do dostawcy przeglądarki za pomocą API Web Speech.",
"cost": "Koszt: zawsze za darmo",
"link": "https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition"
"cost": "Koszt: zawsze za darmo"
},
"azure": {
"label": "Microsoft Azure Cognitive Usługi",
"description": "Korzystając z dostawcy usług Azure Cognitive, Zip Captions wysyła dane audio z urządzenia bezpośrednio do API firmy Microsoft za pomocą bezpiecznego socketu internetowego.",
"cost": "Wskaźnik: 60 tokenów na minutę",
"link": "https://learn.microsoft.com/en-us/javascript/api/overview/azure/microsoft-cognitiveservices-speech-sdk-readme?view=azure-node-latest"
"cost": "Wskaźnik: 60 tokenów na minutę"
},
"dialectRequired": "OSTRZEŻENIE! ten dostawca wymaga wybranego dialektu. z bieżącym ustawieniem, będziesz używać podanego dialektu",
"setSuccess": "Sprzedawca zmienił się z powodzeniem"
"setSuccess": "Sprzedawca zmienił się z powodzeniem",
"balance": "Twoja równowaga"
}
},
"STREAM": {
Expand Down
10 changes: 4 additions & 6 deletions packages/client/src/assets/i18n/pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -351,22 +351,20 @@
"PROVIDER": {
"title": "Provedor de API",
"description": "Escolha qual provedor de serviços você gostaria de usar para processar com segurança o áudio e devolver os resultados. diferentes motores variarão em velocidade, qualidade e custo. Nós fazemos o nosso melhor para trazer-lhe o máximo de escolha possível, mantendo as coisas o mais livre possível.",
"balance": "seus tokens",
"acquire": "Para obter tokens, você pode nos apoiar no Patreon, ou solicitar alguns do Community Pool (vindo em breve)",
"web": {
"label": "navegador (Chrome e Safari)",
"description": "Usando o provedor de navegador, o Zip Captions enviará dados de áudio do seu dispositivo diretamente ao seu provedor de navegador usando a API Web Speech.",
"cost": "Taxa: sempre grátis",
"link": "https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition"
"cost": "Taxa: sempre grátis"
},
"azure": {
"label": "Microsoft Azure Serviços Cognitivos",
"description": "Usando o provedor de Serviços Cognitivos do Azure, o Zip Captions enviará dados de áudio do seu dispositivo diretamente para a API da Microsoft usando um socket web seguro.",
"cost": "Taxa: 60 tokens por minuto",
"link": "https://learn.microsoft.com/en-us/javascript/api/overview/azure/microsoft-cognitiveservices-speech-sdk-readme?view=azure-node-latest"
"cost": "Taxa: 60 tokens por minuto"
},
"dialectRequired": "NOTA: Este provedor requer um diálogo selecionado. com as suas configurações atuais, você usará o diálogo padrão de",
"setSuccess": "O fornecedor mudou com sucesso"
"setSuccess": "O fornecedor mudou com sucesso",
"balance": "O seu equilíbrio"
}
},
"STREAM": {
Expand Down
Loading

0 comments on commit c0cdfef

Please sign in to comment.