How to make Google's SpeechClient.StreamingRecognize.WriteAsync faster? - asynchronous

Google's Cloud Speech-To-Text API is incredible, but for some reason it takes around 90 seconds to complete the WriteAsync() call before anything further happens.
I'm using the C# code, unaltered, right off of GitHub (https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/master/speech/api/Recognize/Recognize.cs). When I invoke any of the methods (StreamingMicRecognizeAsync, SyncRecognizeWithCredentials, etc.) it works as expected except for this huge delay. I don't see anything wrong anywhere, no exceptions being thrown or anything, it just takes forever to get past this code:
var speech = SpeechClient.Create();
var streamingCall = speech.StreamingRecognize();
// Write the initial request with the config.
await streamingCall.WriteAsync(
new StreamingRecognizeRequest()
{
StreamingConfig = new StreamingRecognitionConfig()
{
Config = new RecognitionConfig()
{
Encoding =
RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRateHertz = 16000,
LanguageCode = "en",
},
InterimResults = true,
}
});
This isn't that much of a problem with files, but waiting 90 seconds before being able to speak into a microphone is not a good scenario for our potential customers! :)
Can anyone tell me what I'm doing wrong?
thanks!

Related

Incremental Static Regeneration doesn't work without redeploying

This is my very first time building and deploying a website so bear with me if this is a dumb question. I'm building a Heardle style clone. The idea is that every day there's a new song and people have 6 guesses to figure out which song it is from short clips of the song. Every part of this seems to work with one major exception -- I can't seem to reload today's song dynamically.
I have a function:
export async function getStaticProps() {
const allSearchableSongs = songHelper.getSongData()
const todaysSong = await songHelper.getTodaysSong()
const songURLs: string[] = (todaysSong) ? await songHelper.getTodaysSongClips(todaysSong!) : []
let valid = false
if (songURLs) {
valid = true
}
return {
props: {
allSearchableSongs,
todaysSong,
songURLs,
valid
},
revalidate: 10
};
}
Note that getTodaysSong() and getTodaysSongClips() both make calls to AWS to get data from S3. Whenever I rebuild the website this works well. However, I would like for this to refresh after 60 seconds so that nobody is ever looking at a stale website. But this doesn't change ever. The song is always out of date until I redeploy. I've checked to make sure that the data is changing daily and that's all well and good -- but the website doesn't ever reload.
I'm currently hosting this on Vercel.
What am I doing wrong? How can I ensure that this reloads after 60 seconds?

How do I properly use puppeteer-sharp with server-side Blazor / SignalR?

I can get puppeteer-sharp (with headless both true and false) to obtain server-side-rendered Blazor pages, but it looks like I'm only getting the server pre-render and NOT any client-side initiated events (e.g., for instance the second OnInitialized, or any OnAfterRender, OnAfterRenderAsync).
My best guess is that Signal R is not working properly using puppeteer-sharp.
I do this:
using var browserFetcher = new BrowserFetcher();
await browserFetcher.DownloadAsync();
await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions {
Headless = true
});
await using var page = await browser.NewPageAsync();
await page.SetJavaScriptEnabledAsync(true);
await page.GoToAsync("<<mypage>>,
new NavigationOptions {
WaitUntil = new WaitUntilNavigation[] {
WaitUntilNavigation.Load
}
}
);
string sContent = await page.GetContentAsync();
Is there any way to get ALL of the Blazor events to fire properly, or any good discussion of this on the web somewhere?
Thanks in advance!
The answer here was that puppeteer-sharp is actually working just fine with SignalR in all cases.
I really had a separate, more general problem with my authorization settings where the fallback was improperly set. In that case, pages that supposedly did not require authorization were really only providing a single server-prerender (and no later SignalR-enabled onParameterSet, etc.). This incorrect behavior was the same in both a manual browser windows and puppeteer.

Is it a good / working practice to use Firebase's documentReference.get(GetOptions(source: cache)) in Flutter?

