示例#1
0
 def extract_ordinals(text):
     output = []
     service = NumberService()
     for w in text.split():
         if w in service.__ordinals__:
             output.append(service.__ordinals__[w])
     return [service.parse(w) for w in output]
示例#2
0
 def extractOrdinals(text):
     output = []
     service = NumberService()
     for w in text.split():
         if w in service.__ordinals__:
             output.append(service.__ordinals__[w])
     return [service.parse(w) for w in output]
示例#3
0
        def extractOrdinals(text):
            output = []
            service = NumberService()
            text = text.lower()
            for w in text.split():
 		print (w+ "inside extract Ordinals")
                if w in service.__ordinals__:
		    print(w + " is a n ordinal")
                    output.append(service.__ordinals__[w])
            return [service.parse(w) for w in output]
示例#4
0
def handle(text, mic, profile):
    """
        Responds to user-input, typically speech text, with a summary of
        the day's top news headlines, sending them to the user over email
        if desired.
        Arguments:
        text -- user-input, typically transcribed speech
        mic -- used to interact with the user (for both input and output)
        profile -- contains information related to the user (e.g., phone
                   number)
    """

    max_attempts = 3

    question = get_a_question()

    attempt = 0
    is_correct = False

    while attempt < max_attempts and not is_correct:
        attempt += 1

        mic.say("What is " + str(question[1]) + " plus " + str(question[2]))
        response = mic.activeListen()

        numservice = NumberService()

        try:
            numbers = re.findall(r'\d+', response)
            #user_answer  = numservice.parse(response)

            if len(numbers) > 0:
                user_answer = numbers[0]
                print("You answered " + user_answer)

                if int(user_answer) == question[0]:
                    mic.say("Yay! You are right!")
                    is_correct = True
                else:
                    comment = ''
                    if attempt < max_attempts - 1:
                        comment = "Try again"
                    mic.say("Nah, that is incorrect! " + comment)

            elif len(response) == 0:
                mic.say("Too late!")
            else:
                mic.say("Could not understand your answer!")

        except:
            mic.say("Did not get your answer!")

    if not is_correct:
        mic.say("The correct answer is " + str(question[0]))
示例#5
0
    def test_get_a_story(self):
        numservice = NumberService()
        result = numservice.parse("11")

        print(result)

        self.assertEqual(1, text2num("one"))
        self.assertEqual(12, text2num("twelve"))
        self.assertEqual(72, text2num("seventy two"))
        self.assertEqual(300, text2num("three hundred"))
        self.assertEqual(1200, text2num("twelve hundred"))
        self.assertEqual(12304, text2num("twelve thousand three hundred four"))
        self.assertEqual(6000000, text2num("six million"))
        self.assertEqual(6400005,
                         text2num("six million four hundred thousand five"))
        self.assertEqual(
            123456789012,
            text2num(
                "one hundred twenty three billion four hundred fifty six million seven hundred eighty nine thousand twelve"
            ))
        self.assertEqual(4000000000000000000000000000000000,
                         text2num("four decillion"))
示例#6
0
 def testFloatCutoff(self):
     input = "five point one three seven seven seven seven seven"
     self.assertEqual(NumberService.parseMagnitude(input), '5.14')
