ParserController.scala 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. package com.weEat.controllers
  2. import com.weEat.shared.models._
  3. import javax.inject.{Inject,Singleton}
  4. import play.api.libs.json._
  5. import play.api.mvc._
  6. import scala.concurrent.Future
  7. import com.weEat.models.Authorization
  8. import scalaoauth2.provider.{AuthInfoRequest,OAuth2ProviderActionBuilders}
  9. import com.weEat.services.OAuth2Service
  10. import net.ruippeixotog.scalascraper.browser.JsoupBrowser
  11. import net.ruippeixotog.scalascraper.dsl.DSL._
  12. import net.ruippeixotog.scalascraper.dsl.DSL.Extract._
  13. //import net.ruippeixotog.scalascraper.dsl.DSL.Parse._
  14. import net.ruippeixotog.scalascraper.model.Element
  15. import net.ruippeixotog.scalascraper.scraper.HtmlExtractor
  16. import scala.util._
  17. @Singleton
  18. class ParserController @Inject()(
  19. val controllerComponents: ControllerComponents,
  20. oauth: OAuth2Service,
  21. usdaController: USDAController,
  22. foodController: FoodController
  23. ) extends BaseController
  24. with OAuth2ProviderActionBuilders {
  25. implicit val ec = scala.concurrent.ExecutionContext.global
  26. private val _browser = JsoupBrowser()
  27. def parseURL() = AuthorizedAction[Authorization](oauth).async(parse.text)({ implicit request: AuthInfoRequest[String, Authorization] =>
  28. val url = request.body
  29. _findParser(url).fold(Future.successful(NotFound(s"No parser available for $url."))) { (parser) =>
  30. val doc = _browser.get(url)
  31. val title = doc >> parser.titleExtractor
  32. val servings = doc >> parser.servingExtractor
  33. val prepTime = parser.prepTimeExtractor.flatMap(doc >?> _)
  34. val cookTime = parser.cookTimeExtractor.flatMap(doc >?> _)
  35. val ingredients = doc >> parser.ingredientExtractor
  36. val instructions = doc >> parser.instructionExtractor
  37. Future.sequence(ingredients.map({
  38. case (amt, u, line) => _guessFoodFromStr(line).map(Ingredient(_, amt, u))
  39. }))
  40. .map((ingredients) => Ok(Json.toJson(RecipeNodeNoId(
  41. title,
  42. servings.getOrElse(1.0f),
  43. 1.0f,
  44. UnitType.NUMBER,
  45. ingredients.toSeq,
  46. /* tflucke@[2023-10-26]: Do not pss along the instructions since this
  47. * could be a violation of the Recipe Author's copyright. */
  48. Nil, //instructions.toSeq,
  49. None,
  50. None,
  51. Some(url),
  52. None
  53. ))))
  54. }
  55. })
  56. private def _findParser(url: String): Option[Parser] = {
  57. val host = new java.net.URL(url).getAuthority()
  58. val hostNoWWW = if (host.startsWith("www.")) host.substring("www.".length) else host
  59. Map(
  60. ("epicurious.com" -> Parser.epicurious),
  61. ("mccormick.com" -> Parser.mccormick),
  62. ("recipetineats.com" -> Parser.recipeTinEats),
  63. ("mamalovestocook.com" -> Parser.recipeTinEats),
  64. ("sallysbakingaddiction.com" -> Parser.sallysBakingAddiction)
  65. ).get(hostNoWWW)
  66. }
  67. private def _guessFoodFromStr(foodLine: String): Future[Ingredient.IngredientId] = {
  68. import gov.usda.nal.fdc.models.DataType._
  69. usdaController.fdc.getFoodsSearch(foodLine
  70. .filter(_ <= 0x7f)
  71. .filterNot(_ == ':')
  72. .filterNot(_ == '/'), Seq(
  73. Foundation, Survey, SRLegacy
  74. ), pageSize = Some(10))().flatMap({ (fdcResult) =>
  75. Future.sequence(
  76. fdcResult.foods.map((food) => foodController.getByFdcId(food.fdcId))
  77. ).map(_.flatten
  78. .headOption
  79. .fold[Ingredient.IngredientId](
  80. Ingredient.USDAId(fdcResult.foods.head.fdcId)
  81. )((foodNode) => Ingredient.FoodNodeId(foodNode._id))
  82. ).transform({
  83. case Success(x) => Success(x)
  84. case Failure(x) => println(s"Food lookup failed: $x");Failure(x)
  85. })
  86. })
  87. }
  88. }
  89. case class Parser(
  90. titleExtractor: HtmlExtractor[Element, String],
  91. servingExtractor: HtmlExtractor[Element, Option[Float]],
  92. prepTimeExtractor: Option[HtmlExtractor[Element, String]],
  93. cookTimeExtractor: Option[HtmlExtractor[Element, String]],
  94. ingredientExtractor: HtmlExtractor[Element, Iterable[(Float, MeasureUnit, String)]],
  95. instructionExtractor: HtmlExtractor[Element, Iterable[String]],
  96. )
  97. object Parser {
  98. val mccormick = Parser(
  99. text("h1"),
  100. // TODO use extractors
  101. text(".main-title .count").map(_.toFloatOption),
  102. Some(text(".prep_time .first_content")),
  103. cookTimeExtractor = Some(text(".ingredients .first_content")),
  104. ingredientExtractor = texts(".recipe-about-list li").map(_.map(_parseIngredient _)),
  105. texts(".instructions-main span.para")
  106. )
  107. val epicurious = Parser(
  108. text("h1"),
  109. text("""div[data-testid="IngredientList"] > p""")
  110. .map("Yield: \\D*(\\d+).*".r.findFirstMatchIn(_).map(_.group(1).toFloat)),
  111. None,
  112. None,
  113. texts("""div[data-testid="IngredientList"] > div > div""").map(_.map(_parseIngredient _)),
  114. texts("""div[data-testid="InstructionsWrapper"] > ol > li > p""")
  115. )
  116. val recipeTinEats = Parser(
  117. text("h2.wprm-recipe-name"),
  118. text("span.wprm-recipe-servings").map(_.toFloatOption),
  119. Some(text("span.wprm-recipe-prep_time-minutes")),
  120. Some(text("span.wprm-recipe-cook_time-minutes")),
  121. texts("li.wprm-recipe-ingredient")
  122. .map(_.map(_
  123. .replaceAll("\u00BD", "1/2")
  124. .replaceAll("\u00BC", "1/4")
  125. .replaceAll("\u00BE", "3/4")
  126. .replaceAll("\u2150", "1/7")
  127. .replaceAll("\u2151", "1/9")
  128. .replaceAll("\u2152", "1/10")
  129. .replaceAll("\u2153", "1/3")
  130. .replaceAll("\u2154", "2/3")
  131. .replaceAll("\u2155", "1/5")
  132. .replaceAll("\u2156", "2/5")
  133. .replaceAll("\u2157", "3/5")
  134. .replaceAll("\u2158", "4/5")
  135. .replaceAll("\u2159", "1/6")
  136. .replaceAll("\u215A", "5/6")
  137. .replaceAll("\u215B", "1/8")
  138. .replaceAll("\u215C", "3/8")
  139. .replaceAll("\u215D", "5/8")
  140. .replaceAll("\u215E", "7/8")
  141. .replaceAll("\u215F", "1/")
  142. .trim
  143. ))
  144. .map(_.map(_parseIngredient _)),
  145. texts("div.wprm-recipe-instruction-text")
  146. )
  147. val sallysBakingAddiction = Parser(
  148. text("h2.tasty-recipes-title"),
  149. text("span.tasty-recipes-yield")
  150. .map("\\D*(\\d+).*".r.findFirstMatchIn(_).map(_.group(1).toFloat)),
  151. Some(text("span.tasty-recipes-prep-time")),
  152. Some(text("span.tasty-recipes-cook-time")),
  153. elementList("div.tasty-recipes-ingredients-body > ul > li").map(_.map({(listItem) => (
  154. ((listItem >?> elementList("span"))
  155. .map(_.last)
  156. .fold(0.0f)((elm: Element) => (elm >?> attr("data-amount")).fold(0.0f)(_.toFloat))
  157. ),
  158. (listItem >?> elementList("span"))
  159. .map(_.last)
  160. .fold[MeasureUnit](Gram)((elm: Element) => (elm >?> attr("data-unit")).flatMap(MeasureUnit.guessUnit _).getOrElse(Count)),
  161. listItem >> text("strong")
  162. )})),
  163. texts("div.tasty-recipes-instructions-body > ol > li")
  164. )
  165. private def _parseIngredient(ingredientLine: String): (Float, MeasureUnit, String) = {
  166. val numberPattern = raw"(\d+)[\d-_]*\s(\w+)\s+(.+)".r
  167. val fractionPattern = raw"(\d+)/(\d+)[\d-_]*\s(\w+)\s+(.+)".r
  168. ingredientLine match {
  169. case numberPattern(amount, unit, rest) =>
  170. (amount.toFloat, MeasureUnit.guessUnit(unit).getOrElse(Count), rest)
  171. case fractionPattern(numerator, denominator, unit, rest) =>
  172. (numerator.toFloat/denominator.toFloat, MeasureUnit.guessUnit(unit).getOrElse(Count), rest)
  173. case noUnitLine =>
  174. (1, Count, noUnitLine)
  175. }
  176. }
  177. }