How do I train on time when I already know the date? - bixby

I'm looking to filter by a time interval. For example, from 9am to noon. It is unclear how to create that functionality in the training and action concept. For example, I currently have this:

You should train it with DateTimeExpression and use the DateTimeInterval component to get the actual difference
action (TestDateTimeInterval) {
type(Search)
description (__DESCRIPTION__)
collect {
input (dateTimeExpression) {
type (time.DateTimeExpression)
min (Optional) max (One)
}
}
output (core.Integer)
}
Action Javascript
module.exports.function = function testDateTimeInterval (dateTimeExpression) {
var dates = require ('dates')
var whenStart;
var whenEnd;
if (dateTimeExpression.dateTimeInterval) {
whenStart = dates.ZonedDateTime.of(
dateTimeExpression.dateTimeInterval.start.date.year,
dateTimeExpression.dateTimeInterval.start.date.month,
dateTimeExpression.dateTimeInterval.start.date.day,
dateTimeExpression.dateTimeInterval.start.time.hour,
dateTimeExpression.dateTimeInterval.start.time.minute,
dateTimeExpression.dateTimeInterval.start.time.second);
whenEnd = dates.ZonedDateTime.of(
dateTimeExpression.dateTimeInterval.end.date.year,
dateTimeExpression.dateTimeInterval.end.date.month,
dateTimeExpression.dateTimeInterval.end.date.day,
dateTimeExpression.dateTimeInterval.end.time.hour,
dateTimeExpression.dateTimeInterval.end.time.minute,
dateTimeExpression.dateTimeInterval.end.time.second);
// If you intend to return the difference between the number of hours
return dateTimeExpression.dateTimeInterval.end.time.hour - dateTimeExpression.dateTimeInterval.start.time.hour
}
return -1;
}

Related

Bixby: Audio player concept

I am showing artist to user and following up by asking if user wanted to listen the song of this artist.
Endpoint
action-endpoint (PlayArtist) {
accepted-inputs (artist_id) // here too yellow line (Missing required input `artistToPlay`)
local-endpoint (PlayArtist.js)
}
action-endpoint (BuildArtistAudioInfo) {
accepted-inputs (artist_id)
local-endpoint (BuildArtistAudioInfo.js)
}
BuildArtistAudioInfo.model.bxb
action (BuildArtistAudioInfo) {
type (Search)
description (Makes a meow info to play.)
collect{
input (artist_id){
type (ArtistID)
min (Optional)
max (One)
}
}
output (audioPlayer.AudioInfo)
}
Follow-up
followup {
prompt {
dialog (Would you like to play music for this artist)
on-confirm {
if (false) {
message (I see...)
} else {
intent {
goal: PlayArtist
value: $expr(singleArtistEvent.artistId)
}
}
}
on-deny {
message (OK friend.)
}
}
}
Now i need to pass this value to PlayArtist action file but after seeing your sample capsule i am confused where to pass the input.
PlayArtist Action file
action (PlayArtist) {
type (Search)
collect {
input (artist_id){
type (ArtistID)
min (Optional)
max (One)
}
computed-input (artistToPlay) {
description (Create the playlist to play)
type (audioPlayer.AudioInfo)
min (Required) max (One)
compute {
intent {
goal: BuildArtistAudioInfo
value:ArtistID(artist_id) // i am confused over here, it's giving error ()
}
}
//hidden
}
computed-input (play) {
description (By passing in the AudioInfo object to the PlayAudio action, we ask the client to play our sound.)
type (audioPlayer.Result)
compute {
intent {
goal: audioPlayer.PlayAudio
value: $expr(artistToPlay)
}
}
//hidden
}
}
output (Result)
}
Do i need to extra accept-input? also BuildArtistAudioInfo.js file has songs info, so i need to get the artist id here and proceed it to the api where I will get song info. please guide.
You need an input artistID in action model PlayArtist and action model BuildArtistAudioInfo, that's how the artistID pass to BuildArtistAudioInfo.js as an argument
In computed-input (artistToPlay), intent block should have a value field
Use value in intent instead of value-set, since it's single value, not a set
Make sure in endpoints.bxb you correctly link JS file to action model, that is accepted input and argument name must match.

How to prevent duplicate action execution in Bixby?