示例#7
0
def handle(text, mic, profile):

    serviceNum = NumberService()

    def formatTimeStamp(unix_time):
        return datetime.fromtimestamp(unix_time).strftime("%B %d")

    def getWeeklyWeatherReport(forecast,
                               loc,
                               temp_unit='celsius',
                               report='current'):
        weather_report = "Weather forecast for next week at " + loc + ". "
        rainy_days = len(forecast.when_rain())
        if rainy_days > 0:
            rainy_days_str = "Rainy Days are. "
            for d in range(rainy_days):
                rain_day = forecast.when_rain()[d].get_reference_time()
                date_str = formatTimeStamp(rain_day)
                rainy_days_str += date_str + ". "

            weather_report += rainy_days_str
            date_str = ''

        most_rainy = forecast.most_rainy()
        if most_rainy:
            weather_report += "You will observe heavy rain on. "
            ref_time = most_rainy.get_reference_time()
            date_str = formatTimeStamp(ref_time)
            weather_report += date_str + ". "
            date_str = ''

        sunny_days = len(forecast.when_sun())
        if sunny_days > 0:
            sunny_days_str = "Sunny Days are. "
            for d in range(sunny_days):
                sunny_day = forecast.when_rain()[d].get_reference_time()
                date_str = formatTimeStamp(sunny_day)
                sunny_days_str += date_str + ". "

            weather_report += sunny_days_str
            date_str = ''

        most_hot = forecast.most_hot()
        if most_hot:
            weather_report += "You will feel heat on. "
            ref_time = most_hot.get_reference_time()
            date_str = formatTimeStamp(ref_time)
            weather_report += date_str + ". "
            date_str = ''

        most_windy = forecast.most_windy()
        if most_windy:
            weather_report += "Most windy day will be. "
            ref_time = most_windy.get_reference_time()
            date_str = formatTimeStamp(ref_time)
            weather_report += date_str + ". "
            date_str = ''

        most_humid = forecast.most_humid()
        if most_humid:
            weather_report += "Most humid day will be. "
            ref_time = most_humid.get_reference_time()
            date_str = formatTimeStamp(ref_time)
            weather_report += date_str + ". "
            date_str = ''

        most_cold = forecast.most_cold()
        if most_cold:
            weather_report += "Coolest day will be. "
            ref_time = most_cold.get_reference_time()
            date_str = formatTimeStamp(ref_time)
            weather_report += date_str + ". "
            date_str = ''

        return weather_report

    def getWeatherReport(weather, loc, temp_unit='celsius', report='current'):
        weather_report = 'Server Down.'
        wind = weather.get_wind()
        wind_speed = serviceNum.parseMagnitude(wind["speed"])
        humi = serviceNum.parseMagnitude(weather.get_humidity())
        clou = serviceNum.parseMagnitude(weather.get_clouds())
        stat = weather.get_status()
        detstat = weather.get_detailed_status()

        if report == 'current':
            temp = weather.get_temperature(temp_unit)
            temp_max = serviceNum.parseMagnitude(temp['temp_max'])
            temp_min = serviceNum.parseMagnitude(temp['temp_min'])
            curr_temp = serviceNum.parseMagnitude(temp['temp'])
            weather_report = "Weather at "+loc+". Today is "+stat+". There is a chance of "  \
                              +detstat+". Now Temperature is "+curr_temp+" degree "  \
                              +temp_unit+". Humidity "+humi+" percent. Wind Speed "  \
                              +wind_speed+". with cloud cover "+clou+" percent."

        elif report == 'tommorow':
            temp = weather.get_temperature(temp_unit)
            temp_morn = serviceNum.parseMagnitude(temp['morn'])
            temp_day = serviceNum.parseMagnitude(temp['day'])
            temp_night = serviceNum.parseMagnitude(temp['night'])
            weather_report = "Weather at "+loc+". Tomorrow will be "+stat+". There will be a chance of "  \
                              +detstat+". Temperature in the morning "+temp_morn+" degree "  \
                              +temp_unit+". Days Temperature will be "+temp_day+" degree "  \
                              +temp_unit+". and Temperature at night will be "+temp_night+" degree "  \
                              +temp_unit+". Humidity "+humi+" percent. Wind Speed "  \
                              +wind_speed+". with clouds cover "+clou+" percent."

        return weather_report

    if 'OpenWeatherMap' in profile:
        if 'api_key' in profile['OpenWeatherMap']:
            api_key = profile['OpenWeatherMap']['api_key']
        if 'city_name' in profile['OpenWeatherMap']:
            city_name = profile['OpenWeatherMap']['city_name']
        if 'country' in profile['OpenWeatherMap']:
            country = profile['OpenWeatherMap']['country']
        if 'temp_unit' in profile['OpenWeatherMap']:
            temp_unit = profile['OpenWeatherMap']['temp_unit']

    owm = pyowm.OWM(api_key)

    if re.search(r'\b(TOMORROWS|TOMORROW)\b', text, re.IGNORECASE):
        forecast = owm.daily_forecast(city_name)
        fore = forecast.get_forecast()
        loc = fore.get_location().get_name()
        tomorrow = pyowm.timeutils.tomorrow()
        weather = forecast.get_weather_at(tomorrow)
        weather_report = getWeatherReport(weather,
                                          loc,
                                          temp_unit,
                                          report='tommorow')
        mic.say(weather_report)

    elif re.search(r'\b(WEEKLY)\b', text, re.IGNORECASE):
        forecast = owm.daily_forecast(city_name)
        fore = forecast.get_forecast()
        loc = fore.get_location().get_name()
        weather_report = getWeeklyWeatherReport(forecast,
                                                loc,
                                                temp_unit,
                                                report='weekly')
        mic.say(weather_report)
    else:  # re.search(r'\b(CURRENT|TODAYS|TODAY)\b',text,re.IGNORECASE):
        cw = owm.weather_at_place(city_name + "," + country)
        loc = cw.get_location().get_name()
        weather = cw.get_weather()
        weather_report = getWeatherReport(weather,
                                          loc,
                                          temp_unit,
                                          report='current')
        mic.say(weather_report)
