Beispiel #1
0
def clean_scenario(transaction):
    # This shouldn't be needed - controller class shouln't expose flask dependent params
    # TODO remove
    args = MultiDict([
        ('page_size', 10),
        ('page_num', 1),
        ('attr_format', 'both')
    ])
    req = {
        'headers': {
            'authorization': generate_token()
        },
        'args': args,
        'body': ''
    }

    params = {
        'page_size': 10,
        'page_num':  1,
        'attr_format': 'both',
        'attr': [],
        'attr_type': [],
        'idsOnly':'false'
    }

    token = generate_token()

    result = DeviceHandler.get_devices(token, params)

    for device in result['devices']:
        DeviceHandler.delete_device(device['id'], token)

    result = TemplateHandler.get_templates(params, token)
    for template in result['templates']:
        TemplateHandler.remove_template(template['id'], token)
Beispiel #2
0
def create_actuator_device(transaction):
    template_id = create_actuator_template();
    if not 'proprietary' in transaction:
        transaction['proprietary'] = {}
    transaction['proprietary']['template_id'] = template_id
    device = {
        "label": "test_device",
        "templates": [template_id]
    }
    req = {
        'headers': {
            'authorization': generate_token(),
            'Content-Type': 'application/json'
        },
        'args': {
            'count': 1,
            'verbose': False
        },
        'body': json.dumps(device)
    }

    params = {
            'count': '1',
            'verbose': 'False',
            'content_type': 'application/json',
            'data': json.dumps(device)
        }


    result = DeviceHandler.create_device(params, generate_token())
    device_id = result['devices'][0]['id']
    transaction['proprietary']['device_id'] = device_id
    return device_id
Beispiel #3
0
def create_actuator_template():
    template = {
        "label": "SensorModel",
        "attrs": [
            {
                "label": "temperature",
                "type": "dynamic",
                "value_type": "float"
            },
            {
                "label": "battery",
                "type": "actuator",
                "value_type": "float"
            },
            {
                "label": "position",
                "type": "dynamic",
                "value_type": "geopoint"
            },
            {
                "label": "model-id",
                "type": "static",
                "value_type": "string",
                "static_value": "model-001"
            },
            {
                "label": "shared_key",
                "type": "static",
                "value_type": "psk"
            }
        ]
    }
    req = {
        'headers': {
            'authorization': generate_token(),
            'Content-Type': 'application/json'
        },
        'args': {},
        'body': json.dumps(template)
    }

    params = {
        'content_type': 'application/json',
        'data': json.dumps(template)
    }

    result = TemplateHandler.create_template(params, generate_token())
    template_id = result['template']['id']
    return template_id
def auth_before_each_hook(transaction):
    auth = generate_token()
    if 'request' in transaction:
        if 'headers' in transaction[
                'request'] and 'Authorization' in transaction['request'][
                    'headers']:
            transaction['request']['headers']['Authorization'] = auth
def create_sample_template():
    template = {
        "label":
        "SensorModel",
        "attrs": [{
            "label": "temperature",
            "type": "dynamic",
            "value_type": "float"
        }, {
            "label": "model-id",
            "type": "static",
            "value_type": "string",
            "static_value": "model-001"
        }, {
            "label": "shared_key",
            "type": "static",
            "value_type": "psk"
        }]
    }
    req = {
        'headers': {
            'authorization': generate_token(),
            'Content-Type': 'application/json'
        },
        'args': {},
        'body': json.dumps(template)
    }

    result = TemplateHandler.create_template(Request(req))
    template_id = result['template']['id']
    return template_id
Beispiel #6
0
def prepare_copy_psk_env(transaction):
    device_id = create_single_device(transaction)
    transaction['fullPath'] = transaction['fullPath'].replace(
        'efac', device_id)
    DeviceHandler.gen_psk(generate_token(), device_id, 16, None)
    device_id = create_single_device(transaction)
    transaction['fullPath'] = transaction['fullPath'].replace(
        'acaf', device_id)
def send_token(update, context):
    """Send a message when the command /token is issued."""
    # Set user pin for stoken
    user_pin = "000000"
    # Pass pin to generate_token and return token result
    generated_token = generate_token(pin=user_pin)
    # Build token message
    message = "Your token is: " + generated_token + "."
    # Send token
    update.message.reply_text(message)
