Is there any way I can pick a text from the image (OCR) IN REACT NATIVE - reactjs

This is the image I want to bring those text present in the image in my valve serial number used many libraries https://github.com/ashrithks/rn-text-detector
https://github.com/zsajjad/react-native-text-detector It does not work in iOS but it works in android while implementing in iOS I got this error
CompileC /Users/Macbook/Library/Developer/Xcode/DerivedData/CRANE-ciqqhizauxjmlaevomkjkiypelyu/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RNTextDetector.build/Objects-normal/x86_64/RNTextDetector.o /Users/Macbook/Documents/GitHub/crane-app/CRANE/node_modules/rn-text-detector/ios/RNTextDetector.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler (in target 'RNTextDetector' from project 'Pods')
(1 failure)
The code I used inside the
import RNTextDetector from "rn-text-detector";
const captureImage = async type => {
let options = {
mediaType: type,
maxWidth: 300,
maxHeight: 550,
quality: 1,
videoQuality: 'low',
durationLimit: 30, //Video max duration in seconds
saveToPhotos: true,
};
let isCameraPermitted = await requestCameraPermission();
let isStoragePermitted = await requestExternalWritePermission();
if (isCameraPermitted && isStoragePermitted) {
launchCamera(options, response => {
console.log('Response = ', response
);
if (response.didCancel) {
alert('User cancelled camera picker');
return;
} else if (response.errorCode == 'camera_unavailable') {
alert('Camera not available on device');
return;
} else if (response.errorCode == 'permission') {
alert('Permission not satisfied');
return;
} else if (response.errorCode == 'others') {
alert(response.errorMessage);
return;
}
console.log('base64 -> ', response.assets[0].base64);
console.log('uri -> ', response.assets[0].uri);
console.log('width -> ', response.assets[0].width);
console.log('height -> ', response.assets[0].height);
console.log('fileSize -> ', response.assets[0].fileSize);
console.log('type -> ', response.assets[0].type);
console.log('fileName -> ', response.assets[0].fileName);
setFilePath(response.assets[0].uri);
(async () => {
const textRecognition = await RNTextDetector.detectFromUri(response.assets[0].uri);
console.log('Base64_Image', textRecognition);
setSerialNumber(textRecognition[0].text)
})();
RNFS.readFile(response.assets[0].uri, "base64").then(result => {
// setSingleFileBase64('data:image/png;base64,' + result)
setImage('data:/' + response.assets[0].type + ';' + 'base64,' + result)
// console.log('Base64_Image', 'data:/'+response.assets[0].type+';'+'base64,' + result);
setScreenData({ ...screenData, image1: 'data:/' + response.assets[0].type + ';' + 'base64,' + result });
})
});
}
};
]

Related

How can I implement ocr react native . I have implemented it in android but it does not work in iOS

https://github.com/ashrithks/rn-text-detector
https://github.com/zsajjad/react-native-text-detector
These are the libraries I used while implementing my project.
It does not work in iOS but it works in android while implementing in iOS I got this error
CompileC /Users/Macbook/Library/Developer/Xcode/DerivedData/CRANE-ciqqhizauxjmlaevomkjkiypelyu/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/RNTextDetector.build/Objects-normal/x86_64/RNTextDetector.o /Users/Macbook/Documents/GitHub/crane-app/CRANE/node_modules/rn-text-detector/ios/RNTextDetector.m normal x86_64 objective-c com.apple.compilers.llvm.clang.1_0.compiler (in target 'RNTextDetector' from project 'Pods')
(1 failure)
The code I used inside the
import RNTextDetector from "rn-text-detector";
const captureImage = async type => {
let options = {
mediaType: type,
maxWidth: 300,
maxHeight: 550,
quality: 1,
videoQuality: 'low',
durationLimit: 30, //Video max duration in seconds
saveToPhotos: true,
};
let isCameraPermitted = await requestCameraPermission();
let isStoragePermitted = await requestExternalWritePermission();
if (isCameraPermitted && isStoragePermitted) {
launchCamera(options, response => {
console.log('Response = ', response);
if (response.didCancel) {
alert('User cancelled camera picker');
return;
} else if (response.errorCode == 'camera_unavailable') {
alert('Camera not available on device');
return;
} else if (response.errorCode == 'permission') {
alert('Permission not satisfied');
return;
} else if (response.errorCode == 'others') {
alert(response.errorMessage);
return;
}
console.log('base64 -> ', response.assets[0].base64);
console.log('uri -> ', response.assets[0].uri);
console.log('width -> ', response.assets[0].width);
console.log('height -> ', response.assets[0].height);
console.log('fileSize -> ', response.assets[0].fileSize);
console.log('type -> ', response.assets[0].type);
console.log('fileName -> ', response.assets[0].fileName);
setFilePath(response.assets[0].uri);
(async () => {
const textRecognition = await RNTextDetector.detectFromUri(response.assets[0].uri);
console.log('Base64_Image', textRecognition);
setSerialNumber(textRecognition[0].text)
})();
RNFS.readFile(response.assets[0].uri, "base64").then(result => {
// setSingleFileBase64('data:image/png;base64,' + result)
setImage('data:/' + response.assets[0].type + ';' + 'base64,' + result)
// console.log('Base64_Image', 'data:/'+response.assets[0].type+';'+'base64,' + result);
setScreenData({ ...screenData, image1: 'data:/' + response.assets[0].type + ';' + 'base64,' + result });
})
});
}
};