示例#8
0
def parseNumber(query):
    converter = NumberService()
    return converter.parse(query.replace("and", ""))
示例#9
0
def handle(text, mic, profile):
    # Vocab used in Currency Exchange Rate Module
    phrases = [
        "YES",
        "NO",
        "JAPANESE",
        "YEN",
        "AMERICAN",
        "DOLLAR",
        "INDIAN",
        "RUPEES",
        "EURO",
        "SWISS",
        "FRANC",
        "BRITISH",
        "POUND",
        "CHINESE",
        "YUAN",
    ]

    # Comment out below two lines if you are using Jasper in TEXT Mode
    currexch_stt_engine = mic.active_stt_engine.get_instance("rateexch", phrases)
    mic = Mic(mic.speaker, mic.passive_stt_engine, currexch_stt_enginess)

    serviceNum = NumberService()

    def convertToCode(currency):

        code_list = {
            "INDIAN": "INR",
            "RUPEES": "INR",
            "YEN": "JPY",
            "JAPANESE": "JPY",
            "AMERICAN": "USD",
            "DOLLAR": "USD",
            "YUAN": "CNH",
            "CHINESE": "CNH",
            "EURO": "EUR",
            "POUND": "GBP",
            "BRITISH": "GBP",
            " SWISS": "CHF",
            "FRANC": "CHF",
        }

        for key, value in code_list.iteritems():
            if key in currency.split():
                return value
        return ""

    def currencyConverterYahoo(currency_from, currency_to, currency_input):
        yql_base_url = "https://query.yahooapis.com/v1/public/yql"
        yql_query = (
            'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("' + currency_from + currency_to + '")'
        )
        yql_query_url = (
            yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
        )

        yql_response = urllib2.urlopen(yql_query_url)
        yql_json = json.loads(yql_response.read())
        currency_output = currency_input * float(yql_json["query"]["results"]["rate"]["Rate"])
        return currency_output

    while True:
        mic.say(" First Currency?")
        currency_from = convertToCode(mic.activeListen())

        mic.say(" Second Currency?")
        currency_to = convertToCode(mic.activeListen())

        if currency_from != "" and currency_to != "":
            mic.say(" Getting exchange rate of " + currency_from + " against " + currency_to + ".")
            currency_input = 1
            currency_input_str = serviceNum.parseMagnitude(currency_input)

            try:
                # YAHOO Services
                rate = currencyConverterYahoo(currency_from, currency_to, currency_input)
                rateStr = serviceNum.parseMagnitude(rate)

            except (IOError, ValueError, KeyError, TypeError):
                pass  # invalid json
                mic.say(" An error occurred. Maybe the A P I is off line?")
                break

            else:
                pass  # valid json
                mic.say(" Okay, here is the exchange rate.")
                mic.say(
                    " It is approximately "
                    + rateStr
                    + " "
                    + currency_to
                    + " for "
                    + currency_input_str
                    + " "
                    + currency_from
                    + " ."
                )
                mic.say(" Do you want to continue?")
                ans = mic.activeListen()
                if "NO" in ans.split():
                    break
                continue
        else:
            mic.say(" One or both currencies are not understood. Please try again.")
            continue
示例#10
0
from semantic.numbers import NumberService

service = NumberService()

print service.parse("Two hundred and six")

print service.parse("Five point one five")

print service.parse("Eleven and two thirds")

