def retrieve_workspace(iam_apikey=None,
                       workspace_id=None,
                       url=DEFAULT_PROD_URL,
                       api_version=DEFAULT_API_VERSION,
                       username=DEFAULT_USERNAME,
                       password=None,
                       export_flag=True):
    """
    Retrieve workspace from Assistant instance
    :param iam_apikey:
    :param workspace_id:
    :param url:
    :param api_version:
    :param username:
    :param password:
    :param export_flag:
    :return workspace: workspace json
    """

    if iam_apikey:
        authenticator = IAMAuthenticator(apikey=iam_apikey)
    elif username and password:
        authenticator = BasicAuthenticator(username=username,
                                           password=password)
    else:
        authenticator = NoAuthAuthenticator()

    conversation = ibm_watson.AssistantV1(authenticator=authenticator,
                                          version=api_version)

    if export_flag:
        ws_json = conversation.get_workspace(workspace_id, export=export_flag)
        return conversation, ws_json.get_result()
    return conversation
def retrieve_conversation(
    iam_apikey=None,
    url=DEFAULT_PROD_URL,
    api_version=DEFAULT_API_VERSION,
    username=DEFAULT_USERNAME,
    password=None,
    authenticator_url=DEFAULT_AUTHENTICATOR_URL,
):
    """
    Retrieve workspace from Assistant instance
    :param iam_apikey:
    :param url:
    :param api_version:
    :param username:
    :param password:
    :return workspace: workspace json
    """

    if iam_apikey:
        authenticator = IAMAuthenticator(apikey=iam_apikey,
                                         url=authenticator_url)
    elif username and password:
        authenticator = BasicAuthenticator(username=username,
                                           password=password)
    else:
        authenticator = NoAuthAuthenticator()

    conversation = ibm_watson.AssistantV1(authenticator=authenticator,
                                          version=api_version)
    conversation.set_service_url(url)

    return conversation
def retrieve_workspace(iam_apikey=None,
                       workspace_id=None,
                       url=DEFAULT_PROD_URL,
                       api_version=DEFAULT_API_VERSION,
                       username=DEFAULT_USERNAME,
                       password=None,
                       export_flag=True):
    """
    Retrieve workspace from Assistant instance
    :param iam_apikey:
    :param workspace_id:
    :param url:
    :param api_version:
    :param username:
    :param password:
    :param export_flag:
    :return workspace: workspace json
    """
    conversation = None

    if iam_apikey:
        if url == "https://gateway-s.watsonplatform.net/assistant/api":
            conversation = ibm_watson.AssistantV1(iam_apikey=iam_apikey,
                                                  url=url,
                                                  iam_url=STAGE_IAM_URL,
                                                  version=api_version)
        else:
            conversation = ibm_watson.AssistantV1(iam_apikey=iam_apikey,
                                                  url=url,
                                                  version=api_version)
    elif username and password:
        if url == "https://gateway-s.watsonplatform.net/assistant/api":
            conversation = ibm_watson.AssistantV1(username=username,
                                                  password=password,
                                                  url=url,
                                                  iam_url=STAGE_IAM_URL,
                                                  version=api_version)
        else:
            conversation = ibm_watson.AssistantV1(username=username,
                                                  password=password,
                                                  url=url,
                                                  version=api_version)

    if export_flag:
        ws_json = conversation.get_workspace(workspace_id, export=export_flag)
        return conversation, ws_json.get_result()
    return conversation
    def setup_class(cls):

        create_workspace_data = {
            "name":
            "test_workspace",
            "description":
            "integration tests",
            "language":
            "en",
            "intents": [{
                "intent": "hello",
                "description": "string",
                "examples": [{
                    "text": "good morning"
                }]
            }],
            "entities": [{
                "entity": "pizza_toppings",
                "description": "Tasty pizza toppings",
                "metadata": {
                    "property": "value"
                }
            }],
            "counterexamples": [{
                "text": "string"
            }],
            "metadata": {},
        }

        authenticator = IAMAuthenticator(os.getenv('ASSISTANT_APIKEY'))
        cls.assistant = ibm_watson.AssistantV1(version='2018-07-10',
                                               authenticator=authenticator)
        cls.assistant.set_default_headers({
            'X-Watson-Learning-Opt-Out': '1',
            'X-Watson-Test': '1'
        })

        response = cls.assistant.create_workspace(
            name=create_workspace_data['name'],
            description=create_workspace_data['description'],
            language='en',
            intents=create_workspace_data['intents'],
            entities=create_workspace_data['entities'],
            counterexamples=create_workspace_data['counterexamples'],
            metadata=create_workspace_data['metadata']).get_result()

        cls.workspace_id = response['workspace_id']

        examples = [{"text": "good morning"}]
        response = cls.assistant.create_intent(workspace_id=cls.workspace_id,
                                               intent='test_intent',
                                               description='Test intent.',
                                               examples=examples).get_result()
Beispiel #5
0
def cla(review):
    assistant = ibm_watson.AssistantV1(
        version='2019-02-28',
        iam_apikey='u1N9ThXmpZUk_-1_F1AaAw-11BbBXFtCbonmmerHbnFI',
        url='https://gateway-wdc.watsonplatform.net/assistant/api/')

    response = assistant.message(
        workspace_id='7cb1c0fc-6e91-4b63-9e93-8a30028bd58e',
        input={
            'text': review
        }).get_result()

    a = response
    b = a['intents']
    print(b)
def BankBot():

    # Create session with the Watson Assistant
    assistant = ibm_watson.AssistantV1(
        iam_apikey='PrLJLVykZG4V-FQrADLiZG91oOKcJN0UZWEUAo0HxW8Q',
        version='2018-09-20')

    # Pull the first prompt from the Dialog
    response = assistant.message(
        workspace_id='3e86c7a1-b071-4e6a-ada2-a8ac616e6aa6').get_result()

    # Continue prompting the user and getting their input, until they indicate
    # it's time to quit
    while True:

        # Get the text of the prompt
        prompt = response.get('output').get('text')

        # Display all of the text provided in the prompt
        for text in prompt:
            print(text)

        # Get the user's next utterance
        utterance = input("==> ")

        # Invoke Watson to assess the intent of the utterance and determine how
        # to respond to the user
        response = assistant.message(
            workspace_id='3e86c7a1-b071-4e6a-ada2-a8ac616e6aa6',
            input={
                'text': utterance
            },
            context=response.get('context')).get_result()

        # Ensure there are intents in the response.
        if len(response.get("intents")) > 0:

            #Check whether the dialog indicates an end to the conversation
            if response["intents"][0]["intent"] == "General_Ending":
                if len(response.get("output").get("text")) > 0:
                    # If there are any remaining messages in the response then
                    # print them out.
                    print(response.get("output").get("text")[0] + '\n')
                    # And terminate the conversation.
                    break
Beispiel #7
0
def myCommand(command):

    import ibm_watson
    '''r = sr.Recognizer()

    with sr.Microphone() as source:
        print('listening..')
        r.pause_threshold = 0.5
        r.adjust_for_ambient_noise(source, duration=1)
        audio = r.listen(source)

    
        
        
        command = r.recognize_google(audio).lower()
        '''

    if 'villa' in command or 'billa' in command:
        command = 'okay wheeler'
    print('You said: ' + command + '\n')
    assistant = ibm_watson.AssistantV1(
        version='2019-02-28',
        iam_apikey='u1N9ThXmpZUk_-1_F1AaAw-11BbBXFtCbonmmerHbnFI',
        url='https://gateway-wdc.watsonplatform.net/assistant/api')

    response = assistant.message(
        workspace_id='7cb1c0fc-6e91-4b63-9e93-8a30028bd58e',
        input={
            'text': command  #use the <text> we get with flask
        }).get_result()

    a = response
    b = a['intents']
    if b == []:
        intent = 'nothing'
    else:
        intent = b[0]['intent']

    return intent
def watsoninput(driver):
    #def watsoninput(txt):
    service = ibm_watson.AssistantV1(
        version='2019-02-28',
        iam_apikey='rHPoGMbSy7JGmQh3-nMKSSY7AbTeQ6PMh8i18DPaQdZb',
        url='https://gateway.watsonplatform.net/assistant/api')
    print("Test")
    root1 = Tk()
    topFrame = Frame(root1)
    # topFrame.pack(side= TOP)
    topFrame.pack()
    bottomFrame = Frame(root1)
    # bottomFrame.pack(side=BOTTOM)
    bottomFrame.pack()
    # VoiceFrame= Frame(root1)
    # VoiceFrame = Frame(root1)
    labelaccount = Label(topFrame, text="User Input")
    labelaccount.pack(padx=5, pady=20, side=LEFT)
    # labelaccount.pack(side=LEFT)
    # entryaccount = Entry(topFrame)
    # entryaccount.grid(row=0, column=1)
    txt = tkst.ScrolledText(bottomFrame, width=30, height=10)
    txt.pack(padx=10, pady=10, side=LEFT)
    txt1 = tkst.ScrolledText(bottomFrame, width=30, height=10)
    txt1.pack(padx=10, pady=30, side=LEFT)

    thread = threading.Thread(target=dialouge.messageft,
                              args=(
                                  txt,
                                  txt1,
                                  driver,
                                  service,
                              ))
    #thread = threading.Thread(target=watsonmessage.watsoninput, args=(txt, ))
    thread.start()

    root1.mainloop()
