From 88a8c41b4c8a4f7f7d396c575c279896b0e75444 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mika=20H=C3=A4nninen?= Date: Tue, 12 Mar 2024 11:33:21 +0200 Subject: [PATCH] deconstruct dynamiccore --- .../google/src/RPA/Cloud/Google/__init__.py | 67 +++++++++++++------ .../RPA/Cloud/Google/keywords/apps_script.py | 11 ++- .../src/RPA/Cloud/Google/keywords/base.py | 7 +- .../src/RPA/Cloud/Google/keywords/context.py | 54 +++++---------- .../RPA/Cloud/Google/keywords/document_ai.py | 14 ++-- .../src/RPA/Cloud/Google/keywords/drive.py | 50 +++++++------- .../src/RPA/Cloud/Google/keywords/gmail.py | 18 ++--- .../Cloud/Google/keywords/natural_language.py | 10 +-- .../src/RPA/Cloud/Google/keywords/sheets.py | 11 ++- .../Cloud/Google/keywords/speech_to_text.py | 11 ++- .../src/RPA/Cloud/Google/keywords/storage.py | 15 ++--- .../Cloud/Google/keywords/text_to_speech.py | 11 ++- .../RPA/Cloud/Google/keywords/translation.py | 8 +-- .../Google/keywords/video_intelligence.py | 10 +-- .../src/RPA/Cloud/Google/keywords/vision.py | 21 +++--- 15 files changed, 156 insertions(+), 162 deletions(-) diff --git a/packages/google/src/RPA/Cloud/Google/__init__.py b/packages/google/src/RPA/Cloud/Google/__init__.py index 8d60076a65..08461b0798 100644 --- a/packages/google/src/RPA/Cloud/Google/__init__.py +++ b/packages/google/src/RPA/Cloud/Google/__init__.py @@ -1,9 +1,9 @@ import importlib import logging import os -from robotlibcore import DynamicCore +from .keywords.context import LibraryContext from .keywords import ( AppsScriptKeywords, BaseKeywords, @@ -30,7 +30,21 @@ def import_vault(): return None -class Google(DynamicCore): +class Google( + AppsScriptKeywords, + BaseKeywords, + DocumentAIKeywords, + DriveKeywords, + GmailKeywords, + NaturalLanguageKeywords, + SheetsKeywords, + SpeechToTextKeywords, + StorageKeywords, + TextToSpeechKeywords, + TranslationKeywords, + VideoIntelligenceKeywords, + VisionKeywords, +): # pylint: disable=too-many-ancestors """`Google` is a library for operating with Google API endpoints. **Installation** @@ -124,21 +138,34 @@ def __init__( if self.service_account_file is None: self.service_account_file = os.getenv("GOOGLE_APPLICATION_CREDENTIALS") self.secrets_library = import_vault() - - # Register keyword libraries to LibCore - libraries = [ - AppsScriptKeywords(self), - BaseKeywords(self), - DocumentAIKeywords(self), - DriveKeywords(self), - GmailKeywords(self), - NaturalLanguageKeywords(self), - SheetsKeywords(self), - SpeechToTextKeywords(self), - StorageKeywords(self), - TextToSpeechKeywords(self), - TranslationKeywords(self), - VideoIntelligenceKeywords(self), - VisionKeywords(self), - ] - super().__init__(libraries) + ctx = LibraryContext(self) + AppsScriptKeywords.__init__(self, ctx) + BaseKeywords.__init__(self, ctx) + DocumentAIKeywords.__init__(self, ctx) + DriveKeywords.__init__(self, ctx) + GmailKeywords.__init__(self, ctx) + NaturalLanguageKeywords.__init__(self, ctx) + SheetsKeywords.__init__(self, ctx) + SpeechToTextKeywords.__init__(self, ctx) + StorageKeywords.__init__(self, ctx) + TextToSpeechKeywords.__init__(self, ctx) + TranslationKeywords.__init__(self, ctx) + VideoIntelligenceKeywords.__init__(self, ctx) + VisionKeywords.__init__(self, ctx) + + +__all__ = [ + "AppsScriptKeywords", + "BaseKeywords", + "DocumentAIKeywords", + "DriveKeywords", + "GmailKeywords", + "NaturalLanguageKeywords", + "SheetsKeywords", + "SpeechToTextKeywords", + "StorageKeywords", + "TextToSpeechKeywords", + "TranslationKeywords", + "VideoIntelligenceKeywords", + "VisionKeywords", +] diff --git a/packages/google/src/RPA/Cloud/Google/keywords/apps_script.py b/packages/google/src/RPA/Cloud/Google/keywords/apps_script.py index b7142ca293..ea422b9767 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/apps_script.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/apps_script.py @@ -1,12 +1,9 @@ from typing import Optional -from . import ( - LibraryContext, - keyword, -) +from . import keyword -class AppsScriptKeywords(LibraryContext): +class AppsScriptKeywords: """Class for Google Apps Script API For more information about Google Apps Script API link_. @@ -15,7 +12,7 @@ class AppsScriptKeywords(LibraryContext): """ def __init__(self, ctx): - super().__init__(ctx) + self.ctx = ctx self.service = None @keyword(tags=["init", "apps script"]) @@ -38,7 +35,7 @@ def init_apps_script( apps_scopes = ["script.projects", "drive.scripts", "script.external_request"] if scopes: apps_scopes += scopes - self.service = self.init_service( + self.service = self.ctx.init_service( service_name="script", api_version="v1", scopes=apps_scopes, diff --git a/packages/google/src/RPA/Cloud/Google/keywords/base.py b/packages/google/src/RPA/Cloud/Google/keywords/base.py index 5004cecceb..4af60704b4 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/base.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/base.py @@ -1,9 +1,12 @@ -from . import LibraryContext, keyword +from . import keyword -class BaseKeywords(LibraryContext): +class BaseKeywords: """Base keywords for the Google library""" + def __init__(self, ctx): + self.ctx = ctx + @keyword def set_robocorp_vault( self, diff --git a/packages/google/src/RPA/Cloud/Google/keywords/context.py b/packages/google/src/RPA/Cloud/Google/keywords/context.py index 3f6ce602ca..61b017f0f0 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/context.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/context.py @@ -34,30 +34,6 @@ class LibraryContext: def __init__(self, ctx): self.ctx = ctx - @property - def logger(self): - return self.ctx.logger - - @property - def robocorp_vault_name(self): - return self.ctx.robocorp_vault_name - - @property - def robocorp_vault_secret_key(self): - return self.ctx.robocorp_vault_secret_key - - @property - def use_robocorp_vault(self): - return self.ctx.use_robocorp_vault - - @property - def service_account_file(self): - return self.ctx.service_account_file - - @property - def cloud_auth_type(self): - return self.ctx.cloud_auth_type - def get_secret_from_robocorp_vault(self, secret_type="serviceaccount"): if self.ctx.secrets_library is None: raise KeyError("RPA.Robocorp.Vault library is required to use Vault") @@ -105,7 +81,7 @@ def init_service( """ service = None credentials = None - self.logger.debug("Init service with scopes: %s", scopes) + self.ctx.logger.debug("Init service with scopes: %s", scopes) scopes = [f"https://www.googleapis.com/auth/{scope}" for scope in scopes] if use_robocorp_vault is not None: use_cloud = bool(use_robocorp_vault) @@ -122,17 +98,17 @@ def init_service( save_token, ) elif service_account_file: - self.logger.info("Authenticating with service account file") + self.ctx.logger.info("Authenticating with service account file") credentials = oauth_service_account.Credentials.from_service_account_file( service_account_file, scopes=scopes ) elif token_file: - self.logger.info("Authenticating with oauth token file") + self.ctx.logger.info("Authenticating with oauth token file") credentials = self.get_credentials_with_oauth_token( use_cloud, token_file, credentials_file, scopes, save_token ) elif self.ctx.service_account_file: - self.logger.info("Authenticating with service account file") + self.ctx.logger.info("Authenticating with service account file") credentials = oauth_service_account.Credentials.from_service_account_file( self.ctx.service_account_file, scopes=scopes ) @@ -172,24 +148,24 @@ def init_service_with_object( client_object, cloud_auth_type, service_account_file, **kwargs ) elif service_account_file: - self.logger.info("Authenticating with service account file") + self.ctx.logger.info("Authenticating with service account file") service = client_object.from_service_account_json( service_account_file, **kwargs ) elif token_file: - self.logger.info("Authenticating with oauth token file") + self.ctx.logger.info("Authenticating with oauth token file") token_file_location = Path(token_file).absolute() if os.path.exists(token_file_location): with open(token_file_location, "rb") as token: credentials = pickle.loads(token) service = client_object(credentials=credentials, **kwargs) elif self.ctx.service_account_file: - self.logger.info("Authenticating with service account file") + self.ctx.logger.info("Authenticating with service account file") service = client_object.from_service_account_json( self.ctx.service_account_file, **kwargs ) else: - self.logger.info("Authenticating with default client object") + self.ctx.logger.info("Authenticating with default client object") service = client_object(**kwargs) if service is None: @@ -244,7 +220,7 @@ def get_credentials_with_oauth_token( pickle.dumps(credentials) ).decode("utf-8") self.ctx.secrets_library().set_secret(secrets) - self.logger.debug("Credentials refreshed") + self.ctx.logger.debug("Credentials refreshed") if not credentials: raise GoogleOAuthAuthenticationError( "Could not get Google OAuth credentials" @@ -262,7 +238,7 @@ def get_credentials_from_robocorp_vault( ): credentials = None if cloud_auth_type == "serviceaccount": - self.logger.info( + self.ctx.logger.info( "Authenticating with service account file from Robocorp Vault" ) service_account_file = self.get_secret_from_robocorp_vault("serviceaccount") @@ -270,7 +246,9 @@ def get_credentials_from_robocorp_vault( service_account_file, scopes=scopes ) else: - self.logger.info("Authenticating with oauth token file from Robocorp Vault") + self.ctx.logger.info( + "Authenticating with oauth token file from Robocorp Vault" + ) credentials = self.get_credentials_with_oauth_token( True, token_file, @@ -286,7 +264,7 @@ def get_service_from_robocorp_vault( service = None if cloud_auth_type == "serviceaccount": try: - self.logger.info( + self.ctx.logger.info( "Authenticating with service account file from Robocorp Vault" ) service_account_file = self.get_secret_from_robocorp_vault( @@ -299,7 +277,9 @@ def get_service_from_robocorp_vault( if service_account_file: os.remove(service_account_file) else: - self.logger.info("Authenticating with oauth token file from Robocorp Vault") + self.ctx.logger.info( + "Authenticating with oauth token file from Robocorp Vault" + ) token = self.get_secret_from_robocorp_vault("token") credentials = pickle.loads(base64.b64decode(token)) service = client_object(credentials=credentials, **kwargs) diff --git a/packages/google/src/RPA/Cloud/Google/keywords/document_ai.py b/packages/google/src/RPA/Cloud/Google/keywords/document_ai.py index 8f137365be..ae86f64874 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/document_ai.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/document_ai.py @@ -5,10 +5,10 @@ from google.api_core.client_options import ClientOptions from google.cloud import documentai_v1 as documentai -from . import LibraryContext, keyword +from . import keyword -class DocumentAIKeywords(LibraryContext): +class DocumentAIKeywords: """Keywords for Google Cloud Document AI service. Added on **rpaframework-google** version: 6.1.1 @@ -25,7 +25,7 @@ class DocumentAIKeywords(LibraryContext): """ def __init__(self, ctx): - super().__init__(ctx) + self.ctx = ctx self.service = None @keyword(name="Init Document AI", tags=["init", "document ai"]) @@ -73,8 +73,8 @@ def init_document_ai( api_endpoint=f"{region.lower()}-documentai.googleapis.com" ) kwargs["client_options"] = opts - self.logger.info(f"Using Document AI from '{region.upper()}' region") - self.service = self.init_service_with_object( + self.ctx.logger.info(f"Using Document AI from '{region.upper()}' region") + self.service = self.ctx.init_service_with_object( documentai.DocumentProcessorServiceClient, service_account, use_robocorp_vault, @@ -148,7 +148,9 @@ def process_document( binary_content = binary.read() mime = mime_type or mimetypes.guess_type(file_path)[0] - self.logger.info(f"Processing document '{file_path}' with mimetype '{mime}'") + self.ctx.logger.info( + f"Processing document '{file_path}' with mimetype '{mime}'" + ) # Load Binary Data into Document AI RawDocument Object raw_document = documentai.RawDocument(content=binary_content, mime_type=mime) diff --git a/packages/google/src/RPA/Cloud/Google/keywords/drive.py b/packages/google/src/RPA/Cloud/Google/keywords/drive.py index 39c88d1ebe..bfe665088d 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/drive.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/drive.py @@ -8,7 +8,7 @@ from apiclient.errors import HttpError from apiclient.http import MediaFileUpload, MediaIoBaseDownload -from . import LibraryContext, keyword, UpdateAction +from . import keyword, UpdateAction from .enums import DriveRole, DriveType, to_drive_role, to_drive_type @@ -16,7 +16,7 @@ class GoogleDriveError(Exception): """Raised with errors in Drive API""" -class DriveKeywords(LibraryContext): +class DriveKeywords: """Class for Google Drive API For more information about Google Drive API link_. @@ -25,7 +25,7 @@ class DriveKeywords(LibraryContext): """ def __init__(self, ctx): - super().__init__(ctx) + self.ctx = ctx self.service = None @keyword(tags=["init", "drive"]) @@ -54,7 +54,7 @@ def init_drive( ] if scopes: drive_scopes += scopes - self.service = self.init_service( + self.service = self.ctx.init_service( service_name="drive", api_version="v3", scopes=drive_scopes, @@ -107,7 +107,7 @@ def upload_drive_file( raise GoogleDriveError("Filename '%s' does not exist" % filename) query_string = f"name = '{filepath.name}' and '{folder_id}' in parents" - self.logger.debug("Upload query_string: '%s'" % query_string) + self.ctx.logger.debug("Upload query_string: '%s'" % query_string) target_file = self.search_drive_files(query=query_string, recurse=True) guess_mimetype = mimetypes.guess_type(str(filepath.absolute())) file_mimetype = guess_mimetype[0] if guess_mimetype else "*/*" @@ -119,15 +119,15 @@ def upload_drive_file( "parents": [folder_id], "mimeType": file_mimetype, } - self.logger.debug("Upload file_metadata: '%s'" % file_metadata) + self.ctx.logger.debug("Upload file_metadata: '%s'" % file_metadata) if len(target_file) == 1 and overwrite: - self.logger.info("Overwriting file '%s' with new content", filename) + self.ctx.logger.info("Overwriting file '%s' with new content", filename) return self._file_update(target_file, media) elif len(target_file) == 1 and not overwrite: - self.logger.warn("Not uploading new copy of file '%s'", filepath.name) + self.ctx.logger.warn("Not uploading new copy of file '%s'", filepath.name) return target_file[0]["id"] elif len(target_file) > 1: - self.logger.warn( + self.ctx.logger.warn( "Drive already contains '%s' copies of file '%s'. Not uploading again." % (len(target_file), filepath.name) ) @@ -221,12 +221,12 @@ def download_drive_files( current_time = time.time() files_downloaded.append(f["name"]) if limit and len(files_downloaded) >= limit: - self.logger.info( + self.ctx.logger.info( "Drive download limit %s reached. Stopping the download.", limit ) break if timeout and (current_time - start_time) > float(timeout): - self.logger.info( + self.ctx.logger.info( "Drive download timeout %s seconds reached. " "Stopping the download.", timeout, @@ -323,7 +323,7 @@ def _drive_files_update(self, file_id: str, action: UpdateAction): else: # TODO: mypy should handle enum exhaustivity validation raise ValueError(f"Unsupported update action: {action}") - self.logger.debug(body) + self.ctx.logger.debug(body) try: updated_file = ( self.service.files().update(fileId=file_id, body=body).execute() @@ -371,7 +371,7 @@ def delete_drive_file( self.service.files().delete(fileId=tf).execute() except HttpError as err: if suppress_errors: - self.logger.warn(str(err)) + self.ctx.logger.warn(str(err)) else: raise GoogleDriveError(str(err)) from err delete_count += 1 @@ -416,7 +416,7 @@ def get_drive_folder_id( if len(folders) == 1: drive_file = folders[0] # .get("id", None) else: - self.logger.info( + self.ctx.logger.info( "Found %s directories with name '%s'" % (len(folders), folder) ) if drive_file: @@ -542,7 +542,7 @@ def search_drive_files( if page_token: parameters["pageToken"] = page_token try: - self.logger.debug("Searching with parameters: '%s'" % parameters) + self.ctx.logger.debug("Searching with parameters: '%s'" % parameters) response = self.service.files().list(**parameters).execute() for file_details in response.get("files", []): file_dict = self._drive_file_details_into_file_dict(file_details) @@ -581,13 +581,13 @@ def _drive_file_details_into_file_dict(self, details): kind = details.get("kind") mimetype = details.get("mimeType") is_folder = mimetype == "application/vnd.google-apps.folder" + # fmt: off folder_id = ( file_id if mimetype == "application/vnd.google-apps.folder" - else parents[0] - if parents and len(parents) > 0 - else None + else parents[0] if parents and len(parents) > 0 else None ) + # fmt: on file_link = ( None if mimetype == "application/vnd.google-apps.folder" @@ -642,7 +642,7 @@ def create_drive_directory( folder_id = self.get_drive_folder_id(folder, parent_folder=parent_folder) if folder_id: - self.logger.info( + self.ctx.logger.info( "Folder '%s' already exists. Not creating new one.", folder_id ) return self._folder_response(folder_id) @@ -861,7 +861,7 @@ def remove_drive_share_by_permission_id( if not target_file: raise GoogleDriveError("Did not find target file") - self.logger.info( + self.ctx.logger.info( "Removing permission id '%s' for file_id '%s'" % (permission_id, target_file[0]) ) @@ -874,7 +874,7 @@ def remove_drive_share_by_permission_id( ) except HttpError as err: if suppress_errors: - self.logger.warn(str(err)) + self.ctx.logger.warn(str(err)) else: raise GoogleDriveError(str(err)) from err return response @@ -939,7 +939,7 @@ def remove_drive_share_by_criteria( for tf in target_files: file_permissions_removed = [] if "permissions" in tf and tf["permissions"]: - self.logger.info( + self.ctx.logger.info( "Removing shares from file '%s' id '%s'" % (tf["name"], tf["id"]) ) for p in tf["permissions"]: @@ -982,7 +982,7 @@ def _remove_file_permission( permissions_removed.append(permission) except HttpError as err: if suppress_errors: - self.logger.warn(str(err)) + self.ctx.logger.warn(str(err)) else: raise GoogleDriveError(str(err)) from err @@ -1016,7 +1016,7 @@ def remove_all_drive_shares( permissions_removed = [] for tf in target_files: if "permissions" in tf and tf["permissions"]: - self.logger.info( + self.ctx.logger.info( "Removing shares from file '%s' id '%s'" % (tf["name"], tf["id"]) ) for p in tf["permissions"]: @@ -1052,7 +1052,7 @@ def get_drive_file_by_id(self, file_id: str, suppress_errors: bool = False) -> D response = self._drive_file_details_into_file_dict(raw_response) except HttpError as err: if suppress_errors: - self.logger.warn(str(err)) + self.ctx.logger.warn(str(err)) else: raise GoogleDriveError(str(err)) from err return response diff --git a/packages/google/src/RPA/Cloud/Google/keywords/gmail.py b/packages/google/src/RPA/Cloud/Google/keywords/gmail.py index e042cae309..37b457b1b4 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/gmail.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/gmail.py @@ -13,7 +13,7 @@ from googleapiclient import errors -from . import LibraryContext, keyword +from . import keyword def get_size_format(b, factor=1024, suffix="B"): @@ -35,7 +35,7 @@ def clean(text): return "".join(c if c.isalnum() else "_" for c in text) -class GmailKeywords(LibraryContext): +class GmailKeywords: """Class for Google Gmail API **Note:** The Gmail API does not work with _service accounts_ @@ -46,7 +46,7 @@ class GmailKeywords(LibraryContext): """ def __init__(self, ctx): - super().__init__(ctx) + self.ctx = ctx self.service = None @keyword(tags=["init", "gmail"]) @@ -69,7 +69,7 @@ def init_gmail( gmail_scopes = ["gmail.send", "gmail.compose", "gmail.modify", "gmail.labels"] if scopes: gmail_scopes = scopes - self.service = self.init_service( + self.service = self.ctx.init_service( service_name="gmail", api_version="v1", scopes=gmail_scopes, @@ -116,7 +116,7 @@ def add_attachment_to_message(self, mimeMessage, attachment): if content_type is None or encoding is not None: content_type = "application/octet-stream" main_type, sub_type = content_type.split("/", 1) - self.logger.debug( + self.ctx.logger.debug( f"Adding attachment of main_type: {main_type} and sub_type: {sub_type}" ) mime_type_mapping = { @@ -178,9 +178,9 @@ def send_message( .send(userId=sender, body=message) .execute() ) - self.logger.debug("Message Id: %s" % response["id"]) + self.ctx.logger.debug("Message Id: %s" % response["id"]) except errors.HttpError as he: - self.logger.warning(str(he)) + self.ctx.logger.warning(str(he)) raise he return response @@ -238,7 +238,7 @@ def handle_mimetypes(self, parsed_parts, part, msg, folder_name): if "attachment" in part_header_value: # we get the attachment ID # and make another request to get the attachment itself - self.logger.info( + self.ctx.logger.info( "Saving the file: %s, size:%s" % (filename, get_size_format(filesize)) ) @@ -329,7 +329,7 @@ def list_messages( message_dict["parts"] = parsed_parts messages.append(message_dict) except errors.HttpError as he: - self.logger.warning(str(he)) + self.ctx.logger.warning(str(he)) raise he return messages diff --git a/packages/google/src/RPA/Cloud/Google/keywords/natural_language.py b/packages/google/src/RPA/Cloud/Google/keywords/natural_language.py index 142d3f390c..410bc60b3a 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/natural_language.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/natural_language.py @@ -2,14 +2,14 @@ from google.cloud import language_v1 -from . import LibraryContext, keyword, TextType, to_texttype +from . import keyword, TextType, to_texttype -class NaturalLanguageKeywords(LibraryContext): +class NaturalLanguageKeywords: """Keywords for Google Cloud Natural Language API""" def __init__(self, ctx): - super().__init__(ctx) + self.ctx = ctx self.service = None @keyword(tags=["init", "natural language"]) @@ -25,7 +25,7 @@ def init_natural_language( :param use_robocorp_vault: use credentials in `Robocorp Vault` :param token_file: file path to token file """ - self.service = self.init_service_with_object( + self.service = self.ctx.init_service_with_object( language_v1.LanguageServiceClient, service_account, use_robocorp_vault, @@ -126,5 +126,5 @@ def _analyze_handler( response = self.service.analyze_sentiment( document=document, encoding_type="UTF8" ) - self.write_json(json_file, response) + self.ctx.write_json(json_file, response) return response diff --git a/packages/google/src/RPA/Cloud/Google/keywords/sheets.py b/packages/google/src/RPA/Cloud/Google/keywords/sheets.py index d1d909286e..22afa9a1db 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/sheets.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/sheets.py @@ -1,16 +1,13 @@ from typing import Dict, List, Optional -from . import ( - LibraryContext, - keyword, -) +from . import keyword -class SheetsKeywords(LibraryContext): +class SheetsKeywords: """Keywords for Google Sheets operations""" def __init__(self, ctx): - super().__init__(ctx) + self.ctx = ctx self.service = None @keyword(tags=["init", "sheets"]) @@ -33,7 +30,7 @@ def init_sheets( sheets_scopes = ["drive", "drive.file", "spreadsheets"] if scopes: sheets_scopes += scopes - self.service = self.init_service( + self.service = self.ctx.init_service( service_name="sheets", api_version="v4", scopes=sheets_scopes, diff --git a/packages/google/src/RPA/Cloud/Google/keywords/speech_to_text.py b/packages/google/src/RPA/Cloud/Google/keywords/speech_to_text.py index dd7421ae29..c4019f4c9f 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/speech_to_text.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/speech_to_text.py @@ -2,10 +2,7 @@ from google.cloud import speech from google.cloud.speech_v1.types import RecognitionConfig, RecognitionAudio -from . import ( - LibraryContext, - keyword, -) +from . import keyword ENCODING = { "AMR": RecognitionConfig.AudioEncoding.AMR, @@ -19,7 +16,7 @@ } -class SpeechToTextKeywords(LibraryContext): +class SpeechToTextKeywords: """Class for Google Cloud Speech-To-Text API Possible input audio encodings: @@ -39,7 +36,7 @@ class SpeechToTextKeywords(LibraryContext): """ def __init__(self, ctx): - super().__init__(ctx) + self.ctx = ctx self.service = None @keyword(tags=["init", "speech to text"]) @@ -55,7 +52,7 @@ def init_speech_to_text( :param use_robocorp_vault: use credentials in `Robocorp Vault` :param token_file: file path to token file """ - self.service = self.init_service_with_object( + self.service = self.ctx.init_service_with_object( speech.SpeechClient, service_account, use_robocorp_vault, token_file ) return self.service diff --git a/packages/google/src/RPA/Cloud/Google/keywords/storage.py b/packages/google/src/RPA/Cloud/Google/keywords/storage.py index f8b731aa46..078687a300 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/storage.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/storage.py @@ -2,13 +2,10 @@ from google.cloud import storage -from . import ( - LibraryContext, - keyword, -) +from . import keyword -class StorageKeywords(LibraryContext): +class StorageKeywords: """Class for Google Cloud Storage API and Google Cloud Storage JSON API @@ -18,7 +15,7 @@ class StorageKeywords(LibraryContext): """ def __init__(self, ctx): - super().__init__(ctx) + self.ctx = ctx self.service = None @keyword(tags=["init", "storage"]) @@ -34,7 +31,7 @@ def init_storage( :param use_robocorp_vault: use credentials in `Robocorp Vault` :param token_file: file path to token file """ - self.service = self.init_service_with_object( + self.service = self.ctx.init_service_with_object( storage.Client, service_account, use_robocorp_vault, token_file ) return self.service @@ -254,7 +251,7 @@ def download_storage_files(self, bucket_name: str, files: Any) -> List: if blob: with open(filename, "wb") as f: blob.download_to_file(f) - self.logger.info( + self.ctx.logger.info( "Downloaded object %s from Google to filepath %s", object_name, filename, @@ -268,7 +265,7 @@ def download_storage_files(self, bucket_name: str, files: Any) -> List: if blob: with open(filename, "wb") as f: blob.download_to_file(f) - self.logger.info( + self.ctx.logger.info( "Downloaded object %s from Google to filepath %s", filename, filename, diff --git a/packages/google/src/RPA/Cloud/Google/keywords/text_to_speech.py b/packages/google/src/RPA/Cloud/Google/keywords/text_to_speech.py index 42fb19579c..dfa535ea2a 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/text_to_speech.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/text_to_speech.py @@ -7,13 +7,10 @@ SynthesisInput, ) -from . import ( - LibraryContext, - keyword, -) +from . import keyword -class TextToSpeechKeywords(LibraryContext): +class TextToSpeechKeywords: """Class for Google Cloud Text-to-Speech API Link to `Text To Speech PyPI`_ page. @@ -22,7 +19,7 @@ class TextToSpeechKeywords(LibraryContext): """ def __init__(self, ctx): - super().__init__(ctx) + self.ctx = ctx self.service = None @keyword(tags=["init", "text to speech"]) @@ -38,7 +35,7 @@ def init_text_to_speech( :param use_robocorp_vault: use credentials in `Robocorp Vault` :param token_file: file path to token file """ - self.service = self.init_service_with_object( + self.service = self.ctx.init_service_with_object( texttospeech_v1.TextToSpeechClient, service_account, use_robocorp_vault, diff --git a/packages/google/src/RPA/Cloud/Google/keywords/translation.py b/packages/google/src/RPA/Cloud/Google/keywords/translation.py index 4a61d852dc..409146d5b0 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/translation.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/translation.py @@ -2,10 +2,10 @@ from google.cloud import translate_v3 -from . import LibraryContext, keyword, TextType, to_texttype +from . import keyword, TextType, to_texttype -class TranslationKeywords(LibraryContext): +class TranslationKeywords: """Class for Google Cloud Translation API Link to `Translation PyPI`_ page. @@ -14,7 +14,7 @@ class TranslationKeywords(LibraryContext): """ def __init__(self, ctx): - super().__init__(ctx) + self.ctx = ctx self.service = None self.project_id = None @@ -34,7 +34,7 @@ def init_translation( :param token_file: file path to token file """ self.project_id = project_identifier - self.service = self.init_service_with_object( + self.service = self.ctx.init_service_with_object( translate_v3.TranslationServiceClient, service_account, use_robocorp_vault, diff --git a/packages/google/src/RPA/Cloud/Google/keywords/video_intelligence.py b/packages/google/src/RPA/Cloud/Google/keywords/video_intelligence.py index 0279375c7d..c1ac868bb6 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/video_intelligence.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/video_intelligence.py @@ -2,14 +2,14 @@ from google.cloud import videointelligence -from . import LibraryContext, keyword, to_feature +from . import keyword, to_feature -class VideoIntelligenceKeywords(LibraryContext): +class VideoIntelligenceKeywords: """Keywords for Google Video Intelligence API""" def __init__(self, ctx): - super().__init__(ctx) + self.ctx = ctx self.service = None @keyword(tags=["init", "video intelligence"]) @@ -25,7 +25,7 @@ def init_video_intelligence( :param use_robocorp_vault: use credentials in `Robocorp Vault` :param token_file: file path to token file """ - self.service = self.init_service_with_object( + self.service = self.ctx.init_service_with_object( videointelligence.VideoIntelligenceServiceClient, service_account, use_robocorp_vault, @@ -99,5 +99,5 @@ def annotate_video( operation = self.service.annotate_video(request=parameters) result = operation.result(timeout=timeout) - self.write_json(json_file, result) + self.ctx.write_json(json_file, result) return result diff --git a/packages/google/src/RPA/Cloud/Google/keywords/vision.py b/packages/google/src/RPA/Cloud/Google/keywords/vision.py index f7d9bdb843..50a4c2e8ba 100644 --- a/packages/google/src/RPA/Cloud/Google/keywords/vision.py +++ b/packages/google/src/RPA/Cloud/Google/keywords/vision.py @@ -1,17 +1,14 @@ from typing import Dict, Optional from google.cloud import vision -from . import ( - LibraryContext, - keyword, -) +from . import keyword -class VisionKeywords(LibraryContext): +class VisionKeywords: """Keywords for Google Vision operations""" def __init__(self, ctx): - super().__init__(ctx) + self.ctx = ctx self.service = None @keyword(tags=["init", "vision"]) @@ -27,7 +24,7 @@ def init_vision( :param use_robocorp_vault: use credentials in `Robocorp Vault` :param token_file: file path to token file """ - self.service = self.init_service_with_object( + self.service = self.ctx.init_service_with_object( vision.ImageAnnotatorClient, service_account, use_robocorp_vault, @@ -67,7 +64,7 @@ def detect_labels( """ parameters = self.set_image_type(image_file, image_uri) response = self.service.label_detection(**parameters) - self.write_json(json_file, response) + self.ctx.write_json(json_file, response) return response @keyword(tags=["vision"]) @@ -92,7 +89,7 @@ def detect_text( """ parameters = self.set_image_type(image_file, image_uri) response = self.service.text_detection(**parameters) - self.write_json(json_file, response) + self.ctx.write_json(json_file, response) return response @keyword(tags=["vision"]) @@ -117,7 +114,7 @@ def detect_document( """ parameters = self.set_image_type(image_file, image_uri) response = self.service.document_text_detection(**parameters) - self.write_json(json_file, response) + self.ctx.write_json(json_file, response) return response @keyword(tags=["vision"]) @@ -142,7 +139,7 @@ def annotate_image( """ parameters = self.set_image_type(image_file, image_uri) response = self.service.annotate_image(**parameters) - self.write_json(json_file, response) + self.ctx.write_json(json_file, response) return response @keyword(tags=["vision"]) @@ -167,5 +164,5 @@ def face_detection( """ parameters = self.set_image_type(image_file, image_uri) response = self.service.face_detection(**parameters) - self.write_json(json_file, response) + self.ctx.write_json(json_file, response) return response