def obterTraducaoDeUmTexto(self):
     servico = Google('translate', version='v2', developerKey=self.apiKey)
     resultado = servico.translations().list(source=self.srcLang,
                                             target=self.dstLang,
                                             q=[self.sentencas]).execute()
     if 'translations' in resultado and \
             'translatedText' in resultado['translations'][0] and \
             resultado['translations'][0]['translatedText'] != '':
         return resultado['translations'][0]['translatedText']
     else:
         print('[ - ] Texto não pode ser traduzido')
         return ''
Example #2
0
    async def clean_old_files(service: build):
        twelve_hours_since_now = datetime.now(tz=timezone.utc) - timedelta(hours=12)
        twelve_hours_since_now.strftime("%Y-%m-%dT%H:%M:%SZ")
        date_str = twelve_hours_since_now.isoformat(timespec='milliseconds')
        date_str = str(date_str).replace('+00:00', '')

        response = service.files().list(q=f"modifiedTime < '{date_str}'",
                                        spaces="drive",
                                        fields="nextPageToken, files(id, name)").execute()

        old_files = response.get("files")

        for file in old_files:
            logging.info(f"I am removing {file} from google drive since its already old enough.")
            service.files().delete(fileId=file.get("id")).execute()
    def _plan_event(attendees: List[Dict[str, str]], event_time,
                    service: build):
        event = {
            "summary": "test meeting",
            "start": {
                "dateTime": event_time["start"]
            },
            "end": {
                "dateTime": event_time["end"]
            },
            "attendees": attendees,
            "conferenceData": {
                "createRequest": {
                    "requestId": f"{uuid4().hex}",
                    "conferenceSolutionKey": {
                        "type": "hangoutsMeet"
                    }
                }
            },
            "reminders": {
                "useDefault": True
            }
        }
        event = service.events().insert(calendarId="primary",
                                        sendNotifications=True,
                                        body=event,
                                        conferenceDataVersion=1).execute()

        return event
Example #4
0
 def _create_event(attendees: List[Dict[str, str]], event_time,
                   authe: build, topic):
     event = {
         "conferenceData": {
             "createRequest": {
                 "requestId": f"{uuid4().hex}",
                 "conferenceSolutionKey": {
                     "type": "hangoutsMeet"
                 }
             }
         },
         "attendees": attendees,
         "start": {
             "dateTime": event_time["start"],
             'timeZone': 'Asia/Kolkata'
         },
         "end": {
             "dateTime": event_time["end"],
             'timeZone': 'Asia/Kolkata'
         },
         "summary": topic,
         "reminders": {
             "useDefault": True
         }
     }
     event = authe.events().insert(calendarId="primary",
                                   sendNotifications=True,
                                   body=event,
                                   conferenceDataVersion=1).execute()
     return event
Example #5
0
def get_perspective_api_results(perspective_client: discovery.build,
                                text: dict) -> dict:
    """Calls Perspective API to get toxicity of transcribed text.

    Args:
        perspective_client: discovery.build representing Perspective API Client
        text: Dict with transcript, start_time, end_time

    Returns:
        Dict holding perspective API results.
    """
    logging.info(f'Starting get_perspective_api_results with '
                 f'{perspective_client} and {text}')
    body = {
        'comment': {
            'text': text['transcript']
        },
        'requestedAttributes': {
            'TOXICITY': {}
        },
        'languages': ['en'],
    }
    logging.debug(f'Request: {json.dumps(body)}')
    try:
        response = perspective_client.comments().analyze(body=body).execute()
        logging.debug(f'Response: {json.dumps(response)}')

    except Exception as e:
        logging.error('Calling Perspective API failed.')
        logging.error(e)
    return response
Example #6
0
def add_games(games: Game, service: build) -> None:
    calendar_games = get_calendar_games(service)
    for game in games:
        # Does not modify games in past/games already in the calendar
        if not game.is_in_calendar(
                calendar_games) and game.date > pytz.UTC.localize(
                    datetime.now()):
            with open("event.json", "r", encoding='utf-8') as f:
                event = json.load(f)
                event['start']['dateTime'] = game.date.isoformat()
                event['end']['dateTime'] = game.end_date.isoformat()
                event['source']['title'] = game.identifier
                event['summary'] = game.calendar_title
                event['description'] = game.description
                event['location'] = game.location
            service.events().insert(calendarId=Globals.CALENDAR_ID,
                                    body=event).execute()
