Azure Speech To Text SpeechSDK.SpeechConfig.fromAuthorizationToken() Not Working - javascript

When trying to use Speech to Text, I always get a Websocket Error on Chrome when using this code:
const audioConfig = SpeechSDK.AudioConfig.fromStreamInput(stream);
const config = SpeechSDK.SpeechConfig.fromAuthorizationToken(
"YOUR_SPEECH_API(?)",
"YOUR_REGION"
);
config.speechRecognitionLanguage = "en-US";
recognition = new SpeechSDK.SpeechRecognizer(config, audioConfig);
recognition.startContinuousRecognitionAsync();
I have tried to try any subscription key I know of (LUIS, Cognitive Speech, Subscription from API Manager), but nothing seems to work. I believe that:fromAuthorizationToken() is wrong, but I don't know with what method to replace it.

Well instead of fromAuthorizationToken() you can use the fromSubscription() for authorization.
Now fromSubscription() takes theKEY and REGION as parameter. Both can be found in the portal.
Now code should Look like this :
const speechConfig = sdk.SpeechConfig.fromSubscription("<YOUR KEY>", "<REGION>");
speechConfig.speechRecognitionLanguage = "en-US";
let audioConfig = sdk.AudioConfig.fromStreamInput(InputStream);
let recognizer = new sdk.SpeechRecognizer(speechConfig, audioConfig);
recognizer.recognizeOnceAsync(result => {
console.log(`RECOGNIZED: Text=${result.text}`);
recognizer.close();
});
Here I am running this in a console app and getting the following output without any error :

Related

Language & Char conversion to english keyboard

