Как ввести смешанную строку Amazon Alexa Skills Kit (ASK) с числами?

Я пытаюсь создать Amazon Alexa Skills Kit для какой-то автоматизации, которая потребуется для ввода речевого ввода, состоящего из строк и чисел (a-test12fish).

Когда я использовал пользовательские слоты в Alexa Skills Kit, он не позволял мне вводить строки с числами. Когда я пытаюсь ввести ask alexa, dangerZone find a-test12fish, я получаю следующую ошибку:

Ошибка: Неверный ввод текста. Текст должен начинаться с букв алфавита и должен содержать только буквы, пробелы, точки или апострофы.

Как я могу преодолеть эту ошибку?


person Sathish    schedule 17.03.2016    source источник
comment
Привет, Сатиш, ты уже понял это?   -  person Lightning Evangelist    schedule 07.06.2016


Ответы (4)


Вот решение.

Вы, вероятно, не хотите завершать это в схеме намерения. Вместо этого попробуйте создать собственный режим с помощью Node.js, который компилирует буквы, цифры и символы в один ответ. Это моя версия режима буквенно-цифрового ввода. Обратите внимание: я только что написал это в ответ на ваш вопрос и не проверял его в более широком навыке. С учетом сказанного, я добился большого успеха с MODES и, безусловно, применю это в своих навыках, когда у меня будет шанс.

Идея этого кода заключается в том, что вы переводите пользователей в отдельный режим, который игнорирует все намерения, кроме NumberIntent, LetterIntent, SymbolIntent и некоторых функций справки. Пользователь быстро вводит свое буквенно-цифровое значение и по завершении активирует CompletedIntent. Затем это буквенно-цифровое значение можно использовать в другом месте вашего навыка. Если вы не использовали Modes, обратите внимание, что по завершении или выходе вы будете перенаправлены обратно в LOBBYMODE, где вы сможете продолжить доступ к другим намерениям в вашем навыке.

var lobbyHandlers = Alexa.CreateStateHandler(states.LOBBYMODE, {

    'enterPasswordIntent': function () {
      this.attributes['BUILDPASSWORD'] = '';
      this.handler.state = states.PASSWORDMODE;
      message = ` You will now create a password one letter, number or symbol at a time.  there will be no message after each entry.  simply wait for alexa's ring to become solid blue then stay your next value.  When you are satisfied say complete. Begin now by saying a number, letter, or keyboard symbol. `;
      reprompt = `Please say a number letter or symbol`;
      this.emit(':ask', message, reprompt);
    },

    //Place other useful intents for your Skill here

    'Unhandled': function() {
        console.log("UNHANDLED");
        var reprompt = ` You're kind of in the middle of something.  Say exit to end createing this password.  otherwise say complete if you've stated the whole password.  or repeat to hear the current password you've entered.  `;
        this.emit(':ask', reprompt, reprompt);
    }
});