Example #7
0
def read_google_sheet(service: build, sheet_id: str, sheet_range: str,
                      skip_cols: int or list or tuple = None, skip_rows: int or list or tuple = None,
                      columns: bool = True, indexed: bool = False) -> pd.DataFrame:
    """
    Reads a subset of a google sheet via the google sheets api and returns it converted to a pandas DataFrame

    Args:
        service (googleapiclient.discovery.build): a google api service python instance
        sheet_id (str): the identifier for the google sheet
        sheet_range (str): the absolute reference to the cells to be read. For example: "Sheet1!A:H" reads columns
            A -> H on the sheet names Sheet1 within the specified Google Sheet.
        skip_cols (int): an int or iterable of ints of the spreadsheet columns numbers to be ignored in the output
            (e.g. column A = 1, column B = 2, columns A through C = (1, 2, 3)
        skip_rows (int): an int or iterable of ints of the spreadsheet row numbers to be ignored in the output
        indexed (bool): Indicates whether the first column (after skip columns is applied) should be interpreted
            as the index in pandas
        columns (bool): Indicates whether the first row (after skip rows is applied) should be interpreted as
            labels for the data in the columns

    Returns:
        pd.DataFrame
    """
    # Call the Sheets API to get the spreadsheet data
    sheet = service.spreadsheets()
    result = sheet.values().get(spreadsheetId=sheet_id, range=sheet_range).execute()
    values = result.get('values', [])

    # make all the rows the same length
    length = max(map(len, values))
    array = np.array([xi + [''] * (length - len(xi)) for xi in values])

    # delete any rows or columns specified by the user
    if skip_rows is not None:
        array = np.delete(array, np.asarray(skip_rows) - 1, axis=0)  # subtract 1 -> sheets start at 1, np at 0
    if skip_cols is not None:
        array = np.delete(array, np.asarray(skip_cols) - 1, axis=1)

    # extract index and column labels if applicable
    idx = None
    col = None
    if indexed:
        idx = array[:, 0]
        array = np.delete(array, 0, axis=1)
    if columns:
        col = array[0]
        array = np.delete(array, 0, axis=0)
    if indexed and columns:
        idx = np.delete(idx, 0, axis=0)

    return pd.DataFrame(array, columns=col, index=idx)
Example #8
0
def write_google_sheet(df: pd.DataFrame, service: build, sheet_id: str, sheet_range: str) -> build:
    """
    writes a pandas dataframe to a google sheet on the range specified

    Args:
        service (googleapiclient.discovery.build): a google api service python instance
        sheet_id (str): the identifier for the google sheet
        sheet_range (str): the absolute reference to the cells to be read. For example: "Sheet1!A:H" reads columns
            A -> H on the sheet names Sheet1 within the specified Google Sheet.
        df (pd.DataFrame): the pandas dataframe to be written to the google sheet

    Returns:

    """
    col = np.asarray(df.columns)
    col = col.reshape(1, len(col))
    body = df.to_numpy()
    body = {'values': np.vstack((col, body)).tolist()}
    return service.spreadsheets().values().update(
        spreadsheetId=sheet_id, range=sheet_range, valueInputOption='RAW', body=body).execute()
def extract_mails(threads: list, service: build):
    count = 0
    gift_codes: list = []
    for index, email in enumerate(threads):
        raw_contents = (service.users().messages().get(
            userId="me",
            id=email["id"]).execute())["payload"]["parts"][0]["body"]["data"]
        decoded_contents = base64.urlsafe_b64decode(raw_contents).decode(
            "utf-8")
        match = re.search("and your Gift Card Code is\s+", decoded_contents)

        if match is None:
            generate_file(count=count, codes=gift_codes)

        else:
            matched_number = decoded_contents[match.end():]
            if len(matched_number) != 16:
                print("no gift card code found")
            count += 1
            gift_codes.append(matched_number)
    return count, gift_codes