I want to implement a capsule that does a calculation if the user provides the full input necessary for the calculation or asks the user for the necessary input if the user doesn't provide the full input with the very first request. Everything works if the user provides the full request. If the user doesn't provide the full request but Bixby needs more information, I run into some strange behavior where the Calculation is being called more than once and Bixby takes the necessary information for the Calculation from a result of another Calculation, it looks like in the debug graph.
To easier demonstrate my problem I've extended the dice sample capsule capsule-sample-dice and added numSides and numDice to the RollResultConcept, so that I can access the number of dice and sides in the result.
RollResult.model.bxb now looks like this:
structure (RollResultConcept) {
description (The result object produced by the RollDice action.)
property (sum) {
type (SumConcept)
min (Required)
max (One)
}
property (roll) {
description (The list of results for each dice roll.)
type (RollConcept)
min (Required)
max (Many)
}
// The two properties below have been added
property (numSides) {
description (The number of sides that the dice of this roll have.)
type (NumSidesConcept)
min (Required)
max (One)
}
property (numDice) {
description (The number of dice in this roll.)
type (NumDiceConcept)
min (Required)
max (One)
}
}
I've also added single-lines in RollResult.view.bxb so that the number of sides and dice are being shown to the user after a roll.
RollResult.view.bxb:
result-view {
match {
RollResultConcept (rollResult)
}
render {
layout {
section {
content {
single-line {
text {
style (Detail_M)
value ("Sum: #{value(rollResult.sum)}")
}
}
single-line {
text {
style (Detail_M)
value ("Rolls: #{value(rollResult.roll)}")
}
}
// The two single-line below have been added
single-line {
text {
style (Detail_M)
value ("Dice: #{value(rollResult.numDice)}")
}
}
single-line {
text {
style (Detail_M)
value ("Sides: #{value(rollResult.numSides)}")
}
}
}
}
}
}
}
Edit: I forgot to add the code that I changed in RollDice.js, see below:
RollDice.js
// RollDice
// Rolls a dice given a number of sides and a number of dice
// Main entry point
module.exports.function = function rollDice(numDice, numSides) {
var sum = 0;
var result = [];
for (var i = 0; i < numDice; i++) {
var roll = Math.ceil(Math.random() * numSides);
result.push(roll);
sum += roll;
}
// RollResult
return {
sum: sum, // required Sum
roll: result, // required list Roll
numSides: numSides, // required for numSides
numDice: numDice // required for numDice
}
}
End Edit
In the Simulator I now run the following query
intent {
goal: RollDice
value: NumDiceConcept(2)
}
which is missing the required NumSidesConcept.
Debug view shows the following graph, with NumSidesConcept missing (as expected).
I now run the following query in the simulator
intent {
goal: RollDice
value: NumDiceConcept(2)
value: NumSidesConcept(6)
}
which results in the following Graph in Debug view:
and it looks like to me that the Calculation is being done twice in order to get to the Result. I've already tried giving the feature { transient } to the models, but that didn't change anything. Can anybody tell me what's happening here? Am I not allowed to use the same primitive models in an output because they will be used by Bixby when trying to execute an action?
I tried modifying the code as you have but was unable to run the intent (successfully).
BEGIN EDIT
I added the additional lines in RollDice.js and was able to see the plan that you are seeing.
The reason for the double execution is that you ran the intents consecutively and Bixby derived the value of the NumSidesConcept that you did NOT specify in the first intent, from the second intent, and executed the first intent.
You can verify the above by providing a different set of values to NumSidesConcept and NumDiceConcept in each of the intents.
If you had given enough time between these two intents, then the result would be different. In your scenario, the first intent was waiting on a NumSidesConcept to be available, and as soon as the Planner found it (from the result of the second intent), the execution went through.
How can you avoid this? Make sure that you have an input-view for each of the inputs so Bixby can prompt the user for any values that did not come through the NL (or Aligned NL).
END EDIT
Here is another approach that will NOT require changing the RollResultConcept AND will work according to your expectations (of accessing the number of dice and sides in the result-view)
result-view {
match: RollResultConcept (rollResult) {
from-output: RollDice(action)
}
render {
layout {
section {
content {
single-line {
text {
style (Detail_M)
value ("Sum: #{value(rollResult.sum)}")
}
}
single-line {
text {
style (Detail_M)
value ("Rolls: #{value(rollResult.roll)}")
}
}
// The two single-line below have been added
single-line {
text {
style (Detail_M)
value ("Dice: #{value(action.numDice)}")
}
}
single-line {
text {
style (Detail_M)
value ("Sides: #{value(action.numSides)}")
}
}
}
}
}
}
}
Give it a shot and let us know if it works!

Bixby: How do I set an initial-value to self BirthdayInfo in a date-picker within a input-view?

What additional steps do I need to take set the date-picker's initial-value to the user's birthday using the viv.self library? Is this the best place to handle this? Currently I am setting the default to 30 Years Prior.
render {
date-picker {
// Default Date -30 Years (viv.self Birthday Option)
initial-value ("subtractDuration(now().date, 'P30Y')")
restrictions {
// allow selection 80 Years Ago
min-allowed ("subtractDuration(now().date, 'P80Y')")
// to allow selection 18 Years Ago
max-allowed ("subtractDuration(now().date, 'P18Y')")
}
}
}
You can use a match-pattern to achieve this.
Birthday is a part of the viv.contact library but is not available in the viv.self library.
In your Action, create an additional attribute of type time.Date (or a concept with role-of of time.Date) to hold the Birthday.
Heres how the code would look like.
action (GetBirthDate) {
type(Constructor)
description (Collect the date selected by a user)
collect {
input (usersBirthday) {
type (BirthDate)
min (Required) max (One)
default-init {
intent {
// TO-DO Get the birthday with an intent
}
}
}
// This input will hold the value entered by the user
computed-input (birthDate) {
type (BirthDate)
min (Required) max (One)
compute {
intent {
goal: BirthDate
}
}
}
} output (BirthDate)
}
The BirthDate concept used in the code above looks like this
structure (BirthDate) {
description (__DESCRIPTION__)
role-of (time.Date)
}
Your input-view will look like this. This defines a match-pattern that is invoked whenever we need an input view for BirthDate and that BirthDate is functioning as an input back to the action.
Checkout match patterns here: https://bixbydevelopers.com/dev/docs/dev-guide/developers/customizing-plan.match-patterns
input-view {
match: BirthDate (this) {
to-input {
GetBirthDate (action)
}
}
render {
date-picker {
initial-value (action.usersBirthday)
restrictions {
// allow selection 80 Years Ago
min-allowed ("subtractDuration(now().date, 'P80Y')")
// to allow selection 18 Years Ago
max-allowed ("subtractDuration(now().date, 'P18Y')")
}
}
}
}

