I've implemented a custom model at Azures's form recognizer. In performance test, using PDF and JPEG files to do the text extraction, the hole process is being executed at Azure and are getting ~4.5s to response the requests.
My question is, There's a way to improve these response time?
There's my test code:
const processFile = (path) => axios({
url: RECOGNIZER_URL,
method: "POST",
headers: {
"Ocp-Apim-Subscription-Key": RECOGNIZER_KEY,
'Content-Type': `application/json`
},
data: {
"urlSource": path
}
})
const getResult = (location) => axios({
url: location,
method: "GET",
headers: {
"Ocp-Apim-Subscription-Key": RECOGNIZER_KEY
},
})
const testOcr = async (imageURL) => {
console.time('#testOcrTime');
let res = await processFile(imageURL)
.then(async response => {
let result = await getResult(response.headers["operation-location"])
while(((result.data) || {}).status == "running"){
result = await getResult(response.headers["operation-location"])
}
return result
})
.then(response => {console.log(response)
return response.data.analyzeResult.documents[0].fields})
.catch(err => console.error(err))
console.timeEnd('#testOcrTime');
console.log(res)
return
}
testOcr()
Azure's Documentation
Related
I am trying to make a full stack Transport management system with mern but it runs fine for 15s and after that TypeError: Failed to fetch comes in and it increases exponentially in my console.
useEffect(() => {
const fetchBus = async () => {
try{
const response = await fetch("/api/buses");
const json = await response.json();
if (response.ok) {
dispatch({ type: "SET_BUS", payload: json });
}
}
catch(error){
console.log(error)
}
};
fetchBus();
}, [handleOwnership,handleAvailable]);
As fetch() and response.json() both are asynchronous tasks and both returns a Promise.You need to parse json data inside an if(response.ok){} block:
Replace:
useEffect(() => {
const fetchBus = async () => {
try{
const response = await fetch("/api/buses");
//const json = await response.json();//Not here
if (response.ok) {
const json = await response.json();//But Here
dispatch({ type: "SET_BUS", payload: json });
}
}
catch(error){
console.log(error)
}
};
fetchBus();
}, [handleOwnership,handleAvailable]);
Fetch JSON GET Request:
let url = 'https://someurl.com';
let response = await fetch(url);
let responseOK = response && response.ok;
if (responseOK) {
let data = await response.json();
// do something with data
}
Fetch JSON POST Request:
let url = 'https://someurl.com';
let options = {
method: 'POST',
mode: 'cors',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
body: JSON.stringify({
property_one: value_one,
property_two: value_two
})
};
let response = await fetch(url, options);
let responseOK = response && response.ok;
if (responseOK) {
let data = await response.json();
// do something with data
}
I figured it out. I was getting into a death-loop because I added functions in my dependencies but I learned that one should never do that instead of function add variables or arrays or primitives in dependencies.
For me I used use-state (variable) in dependencies instead of functions
try to insert multiple data in mongodb but not working
Client site code
const onConfirmOrder = (e) => {
const data = {}
const url = `https://damp-coast-51374.herokuapp.com/product`;
fetch(url, {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(name => {
e.target.reset();
console.log(name);
})
};
this is my server site code
app.post('/invoices', async (req, res) => {
const service = req.body;
const options = { ordered: true };
const result = await invoiceCollection.insertMany(service, options);
res.send(result);
});
const fetch = require('node-fetch');
let body = { a: 1 };
const stopId = 413
fetch(`https://api.ashx?stopId=${stopId}`, {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => body = json);
console.log(body)
I'm getting the output: { a: 1 } Instead of the API JsonResponse, however when I use .then(json => console.log(json)); I get the desired response..
I've tried to use await fetch, to pause the code till the promise returned then to console.log body but it needs to be an async function.. Does anyone know how I can assign the let body a new value before proceeding to the code below? Or would there be a way to return from .then ?
So I could do something like: (I know this doesn't work)
function fetchStop(stopId){
fetch(`https://api.ashx?stopId=${stopId}`, {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => return body);
}
console.log(fetchStop(stopId))
Any solutions or explanations/insights on how these things work is much appreciated, very much a noob with async and promises
The fetch executes asynchronously and you can access the result only in the callback.
Here, the console.log(body) executes soon after a network call is initiated.
const fetch = require('node-fetch');
let body = { a: 1 };
const stopId = 413
fetch(`https://api.ashx?stopId=${stopId}`, {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => body = json);
console.log(body)
To access the result,
function fetchStop(stopId){
return fetch(`https://api.ashx?stopId=${stopId}`, {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
}
fetchStop(stopId).then(result => console.log(result))
You are using promise for fetching data from your URL https://api.ashx?stopId=${stopId}. Since this will take time and is asynchronous (nonblocking) so while it is fetching data code will move to console.log(body) and print the previous body (body = { a: 1 };). Because code flow moves to console.log before the promise gets executed, this promise will take time to fetch data. So you have to console.log within then itself. Because that's the point when your promise is getting executed later in time. You can do it easily using async await
const yourFunction = async () => {
const fetch = require('node-fetch');
let body = { a: 1 };
const stopId = 413;
const { hostname: location } = window.location;
const data = {
method: 'post',
body: JSON.stringify(body),
headers: { 'Content-Type': 'application/json' },
}
const response = await fetch(`https://api.ashx?stopId=${stopId}`, data);
if (!response.ok) throw Error(response.message);
try {
body = await response.json();
return;
} catch (err) {
throw err;
}
};
I am sending a post request from the frontend and i am getting a response with a confirmation url, i want to redirect to that url, but it is not doing so
iam using:-
koajs as framework
backend code:-
router.post("/api/pricing/:token/:shop", koaBody(), async (ctx) => {
try {
let shopname = await ctx.params.shop;
let dataBody = await ctx.request.body;
let bodyStringyfy = JSON.stringify(dataBody);
let tokenjson = await ctx.params.token;
const options = {
method: "POST",
body: bodyStringyfy,
headers: {
"X-Shopify-Access-Token": tokenjson,
"Content-Type": "application/json",
},
};
let url = `https://${shopname}/admin/api/2021-01/recurring_application_charges.json`;
await fetch(url, options)
.then((response) => response.json())
.then((res) => {
ctx.redirect(
`https://cors-anywhere.herokuapp.com/${res.recurring_application_charge.confirmation_url}`
);
});
} catch (e) {
console.log(e);
}
});
A snippet of code on the app side. I can't figure out exactly where my mistake is. It is possible that the helper change leaves the method before it has time to wait for a response from the server
Promise((resolve) => {
fetch('/currentDir1',{
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(elem)
})
.then(response => response.json())
.then(json => this.helper = json)
.then(json => this.$emit("newvalue", json))
console.log("helper");
console.log(this.helper);
resolve("result");
});
Server-side handler
router.post('/currentDir1',(req, res) =>{
console.log("POST");
let body = "";
let pathToFile = "";
req.on("data", function (data) {
body += data;
});
req.on("end", function(currentData) {
console.log(JSON.parse(body));
currentData = JSON.parse(body);
if(currentData.sizeOrType === "<папка>"){
let dir = currentData.dir + currentData.fileName;
// dir = "C:\\totalcmd";
console.log(dir);
if(currentData.whichScreen){
foo(dir, './data/firstScreen.json');
pathToFile = './data/firstScreen.json';
res.sendFile(path.resolve('./data/firstScreen.json'));
}else{
console.log('aaaa');
Foo(dir, './data/secondScreen.json');
pathToFile = './data/firstScreen.json';
res.sendFile(path.resolve('./data/secondScreen.json'));
}
}
// res.json({ message: 'goodbye'})
res.json(path.resolve(pathToFile));
});
res.sendFile(path.resolve(pathToFile));
})
Are you sure about the scope of this.helper? Try putting "this" into a variable outside the method to ensure the scope? i.e.
var that = this;
Promise((resolve) => {
fetch('/currentDir1',{
method: 'POST',
mode: 'cors',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(elem)
})
.then(response => response.json())
.then(json => that.helper = json)
.then(json => that.$emit("newvalue", json))
console.log("helper");
console.log(that.helper);
resolve("result");
});