def main(api_endpoint, credentials, device_model_id, device_id, lang, display, verbose, grpc_deadline, *args, **kwargs): # Setup logging. logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) # Load OAuth 2.0 credentials. try: with open(credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) except Exception as e: logging.error('Error loading credentials: %s', e) logging.error('Run google-oauthlib-tool to initialize ' 'new OAuth 2.0 credentials.') return # Create an authorized gRPC channel. grpc_channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, api_endpoint) logging.info('Connecting to %s', api_endpoint) with utils.TextAssistant(lang, device_model_id, device_id, display, grpc_channel, grpc_deadline) as assistant: # If current mode is ECO mode, change it to HEAT mode if (utils.get_mode(assistant) == NestMode.ECO): logging.info('Set mode to HEAT') utils.query_assistant(assistant, constants.SET_MODE_HEAT)
def get_authenticated_service(): flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES) refresh_token = get_refresh_token() if refresh_token: credentials = oauth2client.client.GoogleCredentials( None, flow.client_config['client_id'], flow.client_config['client_secret'], refresh_token, None, 'https://accounts.google.com/o/oauth2/token', None, ) http = credentials.authorize(httplib2.Http()) credentials.refresh(http) set_refresh_token(credentials.refresh_token) else: credentials = flow.run_console() set_refresh_token(credentials.refresh_token) return build( API_SERVICE_NAME, API_VERSION, credentials=credentials, )
def start_google_assistant_client(): api_endpoint = 'embeddedassistant.googleapis.com' credentials = os.path.join(click.get_app_dir('google-oauthlib-tool'), 'credentials.json') device_model_id = 'thursday-6b92e-thursday-p1zrh6' device_id = 'thursday' lang = 'en-US' display = False verbose = False grpc_deadline = 60 * 3 + 5 # Setup logging logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) # Load OAuth 2.0 credentials. try: with open(credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) except Exception as e: logging.error('Error loading credentials: %s', e) logging.error('Run google-oauthlib-tool to initialize ' 'new OAuth 2.0 credentials.') return # Create an authorized gRPC channel. grpc_channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, api_endpoint) logging.info('Connecting to %s', api_endpoint) return SampleTextAssistant(lang, device_model_id, device_id, display, grpc_channel, grpc_deadline)
def get_assistant_transcript(device_model_id, device_id, userquery): api_endpoint = ASSISTANT_API_ENDPOINT credentials = os.path.join(click.get_app_dir('google-oauthlib-tool'), 'credentials.json') lang = 'en-US' grpc_deadline = DEFAULT_GRPC_DEADLINE verbose = None # Setup logging. logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) # Load OAuth 2.0 credentials. try: with open(credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) except Exception as e: logging.error('Error loading credentials: %s', e) logging.error('Run google-oauthlib-tool to initialize ' 'new OAuth 2.0 credentials.') return # Create an authorized gRPC channel. grpc_channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, api_endpoint) logging.info('Connecting to %s', api_endpoint) with SampleTextAssistant(lang, device_model_id, device_id, grpc_channel, grpc_deadline) as assistant: display_text = assistant.assist(text_query=userquery) print(display_text) with open('src/temp/response.txt', 'w+') as responsefile: responsefile.write(display_text)
def main(device_id, verbose, *args, **kwargs): # Setup logging. logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) with open("credentials.json", "r") as f: credentials = google.oauth2.credentials.Credentials(**json.load(f)) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, ASSISTANT_API_ENDPOINT ) logging.info("Connecting to %s", ASSISTANT_API_ENDPOINT) with SampleTextAssistant( LANGUAGE_CODE, DEVICE_MODEL_ID, device_id, False, channel, DEFAULT_GRPC_DEADLINE ) as assistant: while True: query = click.prompt("") click.echo("<you> %s" % query) response_text, response_html = assistant.assist(text_query=query) if response_text: click.echo("<@assistant> %s" % response_text) if response_html: click.echo(response_html)
def _read_ga_data(self): credentials = self.cfg.load_dict(GA_CREDENTIALS) if not isinstance(credentials, dict): self.log( 'Error loading credentials from \'{}\''.format(GA_CREDENTIALS), logger.CRIT) return None data = { 'model_id': credentials.pop('model_id_stt', None) or credentials.pop('model_id', None), 'project_id': credentials.pop('project_id', None) } for key, val in data.items(): if not isinstance(val, str) or not val: self.log( 'Wrong or missing \'{}\' in {}. Add this key.'.format( key, GA_CREDENTIALS), logger.CRIT) return None try: credentials = google.oauth2.credentials.Credentials(token=None, **credentials) credentials.refresh(google.auth.transport.requests.Request()) except Exception as e: self.log( 'Error initialization credentials \'{}\': {}'.format( GA_CREDENTIALS, e), logger.CRIT) return None return data['model_id'], data['project_id'], credentials
def get_assistant(): api_endpoint = ASSISTANT_API_ENDPOINT lang = 'en-US' device_model_id = 'dmi' device_id = 'di' display = False grpc_deadline = DEFAULT_GRPC_DEADLINE # logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) credentials = os.path.join(click.get_app_dir('google-oauthlib-tool'), 'credentials.json') # Load OAuth 2.0 credentials. try: with open(credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) except Exception as e: logging.error('Error loading credentials: %s', e) logging.error('Run google-oauthlib-tool to initialize ' 'new OAuth 2.0 credentials.') return # Create an authorized gRPC channel. grpc_channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, api_endpoint) assistant = SampleTextAssistant(lang, device_model_id, device_id, display, grpc_channel, grpc_deadline) return assistant
def main(api_endpoint, credentials, device_model_id, device_id, lang, display, verbose, grpc_deadline, *args, **kwargs): # Setup logging. logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) # Load OAuth 2.0 credentials. try: with open(credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) except Exception as e: logging.error('Error loading credentials: %s', e) logging.error('Run google-oauthlib-tool to initialize ' 'new OAuth 2.0 credentials.') return # Create an authorized gRPC channel. grpc_channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, api_endpoint) logging.info('Connecting to %s', api_endpoint) with SampleTextAssistant(lang, device_model_id, device_id, display, grpc_channel, grpc_deadline) as assistant: while True: query = click.prompt('') click.echo('<you> %s' % query) response_text, response_html = assistant.assist(text_query=query) if display and response_html: system_browser = browser_helpers.system_browser system_browser.display(response_html) if response_text: click.echo('<@assistant> %s' % response_text)
def get_authenticated_service(): credentials = None if os.path.exists(TOKEN_PICKLE_FILE): print('Loading credentials from file...') with open(TOKEN_PICKLE_FILE, 'rb') as token: credentials = pickle.load(token) # If there are no valid credentials available, then either refresh the token or log in. if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: print('Refreshing access token...') credentials.refresh(Request()) else: print('Fetching new tokens...') flow = InstalledAppFlow.from_client_secrets_file( CLIENT_SECRETS_FILE, scopes=SCOPES) flow.run_local_server(port=8999, prompt='consent', authorization_prompt_message='') credentials = flow.credentials # Save the credentials for the next run with open(TOKEN_PICKLE_FILE, 'wb') as f: print('Saving credentials for future use...') pickle.dump(credentials, f) return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
def loadCredentials(userId): logger = logging.getLogger(__name__) logger.setLevel(loggingLevel) logger.info('in loadCredenitals.') bucketName = os.environ.get( 'BUCKET_NAME', '/' + app_identity.get_default_gcs_bucket_name()) fileName = bucketName + '/cred_' + userId + '.pickle' logger.debug('** file name to be loaded is ' + fileName) fh = cloudstorage.open(fileName) credentials = pickle.loads(fh.read()) fh.close() if not credentials.valid: # 期限切れの場合はrefresh要求を行う logger.info('credentials must be refresh.') import google.auth.transport.requests request = google.auth.transport.requests.Request() credentials.refresh(request) logger.info("refreshed credential acquired: " + var_dump(credentials)) fh = cloudstorage.open(fileName, 'w') fh.write(pickle.dumps(credentials)) fh.close() return (credentials)
def test_refresh_success_iam_endpoint_override( self, use_data_bytes, mock_donor_credentials ): credentials = self.make_credentials( lifetime=None, iam_endpoint_override=self.IAM_ENDPOINT_OVERRIDE ) token = "token" expire_time = ( _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500) ).isoformat("T") + "Z" response_body = {"accessToken": token, "expireTime": expire_time} request = self.make_request( data=json.dumps(response_body), status=http_client.OK, use_data_bytes=use_data_bytes, ) credentials.refresh(request) assert credentials.valid assert not credentials.expired # Confirm override endpoint used. request_kwargs = request.call_args[1] assert request_kwargs["url"] == self.IAM_ENDPOINT_OVERRIDE
def __init__(self, language_code='en-US', volume_percentage=100): self._volume_percentage = volume_percentage # Mutable state. self._conversation_state = None # Mutable state. self._language_code = language_code ## credentials = auth_helpers.get_assistant_credentials() device_model_id, device_id = device_helpers.get_ids_for_service(credentials) logger.info('device_model_id: %s', device_model_id) logger.info('device_id: %s', device_id) http_request = google.auth.transport.requests.Request() try: credentials.refresh(http_request) except Exception as e: raise RuntimeError('Error loading credentials: %s', e) api_endpoint = ASSISTANT_API_ENDPOINT grpc_channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, api_endpoint) logger.info('Connecting to %s', api_endpoint) ## self._assistant = embedded_assistant_pb2_grpc.EmbeddedAssistantStub(grpc_channel) self._device_config = embedded_assistant_pb2.DeviceConfig( device_model_id=device_model_id, device_id=device_id)
def build_calendar_service(): """Shows basic usage of the Google Calendar API. Prints the start and name of the next 10 events on the user's calendar. """ credentials = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: credentials = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( 'client_secret.json', SCOPES) flow.redirect_uri = 'http://localhost:5000/oauthok' #needs to be same as googlecloud credentials = flow.run_local_server(port=5000) # credentials = flow.run_console() # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(credentials, token) service = build('calendar', 'v3', credentials=credentials) authorization(flow) return service
def __build_service(client_secret): """Function to Build service using to call API Gmail. The file token.pickle stores the user's access and refresh tokens, and is created automatically when the authorization flow completes for the first time. Args: client_secret: credential to call GMAIL API. Returns: Return service building. """ credentials = None if os.path.exists(PATH_TOKEN + 'token.pickle'): with open(PATH_TOKEN + 'token.pickle', 'rb') as token: credentials = pickle.load(token) # If there are no (valid) credentials available, let the user log in. if not credentials or not credentials.valid: if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( client_secret, SCOPES) credentials = flow.run_local_server() # Save the credentials for the next run with open(PATH_TOKEN + 'token.pickle', 'wb') as token: pickle.dump(credentials, token) service = build('gmail', 'v1', credentials=credentials) print('SERVICE', service) return service
def test_id_token_with_target_audience(self, mock_donor_credentials, mock_authorizedsession_idtoken): credentials = self.make_credentials(lifetime=None) token = "token" target_audience = "https://foo.bar" expire_time = (_helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)).isoformat("T") + "Z" response_body = {"accessToken": token, "expireTime": expire_time} request = self.make_request(data=json.dumps(response_body), status=http_client.OK) credentials.refresh(request) assert credentials.valid assert not credentials.expired id_creds = impersonated_credentials.IDTokenCredentials(credentials) id_creds = id_creds.with_target_audience( target_audience=target_audience) id_creds.refresh(request) assert id_creds.token == ID_TOKEN_DATA assert id_creds.expiry == datetime.datetime.fromtimestamp( ID_TOKEN_EXPIRY)
def _read_ga_data(self): credentials = self.cfg.load_dict(GA_CREDENTIALS) if not isinstance(credentials, dict): self.log( 'Error loading credentials from \'{}\''.format(GA_CREDENTIALS), logger.CRIT) return None for key in ('project_id', 'model_id'): if not isinstance(credentials.get(key), str) or not credentials[key]: self.log( 'Wrong or missing \'{}\' in {}. Add this key.'.format( key, GA_CREDENTIALS), logger.CRIT) return None model_id = credentials.pop('model_id') project_id = credentials.pop('project_id') try: credentials = google.oauth2.credentials.Credentials(token=None, **credentials) credentials.refresh(google.auth.transport.requests.Request()) except Exception as e: self.log( 'Error initialization credentials \'{}\': {}'.format( GA_CREDENTIALS, e), logger.CRIT) return None return model_id, project_id, credentials
def get_authenticated_service(): credentials = None if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: try: credentials = pickle.load(token) except: print('Error with pickle.dump(credentials, token)') # Check if the credentials are invalid or do not exist if not credentials or not credentials.valid: # Check if the credentials have expired if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(request(google.auth.transport.Request)) else: flow = InstalledAppFlow.from_client_secrets_file( CLIENT_SECRETS_FILE, SCOPES) credentials = flow.run_console() # Save the credentials for the next run with open('token.pickle', 'wb') as token: try: pickle.dump(credentials, token) except: print('Error with pickle.dump(credentials, token)') return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
def create_grpc_channel(target, credentials, ssl_credentials_file=None, grpc_channel_options=[]): """Create and return a gRPC channel. Args: credentials(google.oauth2.credentials.Credentials): OAuth2 credentials. ssl_credentials_file(str): Path to SSL credentials.pem file (for testing). grpc_channel_options([(option_name, option_val)]): gRPC channel options. Returns: grpc.Channel. """ ssl_credentials = None if ssl_credentials_file: with open(ssl_credentials_file) as f: ssl_credentials = grpc.ssl_channel_credentials(f.read()) http_request = google.auth.transport.requests.Request() # TODO(proppy): figure out if/why we need to force a refresh. # if yes, consider remove access token from serialized credentials. credentials.refresh(http_request) return google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, target, ssl_credentials=ssl_credentials, options=grpc_channel_options)
def get_authenticated_service(): # ylopoiisi_me_authentication # flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES) # credentials = flow.run_console() # return build(API_SERVICE_NAME, API_VERSION, credentials = credentials) # ylopoiisi xwris authentication credentials = None if os.path.exists(PICKLE_FILE): with open(PICKLE_FILE, 'rb') as token: credentials = pickle.load(token) # Check if the credentials are invalid or do not exist if not credentials or not credentials.valid: # Check if the credentials have expired if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( CLIENT_SECRETS_FILE, SCOPES) credentials = flow.run_console() # Save the credentials for the next run with open(PICKLE_FILE, 'wb') as token: pickle.dump(credentials, token) return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
def auth(credentials): with open(credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) return http_request, credentials
def test_refresh(authorized_user_file, http_request, token_info): with open(authorized_user_file, "r") as fh: info = json.load(fh) credentials = google.oauth2.credentials.Credentials( None, # No access token, must be refreshed. refresh_token=info["refresh_token"], token_uri=GOOGLE_OAUTH2_TOKEN_ENDPOINT, client_id=info["client_id"], client_secret=info["client_secret"], ) credentials.refresh(http_request) assert credentials.token info = token_info(credentials.token) info_scopes = _helpers.string_to_scopes(info["scope"]) # Canonical list of scopes at https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login # or do `gcloud auth application-defaut login --help` assert set(info_scopes) == set([ "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/cloud-platform", "openid", ])
def __init__(self, language_code, device_model_id, device_id, cred_json: Path, display=True, deadline_sec=DEFAULT_GRPC_DEADLINE): self.language_code = language_code self.device_model_id = device_model_id self.device_id = device_id self.conversation_state = None # Force reset of first conversation. self.is_new_conversation = True self.display = display # open credentials with open(cred_json, 'r') as _file: credentials = google.oauth2.credentials.Credentials( token=None, **json.load(_file)) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) # Create an authorized gRPC channel. grpc_channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, ASSISTANT_API_ENDPOINT) self.assistant = embedded_assistant_pb2_grpc.EmbeddedAssistantStub( grpc_channel) self.deadline = deadline_sec
def get_authenticated_service(): CLIENT_SECRETS_FILE = "my_ytce_client_secret.json" #This is the name of your JSON file # This OAuth 2.0 access scope allows for full read/write access to the # authenticated user's account and requires requests to use an SSL connection. SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl'] API_SERVICE_NAME = 'youtube' API_VERSION = 'v3' credentials = None if os.path.exists('token.pickle'): with open('token.pickle', 'rb') as token: credentials = pickle.load(token) # Check if the credentials are invalid or do not exist if not credentials or not credentials.valid: # Check if the credentials have expired if credentials and credentials.expired and credentials.refresh_token: credentials.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file( CLIENT_SECRETS_FILE, SCOPES) credentials = flow.run_console() # Save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(credentials, token) return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)
def do_refresh_token(id): auth = db[id] credentials = google.oauth2.credentials.Credentials.from_authorized_user_info( auth) request = google.auth.transport.requests.Request() try: credentials.refresh(request) except Exception as e: print(e) return 0 auth = { 'token': credentials.token, 'refresh_token': credentials.refresh_token, 'id_token': credentials.id_token, 'token_uri': credentials.token_uri, 'client_id': credentials.client_id, 'client_secret': credentials.client_secret, 'scopes': credentials.scopes, 'expiry': datetime.datetime.strftime(credentials.expiry, '%Y-%m-%d %H:%M:%S') } db[id] = auth return auth
def test_refresh_success(self, unused_utcnow, refresh_grant): token = 'token' expiry = _helpers.utcnow() + datetime.timedelta(seconds=500) grant_response = {'id_token': mock.sentinel.id_token} refresh_grant.return_value = ( # Access token token, # New refresh token None, # Expiry, expiry, # Extra data grant_response) request = mock.create_autospec(transport.Request) credentials = self.make_credentials() # Refresh credentials credentials.refresh(request) # Check jwt grant call. refresh_grant.assert_called_with(request, self.TOKEN_URI, self.REFRESH_TOKEN, self.CLIENT_ID, self.CLIENT_SECRET, None) # Check that the credentials have the token and expiry assert credentials.token == token assert credentials.expiry == expiry assert credentials.id_token == mock.sentinel.id_token # Check that the credentials are valid (have a token and are not # expired) assert credentials.valid
def test_refresh_source_credentials(self, time_skew): credentials = self.make_credentials(lifetime=None) # Source credentials is refreshed only if it is expired within # _helpers.CLOCK_SKEW from now. We add a time_skew to the expiry, so # source credentials is refreshed only if time_skew <= 0. credentials._source_credentials.expiry = ( _helpers.utcnow() + _helpers.CLOCK_SKEW + datetime.timedelta(seconds=time_skew)) credentials._source_credentials.token = "Token" with mock.patch("google.oauth2.service_account.Credentials.refresh", autospec=True) as source_cred_refresh: expire_time = ( _helpers.utcnow().replace(microsecond=0) + datetime.timedelta(seconds=500)).isoformat("T") + "Z" response_body = {"accessToken": "token", "expireTime": expire_time} request = self.make_request(data=json.dumps(response_body), status=http_client.OK) credentials.refresh(request) assert credentials.valid assert not credentials.expired # Source credentials is refreshed only if it is expired within # _helpers.CLOCK_SKEW if time_skew > 0: source_cred_refresh.assert_not_called() else: source_cred_refresh.assert_called_once()
def __init__(self): verbose = False credentials = os.path.join(click.get_app_dir('google-oauthlib-tool'), 'credentials.json') # Setup logging. logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) # Load OAuth 2.0 credentials. try: with open(credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials( token=None, **json.load(f)) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) except Exception as e: logging.error('Error loading credentials: %s', e) logging.error('Run google-oauthlib-tool to initialize ' 'new OAuth 2.0 credentials.') return # Create an authorized gRPC channel. grpc_channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, ASSISTANT_API_ENDPOINT) logging.info('Connecting to %s', ASSISTANT_API_ENDPOINT) self.assistant = SampleTextAssistant('en-US', 'burton-88a21-burton-ccmqns', 'burton-88a21', False, grpc_channel, DEFAULT_GRPC_DEADLINE)
def checkTokenExpiration(accessToken): with open( 'client_secret_380333357631-mubtpvnl87nlgva0uf6qgtk7o929u6k0.apps.googleusercontent.com.json', 'r') as JSON: gclientjson = json.load(JSON)['web'] try: credentials = google.oauth2.credentials.Credentials( accessToken, refresh_token=None, id_token=None, client_id=gclientjson['client_id'], client_secret=gclientjson['client_secret'], token_uri=gclientjson['token_uri']) print('Checking the validity of credential: {0}'.format( credentials.valid)) if credentials.expired: print('Requesting a new access Token from Google...') request = google.auth.transport.requests.Request() credentials.refresh(request) except BaseException as e: print('Error refreshing token with Google: {0}'.format(str(e))) return False else: return credentials_to_dict(credentials)
def gassist(text_query, lang_code='en-US'): logging.info(text_query) # Load OAuth 2.0 credentials. try: with open(Config.CREDENTIALS, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) session = requests.Session() http_request = google.auth.transport.requests.Request(session) credentials.refresh(http_request) except Exception as e: logging.error('Error loading credentials', exc_info=True) sys.exit(-1) # Create an authorized gRPC channel. grpc_channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, ASSISTANT_API_ENDPOINT) # Create an assistant. assistant = embedded_assistant_pb2_grpc.EmbeddedAssistantStub(grpc_channel) def assist(text_query): def iter_assist_requests(): config = embedded_assistant_pb2.AssistConfig( audio_out_config=embedded_assistant_pb2.AudioOutConfig( encoding='LINEAR16', sample_rate_hertz=16000, volume_percentage=0, ), dialog_state_in=embedded_assistant_pb2.DialogStateIn( language_code=lang_code, conversation_state=None, is_new_conversation=True, ), device_config=embedded_assistant_pb2.DeviceConfig( device_id=Config.DEVICE_ID, device_model_id=Config.DEVICE_MODEL_ID, ), text_query=text_query, ) req = embedded_assistant_pb2.AssistRequest(config=config) yield req text_response = None html_response = None for resp in assistant.Assist(iter_assist_requests(), DEFAULT_GRPC_DEADLINE): if resp.screen_out.data: html_response = resp.screen_out.data if resp.dialog_state_out.supplemental_display_text: text_response = resp.dialog_state_out.supplemental_display_text return text_response, html_response text, html = assist(text_query) logging.info(text) grpc_channel.close() session.close() return text
def wraps(request, *args, **kwargs): # If OAuth redirect response, get credentials if not request: request = args[0].context if not request.user.is_authenticated: return {'success': False, 'redirect_uri': resolved('login')} flow = InstalledAppFlow.from_client_config( json.loads(settings.GOOGLE_CONFIG), SCOPES, redirect_uri=settings.GOOGLE_SERVICE_REDIRECT_URI) existing_state = request.GET.get('state', None) current_path = request.path if existing_state: secure_uri = request.build_absolute_uri().replace( 'http://', 'https://') location_path = urllib.parse.urlparse(existing_state).path flow.fetch_token(authorization_response=secure_uri, state=existing_state) Profile.objects.update_or_create( user=request.user, defaults={'google_service_token': flow.credentials.to_json()}) if location_path == current_path: return func(request, flow.credentials) # Head back to location stored in state when # it is different from the configured redirect uri return redirect(existing_state) # Otherwise, retrieve credential from request session. profile, _ = Profile.objects.get_or_create(user=request.user) stored_credentials = profile.google_service_token if not stored_credentials: # It's strongly recommended to encrypt state. # location is needed in state to remember it. location = request.build_absolute_uri(reverse('home')) # Commence OAuth dance. auth_url, _ = flow.authorization_url(state=location) return {'success': False, 'redirect_uri': auth_url} # Hydrate stored credentials. cr = json.loads(stored_credentials) cr['expiry'] = dateutil.parser.isoparse( cr['expiry']).replace(tzinfo=None) credentials = Credentials(**cr) # If credential is expired, refresh it. if credentials.expired and credentials.refresh_token: credentials.refresh(Request()) # Store JSON representation of credentials in session. Profile.objects.update_or_create( user=request.user, defaults={'google_service_token': credentials.to_json()}) kwargs['credentials'] = credentials.to_json() return func(args[0], *args, **kwargs)
def _load_credentials(credentials_path): migrate = False with open(credentials_path, 'r') as f: credentials_data = json.load(f) if 'access_token' in credentials_data: migrate = True del credentials_data['access_token'] credentials_data['scopes'] = [_ASSISTANT_OAUTH_SCOPE] if migrate: with open(credentials_path, 'w') as f: json.dump(credentials_data, f) credentials = google.oauth2.credentials.Credentials(token=None, **credentials_data) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) return credentials
def main(api_endpoint, credentials, project_id, device_model_id, device_id, device_config, lang, verbose, input_audio_file, output_audio_file, audio_sample_rate, audio_sample_width, audio_iter_size, audio_block_size, audio_flush_size, grpc_deadline, once, *args, **kwargs): """Samples for the Google Assistant API. Examples: Run the sample with microphone input and speaker output: $ python -m googlesamples.assistant Run the sample with file input and speaker output: $ python -m googlesamples.assistant -i <input file> Run the sample with file input and output: $ python -m googlesamples.assistant -i <input file> -o <output file> """ subprocess.Popen(["aplay", "/home/pi/GassistPi/sample-audio-files/Startup.wav"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) # Setup logging. logging.basicConfig(level=logging.DEBUG if verbose else logging.INFO) # Load OAuth 2.0 credentials. try: with open(credentials, 'r') as f: credentials = google.oauth2.credentials.Credentials(token=None, **json.load(f)) http_request = google.auth.transport.requests.Request() credentials.refresh(http_request) except Exception as e: logging.error('Error loading credentials: %s', e) logging.error('Run google-oauthlib-tool to initialize ' 'new OAuth 2.0 credentials.') sys.exit(-1) # Create an authorized gRPC channel. grpc_channel = google.auth.transport.grpc.secure_authorized_channel( credentials, http_request, api_endpoint) logging.info('Connecting to %s', api_endpoint) # Configure audio source and sink. audio_device = None if input_audio_file: audio_source = audio_helpers.WaveSource( open(input_audio_file, 'rb'), sample_rate=audio_sample_rate, sample_width=audio_sample_width ) else: audio_source = audio_device = ( audio_device or audio_helpers.SoundDeviceStream( sample_rate=audio_sample_rate, sample_width=audio_sample_width, block_size=audio_block_size, flush_size=audio_flush_size ) ) if output_audio_file: audio_sink = audio_helpers.WaveSink( open(output_audio_file, 'wb'), sample_rate=audio_sample_rate, sample_width=audio_sample_width ) else: audio_sink = audio_device = ( audio_device or audio_helpers.SoundDeviceStream( sample_rate=audio_sample_rate, sample_width=audio_sample_width, block_size=audio_block_size, flush_size=audio_flush_size ) ) # Create conversation stream with the given audio source and sink. conversation_stream = audio_helpers.ConversationStream( source=audio_source, sink=audio_sink, iter_size=audio_iter_size, sample_width=audio_sample_width, ) device_handler = device_helpers.DeviceRequestHandler(device_id) @device_handler.command('action.devices.commands.OnOff') def onoff(on): if on: logging.info('Turning device on') else: logging.info('Turning device off') if not device_id or not device_model_id: try: with open(device_config) as f: device = json.load(f) device_id = device['id'] device_model_id = device['model_id'] except Exception as e: logging.warning('Device config not found: %s' % e) logging.info('Registering device') if not device_model_id: logging.error('Option --device-model-id required ' 'when registering a device instance.') sys.exit(-1) if not project_id: logging.error('Option --project-id required ' 'when registering a device instance.') sys.exit(-1) device_base_url = ( 'https://%s/v1alpha2/projects/%s/devices' % (api_endpoint, project_id) ) device_id = str(uuid.uuid1()) payload = { 'id': device_id, 'model_id': device_model_id, 'client_type': 'SDK_SERVICE' } session = google.auth.transport.requests.AuthorizedSession( credentials ) r = session.post(device_base_url, data=json.dumps(payload)) if r.status_code != 200: logging.error('Failed to register device: %s', r.text) sys.exit(-1) logging.info('Device registered: %s', device_id) os.makedirs(os.path.dirname(device_config), exist_ok=True) with open(device_config, 'w') as f: json.dump(payload, f) with SampleAssistant(lang, device_model_id, device_id, conversation_stream, grpc_channel, grpc_deadline, device_handler) as assistant: # If file arguments are supplied: # exit after the first turn of the conversation. if input_audio_file or output_audio_file: assistant.assist() return # If no file arguments supplied: # keep recording voice requests using the microphone # and playing back assistant response using the speaker. # When the once flag is set, don't wait for a trigger. Otherwise, wait. wait_for_user_trigger = not once while True: if wait_for_user_trigger: button_state=GPIO.input(22) if button_state==True: continue else: pass continue_conversation = assistant.assist() # wait for user trigger if there is no follow-up turn in # the conversation. wait_for_user_trigger = not continue_conversation # If we only want one conversation, break. if once and (not continue_conversation): break