Updating time and date in wit-ai weather example

I am trying to extend the wit-ai weather example by adding wit/datetime to the mix.
For example a user might type "How cold will it be in Berlin in 1 hour?" and the weather bot will bring back the data for the weather in 1 hour in Berlin.
So far this works, but when I try to setup missingDate in order to ask the date if it's missing it behaves kind of funny.
A dialogue would be:
- How cold will it be in Berlin?
- In what time?
- In 1 hour.
Instead, after the 1 hour step, I get asked again for the location which is in the context, but instead is triggered again.
My action is named getForecast({context, entities}) and I have defined it as below:
actions:
[...],
getForecast({ context, entities }) {
console.log(`The current context is: ${JSON.stringify(context)}`);
console.log(`Wit extracted ${JSON.stringify(entities)}`);
// extract entity
var location = firstEntityValue(entities, "location");
var date = firstEntityValue(entities, "datetime");
// if the entity exists, do a remote weather call.
if (date) {
context.date = date;
delete context.missingDate;
} else {
context.missingDate = true;
delete context.date;
delete context.forecast;
}
if (location) {
context.forecast = '38 degrees';
context.location = location;
delete context.missingLocation;
} else {
context.missingLocation = true;
delete context.forecast;
}
// return the context object
return Promise.resolve(context);
}

moment.js reverse .fromNow()

So i'm working with moment.js.
I see you can translate a date into a human-friendly format using moment().fromNow();
Is there a way to do the opposite?
For example, I want to turn this --> "2 weeks ago" into a normal date format or UNIX timestamp.
I sifted through the documentation but couldnt find anything. Any direction would help, thanks.
Depending on how complicated/different the input strings can be, you could do this:
//parse out the number and the duration
var inputString = "2 weeks ago";
var myRegExp = /^(\d+)\s(\w+)\sago$/;
var results = myRegExp.exec(inputString);
var num = results[1];
var duration = results[2];
moment().subtract(duration,num).toString() //or whatever format you prefer
Note this will work for input strings of the format "number duration ago".
Hope that helps!
In some cases .fromNow() returns string like "30+ days ago". The regex provided in above solution doesn't handle to parse that properly.
Here's the updated regex to handle that case:
var myRegExp = /^(\d+)\+?\s(\w+)\sago$/;
Here is the method that I used to reverse it for the current moment.js locale. I tested it on a few locales and it should work for every locale but it might not.
Change the last two .toString() functions to .valueOf() to get numerical values.
Moment actually doesn't have the week name data for all languages right now, so the function will assume that the string is a week if it could not find the value.
Some languages use translation functions instead of having built in values so the script will not work on those either! If you manually specify your language data then it should work.
//test en locale
moment.locale("en");
console.log(reversefromNow("5 days ago"));
console.log(reversefromNow("in 5 days"));
//test ja locale
moment.locale("ja");
console.log(reversefromNow("5 日前"));
console.log(reversefromNow("5 日後"));
function reversefromNow(input) {
let relativeLocale = JSON.parse(JSON.stringify(moment.localeData()._relativeTime));
let pastfutureObject = {
future: relativeLocale.future,
past: relativeLocale.past
};
delete relativeLocale.future;
delete relativeLocale.past;
//detect if past or future
let pastfuture;
for (const [key, value] of Object.entries(pastfutureObject)) {
if (input.indexOf(value.replace("%s", "")) != -1) {
pastfuture = key;
}
}
//detect the time unit
let unitkey;
for (const [key, value] of Object.entries(relativeLocale)) {
if (input.indexOf(value.replace("%d", "")) != -1) {
unitkey = key.charAt(0);
}
}
//if its not in the data, then assume that it is a week
if (unitkey == null) {
unitkey = "w";
}
const units = {
M: "month",
d: "day",
h: "hour",
m: "minute",
s: "second",
w: "week",
y: "year"
};
//Detect number value
const regex = /(\d+)/g;
let numbervalue = input.match(regex) || [1];
//Add if future, subtract if past
if (pastfuture == "past") {
return moment().subtract(numbervalue, units[unitkey]).valueOf();
} else {
return moment().add(numbervalue, units[unitkey]).valueOf();
}
}

Resources