def app_function():
    try:
        # Read account id and private from environment variables
        account_id = account['ID']
        private_key = ''
        with open('einstein_platform.pem', 'r') as f:
            for line in f:
                private_key += line

        # Set expiry time
        expiry = int(time.time()) + (15 * 60)

        # Generate an assertion using RSA private key
        assertion = jwt_helper.generate_assertion(account_id, private_key,
                                                  expiry)

        # Obtain oauth token
        token = token_generator.generate_token(assertion)
        response = token.json()

        # If there is no token print the response
        if 'access_token' not in response:
            raise ValueError(
                "Access token generation failed. Received reply: \"{}\"".
                format(response))
        else:
            # Collect the access token from response
            access_token = response['access_token']

        # Make a prediction call using image url
        prediction_url_response = prediction.predict_with_url(
            access_token, 'GeneralImageClassifier',
            'https://animalso.com/wp-content/uploads/2017/01/Siberian-Husky_7.jpg'
        )

        # Print prediction response
        pprint.pprint(prediction_url_response.json())

        # Make a prediction call using image file
        # prediction_file_response = prediction.predict_with_image_file(access_token, 'GeneralImageClassifier',
        #     '/path/to/image/file/Siberian-Husky.jpg')

        # Print prediction response
        # pprint.pprint(prediction_file_response.json())

    except Exception as e:
        traceback.print_exc()
Beispiel #9
0
def main():

    try:
        print("Hello")
        # Read account id and private from environment variables
        account_id = os.environ['EINSTEIN_VISION_ACCOUNT_ID']
        private_key = os.environ['EINSTEIN_VISION_PRIVATE_KEY'].decode(
            'string_escape')

        # Set expiry time
        expiry = int(time.time()) + (15 * 60)

        # Generate an assertion using RSA private key
        assertion = jwt_helper.generate_assertion(account_id, private_key,
                                                  expiry)
        # Obtain oauth token
        token = token_generator.generate_token(assertion)
        print("CC")
        response = token.json()
        print(response)
        # If there is no token print the response
        if 'access_token' not in response:
            raise ValueError(
                "Access token generation failed. Received reply: \"{}\"".
                format(response))
        else:
            # Collect the access token from response
            access_token = response['access_token']

        # Make a prediction call using image url
        prediction_url_response = prediction.predict_with_url(
            access_token, 'GeneralImageClassifier',
            'https://animalso.com/wp-content/uploads/2017/01/Siberian-Husky_7.jpg'
        )

        # Print prediction response
        pprint.pprint(prediction_url_response.json())

        # Make a prediction call using image file
        # prediction_file_response = prediction.predict_with_image_file(access_token, 'GeneralImageClassifier',
        #     '/path/to/image/file/Siberian-Husky.jpg')

        # Print prediction response
        # pprint.pprint(prediction_file_response.json())

    except Exception as e:
        traceback.print_exc()
Beispiel #10
0
def create_single_device(transaction):
    global template_id, device_id
    create_sample_template()
    device = {"label": "test_device", "templates": [template_id]}
    req = {
        'headers': {
            'authorization': generate_token(),
            'Content-Type': 'application/json'
        },
        'args': {
            'count': 1,
            'verbose': False
        },
        'body': json.dumps(device)
    }
    result = DeviceHandler.create_device(Request(req))
    device_id = result['devices'][0]['id']
Beispiel #11
0
def clean_scenario(transaction):
    # This shouldn't be needed - controller class shouln't expose flask dependent params
    # TODO remove
    args = MultiDict([('page_size', 10), ('page_num', 1),
                      ('attr_format', 'both')])
    req = {
        'headers': {
            'authorization': generate_token()
        },
        'args': args,
        'body': ''
    }

    result = DeviceHandler.get_devices(Request(req))
    for device in result['devices']:
        DeviceHandler.delete_device(Request(req), device['id'])

    result = TemplateHandler.get_templates(Request(req))
    for template in result['templates']:
        # print(template)
        TemplateHandler.remove_template(Request(req), template['id'])
Beispiel #12
0
def prepare_env_psk(transaction):
    device_id = create_device_and_update_device_id(transaction)
    DeviceHandler.gen_psk(generate_token(), device_id, 16, None)
Beispiel #13
0
def create_single_device_and_gen_psk(transaction):
    device_id = create_single_device(transaction)
    DeviceHandler.gen_psk(generate_token(), device_id, 16, None)