AnyChart 'undefined is not an object' error occurs when touching the graph on a mobile device

When using a mobile device that is viewing an AnyChart graph, when you touch the graph 'undefined is not an object' error is thrown. This occurs on iOS. Anyone have ideas on what causes this and how to resolve the issue? I am using the latest release 8.9.0
I am using iOS 14.4.2 on a chrome browser, though the same occurs when using Safari.
Below is the base code for generating the chart:
this.chart = anychart.stock();
var credits = this.chart.credits();
credits.enabled(false);
this.plot = this.chart.plot(0);
this.plot.yScale().ticks().allowFractional(false);
this.plot.yScale().maximumGap(0);
this.plot.yScale().minimumGap(0);
let activeSeries = this.seriesTypeOptions.find(opt => opt.checked);
if (this.selectedRange === 'intra' && activeSeries.ohlc !== undefined) {
activeSeries = this.seriesTypeOptions.find(opt => opt.value === 'area');
}
let data = activeSeries.ohlc ? this.ohlcMapping : this.valueMapping;
this.series = this.plot[activeSeries.value](data);
this.series.name(this.longName + ' (' + this.symbol + ')');
if (this.mainColor && this.mainColor !== '') {
this.series.stroke(this.mainColor);
this.series.fill(this.mainColor, 0.5);
}
let grouping = this.chart.grouping();
grouping.maxVisiblePoints(700);
if (this.selectedRange !== 'intra') {
switch (this.groupOptions) {
case 'day': {
grouping.levels([
{ unit: 'day', count: 1 },
]);
grouping.forced(true);
break;
}
case 'week': {
grouping.levels([
{ unit: 'week', count: 1 },
]);
grouping.forced(true);
break;
}
case 'month': {
grouping.levels([
{ unit: 'month', count: 1 },
]);
grouping.forced(true);
break;
}
default: {
break;
}
}
}
this.plot.legend().titleFormat('');
this.plot.yAxis().labels().format("{%value}{decimalsCount:0, groupsSeparator:}");
this.plot.crosshair().yLabel().offsetX(-24);
this.plot.xAxis().labels(true);
this.plot.xAxis().minorLabels(true);
this.plot.xAxis().ticks(true);
this.plot.xAxis().minorTicks(true);
this.plot.yGrid().enabled(true);
if (!this.isIndex) {
let volPlot = this.chart.plot(1);
volPlot.legend().titleFormat('');
let volumeSeries = volPlot.column(this.volumeMapping);
volumeSeries.name('Volume ' + ' (' + this.symbol + ')');
volPlot.crosshair().yLabel().offsetX(-24);
volPlot.height('25%');
volPlot.xAxis().labels(false);
volPlot.xAxis().minorLabels(false);
volPlot.xAxis().ticks(false);
volPlot.yGrid().enabled(true);
if (this.mainColor && this.mainColor !== '') {
volumeSeries.stroke(this.mainColor);
volumeSeries.fill(this.mainColor, 0.5);
}
volPlot.yAxis().labels().format("{%value}{decimalsCount:1, scale: (1)(1000)(1000)(1000)|()(K)(M)(B)}");
volPlot.enabled(this.isVolume);
}
// add indicators
if (this.selectedRange !== 'intra') {
let ind = this.indicatorOptions.filter(o => o.checked);
ind.forEach(i => this.addIndicator(i.type));
}
var scroller = this.chart.scroller();
scroller.area(this.scrollMapping);
scroller.listen('scrollerchange', () => {
let mv = this.chart.getSelectedRange();
this.rangeStartDate = new Date(mv.firstVisible);
this.rangeStopDate = new Date(mv.lastVisible);
});
scroller.enabled(this.isScroller);
let offSet: number = (this.isInfo) ? 425 : 275;
if (this.container !== undefined) {
this.container.nativeElement.style.height = (window.innerHeight - offSet) + 'px';
this.chart.container(this.container.nativeElement);
}
// draw chart
this.chart.draw();
If someone encounters the same issue.
Ignore the exception thrown by the chart on a mobile device. This resolved my issue.
We are glad to notify you that a new version of AnyChart library v8.11.0 is available.
Now the Stock chart doesn't throw errors on the user's tap.