Beispiel #9
0
import ibm_watson
import os
import logging

# Configuring IBM-Watson Assistant
service = ibm_watson.AssistantV1(
    version='2019-02-28',
    iam_apikey=os.environ['API_KEY'],
)

# Configuring Database ENV
db_config = dict()
db_config["DB_HOST"] = os.environ['APP_DB_HOST']
db_config["DB_PORT"] = 27017
db_config["DB_USER"] = os.environ['APP_DB_USER']
db_config["DB_PASSWORD"] = os.environ['APP_DB_PASSWORD']
db_config["DB_NAME"] = os.environ['APP_DB_NAME']
db_config["USER_QUERY"] = "userquery"
Beispiel #10
0
def get_names():

    global c
    global intent
    c = 1
    if request.method == 'POST':
        resp_json = request.get_json()
        command = resp_json['text']
        if command == 'cplusplus':
            command = 'open c++'
    assistant = ibm_watson.AssistantV1(
        version='2019-02-28',
        iam_apikey='u1N9ThXmpZUk_-1_F1AaAw-11BbBXFtCbonmmerHbnFI',
        url='https://gateway-wdc.watsonplatform.net/assistant/api')

    response = assistant.message(
        workspace_id='7cb1c0fc-6e91-4b63-9e93-8a30028bd58e',
        input={
            'text': command  #use the <text> we get with flask
        }).get_result()

    a = response
    b = a['intents']
    if b == []:
        if c == 1:

            intent.append('nothing')
        else:
            intent.append('nothing')
    else:
        if c == 1:

            intent.append(b[0]['intent'])
        else:
            intent.append(b[0]['intent'])
    print('user said:', command)
    print(intent)

    while intent[0] == 'python':

        if intent[-1] == 'for_loop':
            to_send = """for x in range (a,b):
    #enter your code here"""
        elif intent[-1] == 'nested_for':
            to_send = """for x in range(a,b):
    for y in range(a,b):
        #enter your code here"""
        elif intent[-1] == 'if_condition':
            to_send = """if a==b:
    #enter your code here"""

        elif intent[-1] == 'nested_if':
            to_send = """if a==b:
    if a==b:
        #enter your code here
    else:
        #enter your code here"""

        elif intent[-1] == 'else_if':
            to_send = """if a>=b:
    #enter your code here
elif a==b:
    #enter your code here"""

        elif intent[-1] == 'else_condition':
            to_send = """elif a &gt;= b:
    #enter your code here
else:
    #enter your code here"""

        elif intent[-1] == 'while_loop':
            to_send = """while x == y:
    #enter your code here"""

        elif intent[-1] == 'do_while_loop':
            to_send = """a = 1
while True: #acts a the 'do' part.
    print(a)
    a+=3
    if(a > 10):
        break
#Python doesn't have a do-while loop. Hence emulating it with boolean."""

        elif intent[-1] == 'print':
            to_send = """print(#your variable or string) """

        elif intent[-1] == 'exit_loop':
            to_send = """    if (condition):
    break"""

        elif intent[-1] == 'init_string' or intent == 'init_char':
            to_send = """var=input()"""

        elif intent[-1] == 'init_int':
            to_send = """var=int(input())"""

        elif intent[-1] == 'init_double':
            to_send = """var=double(input())"""

        elif intent[-1] == 'arith_addition':
            to_send = """def add(a,b):
    return a+b
x=int(input())
y=int(input())
ans=add(x,y)
print(ans)"""

        elif intent[-1] == 'arith_subtraction':
            to_send = """def sub(a,b):
    return a-b
x=int(input())
y=int(input())
ans=sub(x,y)
print(ans)"""

        elif intent[-1] == 'arith_multiplication':
            to_send = """def multi(a,b):
    return a*b
x=int(input())
y=int(input())
ans=multi(x,y)
print(ans)"""

        elif intent[-1] == 'arith_division':
            to_send = """def divi(a,b):
    return a/b
x=int(input())
y=int(input())
ans=divi(x,y)
print(ans)"""

        elif intent[-1] == 'create_array':
            to_send = """var=[]
n=int(input())
for i in range(n):
    app=int(input())
    var.append(app)
print('the array is:',var)"""

        elif intent[-1] == 'def_function':
            to_send = """def func_name(#arguments):
    #write your code here
    return #any variable
x=func_name(#arguments)"""

        elif intent[-1] == 'cplus' or intent[-1] == 'swift' or intent[
                -1] == 'php':
            to_send = """Please Use the Change language option!"""

        elif intent[-1] == 'python':
            to_send = """python running!"""

        elif intent[-1] == 'recus':
            to_send = """def func(a):
    a+=1
    if a<=15:
        print(a)
        func(a) #recusion part.
    else:
        print('a exceeded the limit of 15!')
    return
func(9)"""

        elif intent[-1] == 'switch_condition':
            to_send = """switch={
    1:'monday',
    2:'tuesday',
    3:'wednesday',
    4:'thursday',
    5:'friday',
    6:'saturday',
    7:'sunday'
    }
day=int(input())
print(switch[day])
#python does't have the concept of switch, hence this is achieved using dictionaries."""

        else:
            to_send = """I am sorry, i dont know what that means"""

        c += 1
        return json.dumps({"response": to_send}), 200

########################################################c++#########################################################################################################################
    while intent[0] == 'cplus':
        if intent[-1] == 'for_loop':
            to_send = """for(int x=a ; x&lt;b ; x++) {
    //enter your code; 
}"""

        elif intent[-1] == 'print':
            to_send = """cout << "Enter your string here!" << endl; """

        elif intent[-1] == 'nested_for':
            to_send = """for(int x=a;x&lt;b;x++) {
for(int y=c;y&lt;d;y++) {
    //enter your code; 
}
}"""

        elif intent[-1] == 'if_condition':
            to_send = """int x;
if(x==a) {
    //enter your code; 
}"""

        elif intent[-1] == 'nested_if':
            to_send = """int x,y;
    if(x==a) {
    if(y==a) {
       //enter your code;  
    }
}"""

        elif intent[-1] == 'else_if':
            to_send = """int x;
if(x==a) {
//enter your code; 
}
else if(x==b) {
//enter your code; 
}"""

        elif intent[-1] == 'else_condition':
            to_send = """int x;
if(x==a) {
//enter your code;  
}
else {
//enter your code;  
}"""

        elif intent[-1] == 'while_loop':
            to_send = """while(x!=a) {
//enter your code; 
}"""

        elif intent[-1] == 'exit_loop':
            to_send = """break;"""

        elif intent[-1] == 'do_while_loop':
            to_send = """int x;
do {
//enter your code;  
} while(x&lt;a);"""

        elif intent[-1] == 'init_string':
            to_send = """string x;"""

        elif intent[-1] == 'init_int':
            to_send = """int x;"""

        elif intent[-1] == 'init_char':
            to_send = """char name[100];"""

        elif intent[-1] == 'init_float':
            to_send = """float x;"""

        elif intent[-1] == 'arith_addition':
            to_send = """#include &lt;iostream&gt; 
using namespace std;
int main() {
    int x,y,sum;
    cin>>x>>y;
    sum = x+y;
    cout<<"Sum is: "<< sum << endl;
return 0;
}"""

        elif intent[-1] == 'arith_subtraction':
            to_send = """#include &lt;iostream&gt;
using namespace std;
int main() {
    int x,y,diff;
    cin>>x>>y;
    diff = x-y;
    cout<<"Difference is: "<< diff << endl;
return 0;
}"""

        elif intent[-1] == 'arith_multiplication':
            to_send = """#include &lt;iostream&gt;
using namespace std;
int main() {
    int x,y,prod;
    cin>>x>>y;
    prod = x*y;
    cout<<"Product is: "<< prod << endl;
return 0;
}"""

        elif intent[-1] == 'arith_division':
            to_send = """#include &lt;iostream&gt;
using namespace std;
int main() {
    int x,y,quo;
    cin>>x>>y;
    quo = x/y;
    cout<<"Quotient is: "<< quo << endl;
return 0;
}"""

        elif intent[-1] == 'arith_remainder':
            to_send = """#include &lt;iostream&gt;
using namespace std;
int main() {
    int x,y,rem;
    rem = x%y;
    cout<<"Remainder is: "<< rem << endl;
return 0;
}"""

        elif intent[-1] == 'def_function':
            to_send = """#include &lt;iostream&gt;
// function declaration
int func(int x, int y);
int main () {
    // local variable declaration
    int a,b;
    // calling a function.
    func(a,b);
return 0;
}
// function
int func(int x, int y) {
    //enter your code;
}"""

        elif intent[-1] == 'create_class':
            to_send = """class base { 
// Access specifier 
public:  
// Data Members 
string name; 
// Member Functions() 
void printname() { 
    cout <<"Name is: "<<name; 
} 
};"""

        elif intent[-1] == 'create_object':
            to_send = """// Declare an object of class base 
base obj1;"""

        elif intent[-1] == 'include_lib_basic':
            to_send = """#include &lt;iostream&gt;
#include &lt;conio.h&gt;
#include &lt;string.h&gt;
#include &lt;math.h&gt;
#include &lt;ctype.h&gt;
#include &lt;stdlib.h&gt;"""

        elif intent[-1] == 'include_lib_adv':
            to_send = """#include <vector>
#include &lt;string&gt;
#include &lt;file&gt;
#include &lt;map&gt;
#include &lt;complex&gt;"""

        elif intent[-1] == 'create_array':
            to_send = """int a[100] , x , b;
cout << "Enter array size:" << endl;
cin >> b;
cout << " Enter array elements: " << endl;
for (x=a ; x &lt; b ; x++) {
    cin >> a[x] ;
}
cout << "Array is: " << endl;
for(x=a ; x &lt; b ; x++) {
    cout << a[x] ;
}"""

        elif intent[-1] == 'switch_condition':
            to_send = """char variable;
switch(variable) { 
case valueOne: 
//statements 
break; 
case valueTwo: 
//statements
break; 
default: //optional
//statements
}"""
        elif intent[-1] == 'swift' or intent[-1] == 'python' or intent[
                -1] == 'php':
            to_send = """Please Use the Change language option!"""

        elif intent[-1] == 'cplus':
            to_send = """running c++"""

        else:
            to_send = """I am sorry, i dont know what that means"""

        c += 1
        return json.dumps({"response": to_send}), 200


