Esempio n. 1
0
 def __init__(self, intent_key: str = "intent"):
     self.intent_key = intent_key
     token = os.getenv("WIT_AI_TOKEN")
     if token is None:
         print("Specify WIT_AI_TOKEN as environment variable.")
         sys.exit(1)
     self.wit = wit.Wit(token)
Esempio n. 2
0
    def setUp(self):
        try:
            self.token = os.environ['WIT_ACCESS_TOKEN']
        except KeyError:
            print('WIT Access token not set, skipping test')
            self.token = None

        self.wit = wit.Wit(self.token)
Esempio n. 3
0
 def communtation(self):
     resp = None
     with sr.Microphone() as source:
         self.r.adjust_for_ambient_noise(source)
         audio = self.r.listen(source)
         resp = wit.Wit(self.config['Server_Access']).speech(
             audio, None, {'Content-Type': 'audio/mpeg3'})
     return resp
 def __init__(self, yelp_client, wit_token, fb_token):
     self.yelp_client = yelp_client
     self.fb_token = fb_token
     actions = {
         "search": self.yelp_search_and_display_action,
         "send": self.send_action,
         "requestLocation": self.request_location_action,
         "setContext": self.set_context_action,
     }
     self.wit_client = wit.Wit(access_token=wit_token, actions=actions)
Esempio n. 5
0
    def __init__(self):

        self.custom_kb = []
        self.updater = Updater(token=self.token)
        self.bot = self.updater.bot
        self.dispatcher = self.updater.dispatcher
        self.games = {}
        self.games5 = {}
        self.human = {}
        self.witClient = wit.Wit(wit_token)
        self.dispatcher.add_handler(
            MessageHandler(Filters.voice, self.voice_handler))
Esempio n. 6
0
    def __init__(self, botname):
        print("Wit: {}".format(botname))
        self.client = wit.Wit(access_token=ACCESS_TOKEN)

        self._put = lambda path, data: wit.req(self.client.logger,
                                               self.client.access_token,
                                               'PUT',
                                               path,
                                               _params,
                                               json=data)
        self._post = lambda path, data: wit.req(self.client.logger,
                                                self.client.access_token,
                                                'POST',
                                                path,
                                                _params,
                                                json=data)
        self._get = lambda path: wit.req(self.client.logger, self.client.
                                         access_token, 'GET', path, _params)
Esempio n. 7
0
    def initialize(self,
                   wit_token=None,
                   socket=None,
                   failure_bound=0.1,
                   low_bound=0.3):
        if wit_token is None:
            raise ValueError('needs a wit_token')
        if socket is None:
            raise ValueError('needs a ZeroMQ publish socket')

        self.wit = wit.Wit(wit_token)
        self.failure_bound = failure_bound
        self.low_bound = low_bound

        self.error = Sender(socket, 'wit/error')
        self.failure = Sender(socket, 'wit/failure')
        self.low = Sender(socket, 'wit/low')
        self.high = Sender(socket, 'wit/intent')
Esempio n. 8
0
    def initialize(self, bot_handler: Any) -> None:
        config = bot_handler.get_config_info('witai')

        token = config.get('token')
        if not token:
            raise KeyError('No `token` was specified')

        # `handler_location` should be the location of a module which contains
        # the function `handle`. See `doc.md` for more details.
        handler_location = config.get('handler_location')
        if not handler_location:
            raise KeyError('No `handler_location` was specified')
        self.handle = get_handle(handler_location)

        help_message = config.get('help_message')
        if not help_message:
            raise KeyError('No `help_message` was specified')
        self.help_message = help_message

        self.client = wit.Wit(token)
Esempio n. 9
0
    def initialize(self, bot_handler: BotHandler) -> None:
        config = bot_handler.get_config_info("witai")

        token = config.get("token")
        if not token:
            raise KeyError("No `token` was specified")

        # `handler_location` should be the location of a module which contains
        # the function `handle`. See `doc.md` for more details.
        handler_location = config.get("handler_location")
        if not handler_location:
            raise KeyError("No `handler_location` was specified")
        handle = get_handle(handler_location)
        if handle is None:
            raise Exception("Could not get handler from handler_location.")
        else:
            self.handle = handle

        help_message = config.get("help_message")
        if not help_message:
            raise KeyError("No `help_message` was specified")
        self.help_message = help_message

        self.client = wit.Wit(token)
def record_and_stream():
    p = pyaudio.PyAudio()

    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)

    print("* recording and streaming")

    for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
        yield stream.read(CHUNK)

    print("* done recording and streaming")

    stream.stop_stream()
    stream.close()
    p.terminate()


if __name__ == '__main__':
    output_file = StringIO()
    if 'WIT_ACCESS_TOKEN' not in os.environ:
        os.environ['WIT_ACCESS_TOKEN'] = getpass('Enter Wit Access Token: ')
    wit_token = os.environ['WIT_ACCESS_TOKEN']

    w = wit.Wit(wit_token)
    result = w.post_speech(record_and_stream(), content_type=CONTENT_TYPE)
    pprint(result)
Esempio n. 11
0
import os
import uuid

import ffmpy
import requests
import werkzeug
import wit
from flask_restful import (reqparse, Resource)

from .silent_language import text_to_silent_language_converter

wit_client = wit.Wit(access_token='GNEKSIPCTVCBTRPT2NDVNXXBLPBLNM24')


class SilentLanguage(Resource):
    def __init__(self):
        self._parser = reqparse.RequestParser()
        self._parser.add_argument('text', location="json", type=str)
        self._parser.add_argument(
            'audio',
            type=werkzeug.datastructures.FileStorage,
            location='files',
        )

    def post(self):
        args = self._parser.parse_args()
        audio = args['audio']
        text = args['text']
        if audio is not None:
            text = audio_to_text(audio)
        if text is None:
Esempio n. 12
0
interrupted = False


def signal_handler(signal, frame):
    global interrupted
    interrupted = True


def interrupt_callback():
    global interrupted
    return interrupted


if __name__ == '__main__':

    w = wit.Wit(WIT_TOKEN)

    with open('resources/ding.wav', 'rb') as fd:
        ding_fp = fd.read()

    # with open('resources/dong.wav', 'rb') as fd:
    #     dong_fp = fd.read()

    ding_sound = AudioSegment.from_file(io.BytesIO(ding_fp), format="wav")
    # dong_sound = AudioSegment.from_file(io.BytesIO(dong_fp), format="wav")

    execute_command()
    # # capture SIGINT signal, e.g., Ctrl+C
    # signal.signal(signal.SIGINT, signal_handler)
    #
    # detector = snowboydecoder.HotwordDetector(MODEL, sensitivity=0.5)
Esempio n. 13
0
 def setUp(self):
     self.wit = wit.Wit(os.environ['WIT_ACCESS_TOKEN'])
Esempio n. 14
0
 def __init__(self, access_token=None):
     import wit
     if not access_token:
         raise ValueError("No wit Access Token given")
     self.access_token = access_token
     self.wit = wit.Wit(token=self.access_token, version='20141022')
Esempio n. 15
0
    def __init__(self, config):
        self.config = config

    def adapt(self, witcommand):
        intent = safe_get_value(witcommand, "entities.intent.[0].value")
        if not intent:
            raise NoIntent("does not handle command")

        adapter = self.config.get(intent)
        if not adapter:
            raise NoCommandFound("no command found for intent %s " % intent)

        command = adapter(witcommand)
        return command


wit_client = wit.Wit(config.WIT_TOKEN)


def get_wit_command(msg):
    return wit_client.message(msg)


if __name__ == "__main__":
    witcommand = get_wit_command("show me jira abc-xyz")
    print witcommand
    v = safe_get_value(witcommand, "entities.intent.[0].value")
    cmd = WitToCommandAdapter.create_command(witcommand)
    print cmd
    print cmd.state
Esempio n. 16
0
 def __init__(self):
     self.wit = wit.Wit(self.config["Server_Access"])
Esempio n. 17
0
from wikipedia import WikipediaPage
import wolframalpha
import json
import wikipedia
import wit

witClient = wit.Wit("DTIBACFI5NLIEIR7EOAHBGDNKTYXEA2A")
wolframalphaClient = wolframalpha.Client("QAT4UH-YT4UEQW94X")


def get_response_wikipedia(page: str) -> str:
    """
	Returns a page object containing all information of a Wikipedia page
	:param page: String which is a valid wikipedia page
	:return: WikipediaPage object
	"""
    return wikipedia.page(wikipedia.search(page)[0]).summary


def get_response_wolframaplha(message: str) -> wolframalpha.Result:
    """
	Accepts a message in string format and responds with the response in JSON format from Wit.ai
	:param message: message to be sent to wit.ai for processing
	:return: json containing intent in the message
	"""
    return wolframalphaClient.query(message)


def get_response_wit(message: str) -> json:
    """
	Accepts a message in string format and responds with the response in JSON format from Wit.ai
Esempio n. 18
0
 def setUp(self):
     self.token = 'fake-token'
     self.uri = 'fake-uri'
     self.wit = wit.Wit(self.token, mocks.MockConnector)
Esempio n. 19
0
from flask import Flask, render_template, request, redirect, send_file
import requests, json, wit, sys, ast
client = wit.Wit('ROMP5H3YEJBXQ76GNQHQYG4VHD2YGJ2D')

Client_msgs = []
Wit_Responses = []

cnt = 0

app = Flask(__name__)


@app.route("/")
def fInput():
    return render_template('sam.html')


@app.route("/", methods=['POST', 'GET'])
def fProcess():
    global cnt
    Client_msgs.append(request.form['text'])
    client_query = Client_msgs[cnt]

    cnt += 1

    received_response = client.message(client_query)

    #print(received_response['entities'])

    print(len(received_response['entities']))
Esempio n. 20
0
import wit
import pyaudio
import pvporcupine

from gtts import gTTS
from logmmse import logmmse_from_file
from mpyg321.mpyg321 import MPyg321Player

from responder import Responder

KEYWORDS = ["jarvis", "bumblebee"]

rp = Responder()
pa = pyaudio.PyAudio()
pl = MPyg321Player()
ai = wit.Wit(os.getenv("WITAI_TOKEN"))
porcupine = pvporcupine.create(keywords=KEYWORDS)

sample_rate = porcupine.sample_rate
frames_per_buffer = porcupine.frame_length
DURATION = 4.5

audio_stream = pa.open(
    rate=sample_rate,
    channels=1,
    format=pyaudio.paInt16,
    input=True,
    frames_per_buffer=frames_per_buffer,
)

Esempio n. 21
0
import ffmpy
import wit

from mytokens import wit_token

witClient = wit.Wit(wit_token)


def speech_to_text(file):
    path = 'voice.ogg'
    file.download(path)
    output = convert_to_mp3(path)
    with open(output, 'rb') as f:
        resp = witClient.speech(f, None, {'Content-Type': 'audio/mpeg3'})
    text = resp['_text'].lower()
    return text


# $ ffmpeg - i voice.ogg - ac 1 voice.mp3
def convert_to_mp3(path):
    output = 'voice.mp3'
    ff = ffmpy.FFmpeg(global_options=['-y'],
                      inputs={path: None},
                      outputs={output: '-ac 1'})
    print(ff.cmd)
    ff.run()
    return output