-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathingredients.go
570 lines (513 loc) · 14.9 KB
/
ingredients.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
package ingredients
//go:generate go run corpus/main.go
//go:generate gofmt -w corpus.go
import (
"bytes"
// "encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"strings"
"time"
json "github.com/goccy/go-json"
"github.com/jinzhu/inflection"
log "github.com/schollz/logger"
"golang.org/x/net/html"
"golang.org/x/net/html/atom"
)
func init() {
inflection.AddSingular("(clove)(s)?$", "${1}")
inflection.AddSingular("(potato)(es)?$", "${1}")
inflection.AddSingular("(tomato)(es)?$", "${1}")
inflection.AddUncountable("molasses")
inflection.AddUncountable("bacon")
}
// Recipe contains the info for the file and the lines
type Recipe struct {
FileName string `json:"filename"`
FileContent string `json:"file_content"`
Lines []LineInfo `json:"lines"`
Ingredients []Ingredient `json:"ingredients"`
}
// LineInfo has all the information for the parsing of a given line
type LineInfo struct {
LineOriginal string
Line string `json:",omitempty"`
IngredientsInString []WordPosition `json:",omitempty"`
AmountInString []WordPosition `json:",omitempty"`
MeasureInString []WordPosition `json:",omitempty"`
Ingredient Ingredient `json:",omitempty"`
}
// Ingredient is the basic struct for ingredients
type Ingredient struct {
Name string `json:"name,omitempty"`
Comment string `json:"comment,omitempty"`
Measure Measure `json:"measure,omitempty"`
Line string `json:"line,omitempty"`
}
// Measure includes the amount, name and the cups for conversions
type Measure struct {
Amount float64 `json:"amount"`
Name string `json:"name"`
Cups float64 `json:"cups"`
Weight float64 `json:"weight,omitempty"`
}
// IngredientList is a list of ingredients
type IngredientList struct {
Ingredients []Ingredient `json:"ingredients"`
}
func (il IngredientList) String() string {
s := ""
for _, ing := range il.Ingredients {
name := ing.Name
if ing.Measure.Amount > 1 && ing.Measure.Name == "whole" {
name = inflection.Plural(name)
}
s += fmt.Sprintf("%s %s %s", AmountToString(ing.Measure.Amount), ing.Measure.Name, name)
if ing.Comment != "" {
s += " (" + ing.Comment + ")"
}
s += "\n"
}
return s
}
// Save saves the recipe to a file
func (r *Recipe) Save(fname string) (err error) {
b, err := json.MarshalIndent(r, "", " ")
if err != nil {
return
}
err = ioutil.WriteFile(fname, b, 0644)
return
}
// Load will load a recipe file
func Load(fname string) (r *Recipe, err error) {
b, err := ioutil.ReadFile(fname)
if err != nil {
return
}
r = new(Recipe)
err = json.Unmarshal(b, r)
return
}
// ParseTextIngredients parses a list of ingredients and
// returns an ingredient list back
func ParseTextIngredients(text string) (ingredientList IngredientList, err error) {
r := &Recipe{FileName: "lines"}
r.FileContent = text
lines := strings.Split(text, "\n")
i := 0
goodLines := make([]string, len(lines))
for _, line := range lines {
line = strings.TrimSpace(line)
if len(line) == 0 {
continue
}
goodLines[i] = line
i++
}
_, r.Lines = scoreLines(goodLines)
err = r.parseRecipe()
if err != nil {
return
}
ingredientList = r.IngredientList()
return
}
// NewFromFile generates a new parser from a HTML file
func NewFromFile(fname string) (r *Recipe, err error) {
r = &Recipe{FileName: fname}
b, err := ioutil.ReadFile(fname)
r.FileContent = string(b)
err = r.parseHTML()
return
}
// NewFromString generates a new parser from a HTML string
func NewFromString(htmlString string) (r *Recipe, err error) {
r = &Recipe{FileName: "string"}
r.FileContent = htmlString
err = r.parseHTML()
return
}
// NewFromURL generates a new parser from a url
func NewFromURL(url string) (r *Recipe, err error) {
client := http.Client{
Timeout: 10 * time.Second,
}
resp, err := client.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
html, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
return NewFromHTML(url, string(html))
}
// NewFromHTML generates a new parser from a HTML text
func NewFromHTML(name, htmlstring string) (r *Recipe, err error) {
r = &Recipe{FileName: name}
r.FileContent = htmlstring
err = r.parseHTML()
return
}
func IngredientsFromURL(url string) (ingredients []Ingredient, err error) {
r, err := NewFromURL(url)
if err != nil {
return
}
ingredients = r.Ingredients
return
}
// Parse is the main parser for a given recipe.
func (r *Recipe) parseHTML() (rerr error) {
if r == nil {
r = &Recipe{}
}
if r.FileContent == "" || r.FileName == "" {
rerr = fmt.Errorf("no file loaded")
return
}
r.Lines, rerr = getIngredientLinesInHTML(r.FileContent)
return r.parseRecipe()
}
func (r *Recipe) parseRecipe() (rerr error) {
goodLines := make([]LineInfo, len(r.Lines))
j := 0
for _, lineInfo := range r.Lines {
if len(strings.TrimSpace(lineInfo.Line)) < 3 || len(strings.TrimSpace(lineInfo.Line)) > 150 {
continue
}
if strings.Contains(strings.ToLower(lineInfo.Line), "serving size") {
continue
}
if strings.Contains(strings.ToLower(lineInfo.Line), "yield") {
continue
}
// singularlize
lineInfo.Ingredient.Measure = Measure{}
// get amount, continue if there is an error
err := lineInfo.getTotalAmount()
if err != nil {
log.Tracef("[%s]: %s (%+v)", lineInfo.Line, err.Error(), lineInfo.AmountInString)
continue
}
// get ingredient, continue if its not found
err = lineInfo.getIngredient()
if err != nil {
log.Tracef("[%s]: %s", lineInfo.Line, err.Error())
continue
}
// get measure
err = lineInfo.getMeasure()
if err != nil {
log.Tracef("[%s]: %s", lineInfo.Line, err.Error())
}
// get comment
if len(lineInfo.MeasureInString) > 0 && len(lineInfo.IngredientsInString) > 0 {
lineInfo.Ingredient.Comment = getOtherInBetweenPositions(lineInfo.Line, lineInfo.MeasureInString[0], lineInfo.IngredientsInString[0])
}
// normalize into cups
lineInfo.Ingredient.Measure.Cups, err = normalizeIngredient(
lineInfo.Ingredient.Name,
lineInfo.Ingredient.Measure.Name,
lineInfo.Ingredient.Measure.Amount,
)
if err != nil {
log.Tracef("[%s]: %s", lineInfo.LineOriginal, err.Error())
} else {
log.Tracef("[%s]: %+v", lineInfo.LineOriginal, lineInfo)
}
goodLines[j] = lineInfo
j++
}
r.Lines = goodLines[:j]
rerr = r.ConvertIngredients()
if rerr != nil {
return
}
// consolidate ingredients
ingredients := make(map[string]Ingredient)
ingredientList := []string{}
for _, line := range r.Lines {
if _, ok := ingredients[line.Ingredient.Name]; ok {
if ingredients[line.Ingredient.Name].Measure.Name == line.Ingredient.Measure.Name {
ingredients[line.Ingredient.Name] = Ingredient{
Name: line.Ingredient.Name,
Comment: ingredients[line.Ingredient.Name].Comment,
Measure: Measure{
Name: ingredients[line.Ingredient.Name].Measure.Name,
Amount: ingredients[line.Ingredient.Name].Measure.Amount + line.Ingredient.Measure.Amount,
Cups: ingredients[line.Ingredient.Name].Measure.Cups + line.Ingredient.Measure.Cups,
},
}
} else {
ingredients[line.Ingredient.Name] = Ingredient{
Name: line.Ingredient.Name,
Comment: ingredients[line.Ingredient.Name].Comment,
Measure: Measure{
Name: ingredients[line.Ingredient.Name].Measure.Name,
Amount: ingredients[line.Ingredient.Name].Measure.Amount,
Cups: ingredients[line.Ingredient.Name].Measure.Cups + line.Ingredient.Measure.Cups,
},
}
}
} else {
ingredientList = append(ingredientList, line.Ingredient.Name)
ingredients[line.Ingredient.Name] = Ingredient{
Name: line.Ingredient.Name,
Comment: line.Ingredient.Comment,
Measure: Measure{
Name: line.Ingredient.Measure.Name,
Amount: line.Ingredient.Measure.Amount,
Cups: line.Ingredient.Measure.Cups + line.Ingredient.Measure.Cups,
},
}
}
}
r.Ingredients = make([]Ingredient, len(ingredients))
for i, ing := range ingredientList {
r.Ingredients[i] = ingredients[ing]
}
return
}
func getIngredientLinesInHTML(htmlS string) (lineInfos []LineInfo, err error) {
doc, err := html.Parse(bytes.NewReader([]byte(htmlS)))
if err != nil {
return
}
var f func(n *html.Node, lineInfos *[]LineInfo) (s string, done bool)
f = func(n *html.Node, lineInfos *[]LineInfo) (s string, done bool) {
childrenLineInfo := []LineInfo{}
// log.Tracef("%+v", n)
score := 0
isScript := n.DataAtom == atom.Script
for c := n.FirstChild; c != nil; c = c.NextSibling {
if isScript {
// try to capture JSON and if successful, do a hard exit
lis, errJSON := extractLinesFromJavascript(c.Data)
if errJSON == nil && len(lis) > 2 {
log.Trace("got ingredients from JSON")
*lineInfos = lis
done = true
return
}
}
var childText string
childText, done = f(c, lineInfos)
if done {
return
}
if childText != "" {
scoreOfLine, lineInfo := scoreLine(childText)
childrenLineInfo = append(childrenLineInfo, lineInfo)
score += scoreOfLine
}
}
if score > 2 && len(childrenLineInfo) < 25 && len(childrenLineInfo) > 2 {
*lineInfos = append(*lineInfos, childrenLineInfo...)
for _, child := range childrenLineInfo {
log.Tracef("[%s]", child.LineOriginal)
}
}
if len(childrenLineInfo) > 0 {
// fmt.Println(childrenLineInfo)
childrenText := make([]string, len(childrenLineInfo))
for i := range childrenLineInfo {
childrenText[i] = childrenLineInfo[i].LineOriginal
}
s = strings.Join(childrenText, " ")
} else if n.DataAtom == 0 && strings.TrimSpace(n.Data) != "" {
s = strings.TrimSpace(n.Data)
}
return
}
f(doc, &lineInfos)
return
}
func extractLinesFromJavascript(jsString string) (lineInfo []LineInfo, err error) {
var arrayMap = []map[string]interface{}{}
var regMap = make(map[string]interface{})
err = json.Unmarshal([]byte(jsString), ®Map)
if err != nil {
err = json.Unmarshal([]byte(jsString), &arrayMap)
if err != nil {
return
}
if len(arrayMap) == 0 {
err = fmt.Errorf("nothing to parse")
return
}
parseMap(arrayMap[0], &lineInfo)
err = nil
} else {
parseMap(regMap, &lineInfo)
err = nil
}
return
}
func parseMap(aMap map[string]interface{}, lineInfo *[]LineInfo) {
for _, val := range aMap {
switch val.(type) {
case map[string]interface{}:
parseMap(val.(map[string]interface{}), lineInfo)
case []interface{}:
parseArray(val.([]interface{}), lineInfo)
default:
// fmt.Println(key, ":", concreteVal)
}
}
}
func parseArray(anArray []interface{}, lineInfo *[]LineInfo) {
concreteLines := []string{}
for _, val := range anArray {
switch concreteVal := val.(type) {
case map[string]interface{}:
parseMap(val.(map[string]interface{}), lineInfo)
case []interface{}:
parseArray(val.([]interface{}), lineInfo)
default:
switch v := concreteVal.(type) {
case string:
concreteLines = append(concreteLines, v)
}
}
}
score, li := scoreLines(concreteLines)
log.Trace(score, li)
if score > 20 {
*lineInfo = li
}
return
}
func scoreLines(lines []string) (score int, lineInfo []LineInfo) {
if len(lines) < 2 {
return
}
lineInfo = make([]LineInfo, len(lines))
for i, line := range lines {
var scored int
scored, lineInfo[i] = scoreLine(line)
score += scored
}
return
}
func scoreLine(line string) (score int, lineInfo LineInfo) {
lineInfo = LineInfo{}
lineInfo.LineOriginal = line
lineInfo.Line = SanitizeLine(line)
lineInfo.IngredientsInString = GetIngredientsInString(lineInfo.Line)
lineInfo.AmountInString = GetNumbersInString(lineInfo.Line)
lineInfo.MeasureInString = GetMeasuresInString(lineInfo.Line)
if len(lineInfo.IngredientsInString) == 2 && len(lineInfo.IngredientsInString[1].Word) > len(lineInfo.IngredientsInString[0].Word) {
lineInfo.IngredientsInString[0] = lineInfo.IngredientsInString[1]
}
if len(lineInfo.LineOriginal) > 50 {
return
}
// does it contain an ingredient?
if len(lineInfo.IngredientsInString) > 0 {
score++
}
// disfavor containing multiple ingredients
if len(lineInfo.IngredientsInString) > 1 {
score = score - len(lineInfo.IngredientsInString) + 1
}
// does it contain an amount?
if len(lineInfo.AmountInString) > 0 {
score++
}
// does it contain a measure (cups, tsps)?
if len(lineInfo.MeasureInString) > 0 {
score++
}
// does the ingredient come after the measure?
if len(lineInfo.IngredientsInString) > 0 && len(lineInfo.MeasureInString) > 0 && lineInfo.IngredientsInString[0].Position > lineInfo.MeasureInString[0].Position {
score++
}
// does the ingredient come after the amount?
if len(lineInfo.IngredientsInString) > 0 && len(lineInfo.AmountInString) > 0 && lineInfo.IngredientsInString[0].Position > lineInfo.AmountInString[0].Position {
score++
}
// does the measure come after the amount?
if len(lineInfo.MeasureInString) > 0 && len(lineInfo.AmountInString) > 0 && lineInfo.MeasureInString[0].Position > lineInfo.AmountInString[0].Position {
score++
}
// disfavor lots of puncuation
puncuation := []string{".", ",", "!", "?"}
for _, punc := range puncuation {
if strings.Count(lineInfo.LineOriginal, punc) > 1 {
score--
}
}
// disfavor long lines
if len(lineInfo.Line) > 30 {
score = score - (len(lineInfo.Line) - 30)
}
if len(lineInfo.Line) > 250 {
score = 0
}
// does it start with a list indicator (* or -)?
fields := strings.Fields(lineInfo.Line)
if len(fields) > 0 && (fields[0] == "*" || fields[0] == "-") {
score++
}
// if only one thing is right, its wrong
if score == 1 {
score = 0.0
}
return
}
func (r *Recipe) ConvertIngredients() (err error) {
return
}
// IngredientList will return a string containing the ingredient list
func (r *Recipe) IngredientList() (ingredientList IngredientList) {
ingredientList = IngredientList{make([]Ingredient, len(r.Lines))}
for i, li := range r.Lines {
ingredientList.Ingredients[i] = li.Ingredient
ingredientList.Ingredients[i].Line = li.LineOriginal
}
return
}
func (lineInfo *LineInfo) getTotalAmount() (err error) {
lastPosition := -1
totalAmount := 0.0
wps := lineInfo.AmountInString
for i := range wps {
wps[i].Word = strings.TrimSpace(wps[i].Word)
if lastPosition == -1 {
totalAmount = ConvertStringToNumber(wps[i].Word)
} else if math.Abs(float64(wps[i].Position-lastPosition)) < 6 {
totalAmount += ConvertStringToNumber(wps[i].Word)
}
lastPosition = wps[i].Position + len(wps[i].Word)
}
if totalAmount == 0 && strings.Contains(lineInfo.Line, "whole") {
totalAmount = 1
}
if totalAmount == 0 {
err = fmt.Errorf("no amount found")
} else {
lineInfo.Ingredient.Measure.Amount = totalAmount
}
return
}
func (lineInfo *LineInfo) getIngredient() (err error) {
if len(lineInfo.IngredientsInString) == 0 {
err = fmt.Errorf("no ingredient found")
return
}
lineInfo.Ingredient.Name = inflection.Singular(lineInfo.IngredientsInString[0].Word)
return
}
func (lineInfo *LineInfo) getMeasure() (err error) {
if len(lineInfo.MeasureInString) == 0 {
lineInfo.Ingredient.Measure.Name = "whole"
return
}
lineInfo.Ingredient.Measure.Name = lineInfo.MeasureInString[0].Word
return
}