def run(): # Load the private key downloaded from the StellarStation Console. credentials = google_auth_jwt.Credentials.from_service_account_file( '../../fakeserver/src/main/jib/var/keys/api-key.json', audience='https://api.stellarstation.com') # Setup the gRPC client. jwt_creds = google_auth_jwt.OnDemandCredentials.from_signing_credentials( credentials) channel_credential = grpc.ssl_channel_credentials( open('../../fakeserver/src/main/resources/tls.crt', 'br').read()) channel = google_auth_transport_grpc.secure_authorized_channel( jwt_creds, None, 'localhost:8080', channel_credential) client = stellarstation_pb2_grpc.StellarStationServiceStub(channel) # Open satellite stream request_queue = Queue() request_iterator = generate_request(request_queue) for response in client.OpenSatelliteStream(request_iterator): if response.HasField("receive_telemetry_response"): for telemetry in response.receive_telemetry_response.telemetry: print("Got response: ", base64.b64encode(telemetry.data)[:100]) command = [ bytes(b'a' * 5000), bytes(b'b' * 5000), bytes(b'c' * 5000), bytes(b'd' * 5000), bytes(b'e' * 5000), ] request_queue.put(command) time.sleep(1)
def _init_assistant(self): from google.auth.transport.grpc import secure_authorized_channel self.interactions = [] # Create an authorized gRPC channel. self.grpc_channel = secure_authorized_channel(self.credentials, self.http_request, self.api_endpoint) self.logger.info('Connecting to {}'.format(self.api_endpoint)) # Configure audio source and sink. audio_device = None audio_source = audio_device = ( audio_device or audio_helpers.SoundDeviceStream( sample_rate=self.audio_sample_rate, sample_width=self.audio_sample_width, block_size=self.audio_block_size, flush_size=self.audio_flush_size)) audio_sink = audio_device = (audio_device or audio_helpers.SoundDeviceStream( sample_rate=self.audio_sample_rate, sample_width=self.audio_sample_width, block_size=self.audio_block_size, flush_size=self.audio_flush_size)) # Create conversation stream with the given audio source and sink. self.conversation_stream = audio_helpers.ConversationStream( source=audio_source, sink=audio_sink, iter_size=self.audio_iter_size, sample_width=self.audio_sample_width, ) self._install_device_handlers()
def send_grpc(since_id, service_addr): # set up credentials credentials, _proj = google_auth.default() goog_req = google_auth_transport_requests.Request() channel = google_auth_transport_grpc.secure_authorized_channel(credentials, goog_req, service_addr) stub = bounty_searcher_pb2_grpc.BountySearcherStub(channel) # send tweet processing request if since_id is not None: since_id = int(since_id) tweet_request = bounty_searcher_pb2.BountySearcherRequest(since_id=since_id) # getting auth headers auth_headers = getAuthHeaders() res, _call = stub.GetHomeTimeline.with_call(tweet_request, metadata=auth_headers) return res
def __init__(self): assistantCredentials = Credentials( token=None, **loads(environ["GOOGLE_ASSISTANT_OAUTH"])) http_request = Request() assistantCredentials.refresh(http_request) self.grpc_channel = secure_authorized_channel( assistantCredentials, http_request, "embeddedassistant.googleapis.com")
def run(): # Load the private key downloaded from the StellarStation Console. credentials = google_auth_jwt.Credentials.from_service_account_file( private_key_file, audience='https://api.stellarstation.com') print("Loaded credentials") # Setup the gRPC client. jwt_creds = google_auth_jwt.OnDemandCredentials.from_signing_credentials( credentials) print("Got jwt_creds") # No longer required (not connecting to fakeserver) #channel_credential = grpc.ssl_channel_credentials( # open(certificate_file, 'br').read()) #print("Got channel_credential") channel = google_auth_transport_grpc.secure_authorized_channel( jwt_creds, None, 'api.stellarstation.com:443') # , channel_credential) print("Got channel") client = stellarstation_pb2_grpc.StellarStationServiceStub(channel) print("Got client") now = time.time() - 1000 seconds = int(now) nanos = int((now - seconds) * 10**9) timestamp_before = Timestamp(seconds=seconds, nanos=nanos) now = time.time() seconds = int(now) nanos = int((now - seconds) * 10**9) timestamp_after = Timestamp(seconds=seconds, nanos=nanos) # Create a ListPlansRequest #listreq = stellarstation_pb2.ListPlansRequest() #listreq.satellite_id = str(SATELLITE_ID) # None of these work: #listreq.aos_before = Timestamp(timestamp_before) # TypeError: No positional arguments allowed #listreq.aos_before = timestamp_before # AttributeError: Assignment not allowed to field "aos_before" in protocol message object. #listreq.aos_before.seconds = 0 #listreq.aos_after.seconds = 0 #listreq.aos_before = timestamp_before # TypeError: Can't set composite field (when done AFTER setting seconds manually above) #listreq.aos_after = timestamp_after #listreq.aos_before = copy.deepcopy(timestamp_before) # AttributeError: Assignment not allowed to field "aos_before" in protocol message object. # This works: listreq = stellarstation_pb2.ListPlansRequest( satellite_id=str(SATELLITE_ID), aos_before=timestamp_before, aos_after=timestamp_after) print("Got listreq:") pprint(listreq) print("Sending ListPlans request:") client.ListPlans(listreq) print("Done ListPlans")
def get_conn(self) -> grpc.Channel: base_url = self.conn.host if self.conn.port: base_url = base_url + ":" + str(self.conn.port) auth_type = self._get_field("auth_type") if auth_type == "NO_AUTH": channel = grpc.insecure_channel(base_url) elif auth_type in {"SSL", "TLS"}: credential_file_name = self._get_field("credential_pem_file") with open(credential_file_name, "rb") as credential_file: creds = grpc.ssl_channel_credentials(credential_file.read()) channel = grpc.secure_channel(base_url, creds) elif auth_type == "JWT_GOOGLE": credentials, _ = google_auth.default() jwt_creds = google_auth_jwt.OnDemandCredentials.from_signing_credentials( credentials) channel = google_auth_transport_grpc.secure_authorized_channel( jwt_creds, None, base_url) elif auth_type == "OATH_GOOGLE": scopes = self._get_field("scopes").split(",") credentials, _ = google_auth.default(scopes=scopes) request = google_auth_transport_requests.Request() channel = google_auth_transport_grpc.secure_authorized_channel( credentials, request, base_url) elif auth_type == "CUSTOM": if not self.custom_connection_func: raise AirflowConfigException( "Customized connection function not set, not able to establish a channel" ) channel = self.custom_connection_func(self.conn) else: raise AirflowConfigException( "auth_type not supported or not provided, channel cannot be established, " f"given value: {str(auth_type)}") if self.interceptors: for interceptor in self.interceptors: channel = grpc.intercept_channel(channel, interceptor) return channel
def create_channels(self): """ The request object represents an HTTP transport layer used to renew tokens. Create a channels... """ # Request tokens self.speech_request = google_auth_transport_requests.Request() self.translation_request = google_auth_transport_requests.Request() # Channels self.speech_channel = google_auth_transport_grpc.secure_authorized_channel( self.scoped_credentials, self.speech_request, self.SPEECH_SERVICE_ADDRESS) self.translation_channel = google_auth_transport_grpc.secure_authorized_channel( self.scoped_credentials, self.translation_request, self.TRANSLATION_SERVICE_ADDRESS) # Create a stub object that provides the service interface. self.speech_stub = SpeechStub(self.speech_channel) self.translation_stub = TranslationServiceStub( self.translation_channel)
def get_conn(self): base_url = self.conn.host if self.conn.port: base_url = base_url + ":" + str(self.conn.port) auth_type = self._get_field("auth_type") if auth_type == "NO_AUTH": channel = grpc.insecure_channel(base_url) elif auth_type == "SSL" or auth_type == "TLS": credential_file_name = self._get_field("credential_pem_file") creds = grpc.ssl_channel_credentials(open(credential_file_name).read()) channel = grpc.secure_channel(base_url, creds) elif auth_type == "JWT_GOOGLE": credentials, _ = google_auth.default() jwt_creds = google_auth_jwt.OnDemandCredentials.from_signing_credentials( credentials) channel = google_auth_transport_grpc.secure_authorized_channel( jwt_creds, None, base_url) elif auth_type == "OATH_GOOGLE": scopes = self._get_field("scopes").split(",") credentials, _ = google_auth.default(scopes=scopes) request = google_auth_transport_requests.Request() channel = google_auth_transport_grpc.secure_authorized_channel( credentials, request, base_url) elif auth_type == "CUSTOM": if not self.custom_connection_func: raise AirflowConfigException( "Customized connection function not set, not able to establish a channel") channel = self.custom_connection_func(self.conn) else: raise AirflowConfigException( "auth_type not supported or not provided, channel cannot be established,\ given value: %s" % str(auth_type)) if self.interceptors: for interceptor in self.interceptors: channel = grpc.intercept_channel(channel, interceptor) return channel
def __init__(self): api_key = os.getenv(ENV_API_KEY_NAME) api_url = os.getenv(ENV_API_URL_NAME, "api.stellarstation.com:443") if not api_key: raise Exception('{} need to be set.' % ENV_API_KEY_NAME) credentials = google_auth_jwt.Credentials.from_service_account_file( api_key, audience='https://api.stellarstation.com') jwt_creds = google_auth_jwt.OnDemandCredentials.from_signing_credentials( credentials) self.channel = google_auth_transport_grpc.secure_authorized_channel( jwt_creds, None, api_url)
def _create_channel(self): # Make sure grpc was successfully imported assert available() if not self._secure: return grpc.insecure_channel(self._host) # Authenticate the host. # # You're allowed to override the root certs and server if necessary. For # example, if you're running your proxy on localhost, you'll need to set # GRPC_PROXY_TLS_ROOTS to the "roots.crt" file specifying the certificate # for the root CA that your localhost server has used to certify itself, and # the GRPC_PROXY_TLS_OVERRIDE to the name that your server is using to # identify itself. For example, the ROOTS env var might be # "/path/to/roots.crt" while the OVERRIDE env var might be "test_server," if # this is what's used by the server you're running. # # If you're connecting to a real server with real SSL, none of this should # be used. if not certifi: self._debug_info.append('CERTIFI IS NOT PRESENT;' + ' gRPC HTTPS CONNECTIONS MAY FAIL') root_certs = None roots = os.environ.get('LUCI_GRPC_PROXY_TLS_ROOTS') if roots: self._debug_info.append('Overridden root CA: %s' % roots) with open(roots) as f: root_certs = f.read() else: self._debug_info.append('Using default root CAs from certifi') overd = os.environ.get('LUCI_GRPC_PROXY_TLS_OVERRIDE') options = () if overd: options=(('grpc.ssl_target_name_override', overd),) ssl_creds = grpc.ssl_channel_credentials(root_certificates=root_certs) # Authenticate the user. scopes = ('https://www.googleapis.com/auth/cloud-source-tools',) self._debug_info.append('Scopes are: %r' % scopes) user_creds, _ = google_auth.default(scopes=scopes) # Create the channel. request = google_auth_transport_requests.Request() if len(options) > 0: self._debug_info.append('Options are: %r' % options) else: self._debug_info.append('No options used') return google_auth_transport_grpc.secure_authorized_channel( user_creds, request, self._host, ssl_creds, options=options)
def run(credentials, environment, satelliteId, interval, print_summary): # Setup the gRPC client. jwt_creds = google_auth_jwt.OnDemandCredentials.from_signing_credentials( credentials) channel = google_auth_transport_grpc.secure_authorized_channel( jwt_creds, None, environment) client = stellarstation_pb2_grpc.StellarStationServiceStub(channel) # Open satellite stream request_queue = Queue() request_iterator = generate_request(request_queue, satelliteId) # Initialize variables metrics_data = MetricsData() done = False got_first_time = False timer = RepeatTimer(int(interval), print_summary, args=(metrics_data, )) while not done: print('Listening for messages') try: for response in client.OpenSatelliteStream(request_iterator): if response.HasField("receive_telemetry_response"): num_bytes_in_message = len( response.receive_telemetry_response.telemetry.data) if not got_first_time: print('Receiving messages') got_first_time = True metrics_data.set_initial_time( datetime.datetime.utcnow()) timer.start() metric = Metric( response.receive_telemetry_response.telemetry. time_first_byte_received, response.receive_telemetry_response.telemetry. time_last_byte_received, num_bytes_in_message, datetime.datetime.utcnow()) metrics_data.add_metric(metric) # When CTRL-C is pressed the benchmark ends except KeyboardInterrupt: done = True except Exception as e: print("Encountered error") print(e) break finally: timer.cancel()
def grpc_create_channel(settings: HTTPConnectionSettings) -> Channel: target = f'{settings.host}:{settings.port}' options = [('grpc.max_send_message_length', -1), ('grpc.max_receive_message_length', -1)] if settings.oauth: # noinspection PyPackageRequirements from google.auth.transport.grpc import secure_authorized_channel # noinspection PyPackageRequirements from google.auth.transport.requests import Request as RefreshRequester # noinspection PyPackageRequirements from google.oauth2.credentials import Credentials as OAuthCredentials LOG.debug('Using a secure gRPC connection over OAuth:') credentials = OAuthCredentials( token=settings.oauth.token, refresh_token=settings.oauth.refresh_token, id_token=settings.oauth.id_token, token_uri=settings.oauth.token_uri, client_id=settings.oauth.client_id, client_secret=settings.oauth.client_secret) return secure_authorized_channel(credentials, RefreshRequester(), target, options=options) if settings.ssl_settings: cert_chain = read_file_bytes(settings.ssl_settings.cert_file) cert = read_file_bytes(settings.ssl_settings.cert_key_file) ca_cert = read_file_bytes(settings.ssl_settings.ca_file) LOG.debug('Using a secure gRPC connection:') LOG.debug(' target: %s', target) LOG.debug(' root_certificates: contents of %s', settings.ssl_settings.ca_file) LOG.debug(' private_key: contents of %s', settings.ssl_settings.cert_key_file) LOG.debug(' certificate_chain: contents of %s', settings.ssl_settings.cert_file) credentials = ssl_channel_credentials(root_certificates=ca_cert, private_key=cert, certificate_chain=cert_chain) return secure_channel(target, credentials, options) else: LOG.debug('Using an insecure gRPC connection...') return insecure_channel(target, options)
def setup_api_client(self): if self.test_channel is None: if self.root_cert_path == '' or self.api_key == '': channel = grpc.insecure_channel(self.api_url) else: credentials = google_auth_jwt.Credentials.from_service_account_file( self.api_key, audience='https://api.stellarstation.com') jwt_creds = google_auth_jwt.OnDemandCredentials.from_signing_credentials( credentials) channel_credential = grpc.ssl_channel_credentials( open(self.root_cert_path, 'br').read()) channel = google_auth_transport_grpc.secure_authorized_channel( jwt_creds, None, self.api_url, channel_credential) else: channel = self.test_channel return groundstation_pb2_grpc.GroundStationServiceStub(channel)
def setup_api_client(root_cert_path, api_key, api_url): print('Setting up client to communicate with Ground Station API') if not root_cert_path or not api_key: print( 'Root certificate path or API key not set. Using insecure channel') channel = grpc.insecure_channel(api_url) else: credentials = google_auth_jwt.Credentials.from_service_account_file( api_key, audience='https://api.stellarstation.com') jwt_creds = google_auth_jwt.OnDemandCredentials.from_signing_credentials( credentials) channel_credential = grpc.ssl_channel_credentials( open(root_cert_path, 'br').read()) channel = google_auth_transport_grpc.secure_authorized_channel( jwt_creds, None, api_url, channel_credential) return groundstation_pb2_grpc.GroundStationServiceStub(channel)
def __init__(self, language_code='en-US', device_model_id=None, device_id=None, credentials=None, token=None): loaded_credentials, http_request = self.load_oath2_credentials( credentials, token) channel = secure_authorized_channel(loaded_credentials, http_request, ASSISTANT_API_ENDPOINT) logging.info('Connecting to %s', ASSISTANT_API_ENDPOINT) self.stub = EmbeddedAssistantStub(channel) self.language_code = language_code self.device_model_id = device_model_id self.device_id = device_id self.conversation_state = None
def create_secure_channel(self, addr): """ Creates a secure channel using GOOGLE_APPLICATION_CREDENTIALS from the users path Args: target (str): The host and port of the service Returns: A gRPC channel """ credentials, _ = auth.default(scopes=self.scopes) request = google_auth_transport_requests.Request() channel = google_auth_transport_grpc.secure_authorized_channel( credentials, request, addr) self.channel = channel yield channel
def _createSecureChannel(self, private_key_dir='~', private_key='.infostellar/demo-private-key.json'): """This method creates a client for StellarStation's API""" self._l.info('Creating secure channel...') home = os.path.expanduser(private_key_dir) key = os.path.join(home, private_key) credentials = gauth_jwt.Credentials.from_service_account_file( key, audience=self._url) jwt_creds = gauth_jwt.OnDemandCredentials.from_signing_credentials( credentials) self.channel = gauth_grpc.secure_authorized_channel( jwt_creds, None, self._channel_url) self.client = stellarstation_pb2_grpc.StellarStationServiceStub( self.channel) self._l.info('Connected to (%s), satellite = %s, with protocol = %s', self._url, self.satellite_id, self._protocol_name)
def run(): # Load the private key downloaded from the StellarStation Console. credentials = google_auth_jwt.Credentials.from_service_account_file( '../../fakeserver/src/misc/api-key.json', audience='https://api.stellarstation.com') # Setup the gRPC client. jwt_creds = google_auth_jwt.OnDemandCredentials.from_signing_credentials( credentials) channel_credential = grpc.ssl_channel_credentials( open('../../fakeserver/src/main/resources/tls.crt', 'br').read()) channel = google_auth_transport_grpc.secure_authorized_channel( jwt_creds, None, 'localhost:8080', channel_credential) client = stellarstation_pb2_grpc.StellarStationServiceStub(channel) # Open satellite stream request_iterator = generate_request() for value in client.OpenSatelliteStream(request_iterator): print( "Got response: ", base64.b64encode( value.receive_telemetry_response.telemetry.data)[:100])
def grpc_create_channel(settings: "HTTPConnectionSettings") -> Channel: target = f"{settings.host}:{settings.port}" options = [("grpc.max_send_message_length", -1), ("grpc.max_receive_message_length", -1)] if not settings.enable_http_proxy: options.append(("grpc.enable_http_proxy", 0)) if settings.oauth: from google.auth.transport.grpc import secure_authorized_channel from google.auth.transport.requests import Request as RefreshRequester from google.oauth2.credentials import Credentials as OAuthCredentials LOG.debug("Using a secure gRPC connection over OAuth:") credentials = OAuthCredentials( token=settings.oauth.token, refresh_token=settings.oauth.refresh_token, id_token=settings.oauth.id_token, token_uri=settings.oauth.token_uri, client_id=settings.oauth.client_id, client_secret=settings.oauth.client_secret, ) ssl_credentials = None if settings.ssl_settings: cert_chain = read_file_bytes(settings.ssl_settings.cert_file) cert = read_file_bytes(settings.ssl_settings.cert_key_file) ca_cert = read_file_bytes(settings.ssl_settings.ca_file) LOG.debug("Using a secure gRPC connection:") LOG.debug(" target: %s", target) LOG.debug(" root_certificates: contents of %s", settings.ssl_settings.ca_file) LOG.debug(" private_key: contents of %s", settings.ssl_settings.cert_key_file) LOG.debug(" certificate_chain: contents of %s", settings.ssl_settings.cert_file) ssl_credentials = ssl_channel_credentials( root_certificates=ca_cert, private_key=cert, certificate_chain=cert_chain) return secure_authorized_channel( credentials, RefreshRequester(), target, ssl_credentials=ssl_credentials, options=options, ) if settings.ssl_settings: cert_chain = read_file_bytes(settings.ssl_settings.cert_file) cert = read_file_bytes(settings.ssl_settings.cert_key_file) ca_cert = read_file_bytes(settings.ssl_settings.ca_file) LOG.debug("Using a secure gRPC connection:") LOG.debug(" target: %s", target) LOG.debug(" root_certificates: contents of %s", settings.ssl_settings.ca_file) LOG.debug(" private_key: contents of %s", settings.ssl_settings.cert_key_file) LOG.debug(" certificate_chain: contents of %s", settings.ssl_settings.cert_file) credentials = ssl_channel_credentials(root_certificates=ca_cert, private_key=cert, certificate_chain=cert_chain) return secure_channel(target, credentials, options) else: LOG.debug("Using an insecure gRPC connection...") return insecure_channel(target, options)
SERVICE = 'speech.googleapis.com:443' # We will need credentials to call the service. The default approach # requires setting the GOOGLE_APPLICATION_CREDENTIALS environment variable. scoped_credentials, project = google_auth.default (scopes = SCOPES) # Alternative approach where file is specified directly. # credentials = google_oauth2_service_account.Credentials.from_service_account_file ('account.json') # scoped_credentials = credentials.with_scopes (SCOPES) # The request object represents an HTTP transport layer used to renew tokens. request = google_auth_transport_requests.Request () # Just create a channel, the request object could also be None if token renewal is not needed. with google_auth_transport_grpc.secure_authorized_channel (scoped_credentials, request, SERVICE) as channel: # Create a stub object that provides the service interface. stub = SpeechStub (channel) # Encoding and sample rate are only needed for RAW files. # When using WAV or FLAC files it is detected automatically. config = RecognitionConfig () # config.encoding = RecognitionConfig.LINEAR16 # config.sample_rate_hertz = 16000 config.language_code = 'en_US' audio = RecognitionAudio () audio.content = open (sys.argv [1], 'rb').read () message = RecognizeRequest (config = config, audio = audio)
def assist(handler_input: HandlerInput, text_query: str) -> Response: _logger.info('Input to be processed is: %s', text_query) # Get constants api_endpoint = data.GOOGLE_ASSISTANT_API['api_endpoint'] deadline_sec = data.DEFAULT_GRPC_DEADLINE # Create an authorized gRPC channel. credentials = skill_helpers.get_credentials(handler_input) http_request = Request() grpc_channel = secure_authorized_channel(credentials, http_request, api_endpoint) _logger.info('Connecting to %s', api_endpoint) # Create Assistant stub assistant = embedded_assistant_pb2_grpc.EmbeddedAssistantStub(grpc_channel) # Initial state text_response = None mic_open = False # Open the response PCM file in which we are going to stream Assistant's response fp = open(data.RESPONSE_PCM_FILE, 'wb') # Init WAVE file parser wavep = wave.open(fp, 'wb') wavep.setsampwidth(data.DEFAULT_AUDIO_SAMPLE_WIDTH) wavep.setnchannels(1) wavep.setframerate(data.DEFAULT_AUDIO_SAMPLE_RATE) # The magic happens for resp in assistant.Assist( _iter_assist_requests(handler_input, text_query), deadline_sec): if len(resp.audio_out.audio_data) > 0: _logger.info('Playing assistant response.') buf = resp.audio_out.audio_data buf = audio_helpers.align_buf(buf, data.DEFAULT_AUDIO_SAMPLE_WIDTH) wavep.writeframes(buf) if resp.dialog_state_out.conversation_state: conversation_state = resp.dialog_state_out.conversation_state conversation_state = list( conversation_state) if conversation_state is not None else None _logger.debug('Updating conversation state.') skill_helpers.set_session_attribute(handler_input, 'conversation_state', conversation_state) if resp.dialog_state_out.microphone_mode == _DIALOG_FOLLOW_ON: mic_open = True _logger.info('Expecting follow-on query from user.') elif resp.dialog_state_out.microphone_mode == _CLOSE_MICROPHONE: mic_open = False if resp.dialog_state_out.supplemental_display_text: text_response = resp.dialog_state_out.supplemental_display_text _logger.info('Supplemental display text: %s', text_response) _logger.info('Finished playing assistant response.') # TODO: info on audio file, error if response is empty wavep.close() fp.close() # Encode Assistant's response in an MP3 we can stream to Alexa audio_helpers.encode_from_pcm_to_mp3(data.RESPONSE_PCM_FILE, data.RESPONSE_MP3_FILE) # S3 bucket bucket = os.environ['S3_BUCKET'] key = skill_helpers.get_device_id(handler_input) # Upload the response MP3 to the bucket _s3.upload_file(data.RESPONSE_MP3_FILE, Bucket=bucket, Key=key) # Generate a short-lived signed url to the MP3 params = {'Bucket': bucket, 'Key': key} url = _s3.generate_presigned_url(ClientMethod='get_object', Params=params, ExpiresIn=10) url = escape(url) # Create Alexa response response_builder = handler_input.response_builder response_builder.speak(f'<audio src="{url}"/>') if text_response: response_builder.set_card( SimpleCard(title='Google Assistant', content=text_response)) response_builder.set_should_end_session(not mic_open) return response_builder.response
svcAccountFile = '/path/to/svc_account.json' channel = None if usetls: request = google_auth_transport_requests.Request() id_creds = service_account.IDTokenCredentials.from_service_account_file( svcAccountFile, target_audience=target_audience) with open(ca_certificate, 'rb') as f: trusted_certs = f.read() ssl_credentials = grpc.ssl_channel_credentials( root_certificates=trusted_certs) grpc_channel_options = (( 'grpc.ssl_target_name_override', server_sni_name, ), ) channel = google_auth_transport_grpc.secure_authorized_channel( credentials=id_creds, request=request, target=address, ssl_credentials=ssl_credentials, options=grpc_channel_options) else: channel = grpc.insecure_channel(address) stub = echo_pb2_grpc.EchoServerStub(channel) response = stub.SayHello(EchoRequest(name='you')) print "Echo client received: " + response.message
def assist(handler_input: HandlerInput, text_query: str) -> Response: _logger.info('Input to be processed is: %s', text_query) api_endpoint = data.GOOGLE_ASSISTANT_API['api_endpoint'] deadline_sec = data.DEFAULT_GRPC_DEADLINE # Create an authorized gRPC channel. credentials = util.get_credentials(handler_input) http_request = Request() grpc_channel = secure_authorized_channel(credentials, http_request, api_endpoint) _logger.info('Connecting to %s', api_endpoint) # Create Assistant stub assistant = embedded_assistant_pb2_grpc.EmbeddedAssistantStub(grpc_channel) # TODO: record Assistant's response # self._fp = open(OUTPUT_AUDIO_FILE, 'wb') # self._wave = wave.open(self._fp, 'wb') # self._wave.setsampwidth(DEFAULT_AUDIO_SAMPLE_WIDTH) # self._wave.setnchannels(1) # self._wave.setframerate(DEFAULT_AUDIO_SAMPLE_RATE) text_response = None mic_open = False # TODO: hardcoded default volume? volume = util.get_persistent_attribute(handler_input, 'volume', default=50) # TODO: should refactor this? for resp in assistant.Assist( iter_assist_requests(handler_input, text_query), deadline_sec): if len(resp.audio_out.audio_data) > 0: _logger.info('Playing assistant response.') buf = resp.audio_out.audio_data buf = util.align_buf(buf, data.DEFAULT_AUDIO_SAMPLE_WIDTH) buf = util.normalize_audio_buffer(buf, volume) # TODO: record Assistant's response # self._wave.writeframes(buf) if resp.dialog_state_out.conversation_state: conversation_state = resp.dialog_state_out.conversation_state conversation_state = list( conversation_state) if conversation_state is not None else None _logger.debug('Updating conversation state.') util.set_session_attribute(handler_input, 'conversation_state', conversation_state) if resp.dialog_state_out.volume_percentage != 0: volume_percentage = resp.dialog_state_out.volume_percentage _logger.info('Setting volume to %s%%', volume_percentage) util.set_persistent_attribute(handler_input, 'volume', volume_percentage, save=True) if resp.dialog_state_out.microphone_mode == _DIALOG_FOLLOW_ON: mic_open = True _logger.info('Expecting follow-on query from user.') elif resp.dialog_state_out.microphone_mode == _CLOSE_MICROPHONE: mic_open = False if resp.dialog_state_out.supplemental_display_text: text_response = resp.dialog_state_out.supplemental_display_text _logger.info('Supplemental display text: %s', text_response) _logger.info('Finished playing assistant response.') # TODO: info on audio file, error if response is empty # self._wave.close() # self._fp.close() return handler_input.response_builder.speak( text_response).set_should_end_session(not mic_open).response