analyze_text.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 
4 # beased on example code
5 # https://googleapis.dev/python/language/latest/usage.html#documents
6 #
7 # ros code
8 import actionlib
9 import rospy
10 import os
11 
12 from ros_google_cloud_language.msg import AnalyzeTextAction
13 from ros_google_cloud_language.msg import AnalyzeTextResult
14 from ros_google_cloud_language.msg import AnalyzeTextFeedback
15 from ros_google_cloud_language.msg import TextEntity
16 from ros_google_cloud_language.msg import TextSyntax
17 from diagnostic_msgs.msg import KeyValue
18 
19 # Imports the Google Cloud client library
20 from google.cloud import language_v1 as language
21 
22 class ROSGoogleCloudLanguage(object):
23  def __init__(self):
24  credentials_path = rospy.get_param("~google_cloud_credentials_json", None)
25  if credentials_path:
26  if not os.path.exists(credentials_path):
27  raise Exception("file {} is not found, please specify existing google cloud credentials json file path".format(credentials_path))
28  os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = credentials_path
29  # Instantiates a client
30  self._client = language.LanguageServiceClient()
31  #
32  self._as = actionlib.SimpleActionServer(
33  '~text', AnalyzeTextAction,
34  execute_cb=self.execute_cb, auto_start=False)
35  self._as.start()
36 
37  def execute_cb(self, goal):
38  feedback = AnalyzeTextFeedback()
39  result = AnalyzeTextResult()
40  success = True
41 
42  try:
43  document = language.types.Document(
44  content=goal.text,
45  type='PLAIN_TEXT'
46  )
47  # Detects the entities and sentiment of the text
48  response = self._client.analyze_entities(
49  document=document,
50  encoding_type='UTF32',
51  )
52  for entity in response.entities:
53  result.entities.append(TextEntity(
54  name=entity.name.encode('utf-8'),
55  type=entity.type,
56  metadata=map(lambda kv: KeyValue(kv[0], kv[1]),
57  entity.metadata.items()),
58  salience=entity.salience))
59 
60  # Detects the sentiment of the text
61  sentiment = self._client.analyze_sentiment(
62  document=document,
63  encoding_type='UTF32'
64  ).document_sentiment
65 
66  result.sentiment_score = sentiment.score
67  result.sentiment_magnitude = sentiment.magnitude
68 
69  # # Analayze Syntax
70  syntax = self._client.analyze_syntax(
71  document=document,
72  encoding_type='UTF32'
73  )
74 
75  for token in syntax.tokens:
76  # print("{} {} {}".format(token.part_of_speech.tag, token.text.content.encode('utf-8'), token.dependency_edge.head_token_index)
77  result.syntaxes.append(TextSyntax(
78  name=token.text.content.encode('utf-8'),
79  lemma=token.lemma.encode('utf-8'),
80  dependency_edge=token.dependency_edge.head_token_index,
81  part_of_speech=token.part_of_speech.tag,
82  parse_label=token.dependency_edge.label
83  ))
84 
85  except Exception as e:
86  rospy.logerr("Fail to analyze syntax ... {}".format(str(e)))
87  feedback.status = str(e)
88  success = False
89  finally:
90  self._as.publish_feedback(feedback)
91  self._as.set_succeeded(result)
92 
93 if __name__ == '__main__':
94  rospy.init_node("ros_google_cloud_language")
96  rospy.spin()


ros_google_cloud_language
Author(s): Kei Okada
autogenerated on Sat Jun 24 2023 02:40:35