This repository has been archived by the owner on Oct 25, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FoodList.py
282 lines (206 loc) · 6.42 KB
/
FoodList.py
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
#!/usr/bin/env python
import sys
from Yemek import Yemek, Carb, Portion, Tags
from os.path import abspath
from Config import user_foodlist
from Messages import INFO, RESULT
import Common
import MiniFSChecker
from functools import reduce
class FoodList:
def __init__(self):
self.foodmap={}
self.path= user_foodlist
self.read()
def read(self):
try:
f=open(self.path,'r')
except IOError:
f=open(self.path,'w')
f.write(" ")
f.close()
return
# Strip Headers
f.readline(); f.readline()
for foodentry in f:
if len(foodentry)< 5:
continue
dd = foodentry.split('|')
name = dd[0]
data = dd[1]
portions = ""
tags=""
if len(dd)==3:
portions = dd[2]
if len(dd)==4:
portions = dd[2]
tags = dd[3].strip()
name = name.strip().lower()
tokes = data.split()
#629 11.6 [ 7.4, 4.2] = 4.2 21.1 55.8 100.0 g
kC, carb_total, junk, fibre, sugar, junk, carb_bad_unused, prot, fat, per = tokes[0:10]
unit = ' '.join(tokes[10:])
carbs = Carb(carb_total, fibre[:-1], sugar[:-1])
food = Yemek(name, kC, carbs, prot, fat, per, unit)
# Handle avail portions
if portions!="":
p_data = portions.split(Portion.start_delim)[1:]
for pv in p_data:
p,v = pv.split(Portion.end_delim)
food.portions.insert(p.strip(), int(v))
# Handle Tags
if tags!="":
t_data = tags.split(Tags.delim)
for tv in t_data:
food.tags.insert(tv.strip())
self.foodmap[food.name] = food
f.close()
def write(self):
Common.backup(self.path)
f=open(self.path,'w')
maxlen_name = reduce(lambda x,y: x if len(x) > len(y) else y, list(self.foodmap.keys()))
maxlen_name = len(maxlen_name)+5
maxport_name = reduce(lambda x,y: x if len(self.foodmap[x].unit) > len(self.foodmap[y].unit) else y, list(self.foodmap.keys()))
maxport_name = len(self.foodmap[maxport_name].unit)+5
print(Yemek.printheader(buffer=maxlen_name,
portions_buff=(maxport_name-len('unit')),
tags=True), file=f)
print("", file=f)
for food in sorted(self.foodmap.keys()):
fooditem = self.foodmap[food]
print(fooditem.printout(buffer=maxlen_name, pre="",
portions_buff=(maxport_name-len(fooditem.unit)),
tags=True), file=f)
f.close()
def printlist(self):
keys = sorted(self.foodmap.keys())
print(Yemek.printheader(), file=sys.stderr)
for food in keys:
fooditem = self.foodmap[food]
print(fooditem.printout(), file=sys.stderr) #.strip()
def insertAll(self, yem, input_search=[]):
# Tag prompt
user_input_tags = Tags.tagprompt()
if user_input_tags!=-1:
yem.tags.insertList(user_input_tags)
name = yem.name.strip().lower()
self.foodmap[name] = yem
INFO("Inserted \"%s\"" % name)
self.write()
def insert(self,name, input_search=[]):
INFO("Inserting new food:", name)
per,unit = Common.amountsplit(input("Per Unit (e.g. '100g'): ").strip())
kc, carb_total, carb_sugar, carb_fibre , prot, fat = input("kCal Carb Sug Fibr Prot Fat: ").split()
carbs = Carb(carb_total, carb_fibre, carb_sugar)
y = Yemek(name, kc, carbs, prot, fat, per, unit)
self.insertAll(y, input_search)
def removeprompt(self):
name = input('Food Name: ').strip()
if name in self.foodmap:
del self.foodmap[name]
RESULT("[Removed]", file=sys.stderr)
else:
RESULT("[Does not exist!]", file=sys.stderr)
self.write()
def insertprompt(self):
name = input('Food Name: ').strip()
if name in self.foodmap:
RESULT("[Food already exists!]", file=sys.stderr)
print(self.foodmap[name].printout(header=True), file=sys.stderr)
exit(-1)
self.insert(name)
#This is the main insertion method
def updateprompt(self):
# Print details if exists, else insert, else return close match
name = self.info(input('Food: ').strip())
# Name exists by now, or prog exited
if name in self.foodmap:
edit = input('\nEdit? ')
if edit[0].lower() != 'y':
exit(-1)
else:
RESULT("\n[New Food: \"%s\"]" % name, file=sys.stderr)
self.insert(name)
def closestMatch(self,name):
return self.search(name)[0];
def search(self,name):
searchname = name.split() #d[0].strip()
#print searchfoods, searchname
found=[];
for avail_food, obj in self.foodmap.items():
#words
word_match = 0
for ss in searchname:
for s in avail_food.split():
if ss.strip() in s.strip():
word_match += 1
if word_match != 0:
found.append( [obj, word_match] )
if len(found)==0:
INFO("Searching tags...")
for avail_food, obj in self.foodmap.items():
word_match = 0
for ss in searchname:
for tag in obj.tags.tags:
if ss.strip() in tag:
word_match += 1
if word_match != 0:
found.append( [obj, word_match] )
def sorter(x):return x[1]
return [x for x,y in sorted(found, key=sorter, reverse=True)]
def updateListInfo(self):
for name in list(self.foodmap.keys()):
food = self.foodmap[name]
if not((food.carb.sugar ==0 and food.carb.fibre==0) and (food.carb.total == food.carb.bad)):
continue
if "FS_online" not in food.tags.tags:continue
# if name != 'chicken drumstick (skin eaten)':continue
INFO("Check:")
print(food.printout(pre="---"))
f = MiniFSChecker.FHandler(food.name, food).found
if f!=-1:
del self.foodmap[name]
self.foodmap[f.name.lower()] = f
self.write()
self.write()
def info(self,name):
name = name.strip()
if name in self.foodmap:
print(self.foodmap[name].printout(header=True), file=sys.stderr)
return name
#Search objects for closest match
arg_name = name #store
found = self.search(name)
res = len(found)
if res == 0:
text_options = ("manually insert", "search online")
char_options = ("i", "s")
res = Common.userSingleListPrompt("\nCannot find: \"%s\"" % name, text_options, char_options)
if res == 'i':
self.insert(name, [arg_name])
return name.lower()
elif res == 's':
f = MiniFSChecker.FHandler(name).found
if f==-1:
exit(0)
self.insertAll(f, [arg_name,"FS_online"] )
return f.name
exit(0)
# Found something, print
INFO("\nMatched:", end=' ')
res = Common.choice(found)
if res==-1:
INFO("None")
if Common.ynprompt('Search online? '):
f = MiniFSChecker.FHandler(name).found
if f==-1:exit(0)
self.insertAll(f, [arg_name, "FS_online"]) # Nothing found, include input name as a tag
name = f.name
else:
#Manual insert
self.insert(name, [arg_name]) # Nothing ...
else:
name = res.name
return name
#w = FoodList()
#w.updateListInfo()