########################################################PHP#########################################################################################################################
    while intent[0] == 'php':
        if intent[-1] == 'for_loop':
            to_send = """for ($x = a; $x <= b; $x++) {
//enter your code
} """

        elif intent[-1] == 'print':
            to_send = """ echo " Enter your string here ! " ; """

        elif intent[-1] == 'nested_for':
            to_send = """for ($x = a; $x <= b; $x++) {
    for ($y = c; $y <= d; $y++) {
        //enter your code;
        }
}"""

        elif intent[-1] == 'if_condition':
            to_send = """$t = "varable";
if ($t < "Condition") {
    //enter your code;
    }"""

        elif intent[-1] == 'nested_if':
            to_send = """$x = "variable";
$y = "Variable"
if($x=="condition") {
    if($y=="condition") {
        //enter your code;
    }
}"""

        elif intent[-1] == 'else_if':
            to_send = """$x = "variable";
if($x==a) {
    //enter your code;
}
else if($x==b) {
    //enter your code;
}
else if($x==c) {
    //enter your code;
}"""

        elif intent[-1] == 'else_condition':
            to_send = """$x = "Variable";
if($x==a) {
    //enter your code;
}
else {
    //enter your code;
}"""

        elif intent[-1] == 'while_loop':
            to_send = """while($x!="condition") {
    //enter your code;
}"""

        elif intent[-1] == 'exit_loop':
            to_send = """break;"""

        elif intent[-1] == 'do_while_loop':
            to_send = """$x = "variable";
do {
    //enter your code;
} while($x<"condition");"""

        elif intent[-1] == 'init_string':
            to_send = """string $x; """

        elif intent[-1] == 'init_int':
            to_send = """int $x; """

        elif intent[-1] == 'init_char':
            to_send = """char name[100];"""

        elif intent[-1] == 'init_float':
            to_send = """float $x; """

        elif intent[-1] == 'arith_addition':
            to_send = """<?php
function add(float $x,float $y){
    return $x+$y;
}
?>"""

        elif intent[-1] == 'arith_subtraction':
            to_send = """<?php
function add(float $x,float $y){
    return $x-$y;
}
?>"""

        elif intent[-1] == 'arith_multiplication':
            to_send = """<?php
function add(float $x,float $y){
    return $a*$b;
}
?>"""

        elif intent[-1] == 'arith_division':
            to_send = """<?php
function add(float $x,float $y){
    return $a/$b;
}
?>"""

        elif intent[-1] == 'arith_remainder':
            to_send = """<?php
function add(float $x,float $y){
    return $a%$b;
}
?>"""

        elif intent[-1] == 'def_function':
            to_send = """<?php
function add(float $x,float $y){
    //enter your code
    return "Your Output";
}
add($x,$y);
?>"""

        elif intent[-1] == 'create_array':
            to_send = """int a[100],x,b;
echo 'Enter array size:';
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
echo 'Enter array elements:';
for(x=a;x<b;x++) {
    a[x]=fgets($handle);
}
echo 'Array is: ' ;
for($x=a;$x<b;$x++) {
    echo $a[$x];
}"""

        elif intent[-1] == 'switch_condition':
            to_send = """$x = "variable";
switch ($x) {
    case "1":
        //enter your code
        break;
    case "2":
        //enter your code
        break;
    case "3":
        //enter your code
        break;
    default: //optional
        //default return code;
}"""

        elif intent[-1] == 'cplus' or intent[-1] == 'python' or intent[
                -1] == 'swift':
            to_send = """Please Use the Change language option!"""

        elif intent[-1] == 'php':
            to_send = """running php"""

        else:
            to_send = """I am sorry, i dont know what that means"""

        c += 1
        return json.dumps({"response": to_send}), 200

    ######################################################## SWIFT #########################################################################################################################

    while intent[0] == 'swift':
        if intent[-1] == 'for_loop':
            to_send = """for i in a...b {
    //enter your code here
} """

        elif intent[-1] == 'print':
            to_send = """ print(//enter your code) """

        elif intent[-1] == 'nested_for':
            to_send = """for i in a...b {
    for j in a...b{
        //enter your code here
    }
}"""

        elif intent[-1] == 'if_condition':
            to_send = """let a = 10
if a &lt; b {
	//enter your code
}
//print("This statement is always executed.")"""

        elif intent[-1] == 'nested_if':
            to_send = """let a = 10
if a &gt; b {
	if a &gt; b {
	    //enter your code
    }
}
//print("This statement is always executed.")
"""

        elif intent[-1] == 'else_if':
            to_send = """let a = 10
if a &gt; b {
	//enter your code
} else if a &gt; b {
	//enter your code
}
//print("This statement is always executed.")
"""

        elif intent[-1] == 'else_condition':
            to_send = """let a = 10
if a &gt; b {
    //enter your code
}
else {
    //enter your code
}"""

        elif intent[-1] == 'while_loop':
            to_send = """while a <= b {
    //enter your code 
}"""

        elif intent[-1] == 'exit_loop':
            to_send = """if a &gt; b {
    break
}"""

        elif intent[-1] == 'do_while_loop':
            to_send = """repeat {
    var i = 1
    //enter your code here.
    i = i + 1
} while a &lt; b"""

        elif intent[-1] == 'init_string':
            to_send = """var your_string = 'change it here' """

        elif intent[-1] == 'init_int':
            to_send = """var your_integer = 0 """

        elif intent[-1] == 'init_char':
            to_send = """var your_char = 'C' """

        elif intent[-1] == 'init_float':
            to_send = """var your_float = 0.00 """

        elif intent[-1] == 'arith_addition':
            to_send = """func add(a: Int , b: Int) -> Int {
    let sum = a + b
    return sum
}
print("sum is" , add(a: 2, b: 4), separator: " ")"""

        elif intent[-1] == 'arith_subtraction':
            to_send = """func sub(a: Int , b: Int) -> Int {
    let diff = a - b
    return diff
}
print("diff is" , sub(a: 10, b: 4), separator: " ")"""

        elif intent[-1] == 'arith_multiplication':
            to_send = """func multi(a: Int , b: Int) -> Int {
    let prod = a * b
    return prod
}
print("product is" , multi(a: 2, b: 4), separator: " ")"""

        elif intent[-1] == 'arith_division':
            to_send = """func divi(a: Int , b: Int) -> Int {
    let diff = a / b
    return diff
}
print("quotient is" , divi(a: 19, b: 4), separator: " ")"""

        elif intent[-1] == 'arith_remainder':
            to_send = """func modu(a: Int , b: Int) -> Int {
    let mod = a % b
    return mod
}
print("reminder is" , modu(a: 18, b: 4), separator: " ")"""

        elif intent[-1] == 'def_function':
            to_send = """func your_func_name(a: Int , b: Int) -> String {
    //enter your code
    if a &gt; b{
        The_final_output = "Edit this function"
    }
    return The_final_output
}
print("output:" , your_func_name(a: 18, b: 4), separator: " ")"""

        elif intent[-1] == 'recus':
            to_send = """func your_fun(a: Int) -> String {
    var a = a + 1
    if a <= 15 {
        print(a)
        your_fun(a: a)
        }
    else{
        print("a has exceeded the limit of 15")
    }
    return ""
}
print(your_fun(a: 9))"""

        elif intent[-1] == 'create_array':
            to_send = """var your_array = [1,2,3,4,5,6]
print(your_array)"""

        elif intent[-1] == 'switch_condition':
            to_send = """let someCharacter: Character = "z" // or someinteger: Int = 2
switch someCharacter {
case "a": // case 1:
    // enter your code
case "z": // case 2:
    // enter your code
default:
    // default reply
}"""

        elif intent[-1] == 'cplus' or intent[-1] == 'python' or intent[
                -1] == 'php':
            to_send = """Please Use the Change language option!"""

        elif intent[-1] == 'swift':
            to_send = """running swift"""

        else:
            to_send = """I am sorry, i dont know what that means"""

        c += 1
        return json.dumps({"response": to_send}), 200

    c += 1
    return json.dumps({"response":
                       'Come back later for that language :) '}), 200