print service.parseMagnitude("7e-05")
示例#11
0
def handle(text, mic, profile):
    # Vocab used in Currency Exchange Rate Module
    phrases = [
        "YES", "NO", "JAPANESE", "YEN", "AMERICAN", "DOLLAR", "INDIAN",
        "RUPEES", "EURO", "SWISS", "FRANC", "BRITISH", "POUND", "CHINESE",
        "YUAN"
    ]

    # Comment out below two lines if you are using Jasper in TEXT Mode
    currexch_stt_engine = mic.active_stt_engine.get_instance(
        'rateexch', phrases)
    mic = Mic(mic.speaker, mic.passive_stt_engine, currexch_stt_enginess)

    serviceNum = NumberService()

    def convertToCode(currency):

        code_list = {
            "INDIAN": "INR",
            "RUPEES": "INR",
            "YEN": "JPY",
            "JAPANESE": "JPY",
            "AMERICAN": "USD",
            "DOLLAR": "USD",
            "YUAN": "CNH",
            "CHINESE": "CNH",
            "EURO": "EUR",
            "POUND": "GBP",
            "BRITISH": "GBP",
            " SWISS": "CHF",
            "FRANC": "CHF"
        }

        for key, value in code_list.iteritems():
            if key in currency.split():
                return value
        return ''

    def currencyConverterYahoo(currency_from, currency_to, currency_input):
        yql_base_url = "https://query.yahooapis.com/v1/public/yql"
        yql_query = 'select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20("' + currency_from + currency_to + '")'
        yql_query_url = yql_base_url + "?q=" + yql_query + "&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"

        yql_response = urllib2.urlopen(yql_query_url)
        yql_json = json.loads(yql_response.read())
        currency_output = currency_input * float(
            yql_json['query']['results']['rate']['Rate'])
        return currency_output

    while True:
        mic.say(" First Currency?")
        currency_from = convertToCode(mic.activeListen())

        mic.say(" Second Currency?")
        currency_to = convertToCode(mic.activeListen())

        if currency_from != "" and currency_to != "":
            mic.say(" Getting exchange rate of " + currency_from +
                    " against " + currency_to + ".")
            currency_input = 1
            currency_input_str = serviceNum.parseMagnitude(currency_input)

            try:
                # YAHOO Services
                rate = currencyConverterYahoo(currency_from, currency_to,
                                              currency_input)
                rateStr = serviceNum.parseMagnitude(rate)

            except (IOError, ValueError, KeyError, TypeError):
                pass  # invalid json
                mic.say(" An error occurred. Maybe the A P I is off line?")
                break

            else:
                pass  # valid json
                mic.say(" Okay, here is the exchange rate.")
                mic.say(" It is approximately " + rateStr + " " + currency_to +
                        " for " + currency_input_str + " " + currency_from +
                        " .")
                mic.say(" Do you want to continue?")
                ans = mic.activeListen()
                if "NO" in ans.split():
                    break
                continue
        else:
            mic.say(
                " One or both currencies are not understood. Please try again."
            )
            continue
示例#12
0
 def testScientific(self):
     inp = 5e-05
     self.assertEqual(NumberService.parseMagnitude(inp),
                      '5 times ten to the negative 5')
示例#13
0
 def compareNumbers(self, inp, target):
     service = NumberService()
     result = service.parse(inp)
     self.assertEqual(result, target)
示例#14
0
 def testFloatCutoff(self):
     inp = "five point one three seven seven seven seven seven"
     self.assertEqual(NumberService.parseMagnitude(inp), '5.14')
示例#15
0
 def compareNumbers(self, input, target):
     service = NumberService()
     result = service.parse(input)
     self.assertEqual(result, target)
示例#16
0
 def testScientific(self):
     input = 5e-05
     self.assertEqual(NumberService.parseMagnitude(input),
                      '5 times ten to the negative 5')
示例#17
0
from semantic.dates import DateService

from semantic.dates import DateService

service = DateService()
date = service.extractDate("On March 3 at 12:15pm...")

#---------------------------------------------------
#this fails
# from semantic.solver import ConversionService
# service = ConversionService()
# print (service.convert("Seven and a half kilograms to pounds"))
# print (service.convert("Seven and a half pounds per square foot to kilograms per meter squared"))

#--------------
from semantic.numbers import NumberService

service = NumberService()
print(service.parse("Two hundred and six"))
# 206
print(service.parse("Five point one five"))
# 5.15
print(service.parse("Eleven and two thirds"))
# 11.666666666666666
print(service.parseMagnitude("7e-05"))
#--------------
#from semantic.solver import MathService
#service = MathService()
#print (service.parseEquation("Log one hundred and ten"))