ParserController.scala 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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(
  30. Future.successful(NotFound(s"No parser available for $url."))
  31. ) { (parser) =>
  32. val doc = _browser.get(url)
  33. val title = doc >> parser.titleExtractor
  34. val servings = (doc >?> parser.servingExtractor).flatten
  35. val prepTime = parser.prepTimeExtractor.flatMap(doc >?> _)
  36. val cookTime = parser.cookTimeExtractor.flatMap(doc >?> _)
  37. val ingredients = doc >> parser.ingredientExtractor
  38. val instructions = doc >> parser.instructionExtractor
  39. Future.sequence(ingredients.map({
  40. case (amt, u, line) => _guessFoodFromStr(line).map(Ingredient(_, amt, u))
  41. }))
  42. .map((ingredients) => Ok(Json.toJson(RecipeNodeNoId(
  43. title,
  44. servings.getOrElse(1.0f),
  45. 1.0f,
  46. UnitType.NUMBER,
  47. ingredients.toSeq,
  48. /* tflucke@[2023-10-26]: Do not pass along the instructions since this
  49. * could be a violation of the Recipe Author's copyright. */
  50. Nil, //instructions.toSeq,
  51. None,
  52. None,
  53. Some(url),
  54. None
  55. ))))
  56. }
  57. })
  58. private def _findParser(url: String): Option[Parser] = {
  59. val host = new java.net.URL(url).getAuthority()
  60. val hostNoWWW =
  61. if (host.startsWith("www.")) host.substring("www.".length) else host
  62. Map(
  63. ("epicurious.com" -> Parser.epicurious),
  64. ("mccormick.com" -> Parser.mccormick),
  65. ("recipetineats.com" -> Parser.recipeTinEats),
  66. ("mamalovestocook.com" -> Parser.recipeTinEats),
  67. ("soulfullymade.com" -> Parser.recipeTinEats),
  68. ("familycookierecipes.com" -> Parser.recipeTinEats),
  69. ("familyfreshmeals.com" -> Parser.recipeTinEats),
  70. ("handmadefarmhouse.com" -> Parser.recipeTinEats),
  71. ("sallysbakingaddiction.com" -> Parser.tastyRecipes),
  72. ("darngoodveggies.com" -> Parser.tastyRecipes),
  73. ("pickledplum.com" -> Parser.tastyRecipes),
  74. ("seriouseats.com" -> Parser.seriousEats),
  75. ("greatist.com" -> Parser.greatist),
  76. ("dimitrasdishes.com" -> Parser.dimitrasDishes),
  77. ("jif.com" -> Parser.jif),
  78. ("kingarthurbaking.com" -> Parser.kingArthurBaking)
  79. ).get(hostNoWWW)
  80. }
  81. private def _guessFoodFromStr(
  82. foodLine: String
  83. ): Future[Ingredient.IngredientId] = {
  84. val foodLineFiltered = foodLine
  85. .filter(_ <= 0x7f)
  86. .filterNot(_ == '!')
  87. .filterNot(_ == ':')
  88. .filterNot(_ == '/')
  89. searchFdcIndex(foodLineFiltered).transformWith {
  90. case Success(Some(ingredientId)) => Future.successful(ingredientId)
  91. case Success(None) => searchSelfIndex(foodLineFiltered)
  92. case Failure(e) => Future.failed(e)
  93. }
  94. }
  95. def searchFdcIndex(foodLine: String): Future[Option[Ingredient.IngredientId]] = {
  96. import gov.usda.nal.fdc.models.DataType._
  97. import gov.usda.nal.fdc.models.SearchResult
  98. usdaController.fdc.getFoodsSearch(foodLine, Seq(
  99. // Branded,
  100. Foundation, SRLegacy
  101. ), pageSize = Some(10))().flatMap({
  102. case SearchResult(_, _, _, _, Nil) => Future.successful(None)
  103. case SearchResult(_, _, _, _, foods) =>
  104. Future.sequence(
  105. foods.map((food) => foodController.getByFdcId(food.fdcId))
  106. ).map(_.flatten
  107. .headOption
  108. .fold[Ingredient.IngredientId](
  109. Ingredient.USDAId(foods.head.fdcId)
  110. )((foodNode) => Ingredient.FoodNodeId(foodNode._id))
  111. ).map(Some(_))
  112. })
  113. }
  114. def searchSelfIndex(foodLine: String): Future[Ingredient.IngredientId] = {
  115. foodController.findByName(foodLine)
  116. .transform {
  117. case Success(Nil) =>
  118. Failure(new NoSuchElementException(foodLine))
  119. case Success(foodNode::rest) =>
  120. Success(Ingredient.FoodNodeId(foodNode._id))
  121. case Failure(e) => Failure(e)
  122. }
  123. }
  124. }
  125. case class Parser(
  126. titleExtractor: HtmlExtractor[Element, String],
  127. servingExtractor: HtmlExtractor[Element, Option[Float]],
  128. prepTimeExtractor: Option[HtmlExtractor[Element, String]],
  129. cookTimeExtractor: Option[HtmlExtractor[Element, String]],
  130. ingredientExtractor: HtmlExtractor[Element, Iterable[(Float, MeasureUnit, String)]],
  131. instructionExtractor: HtmlExtractor[Element, Iterable[String]],
  132. )
  133. object Parser {
  134. val mccormick = Parser(
  135. text("h1"),
  136. // TODO use extractors
  137. text(".main-title .count").map(_.toFloatOption),
  138. Some(text(".prep_time .first_content")),
  139. cookTimeExtractor = Some(text(".ingredients .first_content")),
  140. ingredientExtractor = texts(".recipe-about-list li").map(
  141. _.map(_parseIngredient _)
  142. ),
  143. texts(".instructions-main span.para")
  144. )
  145. val epicurious = Parser(
  146. text("h1"),
  147. text("""div[data-testid="IngredientList"] > p""")
  148. .map("Yield: \\D*(\\d+).*".r.findFirstMatchIn(_).map(_.group(1).toFloat)),
  149. None,
  150. None,
  151. texts("""div[data-testid="IngredientList"] > div > div""").map(
  152. _.map(_parseIngredient _)
  153. ),
  154. texts("""div[data-testid="InstructionsWrapper"] > ol > li > p""")
  155. )
  156. val recipeTinEats = Parser(
  157. text("h2.wprm-recipe-name"),
  158. text("span.wprm-recipe-servings").map(_.toFloatOption),
  159. Some(text("span.wprm-recipe-prep_time-minutes")),
  160. Some(text("span.wprm-recipe-cook_time-minutes")),
  161. texts("li.wprm-recipe-ingredient")
  162. .map(_.map(_
  163. .replaceAll("\u00BD", "1/2")
  164. .replaceAll("\u00BC", "1/4")
  165. .replaceAll("\u00BE", "3/4")
  166. .replaceAll("\u2150", "1/7")
  167. .replaceAll("\u2151", "1/9")
  168. .replaceAll("\u2152", "1/10")
  169. .replaceAll("\u2153", "1/3")
  170. .replaceAll("\u2154", "2/3")
  171. .replaceAll("\u2155", "1/5")
  172. .replaceAll("\u2156", "2/5")
  173. .replaceAll("\u2157", "3/5")
  174. .replaceAll("\u2158", "4/5")
  175. .replaceAll("\u2159", "1/6")
  176. .replaceAll("\u215A", "5/6")
  177. .replaceAll("\u215B", "1/8")
  178. .replaceAll("\u215C", "3/8")
  179. .replaceAll("\u215D", "5/8")
  180. .replaceAll("\u215E", "7/8")
  181. .replaceAll("\u215F", "1/")
  182. .replaceAll("\u00F1", "n")
  183. .trim
  184. ))
  185. .map(_.map(_parseIngredient _)),
  186. texts("div.wprm-recipe-instruction-text")
  187. )
  188. val tastyRecipes = Parser(
  189. text("h2.tasty-recipes-title"),
  190. text("span.tasty-recipes-yield")
  191. .map("\\D*(\\d+).*".r.findFirstMatchIn(_).map(_.group(1).toFloat)),
  192. Some(text("span.tasty-recipes-prep-time")),
  193. Some(text("span.tasty-recipes-cook-time")),
  194. elementList("div.tasty-recipes-ingredients-body > ul > li").map(
  195. _.map({(listItem) => (
  196. ((listItem >?> elementList("span"))
  197. .flatMap(_.lastOption)
  198. .fold(0.0f)((elm: Element) =>
  199. (elm >?> attr("data-amount"))
  200. .fold(0.0f)(_.toFloat)
  201. )
  202. ),
  203. (listItem >?> elementList("span"))
  204. .flatMap(_.lastOption)
  205. .fold[MeasureUnit](Gram)((elm: Element) =>
  206. (elm >?> attr("data-unit"))
  207. .flatMap(MeasureUnit.guessUnit _)
  208. .getOrElse(Count)
  209. ),
  210. (listItem >?> text("strong")).getOrElse(listItem.ownText)
  211. )})
  212. ),
  213. texts("div.tasty-recipes-instructions-body > ol > li")
  214. )
  215. val seriousEats = Parser(
  216. text("h2.recipe-decision-block__title"),
  217. text("div.recipe-serving > span > span.meta-text__data")
  218. .map("\\D*(\\d+).*".r.findFirstMatchIn(_).map(_.group(1).toFloat)),
  219. //text("div.recipe-yield > span > span.meta-text__data")
  220. Some(text("div.prep-time > span > span.meta-text__data")),
  221. None, //Some(text("span.tasty-recipes-cook-time")),
  222. elementList("ul.structured-ingredients__list > li > p").map(
  223. _.map({(p) => (
  224. ((p >?> elementList("span"))
  225. .flatMap(_
  226. .filter((s) => (s >?> attr("data-ingredient-quantity")).isDefined)
  227. .lastOption
  228. .map(_ >> text)
  229. ).flatMap(_parseFraction _)
  230. .getOrElse(0.0f)
  231. ),
  232. ((p >?> elementList("span"))
  233. .flatMap(_
  234. .filter((s) => (s >?> attr("data-ingredient-unit")).isDefined)
  235. .lastOption
  236. .map(_ >> text)
  237. ).flatMap(MeasureUnit.guessUnit _)
  238. .getOrElse(Count)
  239. ),
  240. ((p >?> elementList("span"))
  241. .flatMap(_
  242. .filter((s) => (s >?> attr("data-ingredient-name")).isDefined)
  243. .headOption
  244. ).getOrElse(p).ownText
  245. )
  246. )})
  247. ),
  248. texts("div.structured-project__steps_1-0 > ol > li > p")
  249. )
  250. val greatist = Parser(
  251. text("h1"),
  252. elementList("article.article-body > ul > li").map(
  253. _.filter((listItem) => (listItem >?> text("strong")) == Some("Yield"))
  254. .map(_ >> text)
  255. .head
  256. ).map("Yield: \\D*(\\d+).*".r.findFirstMatchIn(_).map(_.group(1).toFloat)),
  257. // tflucke@[2023-11-28]: TODO They don't give passive, only Active + Total
  258. None,
  259. Some(
  260. elementList("article.article-body > ul > li").map(
  261. _.filter((listItem) => (listItem >?> text("strong")) == Some("Active"))
  262. .map(_ >> text)
  263. .head
  264. ).map("Active: \\D*(\\d+).*".r.findFirstMatchIn(_).fold("0")(_.group(1)))
  265. ),
  266. elementList("article.article-body > ul > li").map(_
  267. .filter((listItem) => (listItem >?> text("strong")) == None)
  268. .map(_ >> text)
  269. .map(_.replaceAll("\u00F1", "n"))
  270. .map(_parseIngredient _)
  271. ),
  272. texts("article.article-body > ol > li")
  273. )
  274. val dimitrasDishes = Parser(
  275. text("h2.mv-create-title-primary"),
  276. text("div.mv-create-time-yield > span").map(_.toFloatOption),
  277. None,
  278. None,
  279. texts("div.mv-create-ingredients > ul > li").map(
  280. _.map(_
  281. .replace("and", "")
  282. .replaceAll("\u00BD", "1/2")
  283. .replaceAll("\u00BC", "1/4")
  284. .replaceAll("\u00BE", "3/4")
  285. .replaceAll("\u2150", "1/7")
  286. .replaceAll("\u2151", "1/9")
  287. .replaceAll("\u2152", "1/10")
  288. .replaceAll("\u2153", "1/3")
  289. .replaceAll("\u2154", "2/3")
  290. .replaceAll("\u2155", "1/5")
  291. .replaceAll("\u2156", "2/5")
  292. .replaceAll("\u2157", "3/5")
  293. .replaceAll("\u2158", "4/5")
  294. .replaceAll("\u2159", "1/6")
  295. .replaceAll("\u215A", "5/6")
  296. .replaceAll("\u215B", "1/8")
  297. .replaceAll("\u215C", "3/8")
  298. .replaceAll("\u215D", "5/8")
  299. .replaceAll("\u215E", "7/8")
  300. .replaceAll("\u215F", "1/")
  301. .replaceAll("\u00F1", "n")
  302. .trim
  303. ).map(_parseIngredient _)
  304. ),
  305. texts("div.mv-create-instructions > ol > li")
  306. )
  307. val jif = Parser(
  308. text("h1.recipe-name"),
  309. elementList("div.recipe-breakdown-step").map(
  310. _.filter((listItem) => (listItem >?> text("i.servings")).isDefined)
  311. .map(_ >> text("span.recipe-breakdown-detail"))
  312. .head
  313. ).map(_.toFloatOption),
  314. Some(elementList("div.recipe-breakdown-step").map(
  315. _.filter((listItem) => (listItem >?> text("i.prep")).isDefined)
  316. .map(_ >> text("span.recipe-breakdown-detail"))
  317. .head
  318. )),
  319. Some(elementList("div.recipe-breakdown-step").map(
  320. _.filter((listItem) => (listItem >?> text("i.cook")).isDefined)
  321. .map(_ >> text("span.recipe-breakdown-detail"))
  322. .head
  323. )),
  324. texts("div.recipe-ingredients > ul > li")
  325. .map(_.map(_
  326. .replaceAll("\u00BD", "1/2")
  327. .replaceAll("\u00BC", "1/4")
  328. .replaceAll("\u00BE", "3/4")
  329. .replaceAll("\u2150", "1/7")
  330. .replaceAll("\u2151", "1/9")
  331. .replaceAll("\u2152", "1/10")
  332. .replaceAll("\u2153", "1/3")
  333. .replaceAll("\u2154", "2/3")
  334. .replaceAll("\u2155", "1/5")
  335. .replaceAll("\u2156", "2/5")
  336. .replaceAll("\u2157", "3/5")
  337. .replaceAll("\u2158", "4/5")
  338. .replaceAll("\u2159", "1/6")
  339. .replaceAll("\u215A", "5/6")
  340. .replaceAll("\u215B", "1/8")
  341. .replaceAll("\u215C", "3/8")
  342. .replaceAll("\u215D", "5/8")
  343. .replaceAll("\u215E", "7/8")
  344. .replaceAll("\u215F", "1/")
  345. .replaceAll("\u00F1", "n")
  346. .trim
  347. ))
  348. .map(_.map(_parseIngredient _)),
  349. texts("div.recipe-directions > ul > li > p")
  350. )
  351. val kingArthurBaking = Parser(
  352. text("h1 > span"),
  353. text("div.stat__item--yield > span").map(_.toFloatOption),
  354. Some(text("div.stat__item--prep > span")),
  355. Some(text("div.stat__item--bake > span")),
  356. texts("div.ingredient-section > ul > li")
  357. .map(_.map(_
  358. .replaceAll("\u00BD", "1/2")
  359. .replaceAll("\u00BC", "1/4")
  360. .replaceAll("\u00BE", "3/4")
  361. .replaceAll("\u2150", "1/7")
  362. .replaceAll("\u2151", "1/9")
  363. .replaceAll("\u2152", "1/10")
  364. .replaceAll("\u2153", "1/3")
  365. .replaceAll("\u2154", "2/3")
  366. .replaceAll("\u2155", "1/5")
  367. .replaceAll("\u2156", "2/5")
  368. .replaceAll("\u2157", "3/5")
  369. .replaceAll("\u2158", "4/5")
  370. .replaceAll("\u2159", "1/6")
  371. .replaceAll("\u215A", "5/6")
  372. .replaceAll("\u215B", "1/8")
  373. .replaceAll("\u215C", "3/8")
  374. .replaceAll("\u215D", "5/8")
  375. .replaceAll("\u215E", "7/8")
  376. .replaceAll("\u215F", "1/")
  377. .replaceAll("\u00F1", "n")
  378. .trim
  379. ))
  380. .map(_.map(_parseIngredient _)),
  381. texts("div.field field--recipe-steps > ol > li > p")
  382. )
  383. private def _parseFraction(fractionLine: String) = {
  384. val fractionPattern = raw"(\d+)/(\d+)[\d-_]*".r
  385. val mixedFractionPattern = raw"(\d+)\w+(\d+)/(\d+)[\d-_]*".r
  386. fractionLine match {
  387. case fractionPattern(numerator, denominator) =>
  388. Some(numerator.toFloat/denominator.toFloat)
  389. case mixedFractionPattern(whole, numerator, denominator) =>
  390. Some(whole.toFloat + numerator.toFloat/denominator.toFloat)
  391. case _ => fractionLine.toFloatOption
  392. }
  393. }
  394. private def _parseIngredient(
  395. ingredientLine: String
  396. ): (Float, MeasureUnit, String) = {
  397. val numberPattern = raw"(\d+)[\d-_]*\s(\w+)\s+(.+)".r
  398. val fractionPattern = raw"(\d+)/(\d+)[\d-_]*\s(\w+)\s+(.+)".r
  399. val mixedFractionPattern = raw"(\d+)\w+(\d+)/(\d+)\s(\w+)\s+(.+)".r
  400. ingredientLine match {
  401. case mixedFractionPattern(whole, numerator, denominator, unit, rest) =>
  402. (
  403. whole.toFloat + numerator.toFloat/denominator.toFloat,
  404. MeasureUnit.guessUnit(unit).getOrElse(Count),
  405. rest
  406. )
  407. case fractionPattern(numerator, denominator, unit, rest) =>
  408. (
  409. numerator.toFloat/denominator.toFloat,
  410. MeasureUnit.guessUnit(unit).getOrElse(Count),
  411. rest
  412. )
  413. case numberPattern(amount, unit, rest) =>
  414. (amount.toFloat, MeasureUnit.guessUnit(unit).getOrElse(Count), rest)
  415. case noUnitLine =>
  416. (1, Count, noUnitLine)
  417. }
  418. }
  419. }