<jupyter_start><jupyter_text>SAS Model Deployment Demo - MAS Overview- Setup- Retrieving information about your models- Scoring Data / Executing Decision with MAS  MAS OverviewMAS is a memory-resident, high-performance program execution service, SAS Micro Analytic Service is multi-threaded and can be clustered for high availability. It can host multiple programs simultaneously, as well as multiple user or business contexts that are isolated from one another. It provides hosting for DS2 and Python programs and supports a “compile-once, execute-many-times” usage pattern.<jupyter_code>from IPython.display import Image
i = Image(filename = '/home/sasdemo/MAS_Workflow.PNG')<jupyter_output><empty_output><jupyter_text>Authentication -- optional stepIf you have registered a client (see the authentication use case), uncomment the code below to generate an access token.<jupyter_code># import requests, json, base64
# sasserver = ""
# username = ""
# password = ""
# client_id = ""
# client_secret = ""
# url = sasserver + "/SASLogon/oauth/token"
# data = {
#     'grant_type': 'password',
#     'username': username,
#     'password': password
# }
# headers = {'Accept': 'application/json'}
# response = requests.post(url, headers=headers, data=data, auth=(client_id, client_secret), verify=False).json()
# access_token = response["access_token"]
# print("The access token is: " + access_token)<jupyter_output><empty_output><jupyter_text>Import modules, variable assignmentThe first step of the process is to import the required packages and assign variable values.Note: requests is the only library required to make API calls to MAS. The other imported libraries are specific to the code in this example).<jupyter_code>import requests
import os, json
import pprint
import getpass
import pandas as pd

# Specify the URL for your host server
#Uncoment to dynamically retrieve your IP address
    #Assumption - you are working from a Linux machine  
#ip= os.popen("hostname -I").read()
#host = 'http://' + ip.split()[0]
host = ""
csv_data = "hmeq_test.csv"
access_token = ""<jupyter_output><empty_output><jupyter_text>Retrieving Information about Modules Deployed to your MAS serverUse the `/microanalyticScore/modules/` to retrieve metadata about the all of the modules deployed to MAS. A module represents program code and all the resources required to execute your model.<jupyter_code>url =  host + "/microanalyticScore/modules/" 
headers = {
    'Accept': "application/vnd.sas.collection+json",
    'Authorization': "Bearer " + access_token
}
response = requests.request('GET', url, headers=headers, verify=False)
formatted_response = json.dumps(response.json(), indent=2)<jupyter_output><empty_output><jupyter_text>Format the output and display it using a pandas dataframe table<jupyter_code>df = pd.DataFrame.from_dict(json.loads(formatted_response)['items'])
df.drop(['links', 'properties','warnings'], axis = 1)<jupyter_output><empty_output><jupyter_text>Get the Inputs and Outputs of your Model/DecisionUse the `/steps` endpoint to get the inputs and outputs of your `model/decision`.<jupyter_code># Find your module and add its id to the model_id variable
model_id = ""
url =  host + "/microanalyticScore/modules/" + model_id + '/steps'
headers = {
    'Accept': "application/vnd.sas.collection+json",
    'Authorization': "Bearer " + access_token
}
response = requests.request('GET', url, headers=headers, verify=False)

#Retrieve the inputs and outpus from the last element of the 'items' json object 
inputs = json.loads(response.text)['items'][-1]['inputs']
outputs = json.loads(response.text)['items'][-1]['outputs']<jupyter_output><empty_output><jupyter_text>Print the inputs / outputs results<jupyter_code>print("Inputs:")
print(json.dumps(inputs, indent = 2))
print("Outputs:")
print(json.dumps(outputs, indent = 2))<jupyter_output><empty_output><jupyter_text>Scoring Data  Read in test data for scoring<jupyter_code>test_data = pd.read_csv(csv_data)
#convert test data colums to lowercase to match MAS input parameter names 
test_data.columns = map(str.lower, test_data.columns)
#Fill empty values with 0 
test_data = test_data.fillna(0)
test_data.head()<jupyter_output><empty_output><jupyter_text>Execute DecisionTo execute a *decision*, use the `/steps/execute` endpoint. For *models* use the `/steps/score` endpoint.<jupyter_code>import requests
import json
import random

url =  host + "/microanalyticScore/modules/" + model_id + '/steps/score'
headers = {
  'Authorization': "Bearer " + access_token,
  'Content-Type': "application/vnd.sas.microanalytic.module.step.input+json" 
}

#Build payload from test data
#Ex format: 
'''
'{"inputs": [
            {"name": "<input1_name>", "value": <decimal_value>}, \
            {"name": "<input2_name>", "value": "<string_value>"}, \
            ] }'
'''

#Retrieve values column values from file and dynamically build payload 
for i in range(len(test_data)): 
    row = test_data.iloc[i]
    payload = '{"inputs":[ ' 
    for i in range(len(inputs)):
        payload += '{ "name": ' 
        payload += '"' + inputs[i]['name']  + '"'
        payload += ', "value": '
        #Check if value input is decimal or character
        if inputs[i]['type'] == 'decimal':
            #Add underscore to column names to match MAS parameter format
            payload += str(row[(inputs[i]['name']).replace('_','')])
        #Add quotation marks around character input values
        else: 
           #Add underscore to column names to match MAS parameter format
            payload += '"' + str(row[(inputs[i]['name']).replace('_','')])+ '"'
        if i != (len(inputs) -1):
            payload += "},"
        else: 
            payload += "}"
    payload += "] }"
    
    

    #Send Request to MAS 
    r = requests.request("POST", url, data = payload, headers = headers, verify=False)
    
    #Print Formatted Request 
    formatted_response = json.dumps(r.json(), indent=2)
    print(formatted_response)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12393803098450774, 'fraction_numerical': 0.0026653339996668335, 'mean_word_length': 4.5851162790697675, 'pattern_counts': {'":': 8, '<': 41, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '124975', 'license': 'Apache-2.0', 'n_tokens_mistral': 1830, 'n_tokens_neox': 1769, 'n_words': 543, 'path': 'python/mas-real-time-scoring/mas-real-time-scoring.ipynb', 'repo_name': 'sassoftware/rest-api-use-cases', 'size': '6003'}