Beispiel #14
0
def main():
    try:
        account_id = '*****@*****.**'  # Your Einstein Account ID
        private_key = open("einstein_platform.pem",
                           "r").read()  #Your Einstein Private Key file

        # Set expiry time
        expiry = int(time.time()) + (15 * 60)

        # Generate an assertion using RSA private key
        assertion = jwt_helper.generate_assertion(account_id, private_key,
                                                  expiry)

        # Obtain oauth token
        token = token_generator.generate_token(assertion)
        response = token.json()

        # If there is no token print the response
        if 'access_token' not in response:
            raise ValueError(
                "Access token generation failed. Received reply: \"{}\"".
                format(response))
        else:
            # Collect the access token from response
            access_token = response['access_token']

        #data_file='Rakesh_Sample.csv' #SFCC_Q1_2019_Recognition_Data.csv'
        data_file = 'TextFileForSentimentAnalysis.csv'
        data_file_with_sentiment = "Sentiment_of_" + data_file
        cleandata(data_file)
        df = pandas.read_csv(data_file)

        #Add three additional column to update sentiment value for the text
        df.insert(1, 'positive', '')
        df.insert(2, 'neutral', '')
        df.insert(3, 'negative', '')
        #df.insert(4,'word_count','')

        for index, row in df.iterrows():
            # Make a Sentiment prediction call

            print('Submited request for sentiment analysis of of text index #',
                  index)
            prediction_url_response = predictionSentiment.predict(
                access_token, row['citation'])
            print('Recieved sentiment for text index #', index)
            # Print prediction response
            resp = prediction_url_response.json()
            probabilities = resp['probabilities']

            for sentiment in probabilities:
                #pprint.pprint(sentiment)
                if sentiment['label'] == 'positive':
                    row['positive'] = sentiment['probability']
                elif sentiment['label'] == 'neutral':
                    row['neutral'] = sentiment['probability']
                elif sentiment['label'] == 'negative':
                    row['negative'] = sentiment['probability']

        df.to_csv(data_file_with_sentiment)
        textStatistics(data_file_with_sentiment)

    except Exception as e:
        traceback.print_exc()