DiscordJS role set returns API Error: Missing Permissions

I try to set the member roles, but it doesn't set the permissions.
My index.js file:
var u, s, m;
await bot.users.fetch(message.author.id)
.then(user => { u = user; });
await bot.guilds.fetch('419248578121433100')
.then(guild => { s = guild; });
await s.members.fetch(u)
.then(member => { m = member; });
axios.get('/process')
.then(function (response)
{
var dptos = response.data.dptos;
var attrs = response.data.userAttrs;
var roles = response.data.roles;
if(dptos.length > 0) m.setNickname(dptos[0].position + ' | ' + attrs.name + ' ' + attrs.surname);
else m.setNickname(attrs.name + ' ' + attrs.surname + ' | ' + '123456');
m.roles.set(roles)
.then(function(member)
{
let fd = fs.openSync('log.txt', 'w');
fs.writeSync(fd, JSON.stringify(member.roles.cache));
fs.closeSync(fd);
})
.catch(function(error)
{
let fd = fs.openSync('error.txt', 'w');
fs.writeSync(fd, error);
fs.closeSync(fd);
});
return message.reply('Congrats!');
})
.catch(function (error)
{
return message.reply('error!');
});
}
The axios request works as expected and the data is obtained correctly.
Screenshots:
Bot position
Bot general permissions
UPDATE 1: Nickname permissions
What could be the issue?

code in promise .then firing way before promise finishes