So basically in short im making a bot on discord and there are a few words that I need to censor. No problem, except now users can simply use characters from keyboards that are not english, and bypass the censors. Is there a simple way I can take any string and convert its contents to english keyboard characters? Thanks in advance!
It seems like DiscordJS is running on NodeJS - so here's what we can do.
Here is the example code posted on the website, but we can use it for your project.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'swearword') {
msg.reply('naughty!');
}
});
client.login('token');
With this code in place, you can use an API like Google Translate API to take every word that is processed and pass it to it, and await a response.
Here is the sample provided by Google:
/**
* TODO(developer): Uncomment the following line before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';
// Imports the Google Cloud client library
const {Translate} = require('#google-cloud/translate').v2;
// Instantiates a client
const translate = new Translate({projectId});
async function quickStart() {
// The text to translate
const text = 'Hello, world!';
// The target language
const target = 'ru';
// Translates some text into Russian
const [translation] = await translate.translate(text, target);
console.log(`Text: ${text}`);
console.log(`Translation: ${translation}`);
}
quickStart();
If you combine the translation process along with msg.content you should get a swearword in another language.
Here's an example (I havent tested this but play around with it):
You will need Google API account / key etc. So please read their instructions on how to set it up.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
/**
* TODO(developer): Uncomment the following line before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';
// Imports the Google Cloud client library
const {Translate} = require('#google-cloud/translate').v2;
// Instantiates a client
const translate = new Translate({projectId});
var translation = "";
client.on('message', msg => {
// Translate msg.content
// The target language (i think english is en, you need to check)
const target = 'en';
// Translates some text into English (i think)
translation = await translate.translate(msg.content, target);
if (translation === 'swearword') {
msg.reply('naughty!');
}
});
client.login('token');

How to use bitcoin -rpcwallet flag in deno RPC

I want to create an address in a wallet with bitcoin-cli, the command for this will look like this for the loaded wallet bitcoin-cli getnewaddress some_users and with Deno I can just do
import { createRemote } from "https://deno.land/x/gentleRpc/rpcClient.ts";
let Node = new URL("http://127.0.0.1:8332");
Node.port = "8332";
Node.username = "some_user";
Node.password = "some_password";
const remote = createRemote(Node);
const address = remote.getnewaddress(addressLabel);
I would love to know how to use deno rpc for cases where I need to specify the -rpcwallet flag, like this bitcoin-cli -rpcwallet=some_unique_wallet getnewaddress some_users
So after reading the doc further, I realised I can do this by passing the wallet name to the url like this http://127.0.0.1:8332/wallet/${walletName} or just this http://127.0.0.1:8332/wallet/ for the default wallet.
So the code will look like this,
createConnection(walletName?: string) {
const uri = !!walletName ?
'http://127.0.0.1:8332/wallet/${walletName}' :
'http://127.0.0.1:8332/wallet/';
let Node = new URL(uri);
Node.port = "8332";
Node.username = "some_user";
Node.password = "some_password";
return createRemote(Node);
}

Azure event hub Azure function node js integration not working

I am trying to fetch events from azure eventhub using a timer triggered azure function. I am able to fetch the events successfully with a simple nodejs code while running in my machine locally. But if the same code if i execute through a node js azure function, it doesn't work. I get the below error message. Is there something I am missing ?
TypeError: EventHubConsumerClient is not a constructor' Stack: TypeError: EventHubConsumerClient is not a constructor at Object.<anonymous>
Below is the sample code
const { ContainerClient } = require("#azure/storage-blob");
const { BlobCheckpointStore } = require("#azure/eventhubs-checkpointstore-blob");
const connectionString = "Endpoint=xxxx";
const eventHubName = "yyyy";
const consumerGroup = "default";
const storageConnectionString = "abcd";
const containerName = "eventhubcontainer";
module.exports = async function (context, myTimer) {
const containerClient = new ContainerClient(storageConnectionString, containerName);
const checkpointStore = new BlobCheckpointStore(containerClient);
const consumerClient = new EventHubConsumerClient(consumerGroup, connectionString, eventHubName, checkpointStore);
}
Please help
You are missing this line.
const { EventHubConsumerClient } = require("#azure/event-hubs");
You just need to pass consumerGroup and the ConnectionString to the EventHubConsumerClient constructor
const consumerClient = new EventHubConsumerClient(this.consumerGroup, eventHubConnectionString);
Here is an Example

Connecting to a running process in Winappdriver using Javascript

I am fairly new to JS/Winappdriver.
The application I am trying to test is a windows based "Click Once" application from .Net, so I have to go to a website from IE and click "Install". This will open the application.
Once the application is running, I have no way to connect the application to perform my UI interactions while using JavaScript.
Using C#, I was looping through the processes looking for a process name, get the window handle, convert it to hex, add that as a capability and create the driver - it worked. Sample code below,
public Setup_TearDown()
{
string TopLevelWindowHandleHex = null;
IntPtr TopLevelWindowHandle = new IntPtr();
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.StartsWith($"SomeName-{exec_pob}-{exec_env}"))
{
TopLevelWindowHandle = clsProcess.Handle;
TopLevelWindowHandleHex = clsProcess.MainWindowHandle.ToString("x");
}
}
var appOptions = new AppiumOptions();
appOptions.AddAdditionalCapability("appTopLevelWindow", TopLevelWindowHandleHex);
appOptions.AddAdditionalCapability("ms:experimental-webdriver", true);
appOptions.AddAdditionalCapability("ms:waitForAppLaunch", "25");
AppDriver = new WindowsDriver<WindowsElement>(new Uri(WinAppDriverUrl), appOptions);
AppDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(60);
}
How do I do this in Javascript ? I can't seem to find any code examples.
Based on an example from this repo, I tried the following in JS to find the process to latch on to but without luck.
import {By2} from "selenium-appium";
// this.appWindow = this.driver.element(By2.nativeAccessibilityId('xxx'));
// this.appWindow = this.driver.element(By2.nativeXpath("//Window[starts-with(#Name,\"xxxx\")]"));
// this.appWindow = this.driver.elementByName('WindowsForms10.Window.8.app.0.13965fa_r11_ad1');
// thisappWindow = this.driver.elementByName('xxxxxxx');
async connectAppDriver(){
await this.waitForAppWindow();
var appWindow = await this.appWindow.getAttribute("NativeWindowHandle");
let hex = (Number(ewarpWindow)).toString(16);
var currentAppCapabilities =
{
"appTopLevelWindow": hex,
"platformName": "Windows",
"deviceName": "WindowsPC",
"newCommandTimeout": "120000"
}
let driverBuilder = new DriverBuilder();
await driverBuilder.stopDriver();
this.driver = await driverBuilder.createDriver(currentEwarpCapabilities);
return this.driver;
}
I keep getting this error in Winappdriver
{"status":13,"value":{"error":"unknown error","message":"An unknown error occurred in the remote end while processing the command."}}
I've also opened this ticket here.
It seems like such an easy thing to do, but I couldn't figure this one out.
Any of nodes packages I could use to get the top level window handle easily?
I am open to suggestions on how to tackle this issue while using JavaScript for Winappdriver.
Hope this helps some one out there,
Got around this by creating an exe using C# that generated hex of the app to connect based on the process name, it looks like something like this.
public string GetTopLevelWindowHandleHex()
{
string TopLevelWindowHandleHex = null;
IntPtr TopLevelWindowHandle = new IntPtr();
foreach (Process clsProcess in Process.GetProcesses())
{
if (clsProcess.ProcessName.StartsWith(_processName))
{
TopLevelWindowHandle = clsProcess.Handle;
TopLevelWindowHandleHex = clsProcess.MainWindowHandle.ToString("x");
}
}
if (!String.IsNullOrEmpty(TopLevelWindowHandleHex))
return TopLevelWindowHandleHex;
else
throw new Exception($"Process: {_processName} cannot be found");
}
Called it from JS to get the hex of the top level window handle, like this,
async getHex () {
var pathToExe =await path.join(process.cwd(), "features\\support\\ProcessUtility\\GetWindowHandleHexByProcessName.exe");
var pathToDir =await path.join(process.cwd(), "features\\support\\ProcessUtility");
const result = await execFileSync(pathToExe, [this.processName]
, {cwd: pathToDir, encoding: 'utf-8'}
, async function (err, data) {
console.log("Error: "+ err);
console.log("Data(hex): "+ data);
return JSON.stringify(data.toString());
});
return result.toString().trim();
}
Used the hex to connect to the app like this,
async connectAppDriver(hex) {
console.log(`Hex received to connect to app using hex: ${hex}`);
const currentAppCapabilities=
{
"browserName": '',
"appTopLevelWindow": hex.trim(),
"platformName": "Windows",
"deviceName": "WindowsPC",
"newCommandTimeout": "120000"
};
const appDriver = await new Builder()
.usingServer("http://localhost:4723/wd/hub")
.withCapabilities(currentAppCapabilities)
.build();
await driver.startWithWebDriver(appDriver);
return driver;
}
Solution:
In WebDriverJS (used by selenium / appium), use getDomAttribute instead of getAttribute. Took several hours to find :(
element.getAttribute("NativeWindowHandle")
POST: /session/270698D2-D93B-4E05-9FC5-3E5FBDA60ECA/execute/sync
Command not implemented: POST: /session/270698D2-D93B-4E05-9FC5-3E5FBDA60ECA/execute/sync
HTTP/1.1 501 Not Implemented
let topLevelWindowHandle = await element.getDomAttribute('NativeWindowHandle')
topLevelWindowHandle = parseInt(topLevelWindowHandle).toString(16)
GET /session/DE4C46E1-CC84-4F5D-88D2-35F56317E34D/element/42.3476754/attribute/NativeWindowHandle HTTP/1.1
HTTP/1.1 200 OK
{"sessionId":"DE4C46E1-CC84-4F5D-88D2-35F56317E34D","status":0,"value":"3476754"}
and topLevelWindowHandle have hex value :)

Is there an example site that uses navigator.serial?

I noticed that Chrome Canary has an implementation of a web serial api at navigator.serial, and I'm interested in looking at it. The previous API for serial ports chrome.serial implements listener callbacks, while this new API seems to deal in streams.
I've looked at the example at https://wicg.github.io/serial/#usage-example, but it seems pretty bare bones.
<html>
<script>
var port;
var buffy = new ArrayBuffer(1);
var writer;
buffy[0]=10;
const test = async function () {
const requestOptions = {
// Filter on devices with the Arduino USB vendor ID.
//filters: [{ vendorId: 0x2341 }],
};
// Request an Arduino from the user.
port = await navigator.serial.requestPort(requestOptions);
// Open and begin reading.
await port.open({ baudrate: 115200 });
//const reader = port.in.getReader();
const reader = port.readable.getReader();
writer = port.writable.getWriter();
//const writer = port.writable.getWriter();
//writer.write(buffy);
while (true) {
const {done, data} = await reader.read();
if (done) break;
console.log(data);
}
} // end of function
</script>
<button onclick="test()">Click It</button>
</html>
I'd like to find a working example, and eventually find a way to migrate an app from chrome.serial to navigator.serial
Hey battling this as well. To enable this 'experimental api', open Canary, and punch this into the url: chrome://flags/#enable-experimental-web-platform-features
Enable that feature. Now you can use it.

Categories