Google Translate API: Enable word conversion - google-translate

I'm translating a list of words using google translate API, however I noticed that for words that it cannot translate, it returns the same word in the source language.
For example, let's observe the following request of word array conversion from English to Hebrew:
const response = await axios.post<TranslateResponse>(`https://translation.googleapis.com/language/translate/v2?key=xxxxxxx`,
{
"q": ["SUNFINSH", "DOG"],
"source": "en",
"target": "he",
"format": "text"
});
The returned object is
{"data":{"translations":[{"translatedText":"SUNFINSH"},{"translatedText":"כֶּלֶב"}]}}
in the above example, you can see it translated "DOG", but could not translate "SUNFISH".
However, if I go to translate.google.com, and type in "SUNFISH", even though it does not translate it on the right panel UI, it does offer kind of a "literal" translation, as if it can simply convert the word to how it sounds in Hebrew.
The question is, how can I get the same result using the Google Translate API?

You may try and change "SUNFISH" into "sunfish" and it will return the expected output same as the screenshot you provided using the Google Translate UI.
As seen in the screenshot provided using the Google Translate UI, Google converted "SUNFISH" into "sunfish" first and then from there, it translated it to Hebrew.
Please see the screenshot of my testing.
I also tested using "Sunfish" and still got the expected result in hebrew.
In addition, as mentioned in this official google support forum,
Google Translate must be case sensitive as no two languages follow the same Capitalization rule.
Below is my sample code used in testing for your reference.
// Imports the Google Cloud client library
const {Translate} = require('#google-cloud/translate').v2;
// Creates a client
const translate = new Translate();
const text = ['sunfish', 'DOG'];
const target = 'he';
async function translateText() {
// Translates the text into the target language. "text" can be a string for
// translating a single piece of text, or an array of strings for translating
// multiple texts.
let [translations] = await translate.translate(text, target);
translations = Array.isArray(translations) ? translations : [translations];
console.log('Translations:');
translations.forEach((translation, i) => {
console.log(`${text[i]} => (${target}) ${translation}`);
});
}
translateText();

Related

Redis-OM library error during next js redis implementations

I need some help to figure it our why I am getting error when using macthes API, this is my code:
export async function searchCars(query) {
await connect();
const repository = client.fetchRepository(schema);
const cars = await repository
.search()
.where("make")
.eq(query)
.or("model")
.eq(query)
.or("description")
.matches(query)
.return.all();
return cars;
}
And I am getting this error when making API request
May I ask for help?
Many thanks ~~
I did remove the macthes() API, the whole query works, and I can get results back.
If i add it back, the APi will return redis error ...
Expectation: I would like to do text search which matches the paragraph text, then return the record(s).
Sorry, I think I have figured it our, the issue is we need to ensure the scheme field type must be text rather than string, something like below:
description: { type: "text", textSearch: true },

Querying Firestore documents by Array or Map fields values in Firebase console

