-
Notifications
You must be signed in to change notification settings - Fork 353
/
Analyze Speech & Language with Google APIs: Challenge Lab
92 lines (63 loc) · 2.5 KB
/
Analyze Speech & Language with Google APIs: Challenge Lab
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
export API_KEY=
nano nl_request.json
curl "https://language.googleapis.com/v1/documents:analyzeEntities?key=${API_KEY}" \
-s -X POST -H "Content-Type: application/json" --data-binary @nl_request.json > nl_response.json
Task 3. Create a speech analysis request and call the Speech API
nano speech_request.json
Paste This in speech_request.json
{
"config": {
"encoding":"FLAC",
"languageCode": "en-US"
},
"audio": {
"uri":"gs://cloud-samples-tests/speech/brooklyn.flac"
}
}
curl -s -X POST -H "Content-Type: application/json" --data-binary @speech_request.json \
"https://speech.googleapis.com/v1/speech:recognize?key=${API_KEY}"
curl -s -X POST -H "Content-Type: application/json" --data-binary @speech_request.json \
"https://speech.googleapis.com/v1/speech:recognize?key=${API_KEY}" > speech_response.json
Task 4. Analyze sentiment with the Natural Language API
cat > sentiment_analysis.py <<EOF
import argparse
from google.cloud import language_v1
def print_result(annotations):
score = annotations.document_sentiment.score
magnitude = annotations.document_sentiment.magnitude
for index, sentence in enumerate(annotations.sentences):
sentence_sentiment = sentence.sentiment.score
print(
f"Sentence {index} has a sentiment score of {sentence_sentiment}"
)
print(
f"Overall Sentiment: score of {score} with magnitude of {magnitude}"
)
return 0
def analyze(movie_review_filename):
"""Run a sentiment analysis request on text within a passed filename."""
client = language_v1.LanguageServiceClient()
with open(movie_review_filename) as review_file:
# Instantiates a plain text document.
content = review_file.read()
document = language_v1.Document(
content=content, type_=language_v1.Document.Type.PLAIN_TEXT
)
annotations = client.analyze_sentiment(request={"document": document})
# Print the results
print_result(annotations)
if _name_ == "__main__":
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument(
"movie_review_filename",
help="The filename of the movie review you'd like to analyze.",
)
args = parser.parse_args()
analyze(args.movie_review_filename)
EOF
gsutil cp gs://cloud-samples-tests/natural-language/sentiment-samples.tgz .
gunzip sentiment-samples.tgz
tar -xvf sentiment-samples.tar
python3 sentiment_analysis.py reviews/bladerunner-pos.tx