Beispiel #11
0
###################################################################
######## Slack configuration   ##########################
###################################################################

SLACK_BOT_TOKEN = '******'
SLACK_VERIFICATION_TOKEN = '******'

# instantiate Slack client
slack_client = SlackClient(SLACK_BOT_TOKEN)  # do not change this parameter

###################################################################
######## Watson service configuration   ##########################
###################################################################

service = ibm_watson.AssistantV1(
    iam_apikey='*********',  # replace with Password
    version='2018-09-20')
workspace_id = '**********'  # replace with Assistant ID

###################################################################
######## MySQL Database connection   ##########################
###################################################################

try:
    conn = mysql.connector.connect(host="localhost",
                                   user="******",
                                   password="******",
                                   database="sc_data")
    if conn.is_connected():
        print('Connected to MySQL database')
    else:
import json
import ibm_watson

assistant = ibm_watson.AssistantV1(
    version='2019-02-28',
    iam_apikey='{apikey}',
    url='{url}'
)

response = assistant.message(
    workspace_id='{workspace_id}',
    input={
        'text': 'quem é fulano'
    }
).get_result()

print(response['intents'][0]['intent']+"  "+str(response['intents'][0]['confidence']))
Beispiel #13
0
import json
import ibm_watson




ACCESS_TOKEN = Keys.ACCESS_TOKEN
VERIFY_TOKEN = Keys.VERIFY_TOKEN
WATSON_API = Keys.WATSON_API
bot = Bot(ACCESS_TOKEN)



watson = ibm_watson.AssistantV1(
        version='2019-02-28',
        iam_apikey=WATSON_API,
        url='https://gateway-fra.watsonplatform.net/assistant/api')


#%% Webhook
@app.route('/',methods=['GET','POST'])
def receive_message():
    if request.method == 'GET':
        token_sent= request.args.get("hub.verify_token")
        return verify_fb_token(token_sent)


    else:
        output = request.get_json()
        for event in output['entry']:
            messaging = event['messaging']
Beispiel #14
0
###################################################################
SLACK_BOT_NAME = 'Your_Bot_Name_HERE'

SLACK_BOT_TOKEN = 'xoxb-xxxxxxxxxxxx-xxxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx'  # copy from "Install App" -> "Bot User OAuth Access Token"
SLACK_VERIFICATION_TOKEN = 'xxxxxxxxxxxxxxxxxxxxxxxx'  # copy from "Basic Infromation" -> "App Credential" -> "Verication Token"

# instantiate Slack client
slack_client = SlackClient(SLACK_BOT_TOKEN)  # do not change this parameter

###################################################################
######## Watson service configuration   ##########################
###################################################################

service = ibm_watson.AssistantV1(
    iam_apikey='xxxxxxxxxxxxxxxxxxxxxxxx',  # replace with Password/ API KEY
    url=
    'https://xxxxxxxxxx.watsonplatform.net/assistant/api',  # replace with Watson Assistant's Credentials - URL
    version='2018-09-20')

workspace_id = 'xxxxxxxxxxxxxxxxxxxxxxxx'  # replace with Worksapce ID

###################################################################
######## Log files configuration   ##########################
###################################################################

log_commands_path = location + "logs/log_commands.py"  # do not change this parameter
follow_up_path = location + "logs/followup_email.py"  # do not change this parameter

###################################################################
######## Temp files configuration   ##########################
###################################################################
Beispiel #15
0
def get_names():

    if request.method == 'POST':
        resp_json = request.get_json()
        command = resp_json['text']
        if 'chick' in command or 'mick' in command:
            command= 'okay loco'
        else:
            command= command
    assistant = ibm_watson.AssistantV1(
    version='',
    iam_apikey='',
    url=''
    )

    response = assistant.message(
        workspace_id='',
        input={
            'text': command
        }
    ).get_result()


    a=response
    b=a['intents']
    if b==[]:
        intent= 'not_found'
    else:
        intent = b[0]['intent']
    print('the intent is:' , intent)
    def currentloc():
        send_url = "http://api.ipstack.com/check?access_key="
        geo_req = requests.get(send_url)
        geo_json = json.loads(geo_req.text)
        latitude = geo_json['latitude']
        longitude = geo_json['longitude']
        return [latitude,longitude]

    if intent=='weather':
        latt,long = currentloc()
        endpoint = 'http://api.openweathermap.org/data/2.5/forecast?'
        api_key = ''

        nav_request = 'lat={}&lon={}&APPID={}'.format(latt, long, api_key)
        reequest = endpoint + nav_request
        response = urllib.request.urlopen(reequest).read().decode('utf-8')
        weather = json.loads(response)
        current_temp = weather['list'][0]['main']['temp']
        temp_c = current_temp - 273.15
        temp_c_str = str(int(temp_c)) + ' degree Celsius '
        descript_place = weather['list'][0]['weather'][0]['main']
        if descript_place == 'Clouds':
            descript_place = 'overcast'
        print('It is a little '+descript_place + ' and temperature outside is, ' + temp_c_str +" "+str(latt)+" "+str(long))
        return json.dumps({"response": 'It is a little '+descript_place + ' and temperature outside is, ' + temp_c_str+" "+str(latt)+" "+str(long)}), 200
    elif intent == 'call':

        print("tirgger")
        client = nexmo.Client(key='', secret='')
        client.send_message({'from': 'Nexmo', 'to': '+919082180627', 'text': 'Hello there, your patient needs your assistance please report immediately.'})
        {'message-count': '1', 'messages': [{'to': '+919082180627', 'message-id': '0D00000039FFD940', 'status': '0', 'remaining-balance': '14.62306950', 'message-price': '0.03330000', 'network': '12345'}]}
        return json.dumps({"response": "I will let your nurse know that you need their assistance"}), 200


    elif intent=='person':
        thisdict={
        1:"priyanka.jpeg",
        2:"sneha.jpg",


            }
        n=2
        f=0

        ch='y'
        while(ch=='y'):

            camera = cv2.VideoCapture(0)
            return_value, image = camera.read()
            cv2.imwrite('t.jpeg', image)
            del(camera)


            sourceFile='t.jpeg'
            for i in range(1,n+1):

                targetFile= thisdict[i]
                client=boto3.client('rekognition')

                imageSource=open(sourceFile,'rb')
                imageTarget=open(targetFile,'rb')

                response=client.compare_faces(SimilarityThreshold=70,SourceImage={'Bytes': imageSource.read()},TargetImage={'Bytes': imageTarget.read()})
                print(response)
                f=2
                for faceMatch in response['FaceMatches']:
                    f=1
                    nameee=''
                    for i in targetFile:
                        if i != '.':
                            nameee+=i
                        else:
                            break

                    os.remove("t.jpeg")
                    return json.dumps({"response": 'This is' + ' ' + nameee + ', '+ ' who\'s come to visit you! '
                            }), 200
                imageSource.close()
                imageTarget.close()
            if(f!=1):
                return json.dumps({"response": 'This person doesn\'t exist in our database. Would you like to add him? '
                            }), 200

    elif 'add' in command:
        camera = cv2.VideoCapture(0)
        return_value, image = camera.read()
        cv2.imwrite('new.jpeg', image)
        del(camera)
        namee= command[4::1]
        namee= namee+ ".jpeg"
        n=n+1
        os.rename("new.jpeg", namee)
        d1={n:namee}
        thisdict.update(d1)

    elif intent=='text':
        new=[]
        camera = cv2.VideoCapture(0)
        return_value, image = camera.read()
        cv2.imwrite('t1.jpeg', image)
        del(camera)

        s3 = boto3.resource('s3')
        images=[('t1.jpeg','test'),]

        for image in images:
            file = open(image[0],'rb')
            object = s3.Object('text-identifier',image[0])
            ret = object.put(Body=file,
                                Metadata={'Name':image[1]}
                                )



        bucket='text-identifier'
        photo='t1.jpeg'
        client=boto3.client('rekognition')
        response=client.detect_text(Image={'S3Object':{'Bucket':bucket,'Name':photo}})
        textDetections=response['TextDetections']

        stuff=' '
        for text in textDetections:
            if(' ' in text['DetectedText']):
                stuff+= text['DetectedText'] +'\n'

        print(stuff)

        return json.dumps({"response": stuff}), 200

        s3.Object('aags-wheeler1', 'test1.jpeg').delete()

    elif intent=='news':
        def NewsFromBBC():
            global new
            new=[]
            main_url = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey="
            open_bbc_page = requests.get(main_url).json()
            article = open_bbc_page["articles"]
            results = []
            for ar in article:
                results.append(ar["title"])

            for i in range(0,3):
                stuff= str(str((i+1)) +'. '+ results[i])
                new.append(stuff)
            return new
        new = NewsFromBBC()
        news=' '
        for i in new:
            news+=i+',\n'+'\n'
        return json.dumps({"response": news})

    elif intent=='navigate_home':
        start=[-73.996,40.732]
        end=[-73.991,40.735]
        url = "https://api.mapbox.com/directions/v5/mapbox/walking/" + str(start[0]) + "," + str(start[1]) + ";" + str(end[0]) + "," + str(end[1]) + "?steps=true&geometries=geojson&access_token=pk.eyJ1IjoidGxhenlwYW5kYSIsImEiOiJjazZlZThiNDkxandsM2VtZ282dWhrNnpuIn0.MA9TNuCLK_rdaQVij5k6_w"
        results = requests.get(url)
        string =''
        print(results.json())
        result = results.json()
        steps = result['routes'][0]['legs'][0]['steps']
        for i in range(len(steps)):
            print(steps[i]['maneuver']['instruction'])
            string = string + str(i+1) + ". "+  steps[i]['maneuver']['instruction']+'\n'
        return json.dumps({"response":string})

    else:
        return json.dumps({"response":'Need some help go ahead'}), 200
Beispiel #16
0
###########################################################
# Author: Morgan Langlais, IBM
# Contact: [email protected]
# This script will delete ALL skills in
# the indicated Watson Assistant instance
###########################################################

import json
import ibm_watson
from ibm_watson import ApiException
from ibm_cloud_sdk_core.authenticators import IAMAuthenticator

wa_target_credentials = {'wa_version':'2020-04-01', 'wa_apikey':'123apikey', 'wa_url':'https://api.us-south.assistant.watson.cloud.ibm.com/instances/123myinstanceid'}

authenticator_target = IAMAuthenticator(wa_target_credentials['wa_apikey'])

assistant_service = ibm_watson.AssistantV1(
    version = wa_target_credentials['wa_version'],
    authenticator = authenticator_target
)
assistant_service.set_service_url(wa_target_credentials['wa_url']);

list_wrkspc_response = assistant_service.list_workspaces().get_result()['workspaces']

for space in list_wrkspc_response:
  response=assistant_service.delete_workspace(
      workspace_id=space['workspace_id']
  ).get_result()

  print(json.dumps(response, indent=2))
Beispiel #17
0
import json
import ibm_watson
assistant = ibm_watson.AssistantV1(
    version='2019-02-28',
    iam_apikey='u1N9ThXmpZUk_-1_F1AaAw-11BbBXFtCbonmmerHbnFI',
    url='https://gateway-wdc.watsonplatform.net/assistant/api')

response = assistant.message(
    workspace_id='f5c5d93f-4f4b-46d6-b882-0baf0bf6c0a7',
    input={
        'text':
        'The session was amazing. I understood all the concepts clearly'
    }).get_result()
#print(response)
#print(json.dumps(response, indent=2))

a = response
b = a['intents']
if b == []:
    intent = 0
else:
    intent = b[0]['intent']
print(intent)
def BankBot(research_URL=None):
    def speakAndPrint(text):
        print("Watson: {}".format(text))
        textSpeech(text=text, voice=voice, session=speechSession)

    # Create session with the Watson Assistant
    assistant = ibm_watson.AssistantV1(
        iam_apikey='PrLJLVykZG4V-FQrADLiZG91oOKcJN0UZWEUAo0HxW8Q',
        version='2018-09-20')
    workspace_id = "beb32203-c974-46dd-997f-f91f0968acf5"

    # Get a session to NLU
    nluSession = initNLU()

    # Prep speech output
    speechSession = initTextSpeech()
    voice = 'en-US_AllisonVoice'

    # Prep voice input
    confidence_threshold = 50  # Watson must be greater than this confidence to accept the voice input
    # Create a control object
    SPEECH_CONTROL = StreamSpeechControl()

    # Prepare a thread to recognize the input from the microphone input
    recognize_thread = Thread(target=recognizeUsingWebsocket,
                              args=(SPEECH_CONTROL, ))
    recognize_thread.start()

    # Prep working session
    document_of_interest = ""
    entity_of_interest = ""

    # Pull the first prompt from the Dialog
    response = assistant.message(workspace_id).get_result()

    # Get the text of the prompt
    prompt = response.get("output").get("text")
    context = response.get("context")

    # Display and Say all of the text provided in the prompt
    for text in prompt:
        speakAndPrint(text)

    # Continue prompting the user and getting their input, until they indicate
    # it's time to quit
    while True:

        # Get the user's next utterance
        # First test for voice input

        # Get instances of the needed microphone stream
        microphoneStream = SPEECH_CONTROL.initAudio()

        # Wait for the speech service to transcribe input from the user
        while not SPEECH_CONTROL.MYCALLBACK.isTextTranscribed():
            pass

        # Process the transcribed input
        transcript = SPEECH_CONTROL.MYCALLBACK.getTranscription(True)

        # Turn off the microphone while the transcribed text is being processed
        SPEECH_CONTROL.terminateAudio(microphoneStream)

        # Figure out the confidence of the resulting text
        confidence = int(round(100 * transcript[0].get("confidence")))
        utterance = transcript[0].get("transcript")
        print("You: " + utterance)

        if confidence < confidence_threshold:
            print("Watson had poor confidence in what you said.")
            utterance = "Garbage"

        # Invoke Watson to assess the intent of the utterance and determine how
        # to respond to the user
        response = assistant.message(workspace_id,
                                     input={
                                         'text': utterance
                                     },
                                     context=context).get_result()

        # Get the text and context of the response
        response_text = response.get("output").get("text")
        context = response.get("context")

        # Display and Say all of the text provided in the response
        for text_line in response_text:
            speakAndPrint(text_line)

        # Ensure there are intents in the response.
        if len(response.get("intents")) > 0:

            # Check whether the dialog indicates an end to the conversation
            if response["intents"][0]["intent"] == "Done":
                # Terminate the conversation.
                break

            # Otherwise, process the other intents that may have been expressed

            # Process the #Document-Of-Interest intent
            elif (response["intents"][0]["intent"] == "Document-Of-Interest"
                  ) and (context.get("research_document")):
                document_of_interest = response.get("context").get(
                    "research_document")

            # Process the #Document-Of-Interest intent and prompt for the document URL if needed
            elif (response["intents"][0]["intent"] == "Document-Of-Interest"):
                try:
                    research_URL = raw_input(
                        "What URL do you want to research? ==> ")
                except NameError:
                    research_URL = input(
                        "What URL do you want to research? ==> ")
                utterance = "Let's do research on the document at: " + research_URL
                response = assistant.message(workspace_id,
                                             input={
                                                 'text': utterance
                                             },
                                             context=context).get_result()
                # Get the text and context of the response
                response_text = response.get("output").get("text")
                context = response.get("context")
                # Display and Say all of the text provided in the response
                for text_line in response_text:
                    speakAndPrint(text_line)

            # Summarize the document
            elif (response["intents"][0]["intent"] == "Summarize-Document"
                  ) and (context.get("research_document")):
                # Enumrate the article content
                article_text = getText(research_URL, session=nluSession)
                print(article_text)
                # Enumerate the enties found in the document
                entities = preprocessEntities(
                    getEntities(research_URL, limit=5, session=nluSession))
                if len(entities) > 0:
                    speakAndPrint("The following entities were found:")
                    text_line = ''
                    for i in range(len(entities) - 1):
                        text_line = text_line + entities[i].get("text") + ", "
                    if len(entities) > 1:
                        text_line = text_line + "and "
                        text_line = text_line + entities[len(entities) -
                                                         1].get("text")
                    speakAndPrint(text_line)
                else:
                    speakAndPrint("No entites were mentioned in the document")
                # Enumerate the document categories
                categories = getCategories(research_URL, session=nluSession)
                speakAndPrint("The article spoke about these concepts:")
                for concept in categories:
                    speakAndPrint(concept.get("label"))

            # Process the #Entity-Of-Interest intent
            elif (response["intents"][0]["intent"] == "Entity-Of-Interest"
                  ) and (context.get("research_entity")):
                entity_of_interest = disambiguateEntity(
                    response.get("context").get("research_entity"), entities)

            # Process the #Entity-Personality intent
            elif response["intents"][0]["intent"] == "Entity-Personality":
                entity_twitter = entity2twitter(entity_of_interest)
                if entity_twitter == None:
                    speakAndPrint(
                        "Sorry, I couldn't find a twitter handle for " +
                        entity_twitter["text"])
                else:
                    speakAndPrint(
                        "Here's a twitter-based personality analysis for " +
                        entity_twitter["text"])
                    print(
                        prettyPrintProfile(getProfile(tweets(entity_twitter))))

        # Process the #Entity-Tone intent
            elif response["intents"][0]["intent"] == "Entity-Tone":
                speakAndPrint("The sentiment of " +
                              entity_of_interest["text"] + " is " +
                              entity_of_interest["sentiment"]["label"] +
                              " with an intensity of " +
                              str(entity_of_interest["sentiment"]["score"]))

            # Process the #Classify-Text intent
            elif response["intents"][0]["intent"] == "Classify-Text":
                categories = getCategories(research_URL, session=nluSession)
                speakAndPrint(
                    "The document generally falls into the following categories:"
                )
                for (category_index, category) in enumerate(categories):
                    speakAndPrint("Category " + str(category_index) + " : " +
                                  category["label"])

            # Process the #Translate-Research intent
            elif (response["intents"][0]["intent"] == "Translate-Research"
                  ) and (context.get("translation_language")):
                article_text = getText(research_URL, session=nluSession)
                translated_article = translate(
                    article_text,
                    response.get("context").get("translation_language"))
                speakAndPrint("I've translated your document to " +
                              context.get("translation_language"))
                print(translated_article)

        if SPEECH_CONTROL.SESSION_ENDED == True:
            # The speech session ended prematurely
            break

    # Shut down the input to the SpeechSocket
    SPEECH_CONTROL.AUDIO.terminate()
    SPEECH_CONTROL.AUDIO_SOURCE.completed_recording()
Beispiel #19
0
import os
import time
#from dotenv import load_dotenv
from slackclient import SlackClient
import ibm_watson
from caring.caring import CaringBot

if __name__ == "__main__":
   
   
  ########################################################################################################################
  # Start Watson Assistant service using your credentials
  ########################################################################################################################
  conversation_client = ibm_watson.AssistantV1(
    iam_apikey = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', # replace with apikey
    url = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', # replace with Watson Assistant's Credentials - URL
    version = '2018-09-20'
  )
  workspace_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # replace with Skill ID
  
  ########################################################################################################################
  # Start Watson Tone Analyser service using your credentials
  ########################################################################################################################
  tone_analyser = ibm_watson.ToneAnalyzerV3(
    version='2017-09-21',
    url='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', #replace with gateway URL
    iam_apikey='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  #replace with apikey
  )

  ########################################################################################################################
  # Start Watson Discovery service using your credentials
import json
import ibm_watson
#from _future_ import print_function
import json
import os

service = ibm_watson.AssistantV1(
    version='2019-02-28',
    iam_apikey='rHPoGMbSy7JGmQh3-nMKSSY7AbTeQ6PMh8i18DPaQdZb',
    url='https://gateway.watsonplatform.net/assistant/api')
'''
response=service.create_workspace(
    name='watson assistant',
    description='Example workspace created via API'
).get_result()
# '''
#Q = raw_input("How may i help you: ")
'''
inputtext = service.message(
	#workspace_id = 'b918a20c-a6cb-40af-b428-0f1101436259',
	workspace_id = '19580f54-86d0-45a4-a418-6b02bd93c711',
	input = {
		'text' : 'collision tweets on the 401'
	}
).get_result()
'''


def createintent(str):
    intent = service.create_intent(
        workspace_id='9874ed31-4034-444a-9a9a-f1607c806801',
Beispiel #21
0
def watson_conversation(username, password, version):
    conversation = ibm_watson.AssistantV1(username=username,
                                          password=password,
                                          version=version)
    return conversation
Beispiel #22
0
from ibm_watson import NaturalLanguageUnderstandingV1
from ibm_watson.natural_language_understanding_v1 \
    import Features, EntitiesOptions, KeywordsOptions, ConceptsOptions, SentimentOptions, EmotionOptions

# Appel de l'instance NLU
naturalLanguageUnderstanding = NaturalLanguageUnderstandingV1(
    version='2018-11-16',
    iam_apikey='xxx',
    url=
    'https://gateway-fra.watsonplatform.net/natural-language-understanding/api'
)

#Appel de l'instance Chatbot (Assistant)

assistant = ibm_watson.AssistantV1(
    iam_apikey='xxx',
    version='2018-09-20',
    url='https://gateway-fra.watsonplatform.net/assistant/api')

#Importation modules NLC
from ibm_watson import NaturalLanguageClassifierV1

# Appel de l'instance NLC
natural_language_classifier = NaturalLanguageClassifierV1(
    iam_apikey='xxx',
    url='https://gateway-fra.watsonplatform.net/natural-language-classifier/api'
)


def main(params):

    text = params['text'].replace("\n", "")
Beispiel #23
0
from flask import Flask, request
from pymessenger import Bot
import random
import ibm_watson
from utils import entity_to_nutri, get_nparr

app = Flask(__name__, static_folder='static')

app.config.from_pyfile('configs/constants.py')

bot = Bot(app.config['FACEBOOK_ACCESS_TOKEN'])

assistant = ibm_watson.AssistantV1(version='2019-02-28',
                                   iam_apikey=app.config['ASSISTANT_API_KEY'],
                                   url=app.config['ASSISTANT_URL'])

nparr = get_nparr()
nparr = [tmp[0] for tmp in nparr]


@app.route("/", methods=['GET', 'POST'])
def receive_message():
    if request.method == 'GET':
        """Before allowing people to message your bot, Facebook has implemented a verify token
        that confirms all requests that your bot receives came from Facebook."""
        token_sent = request.args.get("hub.verify_token")
        return verify_fb_token(token_sent)
    #if the request was not get, it must be POST and we can just proceed with sending a message back to user
    else:
        # get whatever message a user sent the bot
        output = request.get_json()
Beispiel #24
0
##====================================================================
# This file used to connect IBM watson assistant by API, for chatbot
##====================================================================

import ibm_watson

service = ibm_watson.AssistantV1(
    iam_apikey = '_K2FiFz17kUwgtW2lJQSK2DnZQvpktJE7CIuA2iSz_9F', # replace with Password/ API KEY
    url = 'https://gateway-syd.watsonplatform.net/assistant/api', # replace with Watson Assistant's Credentials - URL
    version = '2018-09-20'
)

workspace_id = '7de4544a-1944-4559-895a-fc1605340ab9' # replace with Worksapce ID
Beispiel #25
0
def Service(apikey: str, url: str) -> watson.AssistantV1:
    authenticator = IAMAuthenticator(apikey)
    service = watson.AssistantV1(version=VERSION, authenticator=authenticator)
    service.set_service_url(url)
    return service
Beispiel #26
0
def process():
    if request.method == 'POST':
        resp = request.get_json()
        print(resp)

    #text = request.form['text']

    assistant = ibm_watson.AssistantV1(
        version='2019-02-28',
        iam_apikey='u1N9ThXmpZUk_-1_F1AaAw-11BbBXFtCbonmmerHbnFI',
        url='https://gateway-wdc.watsonplatform.net/assistant/api')

    response = assistant.message(
        workspace_id='7cb1c0fc-6e91-4b63-9e93-8a30028bd58e',
        input={
            'text': resp
        }).get_result()

    a = response
    b = a['intents']
    if b == []:
        intent = 0
    else:
        intent = b[0]['intent']

    print(intent)

    if intent == 'greeting':  # if intent =='greeting':
        talkout = 'how can i help you? /// Listen'

    else:
        if intent == 'maps':
            reg_ex = re.search('open maps (.*)')
            url = 'https://www.google.com/maps'
            if reg_ex:
                subreddit = reg_ex.group(1)
                url = url + 'r/'  #+ subreddit
            webbrowser.open(url)
            print('Done!')

        elif intent == 'open':
            reg_ex = re.search('open (.+)')
            if reg_ex:
                domain = reg_ex.group(1)
                url = 'https://www.' + domain
                webbrowser.open(url)
                print('Done!')
            else:
                pass

        elif intent == 'joke':
            res = requests.get('https://icanhazdadjoke.com/',
                               headers={"Accept": "application/json"})
            if res.status_code == requests.codes.ok:
                talkout = str(res.json()['joke'])
            else:
                talkout = 'oops!I ran out of jokes'

        elif intent == 'weather':

            send_url = "http://api.ipstack.com/check?access_key=9a86bc5e18df530bd1ded7ff6620187d"
            geo_req = requests.get(send_url)
            geo_json = json.loads(geo_req.text)
            latt = geo_json['latitude']
            long = geo_json['longitude']
            endpoint = 'http://api.openweathermap.org/data/2.5/forecast?'
            api_key = 'e33c84cc9eb1157c533611a494f638a3'

            nav_request = 'lat={}&lon={}&APPID={}'.format(latt, long, api_key)
            requeest = endpoint + nav_request
            response = urllib.requeest.urlopen(requeest).read().decode('utf-8')
            weather = json.loads(response)
            current_temp = weather['list'][0]['main']['temp']
            temp_c = current_temp - 273.15
            temp_c_str = str(int(temp_c)) + ' degree Celsius '
            descript_place = weather['list'][0]['weather'][0]['main']
            talkout = 'The Current weather is ' + descript_place + ' and temperature is ' + temp_c_str

        elif intent == 'person':
            thisdict = {
                1: "akshat.jpeg",
                2: "prateek.jpeg",
                3: "anshu.jpeg",
                4: "sandeep.jpeg",
                5: "goldy.jpeg"
            }
            n = 5
            f = 0

            ch = 'y'
            chcounter = 0
            if __name__ == "__main__":
                while (ch == 'y'):

                    camera = cv2.VideoCapture(0)
                    return_value, image = camera.read()
                    cv2.imwrite('test.jpeg', image)
                    del (camera)

                    sourceFile = 'test.jpeg'  #from camera
                    for i in range(1, n + 1):
                        # targetFile='anand.jpeg'
                        targetFile = thisdict[i]
                        client = boto3.client('rekognition')

                        imageSource = open(sourceFile, 'rb')
                        imageTarget = open(targetFile, 'rb')

                        response = client.compare_faces(
                            SimilarityThreshold=70,
                            SourceImage={'Bytes': imageSource.read()},
                            TargetImage={'Bytes': imageTarget.read()})

                        for faceMatch in response['FaceMatches']:
                            position = faceMatch['Face']['BoundingBox']
                            confidence = str(faceMatch['Face']['Confidence'])
                            f = 1
                            talkout = 'The face at matches with ' + confidence + '% confidence' + str(
                                thisdict[i].split(".jpeg"))
                        imageSource.close()
                        imageTarget.close()
                    if (f != 1):
                        talkout = 'This person doesn\'t exist in our databse, what is the name of this person?: '
                        #namee= input()+".jpeg"
                        namee = myCommand()
                        namee = namee + ".jpeg"
                        n = n + 1
                        os.rename("test.jpeg", namee)
                        d1 = {n: namee}
                        thisdict.update(d1)
                    elif (f == 1):
                        os.remove("test.jpeg")
                        ch = 'n'
        elif intent == 'text':
            camera = cv2.VideoCapture(0)
            return_value, image = camera.read()
            cv2.imwrite('test1.jpeg', image)
            del (camera)

            s3 = boto3.resource('s3')
            images = [
                ('test1.jpeg', 'test'),
            ]

            for image in images:
                file = open(image[0], 'rb')
                object = s3.Object('s3-wheeler', image[0])
                ret = object.put(Body=file, Metadata={'Name': image[1]})

            if __name__ == "__main__":

                bucket = 's3-wheeler'
                photo = 'test1.jpeg'
                client = boto3.client('rekognition')
                response = client.detect_text(
                    Image={'S3Object': {
                        'Bucket': bucket,
                        'Name': photo
                    }})
                textDetections = response['TextDetections']

                for text in textDetections:
                    if (' ' in text['DetectedText']):
                        talkout = str(text['DetectedText'])

            s3.Object('s3-wheeler', 'test1.jpeg').delete()

        elif intent == 'news':

            def NewsFromBBC():
                main_url = " https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=e4313a22f54042c9aba095ce5354be51"
                open_bbc_page = requests.get(main_url).json()
                article = open_bbc_page["articles"]
                results = []
                stuff = []
                for ar in article:
                    results.append(ar["title"])

                for i in range(0, 3):
                    stuff = (str((i + 1)) + ' ' + results[i]).append(i)
                talkout = 'The top headlines are,' + stuff

            NewsFromBBC()

        elif intent == 'bye':
            talkout = 'See ya soon! bye bye byebyebyee'
            exit()

    return 'it worked'
    '''
Beispiel #27
0
import ibm_cloud_sdk_core
import ibm_watson

APIKEY = "A4LMwqnkIQac81v88v14_AZLj5F__wjY83S9WOgjqAXw"
APIVERSION = '2019-02-28'
APIURL = 'https://gateway-wdc.watsonplatform.net/assistant/api'
ASSISTANT_ID = 'f2ddf51f-1048-44ad-a4a8-3d5a5289178a'

service = ibm_watson.AssistantV1(
    iam_apikey=APIKEY,
    version=APIVERSION,
    url=APIURL
)

workspaceID = service.list_workspaces(
    assistant_id=ASSISTANT_ID
).get_result()["workspaces"][0]["workspace_id"]


def find_action(text: str) -> (str, str):
    """
    A support function for send_input

    :param
    text(str): the text from send_input to get the action required.
    :return:
    str: the trimmed message
    str: the action requested. Empty if no action required.
    """
    start = text.find("!<+")
    if start == -1:  # The symbol not found
Beispiel #28
0
def get_names():

    if request.method == 'POST':
        resp_json = request.get_json()
        command = resp_json['text']
        if 'villa' in command or 'billa' in command:
            command = 'okay wheeler'
        else:
            command = command
    #print('You said: ' + command + '\n')
    assistant = ibm_watson.AssistantV1(
        version='2019-02-28',
        iam_apikey='u1N9ThXmpZUk_-1_F1AaAw-11BbBXFtCbonmmerHbnFI',
        url='https://gateway-wdc.watsonplatform.net/assistant/api')

    response = assistant.message(
        workspace_id='7cb1c0fc-6e91-4b63-9e93-8a30028bd58e',
        input={
            'text': command  #use the <text> we get with flask
        }).get_result()

    a = response
    b = a['intents']
    if b == []:
        intent = 'nothing'
    else:
        intent = b[0]['intent']
    print('the intent is:', intent)

    def currentad():
        send_url = "http://api.ipstack.com/check?access_key=9a86bc5e18df530bd1ded7ff6620187d"
        geo_req = requests.get(send_url)
        geo_json = json.loads(geo_req.text)
        latitude = geo_json['latitude']
        longitude = geo_json['longitude']
        return [latitude, longitude]

    if intent == 'weather':
        latt, long = currentad()
        endpoint = 'http://api.openweathermap.org/data/2.5/forecast?'
        api_key = 'e33c84cc9eb1157c533611a494f638a3'

        nav_request = 'lat={}&lon={}&APPID={}'.format(latt, long, api_key)
        reequest = endpoint + nav_request
        # Sends the request and reads the response.
        response = urllib.request.urlopen(reequest).read().decode('utf-8')
        # Loads response as JSON
        weather = json.loads(response)
        current_temp = weather['list'][0]['main']['temp']
        temp_c = current_temp - 273.15
        temp_c_str = str(int(temp_c)) + ' degree Celsius '
        descript_place = weather['list'][0]['weather'][0]['main']
        #print(descript_place + ' ' + temp_c_str)
        if descript_place == 'Clouds':
            descript_place = 'overcast'
        print('It is a little ' + descript_place +
              ' and temperature outside is, ' + temp_c_str)

        #response = assistant.assistant(resp_json["test"])
        return json.dumps({
            "response":
            'It is a little ' + descript_place +
            ' and temperature outside is, ' + temp_c_str
        }), 200

    elif intent == 'maps':
        #webbrowser.open('http:127.0.0.1:5000/map.html')
        #print('Done!')
        gmaps = googlemaps.Client(
            key='AIzaSyAMP6SIK4ruB5Tsl5qR6h54XDcl4FDl3HQ')
        SUBSCRIPTION_KEY_ENV_NAME = "bc20ced3c3014badbf34d1799e28f2a2"
        now = datetime.now()
        x = az.entity_extraction(SUBSCRIPTION_KEY_ENV_NAME, command)
        if x[1] == 'Location' or x[1] == 'Organization':
            c = x[0]
        else:
            return json.dumps({"response":
                               'Give me a specific destination'}), 200

        send_url = "http://api.ipstack.com/check?access_key=9a86bc5e18df530bd1ded7ff6620187d"
        geo_req = requests.get(send_url)
        geo_json = json.loads(geo_req.text)
        lat = geo_json['latitude']
        lon = geo_json['longitude']
        results = geocoder.reverse_geocode(lat, lon)
        print(lat + 0.4, lon + 0.4)
        #pprint(results[0]['formatted'])
        our_loc = str(results[0]['formatted'])
        print(our_loc)
        '''directions_result = gmaps.directions(our_loc,
                                     c,
                                     mode="walking",
                                     departure_time=now)'''
        directions_result = gmaps.directions('Hodson Hall, Baltimore, MD',
                                             c,
                                             mode="walking",
                                             departure_time=now)
        time = directions_result[0]['legs'][0]['duration']['text']
        dis = directions_result[0]['legs'][0]['distance']['text']
        start_loc_lat = dis = directions_result[0]['legs'][0][
            'start_location']['lat']
        start_loc_lng = dis = directions_result[0]['legs'][0][
            'start_location']['lng']
        end_loc_lat = dis = directions_result[0]['legs'][0]['end_location'][
            'lat']
        end_loc_lng = dis = directions_result[0]['legs'][0]['end_location'][
            'lng']

        instru = []
        for i in directions_result[0]['legs'][0]['steps']:
            instru.append(i['html_instructions'] + " " +
                          i['distance']['text'] + ' ' + i['duration']['text'] +
                          " Moving from lat : " +
                          str(i['start_location']['lat']) + " , lon : " +
                          str(i['start_location']['lng']) + " to lat : " +
                          str(i['end_location']['lat']) + " , lon : " +
                          str(i['end_location']['lng']))
        webbrowser.open('http:127.0.0.1:5000/map.html')
        #print("distance isssshabdgyjasvkd", dis)
        global value
        value = 'ETA ' + str(time) + ' :)'
        global loc
        loc = [start_loc_lat, start_loc_lng, end_loc_lat, end_loc_lng]
        mytext = 'Opened in a new tab.'
        language = 'en'
        myobj = gTTS(text=mytext, lang=language, slow=False)
        myobj.save("welcome.mp3")
        subprocess.call(['afplay', 'welcome.mp3'])
        return render_template('map.html'), json.dumps(
            {"response": 'It openend on a new Tab'}), 200

    elif intent == 'person':
        thisdict = {
            1: "anand.jpeg",
            2: "sandeep.jpeg",
            3: "Akshay.jpeg",
            4: "prateek.jpeg",
            5: "goldy.jpeg",
            6: "diya.jpeg",
            7: "Akshat.jpeg"
        }
        n = 5
        f = 0

        ch = 'y'
        while (ch == 'y'):

            camera = cv2.VideoCapture(0)
            return_value, image = camera.read()
            cv2.imwrite('test.jpeg', image)
            del (camera)

            sourceFile = 'test.jpeg'  #from camera
            for i in range(1, n + 1):
                # targetFile='anand.jpeg'
                targetFile = thisdict[i]
                client = boto3.client('rekognition')

                imageSource = open(sourceFile, 'rb')
                imageTarget = open(targetFile, 'rb')

                response = client.compare_faces(
                    SimilarityThreshold=70,
                    SourceImage={'Bytes': imageSource.read()},
                    TargetImage={'Bytes': imageTarget.read()})
                f = 2
                for faceMatch in response['FaceMatches']:
                    f = 1
                    nameee = ''
                    for i in targetFile:
                        if i != '.':
                            nameee += i
                        else:
                            break
                    return json.dumps({
                        "response":
                        'This is' + ' ' + nameee + ', ' +
                        ' who\'s come to visit you! '
                    }), 200
                    '''print('The face at ' +
                            str(position['Left']) + ' ' +
                            str(position['Top']) +
                            ' matches with ' + confidence + '% confidence')
                    print(str(thisdict[i].split(".jpeg")))'''
                imageSource.close()
                imageTarget.close()
            if (f != 1):
                return json.dumps({
                    "response":
                    'This person doesn\'t exist in our database. Would you like to add him? '
                }), 200
                #print ( 'This person doesn\'t exist in our database, what is the name of this person?: ')
                #namee= input()+".jpeg"
                namee = "damn this wont work"
                namee = namee + ".jpeg"
                n = n + 1
                os.rename("test.jpeg", namee)
                d1 = {n: namee}
                thisdict.update(d1)
            elif (f == 1):
                os.remove("test.jpeg")
                ch = 'n'

    elif intent == 'text':
        new = []
        camera = cv2.VideoCapture(0)
        return_value, image = camera.read()
        cv2.imwrite('test1.jpeg', image)
        del (camera)

        s3 = boto3.resource('s3')
        images = [
            ('test1.jpeg', 'test'),
        ]

        for image in images:
            file = open(image[0], 'rb')
            object = s3.Object('aags-wheeler1', image[0])
            ret = object.put(Body=file, Metadata={'Name': image[1]})

        bucket = 'aags-wheeler1'
        photo = 'test1.jpeg'
        client = boto3.client('rekognition')
        response = client.detect_text(
            Image={'S3Object': {
                'Bucket': bucket,
                'Name': photo
            }})
        textDetections = response['TextDetections']

        stuff = ' '
        for text in textDetections:
            if (' ' in text['DetectedText']):
                stuff += text['DetectedText'] + '\n'

        print(stuff)

        return json.dumps({"response": stuff}), 200
        #talkToMe(str(text['DetectedText']))

        s3.Object('aags-wheeler1', 'test1.jpeg').delete()

    elif intent == 'news':

        def NewsFromBBC():
            global new
            new = []
            main_url = "https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=e4313a22f54042c9aba095ce5354be51"
            open_bbc_page = requests.get(main_url).json()
            article = open_bbc_page["articles"]
            results = []
            for ar in article:
                results.append(ar["title"])

            for i in range(0, 3):
                stuff = str(str((i + 1)) + '. ' + results[i])
                new.append(stuff)
            return new
            #return json.dumps({"response": str(stuff)})
            #talkToMe(stuff)

        new = NewsFromBBC()
        news = ' '
        for i in new:
            news += i + ',\n' + '\n'
        return json.dumps({"response": news})

    return json.dumps({"response": ''}), 200
import pandas as pd
import numpy as np
import json
import sys
import csv
import ibm_watson
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score

assistant = ibm_watson.AssistantV1(
    version='2019-02-28',
    iam_apikey='{api_key}',
    url='https://gateway.watsonplatform.net/assistant/api')

result = pd.DataFrame(columns=['class', 'predicted', 'confidence'])
with open('../data/test.csv', newline='') as f:
    reader = csv.reader(f)
    count = 0
    for row in reader:
        response = assistant.message(
            workspace_id='233eb6a2-4977-45a3-93db-f79a7c21150a',
            input={
                'text': row[0]
            }).get_result()
        try:
            result.loc[-1] = [
                row[1], response['intents'][0]['intent'],
                response['intents'][0]['confidence']
            ]
            count = count + 1
            print(count, [
Beispiel #30
0
    for creds in wa_credentials:
        wa_version = creds['wa_version']
        wa_apikey = creds['wa_apikey']
        wa_url = creds['wa_url']

        if (wa_version == '' or wa_apikey == '' or wa_url == ''):
            print(
                "No or invalid Watson Assistant credentials detected. Skipping."
            )
        else:
            print("Starting Watson Assistant backup...")
            start_time = time.time()

            authenticator = IAMAuthenticator(wa_apikey)

            assistant_service = ibm_watson.AssistantV1(
                version=wa_version, authenticator=authenticator)

            assistant_service.set_service_url(wa_url)

            # Get all workspace IDs
            try:
                list_wrkspc_response = assistant_service.list_workspaces(
                ).get_result()['workspaces']
            except ApiException as ex:
                print("Method failed with status code " + str(ex.code) + ": " +
                      ex.message)

            print("Beginning Watson Assistant backup...")
            print()
            for space in list_wrkspc_response:
                print()