Here, I want to query by the value "ministoreid1" in Firebase console. But I am not able to figure out. Here, I am trying to do the query in console not using codes.
I have filed the feature request at Alex' suggestion. And the reply I received from Firebase Support:
Currently, there is no query similar to array-contains available in the Firestore Console. I can file a feature request ticket on your behalf. However, I can't guarantee anything at the moment, so please watch out for any updates on our blog or release notes for now. For the map field, you can try to filter on the console using the format: 'mapFieldName.keyName' in the field text box
So we can query for map values by 'mapFieldName.keyName'. I didn't know this before.
Here, I am trying to do the query in console not using codes.
Unfortunately, there is currently no way you can filter your documents in the Firebase console according to a value that exist in an array. As you can see, there are only the following operators:
== is equal to
> is after
>= is after and includes
< is before
<= is before and includes
But an whereArrayContains option it is not present yet. I recommend you file a feature request for that. It might be also useful for other developers.
The query that you perform in the console does't return any results because you are checking if the mini_stores_assigned is equal to ministoreid1, which obviously is not since the mini_stores_assigned property is an array and not a String so you can compare them.
For future use, Firebase has added the feature request by Ssuburat. You can now can filter your documents in the Firebase console according to a value that exist in an array.
###FILTER BLOGS BY USER.
for example if you have two collections (one to many)
/users
/blogs
blog and user has these schemes:
blog: { name,date,user:{myusername:true}}
//notice that user is a map or object and document blog has id itself wich you can use in user document and viceversa.
user:{name,lastname,blogs:{idblog1:true,idblog2:true}} //blogs is a map or object
if you want to filter by map object you can do this:
import firebase from "firebase/compat/app";
import { getFirestore } from "firebase/firestore";
const appFirebase = firebase.initializeApp(firebaseConfig);
export const dbFirebase = getFirestore(appFirebase);
const myuser= "myusername"
const q = query(collection(dbFirebase, "blogs"), where(`user.${myuser}`, "==", true));
const blogsSnapshot = await getDocs(q);
blogsSnapshot.forEach((doc) => {
// doc.data() is never undefined for query doc snapshots
console.log(doc.id, " => ", doc.data());
});
console.log({blogsSnapshot});

How to filter on a long text just one word via Firestore on Ionic 4?

I'm trying to filter using (ionChange) on a searchbar just for a word on a long text (body of a letter) using Firestore, but the problem I don't know how to start, cannot see any option using Firestore (The filter is not about <=, ==...)
I was googleing a lot but didn't find any solution. Any idea?
Just what i want is to filter a list of ion-card (retrieved from firestore) just a word from a long text. Thank you so much
Unfortunately, Firestore does not support full-text search. So there is currently no way you can search a single word in a very long text. According to the official documentation regarding full-text search in Firestore:
To enable full text search of your Cloud Firestore data, use a third-party search service like Algolia.
If the those words that you want to search can be considered "tags", then store those tags in an array and use array-contains option.
Here is your answer find data from Firesote.
searcData( event ) {
const value = event.target.value;
this.loader.presentLoading();
const fireStoreData = this.afStore
.collection('CollectionName', ref => ref
.orderBy('fieldName')
.startAt(value.toLowerCase())
.endAt(value.toLowerCase() + '\uf8ff')
.limit(10)).valueChanges();
fireStoreData.subscribe(data => {
this.data = data;
this.loader.hideLoading();
// console.log(data);
}, err =>{
this.loader.hideLoading();
console.log(err);
});
}

How to extract params from received link in react native firebase dynamiclink?

I tried to migrate from react navigation deeplinks to firebase dynamic linking using this library (react-native-firebase).
I have set up everthing and links are being generated and received on the app. However, is there any way to extract the params sent in the link properly using this library?. Currenty this is my code for handling received link:
handleDynamicLink = () => {
firebase
.links()
.getInitialLink()
.then((url) => {
console.tron.log('link is ', url);
})
.catch((error) => {
console.tron.log(error);
});
};
The url received is
https://links.dev.customdomain.in/?link=products%2F1122
I want to extract the product id 1122 from the url. The only way for me right now is to parse the string and manually extract the relevant params. Unlike in react navigation deeplinks where I used to specify the path, like
Product: {
screen: Product,
path: 'customdomain/products/:slug',
},
Where the slug or id data used to pass as navigation param in the respective screen. Am I missing something? How can I pass mutliple params this way?
Point 2 in this link here says:
The response contains the URL string only.
This means that the firebase.links().getInitialLink() method does not return query parameters, at least as at the time of writing this (v5.5.5). To add your paramaters, you should use a URL with your query param as part of the URL. What I mean is this
Use https://links.dev.customdomain.in/link/products/1122
and use Regex to extract the product id which is of interest to you. This is what works for me and I hope it helps.

Google Cloud Vision Raw JSON Response

