PageRenderTime 89ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/DDG/Spice/Nutrition.pm

http://github.com/duckduckgo/zeroclickinfo-spice
Perl | 50 lines | 47 code | 2 blank | 1 comment | 0 complexity | 2311d0c4e0b1749489e138a615072fa3 MD5 | raw file
Possible License(s): Apache-2.0
  1. package DDG::Spice::Nutrition;
  2. # ABSTRACT: Nutrition information
  3. use strict;
  4. use DDG::Spice;
  5. my $attribute_regex = qr/(?^:(?^:(?:c(?:a(?:l(?:ories(?: from fat)?|cium|s)|rb(?:ohydrate)?s)|holesterol)|p(?:olyunsaturated fat|rotein)|trans(?: fat(?:ty acid)?|-fat)|s(?:aturated fat|odium|ugar)|monounsaturated fat|dietary fiber|f(?:iber|at)|vitamin [ac]|kcals|iron)))/;
  6. my $question_regex = qr/(?:how|what)?\s?(?:'s |is |are |many |much )?(?:the |there )?(?:total |amount of |number of )?/;
  7. # measurement triggers
  8. my @measurement_triggers = qw(calories kcals cals);
  9. # List of fruits, vegetables, meat, animal products triggers
  10. my @fruits = share('fruits.txt')->slurp(chomp => 1); # source https://simple.wikipedia.org/wiki/List_of_fruits
  11. my @vegetables = share('vegetables.txt')->slurp(chomp => 1); # source https://simple.wikipedia.org/wiki/List_of_vegetables
  12. my @meat = share('meat.txt')->slurp(chomp => 1);
  13. my @animal_products = share('animal_products.txt')->slurp(chomp => 1);
  14. my @fish = share('fish.txt')->slurp(chomp => 1);
  15. my @seafood = share('seafood.txt')->slurp(chomp => 1);
  16. my @otherfood = share('otherfood.txt')->slurp(chomp => 1);
  17. my @food_triggers = (@fruits, @vegetables, @meat, @animal_products, @fish, @seafood, @otherfood);
  18. my %food_triggers = map { $_ => 1 } @food_triggers;
  19. triggers any => @measurement_triggers;
  20. triggers startend => @food_triggers;
  21. # brand_id is hard coded to USDA for now. Eventually could support searches across brands (i.e. packaged goods or restaurants, but requires multiple
  22. # calls to their API so waiting for now
  23. spice to => 'http://api.nutritionix.com/v1_1/search/$1?results=0%3A20&brand_id=513fcc648110a4cafb90ca5e&fields=*&appId={{ENV{DDG_SPICE_NUTRITIONIX_APPID}}}&appKey={{ENV{DDG_SPICE_NUTRITIONIX_APIKEY}}}';
  24. spice wrap_jsonp_callback => 1;
  25. handle query_lc => sub {
  26. # check for matching fruits, vegetables, animal products, meat, ...
  27. return $_ if defined $food_triggers{$_};
  28. # check for queries like "how many calories are in a cucumber"
  29. if (/^$question_regex$attribute_regex\s?(?:are |contained |is )?(?:there )?(?:in )?(?:a |an )?(.+?)(?:\?)?$/) {
  30. return $1 if $1;
  31. }
  32. # for queries like "cucumber calories" or "tofu how much protein"
  33. if (/^(.+?)\s?$question_regex$attribute_regex(?:\?)?/) {
  34. return $1 if $1;
  35. }
  36. return;
  37. };
  38. 1;