<commit_before>import sys
import logging

# logging config needs to be before other imports
# in order not to be overwritten
LOGGING_TRACE_LVL = 5
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
                    format='%(name)s (%(levelname)s): %(message)s')

from postcard_creator import postcard_creator
import base64
import json
import os
import argparse
from argparse import RawTextHelpFormatter
import urllib


class Postcards:
    def __init__(self, logger=None):
        self.logger = self._create_logger(logger)

    def main(self, argv):
        args = self.get_argparser(argv)
        self._configure_logging(self.logger, args.verbose_count)
        self.validate_cli_args(args=args)

        if args.encrypt:
            self.encrypt_credential(args.encrypt[0], args.encrypt[1])
            exit(0)
        elif args.decrypt:
            self.decrypt_credential(args.decrypt[0], args.decrypt[1])
            exit(0)

        config = self._read_config(args.config[0])
        accounts = self._get_accounts(config=config, key=args.key[0],
                                      username=args.username, password=<PASSWORD>)
        self._validate_config(config, accounts)

        self.send(accounts=accounts,
                  recipient=config.get('recipient'),
                  sender=config.get('sender') if config.get('sender') else config.get('recipient'),
                  mock=bool(args.mock),
                  plugin_payload=config.get('payload'),
                  picture_stream=self._read_picture(args.picture) if args.picture else None,
                  message=args.message,
                  cli_args=args)

    def send(self, accounts, recipient, sender, mock=False, plugin_payload={},
             message=None, picture_stream=None, cli_args=None):

        self.logger.info('checking for valid accounts')
        pcc_wrapper = None
        for account in accounts:
            token = postcard_creator.Token()
            if token.has_valid_credentials(account.get('username'), account.get('password')):
                pcc = postcard_creator.PostcardCreator(token)
                if pcc.has_free_postcard():
                    pcc_wrapper = pcc
                    self.logger.info(f'account {account.get("username")} is valid')
                    break

        if not pcc_wrapper:
            self.logger.error('no valid account given. run later again or check accounts.')
            exit(1)

        if self._is_plugin():
            img_and_text = self.get_img_and_text(plugin_payload, cli_args=cli_args)

            if not message:
                message = img_and_text['text']
            if not picture_stream:
                picture_stream = img_and_text['img']

        card = postcard_creator.Postcard(message=message,
                                         recipient=self._create_recipient(recipient),
                                         sender=self._create_sender(sender),
                                         picture_stream=picture_stream)

        # Never send postcard, because postcard_wrapper is not yet working correctly
        self.logger.info('uploading postcard to server')
        pcc_wrapper.send_free_card(card, mock_send=True)

        if mock or True:  # TODO: never send postcards until wrapper works
            self.logger.info('postcard not sent because of mock=True')
        else:
            self.logger.info('postcard is successfully sent')

    def encrypt_credential(self, key, credential):
        self.logger.info('encrypted credential:')<commit_msg>wrap call to send postcard with try/except<commit_after>import sys
import logging

# logging config needs to be before other imports
# in order not to be overwritten
LOGGING_TRACE_LVL = 5
logging.basicConfig(stream=sys.stdout, level=logging.INFO,
                    format='%(name)s (%(levelname)s): %(message)s')

from postcard_creator import postcard_creator
import base64
import json
import os
import argparse
from argparse import RawTextHelpFormatter
import urllib


class Postcards:
    def __init__(self, logger=None):
        self.logger = self._create_logger(logger)

    def main(self, argv):
        args = self.get_argparser(argv)
        self._configure_logging(self.logger, args.verbose_count)
        self.validate_cli_args(args=args)

        if args.encrypt:
            self.encrypt_credential(args.encrypt[0], args.encrypt[1])
            exit(0)
        elif args.decrypt:
            self.decrypt_credential(args.decrypt[0], args.decrypt[1])
            exit(0)

        config = self._read_config(args.config[0])
        accounts = self._get_accounts(config=config, key=args.key[0],
                                      username=args.username, password=args.password)
        self._validate_config(config, accounts)

        self.send(accounts=accounts,
                  recipient=config.get('recipient'),
                  sender=config.get('sender') if config.get('sender') else config.get('recipient'),
                  mock=bool(args.mock),
                  plugin_payload=config.get('payload'),
                  picture_stream=self._read_picture(args.picture) if args.picture else None,
                  message=args.message,
                  cli_args=args)

    def send(self, accounts, recipient, sender, mock=False, plugin_payload={},
             message=None, picture_stream=None, cli_args=None):

        self.logger.info('checking for valid accounts')
        pcc_wrapper = None
        for account in accounts:
            token = postcard_creator.Token()
            if token.has_valid_credentials(account.get('username'), account.get('password')):
                pcc = postcard_creator.PostcardCreator(token)
                if pcc.has_free_postcard():
                    pcc_wrapper = pcc
                    self.logger.info(f'account {account.get("username")} is valid')
                    break

        if not pcc_wrapper:
            self.logger.error('no valid account given. run later again or check accounts.')
            exit(1)

        if self._is_plugin():
            img_and_text = self.get_img_and_text(plugin_payload, cli_args=cli_args)

            if not message:
                message = img_and_text['text']
            if not picture_stream:
                picture_stream = img_and_text['img']

        card = postcard_creator.Postcard(message=message,
                                         recipient=self._create_recipient(recipient),
                                         sender=self._create_sender(sender),
                                         picture_stream=picture_stream)

        # Never send postcard, because postcard_wrapper is not yet working correctly
        self.logger.info('uploading postcard to server')
        try:
            pcc_wrapper.send_free_card(card, mock_send=True)
        except Exception as e:
            self.logger.fatal('can not send postcard: ' + str(e))
            raise e

        if mock or True:  # TODO: never send postcards until wrapper works
            self.logger.info('postcard not sent because of mock=True')
        else:
            self.logger.info('postcard is successfully sent')

    def encrypt_credential(self, key, credential):
        self.logger.info('encrypted credential:')
{'fraction_non_alphanumeric': 0.09133425034387896, 'fraction_numerical': 0.003301237964236589, 'mean_word_length': 2.2129916040654, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 14, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4504705', 'n_tokens_mistral': 1998, 'n_tokens_neox': 1920, 'n_words': 431}