Beispiel #15
0
def main():

    try:
        # Read account id and private from environment variables
        #account_id = os.environ['EINSTEIN_VISION_ACCOUNT_ID']
        #private_key = os.environ['EINSTEIN_VISION_PRIVATE_KEY'].decode('string_escape')

        account_id = '*****@*****.**'
        private_key = """
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEApndK94LOWGJATet94opTPR4kjv0j66LrhsQtzyG+Ji6pVrJa
Nv6HEVpbE4Iy1cZJ4IyyeQ0yUMNDcJ4E0HZVT514ckNhJWIS0pO9lCrFsWNabc+7
U2q7nL4/7iS5QGvbFU37E1l7Vwtx2Ic0/Xm7czSHngALs9j0IWE6CGbaJfKosJKZ
CCsVIF6hnRV5/mjDWhav8m6gEeqqMPhZ6in74sPTEd/r5xXJ7hQu1lbtb2IyMNN6
K0o3gGPSiREvPvkh8KPWOtqzuMH+LHXvb/TPMCDV10q2/5b05NJ9sEnVQ9Rh54R/
EibKaBvNLBAmVm3IzW4sIFjE4bn8OIG11xz2CQIDAQABAoIBAQCjOO0k6/lv6Eat
IG76pi8gCmJGYifKcKEIL2vLYYaU4cPg4lha/A9sEHClHFDEE/10VADbePkQ/6Us
04Rc8uqLehgT0cV7ZkKWf46vrZDSclzEt58yF8GF23XMB+4tIJRcu22od2Dc5Lfo
XAq1T5thRuyDHABdhCk8YZ0Jh+/2q/L+k9utFZuHkHfBfKrzzpDktFu1vh4qK2xi
ZCu+3/P72oZ5OUKz/kheDP2NTKJiIjt3HPxXuIBXDDlarVb+8YA05KIYOvSaSH0b
r1Odm4CRJbJkkCkXp+5GPxuJRI5Iz4kXfJO4nQEPYDelTFW0c9e1Rwn4adJUrs7s
+juOarRRAoGBAPBWvVnDm9Ito7urQhWXinOGfQHIfujltWmtzV6Pq8F+MDLt9yfc
TWdenVx1N951U3l26bNtB7tjnJKFaYefX+Ox+N1eAVGdoAm6SqsN/hsoIIUI5FzR
C0QSEDLTYEfk/pJrqQ7DBgtWkNc9OMyGvOzguckMLfE2HobVzpSg+y63AoGBALFQ
OoXPOSEEbyUKXUc9CEQ+mcIjZUlILxtUA2Pgbh9BglOWmKzqQUS6b6cK0rrX8Aoy
pyMiDxPRYudzUYixJC+jeJKqmeC9FA/OXmPmHkswyVdAQ1X91+rVu7xmcv7jSCeD
nGr7Yp226fRlq6kJzPPKi19mYM34spD0U9WxEEE/AoGBAOmzfrY9llR/GrqPYlg6
nl+NxBqqynVPgOM9JPkxfVNOkDHF4dJ5zy6X+y5/sQ75SW1QKxnVCHK3/vUfE6nU
WNrBIXyoP2IMgyVSZ+8DUTc5Ar46Ek0K3QiZA/VYQ0RFsSHR3HdFPqhhyb/ygTuo
PSedsiqEVFw8QtzcJN+z1evrAoGABflN/3Qb2KDtnbHbsqq7vJDfXUsT/oQQEjui
YZsOGr96RJauTiUWTdp6KIaU0vazf6R1PRnIqEJFssaP2KsfLPu09DwLMycrpdyu
EW+PVbkvD2F640rKG39X8+D/vtapd6tXecM+b1HaUAGc5vUNkqkgSPaKDGZ0na2d
pXVxtsECgYBi/XuDRPviQuZE7nWGRhKOSKmQZ2qy/6zBaUGU1m/ArUACmU6NuI2t
KeF7J38BAtTCrhpp5whWW7Uooe8FxvhWNe+CkxdNoNoz5GyFUAl4IKfb/HX5nUkL
Xpd2APOZoLNf2gJZCycDmratthie+Ex9YULGSxYFgAlg3Ev5tQz20g==
-----END RSA PRIVATE KEY-----
"""

        # Set expiry time
        expiry = int(time.time()) + (15 * 60)

        # Generate an assertion using RSA private key
        assertion = jwt_helper.generate_assertion(account_id, private_key,
                                                  expiry)

        # Obtain oauth token
        token = token_generator.generate_token(assertion)
        response = token.json()

        # If there is no token print the response
        if 'access_token' not in response:
            raise ValueError(
                "Access token generation failed. Received reply: \"{}\"".
                format(response))
        else:
            # Collect the access token from response
            access_token = response['access_token']

        # Upload the dataset to einstein.ai
        DS = dataset(access_token=access_token)
        #path = 'https://raw.githubusercontent.com/kaul-vineet/socialstudio-ml/master/data/intent_tagging.csv'
        #response = DS.create_intent_dataset(path)
        #print(json.dumps(response, indent=4, sort_keys=True))

        # Train the model on einstein.ai []
        id = '1127772'
        #DS = dataset(access_token=access_token)
        response = DS.train_dataset(id)
        #if('available' in response):
        #    print(json.dumps(response, indent=4, sort_keys=True))
        #else:
        #    print('Response status ok?: ' + str(response.ok))
        #    print(json.dumps(response.text, indent=4, sort_keys=True))

        # Check the model training status on einstein.ai []
        id = 'YRVFEBIDWGX4I6EBKDOFU5KRQM'
        #response = DS.get_train_status(id)
        #print(json.dumps(response, indent=4, sort_keys=True))
        #data = json.loads(json.dumps(response))
        #print ('************ THE MODEL TRAINING IS IN PROGRESS ************')
        #while data['status'] != 'SUCCEEDED':
        #    print ('THE MODEL STATUS IS :' + data['status'])
        #    time.sleep(30)
        #else:
        #    print ('THE MODEL STATUS IS :' + data['status'] + ' WITH LEARNING RATE OF ' + str(data['learningRate']))

        # Check the predictions on einstein.ai []
        model_id = 'YRVFEBIDWGX4I6EBKDOFU5KRQM'
        document = 'hey guys, im a black trans creative named wondy!! i make art, unfortunately my account was suspended and i lost my 3.5k following and clientele :( please retweet this post so i can get my product back out there as this is my income!! any support is phenomenal'
        predict = prediction(access_token=access_token)
        response = predict.predict_social_tag(document, model_id)
        probabilities = response['probabilities']
        max_prob = 0
        max_tag = ''
        for x in probabilities:
            if max_prob < x['probability'] * 100:
                max_prob = x['probability'] * 100
                max_tag = str(x['label'])
        print('There is ' + str(max_prob) + ' probability that this is ' +
              max_tag + ' post.')

    except Exception as e:
        traceback.print_exc()