My issue was, that with the default GetOptions (omitting the parameter), a request like the following could load seconds if not minutes if the client is offline:
await docRef.get()...
If I check if the client is offline and in this case purposefully change the Source to Source.cache, I have performance that is at least as good, if not better, than if the client was online.
Source _source = Source.serverAndCache;
try {
final result = await InternetAddress.lookup('example.com');
if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
_source = Source.serverAndCache;
}
} on SocketException catch (_) {
_source = Source.cache;
}
and then use this variable in the following way:
docRef.get(GetOptions(source: _source))
.then(...
This code works perfectly for me now, but I am not sure, if there are any cases in which using the code like this could raise issues.
Also it seems like a lot of boilerplate code (I refactored it into a function so I can use it in any Database methods but still...)
If there are no issues with this, why wouldn't this be the Firebase default, since after trying the server for an unpredictably long time it switches to cache anyways.

Google Maps API In Apps Script Keeps Failing

I'm using google apps script to code a distance finder for Google Maps. I've found examples of such, but they keep failing, so I thought I'd code my own. Sadly, this is failing with the same error:
TypeError: Cannot read property "legs" from undefined. (line 16).
It seems to be that it's sometimes working, and sometimes not. I have a few (3) places in my sheet that are calling the same functions, and at times one or more will return a valid response.
I saw elsewhere that people were suggesting using an API key to make sure that you get a good response, so that's what I've implemented below. (api keys redacted! is there a good way to tell if they've been recognised?)
Any ideas what might be going awry?!
Thanks in advance,
Mike
function mikeDistance(start, end){
start = "CV4 8DJ";
end = "cv4 9FE";
var maps = Maps;
maps.setAuthentication("#####", "#####");
var dirFind = maps.newDirectionFinder();
dirFind.setOrigin(start);
dirFind.setDestination(end);
var directions = dirFind.getDirections();
var rawDistance = directions["routes"][0]["legs"][0]["distance"]["value"];
var distance = rawDistance/1609.34;
return distance;
}
Here's my short term solution while the issue is being fixed.
Not ideal, but at least reduces using your API limit as much as possible.
function getDistance(start, end) {
return hackyHack(start, end, 0);
}
function hackyHack(start, end, level) {
if (level > 5) {
return "Error :(";
}
var directions = Maps.newDirectionFinder()
.setOrigin(start)
.setDestination(end)
.setMode(Maps.DirectionFinder.Mode.DRIVING)
.getDirections();
var route = directions.routes[0];
if (!route) return hackyHack(start, end, level+1); // Hacky McHackHack
var distance = route.legs[0].distance.text;
// var time = route.legs[0].duration.text;
return distance;
}

Meteor multiplayer game clients get out of sync - how to debug?

I've built a simple real-time multiplayer math game in Meteor that you can try out here: http://mathplay.meteor.com
When playing locally (using different browsers), everything works fine. But when I play over the Internet with friends, the clients often get out of sync: a question listed as active for one player is actually already solved by another player.
My guess is that some code that should be server-only gets executed on one of the clients instead. Any suggestions on how to debug this behavior?
Here is what happens on the client when user submits an answer:
Template.number_input.events[okcancel_events('#answertextbox')] = make_okcancel_handler({
ok: function (text, event) {
question = Questions.findOne({ order_number: Session.get("current_question_order_number") });
if (question.answer == document.getElementById('answertextbox').value) {
console.log('True');
Questions.update(question._id, {$set: {text: question.text.substr(0, question.text.length - 1) + question.answer, player: Session.get("player_name")}});
callGetNewQuestion();
}
else {
console.log('False');
}
document.getElementById('answertextbox').value = "";
document.getElementById('answertextbox').focus();
}
});
callGetNewQuestion() triggers this on both client and server:
getNewQuestion: function () {
var nr1 = Math.round(Math.random() * 100);
var nr2 = Math.round(Math.random() * 100);
question_string = nr1 + " + " + nr2 + " = ?";
question_answer = (nr1 + nr2);
current_order_number = Questions.find({}).count() + 1;
current_question_id = Questions.insert({ order_number: current_order_number, text: question_string, answer: question_answer });
return Questions.findOne({_id: current_question_id});//current_question_id;
},
Full source code is here for reference: https://github.com/tomsoderlund/MathPlay
Your problem lies with this:
callGetNewQuestion() triggers this on both client and server
This will generate a different _id because of the timing difference, as well as a different question which will then get replaced with that one that the server generated. However, this might not always be the case. This makes it very easy to let things get out of sync, simply because your client is generating its own stuff.
You'll need to figure out a better approach at making sure the client generates the same data as the server. Which can be done by making sure that a random number generator is seeded the same way and thus would give the same random numbers every time. This will resolve any flickering because the values are different.
Then, for the actual bug you might not want to do this:
return Questions.findOne({_id: current_question_id});
But do this instead (only on the client, do nothing on the server):
Session.set('current_order', current_order_number); // ORDER! Not the _id / question_id.
That way, you can put the following in a template helper:
return Questions.findOne({ order_number: Session.get('current_order') });
In essence, this will work in a reactive way on the Collection and not dependent on the return value.

Resources