When trying out google cloud vision with the drag and drop Try Drag and Drop, the last tab has raw JSON. What parameter do we need to pass to get that data?
I'm currently doing DOCUMENT_TEXT_DETECTION but it only gives data at the level of words and not of individual characters.
Edit: I modified this code vision test and changed the feature ...
feature := &vision.Feature{
Type: "DOCUMENT_TEXT_DETECTION",
}
and the printing to ...
body, err := json.Marshal(res)
fmt.Println(string(body))
I'm only seeing textAnnotations in the output.
The JSON file contains different things like text, locations and etc etc, Your concern is about getting full text.
Here I am adding a Python code, it says that you can get the full text by rendering the JSON file, you will find your required result using data['fullTextAnnotation']['text'], and you can get characters by breaking this file into smaller chunks and I guess JSON file has individual characters in it but I have never worked on it.
import json
from pprint import pprint
data = json.load(open('File Path'))
pprint(data['fullTextAnnotation']['text'])
Well, if you check properly there are various things available in that last tab containing raw JSON.
Based on your requirements you can fetch any of them.
From the response that you get from DOCUMENT_TEXT_DETECTION, you can fetch text_annotations, full_text_annotations, etc.
From text_annotations, you can fetch description, language of entire text, each words of texts, numeric digits, special characters and their respective co-ordinates.
From full_text_annotations, you can fetch pages, blocks of data, paragraphs, and individual characters, with their respective co-ordinates and confidence score.
Using the same code template you are using in Go language:
Search “type Feature struct” in the browser in this page. You can see the following feature types and descriptions:
// Type: The feature type.
//
// Possible values:
// "TYPE_UNSPECIFIED" - Unspecified feature type.
// "FACE_DETECTION" - Run face detection.
// "LANDMARK_DETECTION" - Run landmark detection.
// "LOGO_DETECTION" - Run logo detection.
// "LABEL_DETECTION" - Run label detection.
// "TEXT_DETECTION" - Run text detection / optical character
// recognition (OCR). Text detection
// is optimized for areas of text within a larger image; if the image
// is
// a document, use `DOCUMENT_TEXT_DETECTION` instead.
// "DOCUMENT_TEXT_DETECTION" - Run dense text document OCR. Takes
// precedence when both
// `DOCUMENT_TEXT_DETECTION` and `TEXT_DETECTION` are present.
// "SAFE_SEARCH_DETECTION" - Run Safe Search to detect potentially
// unsafe
// or undesirable content.
// "IMAGE_PROPERTIES" - Compute a set of image properties, such as
// the
// image's dominant colors.
// "CROP_HINTS" - Run crop hints.
// "WEB_DETECTION" - Run web detection.
There is not an option to directly show the JSON tab contents. The JSON tab contents are the addition of all the tabs “output”. Users tend to ask just for one. For example, when someone is analyzing faces is not interested in text detection.
If you need more than one, you can obtain multiple features outputs by “adding” the result of all the possible values together. Based on the facts mentioned, I have added the following lines to your code:
feature2 := &vision.Feature{
Type: "LABEL_DETECTION",
MaxResults: 10,
}
req2 := &vision.AnnotateImageRequest{
Image: img,
Features: []*vision.Feature{feature2},
}
batch2 := &vision.BatchAnnotateImagesRequest{
Requests: []*vision.AnnotateImageRequest{req2},
}
res2, err := svc.Images.Annotate(batch2).Do()
if err != nil {
log.Fatal(err)
}
body2, err := json.Marshal(res2)
fmt.Println(string(body2))
I have tested it and works. You should add this block of code for all the features in which you are interested. If you intend to add many of them, I would suggest to create a function/loop to avoid repeating code.
Anyway, I suggest you to fulfill the request here in order to exactly obtain the JSON output (that gives data at the level of words or letters) through calling the API instead of using a client library. I have used the next code to obtain the bounding box for the numbers of my interest:
{
"requests":
[
{
"features":
[
{
"type":
""
"maxResults":
-- add a property --model
}
{
"type":
""
-- add a property --maxResultsmodel
}
]
"image":
{
"source":
{
"gcsImageUri":
""
-- add a property --imageUri
}
-- add a property --content
}
-- add a property --imageContext
}
]
-- add a property --
}

Resources