Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Merixstudio GCP Demo
"""
This gist is a part of a presentation for Merixstudio
Piorunujące Spotkania event "Finding intelligence in the
Google Cloud Platform". Feel free to look through the code.
The presentation is available here:
docs.google.com/presentation/d/16FqklnyY1ub-ThsKr81o_g4YZ3pkZTK9ckXmVFjMigA/
"""
# Add imports
import json
import os
from google.cloud import translate_v2 as translate
from google.cloud import language_v1 as language
# Add the text you want to translate
# Example taken from: https://www.merixstudio.com/blog/april_2021/
INPUT_TEXT = (
"April in Merixstudio wasn't really a 'quiet' month. "
"And certainly not boring! We've made lots of excellent "
"coding on antique computers, interviewed extraordinary "
"startupers, gained new benefits, and… read on, folks!"
)
# Create the translation client, notice target language.
translate_client = translate.Client(target_language="pl")
# Translate the text
result = translate_client.translate(INPUT_TEXT)
# Print results in a pretty way
print("Cloud Translate output:")
print(json.dumps(result, indent=4))
# Create the NL client
language_client = language.LanguageServiceClient()
# Create the NL document
document = language.Document(
content=INPUT_TEXT,
type_=language.Document.Type.PLAIN_TEXT,
)
# Do NLP magic using GCP
sentiment = language_client.analyze_sentiment(
request={"document": document},
).document_sentiment
entities = language_client.analyze_entities(
request={"document": document},
).entities
syntax = language_client.analyze_syntax(
request={"document": document},
).tokens
# Print NL results
# The API responses are quite big, so we just pick a few keys
nl_results = {
"sentiment": {
"score": sentiment.score,
"magnitude": sentiment.magnitude,
},
"entities": [
{
"name": entity.name,
"type": entity.type_.name,
}
for entity in entities
],
"syntax": [
{
"text": token.text.content,
"part": language.PartOfSpeech.Tag(token.part_of_speech.tag).name,
"voice": language.PartOfSpeech.Voice(token.part_of_speech.voice).name,
"lemma": token.lemma,
}
for token in syntax
],
}
print("Cloud Language output:")
print(json.dumps(nl_results, indent=4))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment