コード例 #1
0
def main():
    parser = argparse.ArgumentParser("cog agent - ")
    parser.add_argument('-text', '--text_to_query', help='The text to send')
    parser.add_argument('-token',
                        '--auth_token',
                        help='The token to authenticate on Dialogflow')

    ai = apiai.ApiAI(parser.auth_token)

    argparser = argparse.ArgumentParser()

    request = ai.text_request()

    request.lang = 'en'  # optional, default value equal 'en'

    # request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"

    # request.query = "who is albert einstein?"
    #Who was Albert Einstein?
    request.query = "play rihanna"
    response = request.getresponse()
    intent = Intent(response.read())
    #intent.createIntentFromJson(response.read())
    print ' intent name is: ', intent.getIntentName()
    intent.handleIntent()
コード例 #2
0
    def sphinx_recognize(self, audio, sphinx):
        try:
            sphinx_start = timeit.default_timer()
            original_speech = sphinx.recognize(audio)
            sphinx_stop = timeit.default_timer()

            running_time = sphinx_stop - sphinx_start

            speech = multi_replace(self.similar, original_speech)

            intent_start = timeit.default_timer()
            i = Intent(speech)
            message = i.parse_intents()
            intent_end = timeit.default_timer()

            sphinx_end = timeit.default_timer()

            log_message = 'Sphinx (running time ' + str(running_time) + '):\n'\
             + original_speech \
             + '\nIntent processing running time: ' \
             + str(intent_end - intent_start) \
             + '\nTotal running time: ' + str(sphinx_end-sphinx_start)

            self.log.info(log_message)
            return message
        except Exception as e:
            self.log.debug('Error: ' + str(e))
            return {}
コード例 #3
0
    def request(self, query):
        '''
            ikea请求处理
                query:http请求句柄
                返回值:结果字典
        '''
        rsp_dict = {}

        unit_rst = self.unit.query_request(self.scene_id, query, "").text
        print "unit_rst=", unit_rst
        bot_intent = Intent(unit_rst)
        if (bot_intent.get_intent_confidence() < self.min_confidence):
            # 使用图灵机器人兜底
            rsp_dict[wechat_msg_params.
                     key_message_type] = wechat_msg_params.val_msg_type_invalid
        else:
            query_intent = bot_intent.get_intent()

            if (query_intent == 'USER_LOCATION'):
                return self.user_location_processor.process(bot_intent)
            elif (query_intent == 'USER_BUY'):
                return self.user_buy_processor.process(bot_intent)
            else:
                # 兜底
                rsp_dict[
                    wechat_msg_params.
                    key_message_type] = wechat_msg_params.val_msg_type_invalid

        return rsp_dict
コード例 #4
0
ファイル: send_text_query.py プロジェクト: kohn1001/ai_agent
def main():
    """
        Get the token from the Dialogue Flow  WebSite, you should create an account and get it from you the agent
    """
    parser = argparse.ArgumentParser("cog agent - ")
    parser.add_argument('-text',
                        '--text_to_query',
                        help='The text to send',
                        required=True)
    parser.add_argument('-token',
                        '--auth_token',
                        help='The token to authenticate on Dialogflow',
                        required=True)
    args = parser.parse_args()
    ai = apiai.ApiAI(args.auth_token)

    request = ai.text_request()

    request.lang = 'en'  # optional, default value equal 'en'

    # request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"

    # request.query = "who is albert einstein?"
    #Who was Albert Einstein?
    # request.query = "play sia"
    request.query = args.text_to_query
    response = request.getresponse()
    intent = Intent(response.read())
    #intent.createIntentFromJson(response.read())
    print('intent name is: ', intent.getIntentName())
    intent.handleIntent()
コード例 #5
0
ファイル: app.py プロジェクト: husam88/DroidbotX
 def get_start_with_profiling_intent(self, trace_file, sampling=None):
     """
     get an intent to start the app with profiling
     :return: Intent
     """
     package_name = self.get_package_name()
     if self.get_main_activity():
         package_name += "/%s" % self.get_main_activity()
     if sampling is not None:
         return Intent(prefix="start --start-profiler %s --sampling %d" % (trace_file, sampling), suffix=package_name)
     else:
         return Intent(prefix="start --start-profiler %s" % trace_file, suffix=package_name)
コード例 #6
0
ファイル: go_home_txt.py プロジェクト: kohn1001/ai_agent
def main():
    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)

    request = ai.text_request()

    request.lang = 'en'  # optional, default value equal 'en'

    # request.session_id = "<SESSION ID, UNIQUE FOR EACH USER>"

    # request.query = "who is albert einstein?"
    #Who was Albert Einstein?
    request.query = "go home"
    response = request.getresponse()
    intent = Intent()
    intent.createIntentFromJson(response.read())
コード例 #7
0
ファイル: app.py プロジェクト: soupwaylee/droidbot
 def get_stop_intent(self):
     """
     get an intent to stop the app
     :return: Intent
     """
     package_name = self.get_package_name()
     return Intent(prefix="force-stop", suffix=package_name)
コード例 #8
0
ファイル: app.py プロジェクト: soupwaylee/droidbot
    def get_possible_broadcasts(self):
        possible_broadcasts = set()

        androguard_a = self.get_androguard_analysis().a
        receivers = androguard_a.get_receivers()

        for receiver in receivers:
            intent_filters = androguard_a.get_intent_filters(
                'receiver', receiver)
            if 'action' in intent_filters:
                actions = intent_filters['action']
            else:
                actions = []
            if 'category' in intent_filters:
                categories = intent_filters['category']
            else:
                categories = []
            categories.append(None)
            for action in actions:
                for category in categories:
                    intent = Intent(prefix='broadcast',
                                    action=action,
                                    category=category)
                    possible_broadcasts.add(intent)
        return possible_broadcasts
コード例 #9
0
 def __init__(self, obstacle_number, x, y, length, width, intent):
     self.number = obstacle_number
     self.x = x
     self.y = y
     self.length = length
     self.width = width
     self.intent = Intent(intent)
コード例 #10
0
ファイル: wit.py プロジェクト: edouardcuny/witlike
 def new_intent(self, nom):
     '''
     Outil de création d'un nouvel intent.
     A développer.
     '''
     intent = Intent(word_to_vec=self.word_to_vec, nom=nom)
     self.intents.append(intent)
コード例 #11
0
def test_ignore_other_intents():
    handler = EchoHandler(
        intents=[IntentName.ask_for_wise_quote, IntentName.play_among_us])

    message = create_message("hello", channel="a")
    assert handler(message,
                   Intent(name=IntentName.ask_for_wise_quote,
                          probability=0.9)) == "hello"

    message = create_message("hello", channel="a")
    assert handler(message,
                   Intent(name=IntentName.play_among_us,
                          probability=0.9)) == "hello"

    message = create_message("hello", channel="a")
    assert handler(message, Intent(name=IntentName.thank_bot,
                                   probability=0.9)) is None
コード例 #12
0
ファイル: app.py プロジェクト: soupwaylee/droidbot
 def get_start_intent(self):
     """
     get an intent to start the app
     :return: Intent
     """
     package_name = self.get_package_name()
     if self.get_main_activity():
         package_name += "/%s" % self.get_main_activity()
     return Intent(suffix=package_name)
コード例 #13
0
 def call(self, phone=DEFAULT_NUM):
     """
     simulate a outcome phonecall
     :param phone: str, phonenum
     :return:
     """
     call_intent = Intent(prefix='start',
                          action="android.intent.action.CALL",
                          data_uri="tel:%s" % phone)
     return self.send_intent(intent=call_intent)
コード例 #14
0
    def get_random_instance(device, app):
        if not device.is_foreground(app):
            # if current app is in background, bring it to foreground
            component = app.get_package_name()
            if app.get_main_activity():
                component += "/%s" % app.get_main_activity()
            return IntentEvent(Intent(suffix=component))

        else:
            choices = {TouchEvent: 6, LongTouchEvent: 2, SwipeEvent: 2}
            event_type = utils.weighted_choice(choices)
            return event_type.get_random_instance(device, app)
コード例 #15
0
ファイル: app.py プロジェクト: husam88/DroidbotX
 def get_possible_broadcasts(self):
     possible_broadcasts = set()
     for receiver in self.apk.get_receivers():
         intent_filters = self.apk.get_intent_filters('receiver', receiver)
         actions = intent_filters['action'] if 'action' in intent_filters else []
         categories = intent_filters['category'] if 'category' in intent_filters else []
         categories.append(None)
         for action in actions:
             for category in categories:
                 intent = Intent(prefix='broadcast', action=action, category=category)
                 possible_broadcasts.add(intent)
     return possible_broadcasts
コード例 #16
0
ファイル: main.py プロジェクト: schiegl/tuwien-ds-discord-bot
async def on_message(message: discord.Message):
    # avoid responding to itself
    if message.author.bot:
        return

    # replace mentions with something snips can recognize
    clean_text = message.content.replace(f"<@!{client.user.id}>", "@bot")
    result = snips.parse(clean_text)
    intent_name = IntentName(result["intent"]["intentName"])
    intent = Intent(name=intent_name, probability=result["intent"]["probability"])

    for handler in handlers:
        response = handler(message, intent)
        if response:
            await message.channel.send(response)
            break
コード例 #17
0
 def send_sms(self, phone=DEFAULT_NUM, content=DEFAULT_CONTENT):
     """
     send a SMS
     :param phone: str, phone number of receiver
     :param content: str, content of sms
     :return:
     """
     send_sms_intent = Intent(prefix='start',
                              action="android.intent.action.SENDTO",
                              data_uri="sms:%s" % phone,
                              extra_string={'sms_body': content},
                              extra_boolean={'exit_on_sent': 'true'})
     self.send_intent(intent=send_sms_intent)
     time.sleep(2)
     self.get_adb().press('66')
     return True
コード例 #18
0
 def add_contact(self, contact_data):
     """
     add a contact to device
     :param contact_data: dict of contact, should have keys like name, phone, email
     :return:
     """
     assert self.get_adb() is not None
     contact_intent = Intent(prefix="start",
                             action="android.intent.action.INSERT",
                             mime_type="vnd.android.cursor.dir/contact",
                             extra_string=contact_data)
     self.send_intent(intent=contact_intent)
     time.sleep(2)
     self.get_adb().press("BACK")
     time.sleep(2)
     self.get_adb().press("BACK")
     return True
コード例 #19
0
 def start_app(self, app):
     """
     start an app on the device
     :param app: instance of App, or str of package name
     :return:
     """
     if isinstance(app, str):
         package_name = app
     elif isinstance(app, App):
         package_name = app.get_package_name()
         if app.get_main_activity():
             package_name += "/%s" % app.get_main_activity()
     else:
         self.logger.warning("unsupported param " + app + " with type: ", type(app))
         return
     intent = Intent(suffix=package_name)
     self.send_intent(intent)
コード例 #20
0
    def __init__(self):
        self.count = 0
        socket_client.connect("127.0.0.1", 1234, "RailBot", self.show_error)

        self.vocab, self.documents, self.intent_categories = Intent(
        ).create_vocab()

        self.i = InferIntent()
        self.en = Entity()

        self.slots = {}
        self.pnr = None
        self.date = None
        self.intent = None

        self.query = socket_client.start_listening(self.incoming_message,
                                                   self.show_error)
        self.message = ''
コード例 #21
0
ファイル: test_intent.py プロジェクト: kohn1001/ai_agent
#!/usr/bin/env python

from intent import Intent

intent = Intent()
uuid = intent.getUUID()
print 'uuid is: ', uuid
コード例 #22
0
def handle_message(event):
    global latest_image_path
    global reportList

    if event.reply_token == "00000000000000000000000000000000":
        return "OK"

    # saveToFirebase(event)
    #resume exiting
    print(conversation.keys())
    uid = event.source.user_id
    if uid in conversation:
        intent = conversation[uid]
        o = intent.handle(event.message.text)
        line_bot_api.reply_message(event.reply_token,
                                   [TextSendMessage(text=o)])
        if intent.endIntent():
            output = intent.getData()
            print(output)
            saveFirebase(output, event.source.user_id)
            del conversation[uid]
        return

    userIntent = Intent.evaluateIntent(event.message.text)
    if uid in reportingUsers:
        if isinstance(userIntent, EndReportIntent):
            profile = line_bot_api.get_profile(uid)
            del reportingUsers[uid]
            line_bot_api.reply_message(event.reply_token, [
                TextSendMessage(text='บันทึกเสร็จสิ้นค่ะ คุณ%s' %
                                profile.display_name)
            ])
            return
        catalog = reportingUsers[uid]
        saveToFirebase(catalog, event)
        print('Saving to firebase')
        return

    if isinstance(userIntent, StartReportIntent):
        profile = line_bot_api.get_profile(uid)
        dateStr = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
        reportingUsers[uid] = "report-%s-%s" % (uid, dateStr)
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='กำลังจดบันทึกให้ค่ะ คุณ%s' %
                            profile.display_name)
        ])
        return

        # rego = None

        if uid in conversation:
            rego = conversation[uid]
        else:
            rego = keepdata()
            conversation[uid] = rego
            o = rego.handle(event.message.text)
            line_bot_api.reply_message(event.reply_token,
                                       [TextSendMessage(text=o)])

    if isinstance(userIntent, ViewReportIntent):
        id = int(userIntent.id)
        print('id:', id)
        (uid, dateStr) = reportList[id - 1]
        d, t = dateStr.split()
        (ye, mo, da) = d.split('-')
        (h, m, s) = t.split(':')
        key = 'report-%s-%s-%s-%s-%s-%s-%s' % (uid, ye, mo, da, h, m, s)
        print('Key:', key)
        report = Report.viewReport(key)
        line_bot_api.reply_message(event.reply_token,
                                   [TextSendMessage(text=report)])
        return

    if isinstance(userIntent, ListReportIntent):
        reportList = Report.listReports()
        s = 'รายงานทั้งหมด\n'
        i = 1
        for r in reportList:
            (uid, dateStr) = r
            profile = line_bot_api.get_profile(uid)
            s += "%d: %s (%s)\n" % (i, profile.display_name, dateStr)
            i += 1

        line_bot_api.reply_message(event.reply_token,
                                   [TextSendMessage(text=s)])
        return

    if event.message.text == 'ออกไปได้แล้ว':
        if isinstance(event.source, SourceGroup):
            if event.source.user_id == 'U991007deaa6c52bd776443e7d89f2032':
                line_bot_api.reply_message(event.reply_token,
                                           TextMessage(text='บะบายค่า'))
                line_bot_api.leave_group(event.source.group_id)
            else:
                line_bot_api.reply_message(event.reply_token,
                                           TextMessage(text='ไม่!'))

    if event.message.text == 'ราคาน้ำมัน':
        l = oil_price.get_prices()
        s = ""
        for p in l:
            s += "%s %.2f บาท\n" % (p[0], p[1])

        line_bot_api.reply_message(event.reply_token, TextSendMessage(text=s))
    elif event.message.text == 'วิเคราะห์รูป':
        line_bot_api.reply_message(event.reply_token,
                                   [TextSendMessage(text='สักครู่ค่ะ')])

        # Process image
        try:
            lp = LicencePlate()
            result = lp.process(latest_image_path)
            s = lp.translate(result)

            line_bot_api.push_message(event.source.user_id,
                                      [TextSendMessage(text=s)])

        except Exception as e:
            print('Exception:', type(e), e)
            line_bot_api.push_message(
                event.source.user_id,
                [TextSendMessage(text='ไม่สามารถวิเคราะห์รูปได้')])

    else:
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text=event.message.text + 'จ้า'))
コード例 #23
0
ファイル: __main__.py プロジェクト: edouardcuny/witlike
import os
import pandas as pd
import pickle # pour dumper witlike object

from intent import Intent

import random
random.seed(7)

from wit import Wit

# importation du W2V
os.chdir("/Users/edouardcuny/Desktop/witlike/wit")

# Lumière
LUX = Intent(nom="lux")
LUX.train("allumer")
LUX.train("lumière")
LUX.train("lampe")
LUX.train("éteindre")

# RATP
RATP = Intent(nom="ratp")
RATP.train("trajet")
RATP.train("itinéraire")
RATP.train("aller")
RATP.train("métro")

# Musique
MUSIC = Intent(nom="music")
MUSIC.train("jouer")
コード例 #24
0
from intent import Intent

from . import config, db_state
from .exceptions import AmbiguousRedoError, InTransactionError, NoTransactionActiveError, AmbiguousUndoError
from .transaction import Transaction
from .trie import Trie, split

__all__ = [
    'connect', 'undo', 'redo', 'checkout', 'get_commit_dag', 'safe_get', 'get',
    'put', 'delete', 'discard', 'has', 'count_up_or_set', 'count_down_or_del',
    'match_count', 'match_keys', 'match_items', 'transaction',
    'intent_db_connected'
]

# todo: add more hooks
intent_db_connected: Intent[str] = Intent()


def get_commit_dag() -> Tuple[str, Dict[str, List[str]], Dict[str, List[str]],
                              Dict[str, List[str]]]:
    return (db_state.head, deepcopy(db_state.commit_parents),
            deepcopy(db_state.commit_children),
            deepcopy(db_state.commit_messages))


def connect(directory: str) -> None:
    print('connecting to db at', directory)
    db_state.directory = directory
    head_path = os.path.join(db_state.directory,
                             f'{config.head_file}_{config.device_name}')
    state = Trie()
コード例 #25
0
ファイル: result.py プロジェクト: mertaytore/weatherpython
## After being done with dependencies and API keys:
## Run this file simply with the command -> python result.py
## 
## Have fun! :P
##

from intent import Intent

intent = Intent()
result_weather = intent.start()
print result_weather
コード例 #26
0
ファイル: ogm.py プロジェクト: AgarwalPragy/py-revert
# noinspection PyUnresolvedReferences
import uuid
from typing import Any, Dict as tDict, Optional, Type, cast

from intent import Intent

import revert
from . import config
from .exceptions import ClassAlreadyRegisteredError, UnsavableObjectError
from .graph import Edge, Node

node_classes: tDict[str, Type[Node]] = {}
edge_classes: tDict[str, Type[Edge]] = {}
node_cache: tDict[str, Node] = {}

intent_class_registered: Intent[Type[Node]] = Intent()
intent_entity_created: Intent[Node] = Intent()
intent_entity_before_delete: Intent[Node] = Intent()


def db_connected(directory: str) -> None:
    with revert.transaction(message='schema change'):
        for cls in node_classes.values():
            mro = ','.join([
                parent.class_reference() for parent in cls.mro()
                if issubclass(parent, Node)
            ])
            revert.put(f'{config.base}/classes/{cls.class_reference()}/mro',
                       mro)