var buildAlphaNumericPasswordHandlers = Alexa.CreateStateHandler(states.PASSWORDMODE, {
    'numberIntent': function () {// Sample Utterance: ninty nine  AMAZON.NUMBER
      var number = this.event.request.intent.slots.number.value; //I believe this returns a string of digits ex: '999'
      this.attributes['BUILDPASSWORD'] = this.attributes['BUILDPASSWORD'].concat(number);
      message = ``; //No message to make saying the next letter, number or symbol as fluid as possible.
      reprompt = `Please say the next number letter or symbol`;
      this.emit(':ask', message, reprompt);
    },
    'letterIntent': function () {// Sample Utterance: A   -- Custom Slot LETTERS [A, b, c, d, e, ... ]
      var letter = this.event.request.intent.slots.letter.value;
      this.attributes['BUILDPASSWORD'] = this.attributes['BUILDPASSWORD'].concat(letter);
      message = ``; //No message to make saying the next letter, number or symbol as fluid as possible.
      reprompt = `Please say the next number letter or symbol`;
      this.emit(':ask', message, reprompt);
    },
    'symbolIntent': function () {// Sample Utterance: Dash -- Custom Slot SYMBOLS [Pound, Dash, Dollar Sign, At, Exclamation point... ]
      var symbol = this.event.request.intent.slots.symbol.value;

      // Create a dictionary object to map words to symbols ex Dollar Sign => $.  Will need this because you likely cant put $ as a custom slot value. Can also map multiple names to the same value  ex. Dash => Tack = \> "-"
      var singleCharacterSymbol = symbolDict[symbol]; //^^^ Need to create dictionary

      this.attributes['BUILDPASSWORD'] = this.attributes['BUILDPASSWORD'].concat(singleCharacterSymbol);
      message = ``; //No message to make saying the next letter, number or symbol as fluid as possible.
      reprompt = `Please say the next number letter or symbol`;
      this.emit(':ask', message, reprompt);
    },
    'CompleteIntent': function() { //Sample Utterance: Complete
        console.log("COMPLETE");
        this.handler.state = states.LOBBYMODE;
        var reprompt = ` Your entry has been saved, used to execute another function or checked against our database. `;
        this.emit(':ask', reprompt, reprompt);
    },
    'ExitIntent': function() { //Sample Utterance: Exit
        console.log("EXIT");
        this.handler.state = states.LOBBYMODE;
        message = `You have returned to the lobby, continue with the app or say quit to exit.`;
        this.emit(':ask', message, message);
    },
    'RepeatIntent': function() {
        var currentPassword = this.attributes['BUILDPASSWORD'];
        var currentPasswordExploded  =  currentPassword.replace(/(.)(?=.)/g, "$1 "); //insert a space between each character so alexa reads correctly.
        var message = ` Your current entry is as follows. `+currentPasswordExploded;
        var reprompt = `  say complete if you've stated the whole password. Otherwise continue to say numbers letters and symbols. `;
        this.emit(':ask', reprompt, reprompt);
    },
    'Unhandled': function() {
        console.log("UNHANDLED");
        var reprompt = ` You're kind of in the middle of something.  Say exit to end creating this password, say complete if you've stated the whole password, say repeat to hear the current password you've entered, or continue to state letters, numbers and symbols  `;
        this.emit(':ask', reprompt, reprompt);
    }
});
person Caleb Gates    schedule 04.08.2017

Вы не указали, как вы намеревались, чтобы пользователь сказал значение. Например, «проверка на двенадцать рыб» или «проверка на две рыбы». В любом случае, система распознавания предназначена для распознавания слов, и эти данные не являются действительным словом.

Что касается решения проблемы, вы можете попробовать создать решение для правописания (последний вход), создав пользовательский тип слота со всеми допустимыми значениями символов и образцами высказываний, поддерживающими допустимую длину.

Вам придется немного потрудиться, чтобы заново собрать сообщение, но это не должно быть слишком сложно. Вероятный вызов все равно будет исходить от распознавателя. Хотя я не тестировал этот сценарий под Alexa, большинство из тех, что я использовал, довольно плохо работают с буквенно-цифровыми строками переменной длины. Звуки слишком похожи, и есть несколько значений, которые можно легко принять за паузы и фоновые шумы. Типичный обходной путь – использование фонетического алфавита.

person Jim Rush    schedule 18.03.2016
comment
Спасибо за вклад, я хотел бы сказать, что это тест дефиса одна две рыбы, имею в виду, пока я пытаюсь использовать фонетический алфавит, как было предложено - person Sathish; 26.03.2016

Другой подход — играть в пределах ограничений системы. Вы могли бы сослаться на это с другим именем.

Подскажите пользователю "скажем 1 для a-test12fish" и так далее. И внутренне сопоставьте его с вашим конкретным значением.

person Markiv    schedule 23.11.2016

Используйте SSML, где вы можете создать свой собственный стиль произношения. Пожалуйста, проверьте.

person user1467280-Satyajit the truth    schedule 16.12.2016