I have this code...sorry for the messiness I've been at this a while:
loadAvailabilities() {
let promises = [];
let promises2 = [];
let indexi = 0;
//return new Promise((resolve, reject) => {
this.appointments = this.af.list('/appointments', { query: {
orderByChild: 'selected',
limitToFirst: 10
}});
let mapped;
this.subscription2 = this.appointments.subscribe(items => items.forEach(item => {
//promises.push(new Promise((resolve, reject) => {
console.log(item);
let userName = item.$key;
//this.availabilities = [];
for(let x in item) {
let month = x;
console.log(x + " month");
this.appointmentsMonth = this.af.list('/appointments/' + userName + '/' + month);
this.subscription3 = this.appointmentsMonth.subscribe(items => items.forEach(item => {
this.startAtKeyAvail = item.$key;
//console.log(JSON.stringify(item) + " item");
let date = new Date(item.date.day * 1000);
let today = new Date();
console.log(date.getMonth() + "==" + today.getMonth() + "&&" + date.getDate() + "==" + today.getDate());
console.log("IN LOAD AVAILABILITIES *(*((**(*(*(*(*(*(*&^^^^%^%556565656565");
if(date.getMonth() == today.getMonth() && date.getDate() == today.getDate()) {
console.log(" inside the if that checks if its today");
console.log(item.reserved.appointment + " *************appointment");
//let counter = 0;
//mapped = item.reserved.appointment.map((r) => {
//item.reserved.appointment.forEach((r, index) => {
for(let r of item.reserved.appointment) {
promises.push(new Promise((resolve, reject) => {
if(r.selected == true) {
//this.renderer.setElementStyle(this.noavail.nativeElement, 'display', 'none');
let storageRef = firebase.storage().ref().child('/settings/' + userName + '/profilepicture.png');
let obj = {'pic':"", 'salon': userName, 'time': r.time};
storageRef.getDownloadURL().then(url => {
console.log(url + "in download url !!!!!!!!!!!!!!!!!!!!!!!!");
obj.pic = url;
this.availabilities.push(obj);
console.log(JSON.stringify(this.availabilities));
resolve();
}).catch((e) => {
console.log("in caught url !!!!!!!$$$$$$$!!");
obj.pic = 'assets/blankprof.png';
this.availabilities.push(obj);
console.log(JSON.stringify(this.availabilities));
resolve();
});
}
}))
}
}
}))
}
}))
//}));
Promise.all(promises).then(() => {
console.log("in load availabilities ......... ")
console.log(JSON.stringify(this.availabilities));
this.availabilities.sort(function(a,b) {
return Date.parse('01/01/2013 '+a.time) - Date.parse('01/01/2013 '+b.time);
});
console.log('*****previous******');
console.log(JSON.stringify(this.availabilities));
console.log('*****sorted********');
for(let i of this.availabilities) {
console.log(i.time + " this is itime");
let date = new Date('01/01/2013 ' + i.time);
console.log(date + " this is date in idate");
let str = date.toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });
console.log(str);
i.time = str;
}
});
//}))
//})
}
I can tell from the log messages that the storageRef.getDownloadURL() function happens close to the end of when my page loads...this is where the objects actually get pushed to this.availabilities (eventually used to populate a list). The code in the Promise.all .then() actually fires before anything gets pushed to this.availabilities so when the sorting happens it is an empty array and nothing gets sorted.
I used a promise inside each forEach loop. I pushed all the promises to the same array and used Promise.all(array).then(...) how it is being used above - and the promises did their job - the array is sorted because everything is happening asynchronously.

Can't use HTML5 geolocation with Android 4.4

I'm developing a web-app which is supposed to work on iOS and Android, and uses geolocation with HTML5.
We have tested it on Android 4.1 (Samsung Galaxy Tab 2) and on several iOs versions with iOS simulator and devices, everything was fine and the onSuccess callback is passed,
but when we tried to test it on a Wiko Sunset phone, with Android 4.4.2, and neither the success nor the fail one passed.
When we visited some websites asking our position (such as Mappy), we experienced a pop-up error which said that our position that it couldn't get our position, and that we should check that geolocation service was activated (which did was).
We experienced this situation with 4 browsers:
Opera
Firefox
Chrome
The native Android browser.
Is it possible to use HTML 5 geolocation API with Android 4.4?
Here is our testing Angular controller code.
testTTS.controller('mainCtrl', ['$scope', '$ionicPlatform', function($scope, $ionicPlatform) {
testTTS.geolocation = false;
var options = {
enableHighAccuracy: true
};
onSuccess = function(position) {
alert('Latitude: ' + position.coords.latitude + '\n' +
'Longitude: ' + position.coords.longitude + '\n' +
'Altitude: ' + position.coords.altitude + '\n' +
'Accuracy: ' + position.coords.accuracy + '\n' +
'Altitude Accuracy: ' + position.coords.altitudeAccuracy + '\n' +
'Heading: ' + position.coords.heading + '\n' +
'Speed: ' + position.coords.speed + '\n' +
'Timestamp: ' + position.timestamp + '\n');
};
onFail = function(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
};
navigator.geolocation.getCurrentPosition(onSuccess, onFail, options);
}]);
Try this it worked for me on android devices
function getGpsCordinates(callback) {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(
//Success
function (position) {
console.log("GPS: Success");
callback(position);
},
//Error
function (error) {
console.log("GPS: Error");
var position = {
coords: {
longitude: 0,
latitude: 0,
speed: 0
}
};
callback(position);
},
{ timeout: 7000, enableHighAccuracy: false});
} else {
var position = {
coords: {
longitude: 0,
latitude: 0,
speed: 0
}
};
console.log("GPS: Not Supported");
callback(position);
}
console.log("GPS: Continued");
}
getGpsCordinates(function(mycallback) {
alert(mycallback.coords.latitude);
});

Resources