Example #1
0
 def apply_amt_convert(self, *args):
     to_unit = cb.cb_get_active_text(self.toUnitCombo)
     base_convert = self.nd.conv.converter('g', to_unit)
     if not base_convert:
         self.densities, self.extra_units = self.nd.get_conversions(
             self.ingkey)
         if to_unit in self.extra_units:
             base_convert = 1 / self.extra_units[to_unit]
         else:
             # this is a density, we hope...
             if to_unit.find(' (') > 0:
                 to_unit, describer = to_unit.split(' (')
                 describer = describer[0:-1]
                 density = self.densities[describer]
             else:
                 if None not in self.densities:
                     raise RuntimeError(
                         "Unable to make sense of conversion from %s %s" %
                         (to_unit, self.ingkey))
                 density = self.densities[None]
             base_convert = self.nd.conv.converter('g',
                                                   to_unit,
                                                   density=density)
     to_amount = convert.frac_to_float(self.toAmountEntry.get_text())
     from_amount = convert.frac_to_float(self.fromAmountEntry.get_text())
     ratio = from_amount / to_amount
     factor = base_convert * ratio
     from_unit = self.fromUnit
     self.nd.set_conversion(self.ingkey, from_unit, factor)
Example #2
0
def parse_ingredient(s, conv=None, get_key=True):
    """Handed a string, we hand back a dictionary representing a parsed ingr
edient (sans recipe ID)"""
    #if conv:
    #    print 'parse_ingredient: conv argument is now ignored'
    debug('ingredient_parser handed: %s' % s, 0)
    # Strip whitespace and bullets...
    d = {}
    #s = s.decode('utf8').strip(
    s = s.strip(
        u'\u2022\u2023\u2043\u204C\u204D\u2219\u25C9\u25D8\u25E6\u2619\u2765\u2767\u29BE\u29BF\n\t #*+-'
    )
    s = str(s)
    option_m = re.match('\s*optional:?\s*', s, re.IGNORECASE)
    if option_m:
        s = s[option_m.end():]
        d['optional'] = True
    debug('ingredient_parser handed: "%s"' % s, 1)
    m = convert.ING_MATCHER.match(s)
    if m:
        debug('ingredient parser successfully parsed %s' % s, 1)
        a, u, i = (m.group(convert.ING_MATCHER_AMT_GROUP),
                   m.group(convert.ING_MATCHER_UNIT_GROUP),
                   m.group(convert.ING_MATCHER_ITEM_GROUP))
        if a:
            debug('ingredient parser matched ammount %s' % a, 1)
            asplit = convert.RANGE_MATCHER.split(a)
            if len(asplit) == 2:
                d['amount'] = convert.frac_to_float(asplit[0].strip())
                d['rangeamount'] = convert.frac_to_float(asplit[1].strip())
            else:
                d['amount'] = convert.frac_to_float(a.strip())
        if u:
            debug('ingredient parser matched unit %s' % u, 1)
            conv = convert.get_converter()
            if conv and conv.unit_dict.has_key(u.strip()):
                # Don't convert units to our units!
                d['unit'] = u.strip()
            else:
                # has this unit been used
                prev_uses = False  # self.fetch_all(self.ingredients_table,unit=u.strip())
                if prev_uses:
                    d['unit'] = u
                else:
                    # otherwise, unit is not a unit
                    i = u + ' ' + i
        if i:
            optmatch = re.search('\s+\(?[Oo]ptional\)?', i)
            if optmatch:
                d['optional'] = True
                i = i[0:optmatch.start()] + i[optmatch.end():]
            d['item'] = i.strip()
            # if get_key: d['ingkey']=self.km.get_key(i.strip())
        debug('ingredient_parser returning: %s' % d, 0)
        return d
    else:
        debug("Unable to parse %s" % s, 0)
        d['item'] = s
        return d
Example #3
0
 def write_ing(self,
               amount=1,
               unit=None,
               item=None,
               key=None,
               optional=False):
     # item's are the same as keys in cozyland...
     if not key: key = item
     # grab info from our nutrition data info. This relies on rd.nd
     # being a reference to our NutritionData class -- this is
     # hackishly taken care of in CozyImporter.py.
     #
     # If this code is ever included in Gourmet proper, we should
     # delete all references to self.rd.nd
     ndbno = self.rd.nd.get_ndbno(key)
     if amount.find('-') >= 0:
         gram_amount = [
             self.rd.nd.convert_to_grams(convert.frac_to_float(a), unit,
                                         item) for a in amount.split('-')
         ]
     else:
         gram_amount = self.rd.nd.convert_to_grams(
             convert.frac_to_float(amount), unit, item)
     # Write our XML
     e_parent = self.e_ingredients
     e = self.xmlDoc.createElement('ing')
     e_parent.appendChild(e)
     e_parent = e
     e_amount = self.xmlDoc.createElement('amount')
     if gram_amount:
         if type(gram_amount) not in [tuple, list
                                      ] or None not in gram_amount:
             e_amount.appendChild(self.quantity_element(
                 gram_amount, 'gram'))
     e_parent.appendChild(e_amount)
     e_displayamount = self.xmlDoc.createElement('displayamount')
     e_displayamount.appendChild(self.quantity_element(amount, unit))
     e_parent.appendChild(e_displayamount)
     e_item = self.xmlDoc.createElement('item')
     e_parent.appendChild(e_item)
     t = self.xmlDoc.createTextNode(item)
     e_item.appendChild(t)
     if ndbno:
         e_usda = self.xmlDoc.createElement('usdaid')
         if ndbno:
             t = self.xmlDoc.createTextNode("%05i" % ndbno)
             e_usda.appendChild(t)
             e_parent.appendChild(e_usda)
Example #4
0
 def ingredient_parser(self, s, conv=None, get_key=True):
     """Handed a string, we hand back a dictionary representing a parsed ingredient (sans recipe ID)"""
     debug("ingredient_parser handed: %s" % s, 0)
     s = unicode(s)  # convert to unicode so our ING MATCHER works properly
     s = s.strip("\n\t #*+-")
     debug('ingredient_parser handed: "%s"' % s, 1)
     m = convert.ING_MATCHER.match(s)
     if m:
         debug("ingredient parser successfully parsed %s" % s, 1)
         d = {}
         g = m.groups()
         a, u, i = (
             g[convert.ING_MATCHER_AMT_GROUP],
             g[convert.ING_MATCHER_UNIT_GROUP],
             g[convert.ING_MATCHER_ITEM_GROUP],
         )
         if a:
             asplit = convert.RANGE_MATCHER.split(a)
             if len(asplit) == 2:
                 d["amount"] = convert.frac_to_float(asplit[0].strip())
                 d["rangeamount"] = convert.frac_to_float(asplit[1].strip())
             else:
                 d["amount"] = convert.frac_to_float(a.strip())
         if u:
             if conv and conv.unit_dict.has_key(u.strip()):
                 # Don't convert units to our units!
                 d["unit"] = u.strip()
             else:
                 # has this unit been used
                 prev_uses = self.normalizations["unit"].select(unit=str(u.strip()))
                 if len(prev_uses) > 0:
                     d["unit"] = u
                 else:
                     # otherwise, unit is not a unit
                     i = u + i
         if i:
             optmatch = re.search("\s+\(?[Oo]ptional\)?", i)
             if optmatch:
                 d["optional"] = True
                 i = i[0 : optmatch.start()] + i[optmatch.end() :]
             d["item"] = i.strip()
             if get_key:
                 d["ingkey"] = self.km.get_key(i.strip())
         debug("ingredient_parser returning: %s" % d, 0)
         return d
     else:
         debug("Unable to parse %s" % s, 0)
         return None
Example #5
0
 def get_value (self):
     txt = gtk.get_text()
     split = convert.RANGE_MATCHER.split(txt)
     if len(split)==1: return NumberEntry.get_value(self)
     if len(split)>2: return None
     else:
         return tuple([convert.frac_to_float(t) for t in split])
Example #6
0
 def applyEntriesCB(self, *args):
     newdic = {}
     for k, e in self.entries.items():
         txt = e.get_text()
         if txt:
             if k == 'amount':
                 try:
                     newdic[k] = convert.frac_to_float(txt)
                 except:
                     de.show_amount_error(txt)
                     return
             else:
                 newdic[k] = txt
     if not newdic:
         print 'We called applyEntriesCB with no text -- that shouldn\'t be possible'
         return
     mod, rows = self.treeview.get_selection().get_selected_rows()
     if not de.getBoolean(
             label=_("Change all selected rows?"),
             sublabel=
         (_('This action will not be undoable. Are you that for all %s selected rows, you want to set the following values:'
            ) % len(rows) +
          (newdic.has_key('ingkey') and _('\nKey to %s') % newdic['ingkey']
           or '') +
          (newdic.has_key('item') and _('\nItem to %s') % newdic['item']
           or '') +
          (newdic.has_key('unit') and _('\nUnit to %s') % newdic['unit']
           or '') + (newdic.has_key('amount')
                     and _('\nAmount to %s') % newdic['amount'] or ''))):
         return
     # Now actually apply our lovely new logic...
     changed_iters = True
     updated_iters = []
     for path in rows:
         itr = self.treeModel.get_iter(path)
         # We check to see if we've updated the parent of our iter,
         # in which case the changes would already be inherited by
         # the current row (i.e. if the tree has been expanded and
         # all rows have been selected).
         parent = mod.iter_parent(itr)
         already_updated = False
         while parent:
             if parent in updated_iters:
                 already_updated = True
             else:
                 parent = mod.iter_parent(parent)
         if already_updated: continue
         # Now that we're sure we really need to update...
         curdic, field = self.get_dic_describing_iter(itr)
         curkey = self.treeModel.get_value(itr, self.VALUE_COL)
         if not already_updated:
             self.rd.update_by_criteria(
                 self.rd.ingredients_table,
                 curdic,
                 newdic,
             )
             if curdic.has_key('ingkey') and newdic.has_key('ingkey'):
                 self.rd.delete_by_criteria(self.rd.keylookup_table,
                                            {'ingkey': curdic['ingkey']})
     self.resetTree()
Example #7
0
 def get_multiplier (self, *args):
     d=None
     # Grab our density (either the default density for the food, or the density for the
     # user-selected description, such as chopped, sliced, etc).
     if self.densities.has_key(None) or self.densities and self.get_choice(self.descChoiceWidget):
         d=self.densities[self.get_choice(self.descChoiceWidget) or None]
     multiplier=self.nut and self.nd.convert_amount(self.amount,
                                                    self.unit,
                                                    d)
     if multiplier:
         self.set_unit_visibility(False) # if we don't need unit info, don't show it
         return multiplier
     elif self.nut: #if we just need the right unit, see if the user has entered an equivalent...
         # otherwise, we do need unit info, keep it visible
         self.set_unit_visibility(True)
         try:
             amt = convert.frac_to_float(self.amountWidget.get_text())
         except:
             # if there's not a number in Amt, we want to grab it
             self.amountWidget.grab_focus()
             return
         else:
             unit = self.get_choice(self.unitChoiceWidget)
             if self.extra_units.has_key(unit):
                 return self.nd.convert_amount(amt*self.extra_units[unit],'g.')
             else:
                 return self.nd.convert_amount(amt,unit,d)
Example #8
0
 def get_multiplier (self, *args):
     d=None
     # Grab our density (either the default density for the food, or the density for the
     # user-selected description, such as chopped, sliced, etc).
     if self.densities.has_key(None) or self.densities and self.get_choice(self.descChoiceWidget):
         d=self.densities[self.get_choice(self.descChoiceWidget) or None]
     multiplier=self.nut and self.nd.convert_amount(self.amount,
                                                    self.unit,
                                                    d)
     if multiplier:
         self.set_unit_visibility(False) # if we don't need unit info, don't show it
         return multiplier
     elif self.nut: #if we just need the right unit, see if the user has entered an equivalent...
         # otherwise, we do need unit info, keep it visible
         self.set_unit_visibility(True)
         try:
             amt = convert.frac_to_float(self.amountWidget.get_text())
         except:
             # if there's not a number in Amt, we want to grab it
             self.amountWidget.grab_focus()
             return
         else:
             unit = self.get_choice(self.unitChoiceWidget)
             if self.extra_units.has_key(unit):
                 return self.nd.convert_amount(amt*self.extra_units[unit],'g.')
             else:
                 return self.nd.convert_amount(amt,unit,d)
Example #9
0
 def get_value (self):
     txt = Gtk.get_text()
     split = convert.RANGE_MATCHER.split(txt)
     if len(split)==1: return NumberEntry.get_value(self)
     if len(split)>2: return None
     else:
         return tuple([convert.frac_to_float(t) for t in split])
Example #10
0
 def convert_str_to_num (self, str):
     """Return a numerical servings value"""
     timeaction = TimeAction('importer.convert_str_to_num',10)
     debug('converting servings for %s'%str,5)
     try:
         return float(str)
     except:
         conv = convert.frac_to_float(str)
         if conv: return conv
         m=re.match("([0-9/. ]+)",str)
         if m:
             num=m.groups()[0]
             try:
                 return float(num)
             except:
                 return convert.frac_to_float(num)
     timeaction.end()
Example #11
0
 def add_ingredient (self):
     key=raw_input('Enter ingredient key: ')
     amt = convert.frac_to_float(raw_input('Enter amount: '))
     unit = raw_input('Enter unit: ')
     if not self.ings:
         self.ings = NutritionInfoList([self.nd.get_nutinfo_for_item(key,amt,unit)])
     else:
         self.ings = self.ings + self.nd.get_nutinfo_for_item(key,amt,unit)
Example #12
0
 def convert_str_to_num (self, str):
     """Return a numerical servings value"""
     timeaction = TimeAction('importer.convert_str_to_num',10)
     debug('converting servings for %s'%str,5)
     try:
         return float(str)
     except:
         conv = convert.frac_to_float(str)
         if conv: return conv
         m=re.match("([0-9/. ]+)",str)
         if m:
             num=m.groups()[0]
             try:
                 return float(num)
             except:
                 return convert.frac_to_float(num)
     timeaction.end()
 def write_ing (self, amount=1, unit=None, item=None,
                key=None, optional=False):
     # item's are the same as keys in cozyland...
     if not key: key = item
     # grab info from our nutrition data info. This relies on rd.nd
     # being a reference to our NutritionData class -- this is
     # hackishly taken care of in CozyImporter.py.
     #
     # If this code is ever included in Gourmet proper, we should
     # delete all references to self.rd.nd
     ndbno = self.rd.nd.get_ndbno(key)
     if amount.find('-')>=0:
         gram_amount = [self.rd.nd.convert_to_grams(convert.frac_to_float(a),
                                                    unit,
                                                    item)
                        for a in amount.split('-')]
     else:
         gram_amount = self.rd.nd.convert_to_grams(convert.frac_to_float(amount),unit,item)
     # Write our XML
     e_parent = self.e_ingredients
     e = self.xmlDoc.createElement('ing')
     e_parent.appendChild(e)
     e_parent = e
     e_amount = self.xmlDoc.createElement('amount')
     if gram_amount:
         if type(gram_amount) not in [tuple,list] or None not in gram_amount:
             e_amount.appendChild(
                 self.quantity_element(gram_amount,
                                       'gram')
                 )
     e_parent.appendChild(e_amount)
     e_displayamount = self.xmlDoc.createElement('displayamount')
     e_displayamount.appendChild(
         self.quantity_element(amount,unit)
         )
     e_parent.appendChild(e_displayamount)
     e_item = self.xmlDoc.createElement('item')
     e_parent.appendChild(e_item)
     t = self.xmlDoc.createTextNode(item)
     e_item.appendChild(t)
     if ndbno:
         e_usda = self.xmlDoc.createElement('usdaid')
         if ndbno:
             t = self.xmlDoc.createTextNode("%05i"%ndbno)
             e_usda.appendChild(t)
             e_parent.appendChild(e_usda)
Example #14
0
 def ingredient_parser(self, s, conv=None, get_key=True):
     """Handed a string, we hand back a dictionary representing a parsed ingredient (sans recipe ID)"""
     debug('ingredient_parser handed: %s' % s, 0)
     s = unicode(s)  # convert to unicode so our ING MATCHER works properly
     s = s.strip("\n\t #*+-")
     debug('ingredient_parser handed: "%s"' % s, 1)
     m = convert.ING_MATCHER.match(s)
     if m:
         debug('ingredient parser successfully parsed %s' % s, 1)
         d = {}
         g = m.groups()
         a, u, i = (g[convert.ING_MATCHER_AMT_GROUP],
                    g[convert.ING_MATCHER_UNIT_GROUP],
                    g[convert.ING_MATCHER_ITEM_GROUP])
         if a:
             asplit = convert.RANGE_MATCHER.split(a)
             if len(asplit) == 2:
                 d['amount'] = convert.frac_to_float(asplit[0].strip())
                 d['rangeamount'] = convert.frac_to_float(asplit[1].strip())
             else:
                 d['amount'] = convert.frac_to_float(a.strip())
         if u:
             if conv and conv.unit_dict.has_key(u.strip()):
                 # Don't convert units to our units!
                 d['unit'] = u.strip()
             else:
                 # has this unit been used
                 prev_uses = self.normalizations['unit'].select(
                     unit=str(u.strip()))
                 if len(prev_uses) > 0:
                     d['unit'] = u
                 else:
                     # otherwise, unit is not a unit
                     i = u + i
         if i:
             optmatch = re.search('\s+\(?[Oo]ptional\)?', i)
             if optmatch:
                 d['optional'] = True
                 i = i[0:optmatch.start()] + i[optmatch.end():]
             d['item'] = i.strip()
             if get_key: d['ingkey'] = self.km.get_key(i.strip())
         debug('ingredient_parser returning: %s' % d, 0)
         return d
     else:
         debug("Unable to parse %s" % s, 0)
         return None
Example #15
0
 def applyEntriesCB (self, *args):
     newdic = {}
     for k,e in self.entries.items():
         txt = e.get_text()
         if txt:
             if k=='amount':
                 try:
                     newdic[k]=convert.frac_to_float(txt)
                 except:
                     print 'Problem with amount:',txt
                     import traceback; traceback.print_exc()
                     de.show_amount_error(txt)
                     return
             else:
                 newdic[k]=txt
     if not newdic:
         print 'We called applyEntriesCB with no text -- that shouldn\'t be possible'
         return
     mod,rows = self.treeview.get_selection().get_selected_rows()
     if not de.getBoolean(
     label=_("Change all selected rows?"),
     sublabel=(_('This action will not be undoable. Are you that for all %s selected rows, you want to set the following values:')%len(rows)
     + (newdic.has_key('ingkey') and _('\nKey to %s')%newdic['ingkey'] or '')
     + (newdic.has_key('item') and _('\nItem to %s')%newdic['item'] or '')
     + (newdic.has_key('unit') and _('\nUnit to %s')%newdic['unit'] or '')
     + (newdic.has_key('amount') and _('\nAmount to %s')%newdic['amount'] or ''))):
         return
     # Now actually apply our lovely new logic...
     changed_iters = True
     updated_iters = []
     for path in rows:
         itr=self.treeModel.get_iter(path)
         # We check to see if we've updated the parent of our iter,
         # in which case the changes would already be inherited by
         # the current row (i.e. if the tree has been expanded and
         # all rows have been selected).
         parent = mod.iter_parent(itr); already_updated = False
         while parent:
             if parent in updated_iters:
                 already_updated = True
             else:
                 parent = mod.iter_parent(parent)
         if already_updated: continue
         # Now that we're sure we really need to update...
         curdic,field = self.get_dic_describing_iter(itr)
         curkey = self.treeModel.get_value(itr,self.VALUE_COL)
         if not already_updated:
             self.rd.update_by_criteria(
                 self.rd.ingredients_table,
                 curdic,
                 newdic,
                 )
             if curdic.has_key('ingkey') and newdic.has_key('ingkey'):
                 self.rd.delete_by_criteria(
                     self.rd.keylookup_table,
                     {'ingkey':curdic['ingkey']}
                     )
     self.resetTree()
Example #16
0
 def finish_ing (self):
     timeaction = TimeAction('importer.finish_ing 1',10)
     # Strip whitespace...
     for key in ['item','ingkey','unit']:
         if self.ing.has_key(key):
             self.ing[key]=re.sub('\s+',' ',self.ing[key]).strip()
     if not (
         (self.ing.has_key('refid') and
          self.ing['refid'])
         or
         (self.ing.has_key('ingkey') and
          self.ing['ingkey'])
         ):
         #self.ing['ingkey']=self.km.get_key(self.ing['item'],0.9)
         if self.ing.has_key('item'):
             self.ing['ingkey']=self.km.get_key_fast(self.ing['item'])
         else:
             debug('Ingredient has no item! %s'%self.ing,-1)
     timeaction.end()
     # if we have an amount (and it's not None), let's convert it
     # to a number
     if self.ing.has_key('amount') and self.ing['amount']\
            and not self.ing.has_key('rangeamount'):
         if convert.RANGE_MATCHER.search(str(self.ing['amount'])):
             self.ing['amount'],self.ing['rangeamount']=parse_range(self.ing['amount'])
     if self.ing.has_key('amount'):
         self.ing['amount']=convert.frac_to_float(
             self.ing['amount']
             )
     if self.ing.has_key('rangeamount'):
         self.ing['rangeamount']=convert.frac_to_float(
             self.ing['rangeamount']
             )
     timeaction = TimeAction('importer.commit_ing 2',10)
     if not (self.ing.has_key('position') and self.ing['position']):
         self.ing['position']=self.position
         self.position+=1
     timeaction.end()
     timeaction = TimeAction('importer.commit_ing 3',10)
     if self.group:
         self.ing['inggroup']=self.group
     timeaction.end()
     timeaction = TimeAction('importer.commit_ing 4',10)
     self.added_ings.append(self.ing); self.ing = {}
     timeaction.end()
Example #17
0
 def finish_ing (self):
     timeaction = TimeAction('importer.finish_ing 1',10)
     # Strip whitespace...
     for key in ['item','ingkey','unit']:
         if self.ing.has_key(key):
             self.ing[key]=re.sub('\s+',' ',self.ing[key]).strip()
     if not (
         (self.ing.has_key('refid') and
          self.ing['refid'])
         or
         (self.ing.has_key('ingkey') and
          self.ing['ingkey'])
         ):
         #self.ing['ingkey']=self.km.get_key(self.ing['item'],0.9)
         if self.ing.has_key('item'):
             self.ing['ingkey']=self.km.get_key_fast(self.ing['item'])
         else:
             debug('Ingredient has no item! %s'%self.ing,-1)
     timeaction.end()
     # if we have an amount (and it's not None), let's convert it
     # to a number
     if self.ing.has_key('amount') and self.ing['amount']\
            and not self.ing.has_key('rangeamount'):
         if convert.RANGE_MATCHER.search(str(self.ing['amount'])):
             self.ing['amount'],self.ing['rangeamount']=parse_range(self.ing['amount'])
     if self.ing.has_key('amount'):
         self.ing['amount']=convert.frac_to_float(
             self.ing['amount']
             )
     if self.ing.has_key('rangeamount'):
         self.ing['rangeamount']=convert.frac_to_float(
             self.ing['rangeamount']
             )
     timeaction = TimeAction('importer.commit_ing 2',10)
     if not (self.ing.has_key('position') and self.ing['position']):
         self.ing['position']=self.position
         self.position+=1
     timeaction.end()
     timeaction = TimeAction('importer.commit_ing 3',10)
     if self.group:
         self.ing['inggroup']=self.group
     timeaction.end()
     timeaction = TimeAction('importer.commit_ing 4',10)
     self.added_ings.append(self.ing); self.ing = {}
     timeaction.end()
Example #18
0
 def parse_yields(self, str):
     """Parse number and field."""
     m = re.match("([0-9/. ]+)", str)
     if m:
         num = m.groups()[0]
         num = convert.frac_to_float(num)
         unit = str[m.end() :].strip()
         return num, unit
     else:
         return None, None
Example #19
0
 def add_ingredient(self):
     key = input('Enter ingredient key: ')
     amt = convert.frac_to_float(input('Enter amount: '))
     unit = input('Enter unit: ')
     if not self.ings:
         self.ings = NutritionInfoList(
             [self.nd.get_nutinfo_for_item(key, amt, unit)])
     else:
         self.ings = self.ings + self.nd.get_nutinfo_for_item(
             key, amt, unit)
Example #20
0
 def parse_yields (self, str):
     '''Parse number and field.'''
     m = re.match("([0-9/. ]+)",str)
     if m:
         num = m.groups()[0]
         num = convert.frac_to_float(num)
         unit = str[m.end():].strip()
         return num,unit
     else:
         return None,None
Example #21
0
 def testFractToFloat(self):
     for s, n in [
         ('1', 1),
         ('123', 123),
         ('1 1/2', 1.5),
         ('74 2/5', 74.4),
         ('1/10', 0.1),
         ('one', 1),
         ('a half', 0.5),
         ('three quarters', 0.75),
     ]:
         self.assertEqual(convert.frac_to_float(s), n)
Example #22
0
 def ingredient_parser (self, s, conv=None, get_key=True):
     """Handed a string, we hand back a dictionary (sans recipe ID)"""
     debug('ingredient_parser handed: %s'%s,0)
     s = unicode(s) # convert to unicode so our ING MATCHER works properly
     s=s.strip("\n\t #*+-")
     debug('ingredient_parser handed: "%s"'%s,1)
     m=convert.ING_MATCHER.match(s)
     if m:
         debug('ingredient parser successfully parsed %s'%s,1)
         d={}
         g=m.groups()
         a,u,i=(g[convert.ING_MATCHER_AMT_GROUP],
                g[convert.ING_MATCHER_UNIT_GROUP],
                g[convert.ING_MATCHER_ITEM_GROUP])
         if a:
             asplit = convert.RANGE_MATCHER.split(a)
             if len(asplit)==2:
                 d['amount']=convert.frac_to_float(asplit[0].strip())
                 d['rangeamount']=convert.frac_to_float(asplit[1].strip())
             else:
                 d['amount']=convert.frac_to_float(a.strip())
         if u:
             if conv and conv.unit_dict.has_key(u.strip()):
                 d['unit']=conv.unit_dict[u.strip()]
             else:
                 d['unit']=u.strip()
         if i:
             optmatch = re.search('\s+\(?[Oo]ptional\)?',i)
             if optmatch:
                 d['optional']=True
                 i = i[0:optmatch.start()] + i[optmatch.end():]
             d['item']=i.strip()
             if get_key: d['ingkey']=self.km.get_key(i.strip())
         debug('ingredient_parser returning: %s'%d,0)
         return d
     else:
         debug("Unable to parse %s"%s,0)
         return None
Example #23
0
 def finish_ing(self):
     timeaction = TimeAction("importer.finish_ing 1", 10)
     # Strip whitespace...
     for key in ["item", "ingkey", "unit"]:
         if self.ing.has_key(key):
             self.ing[key] = re.sub("\s+", " ", self.ing[key]).strip()
     if not (
         (self.ing.has_key("refid") and self.ing["refid"]) or (self.ing.has_key("ingkey") and self.ing["ingkey"])
     ):
         # self.ing['ingkey']=self.km.get_key(self.ing['item'],0.9)
         if self.ing.has_key("item"):
             self.ing["ingkey"] = self.km.get_key_fast(self.ing["item"])
         else:
             debug("Ingredient has no item! %s" % self.ing, -1)
     timeaction.end()
     # if we have an amount (and it's not None), let's convert it
     # to a number
     if self.ing.has_key("amount") and self.ing["amount"] and not self.ing.has_key("rangeamount"):
         if convert.RANGE_MATCHER.search(str(self.ing["amount"])):
             self.ing["amount"], self.ing["rangeamount"] = parse_range(self.ing["amount"])
     if self.ing.has_key("amount"):
         self.ing["amount"] = convert.frac_to_float(self.ing["amount"])
     if self.ing.has_key("rangeamount"):
         self.ing["rangeamount"] = convert.frac_to_float(self.ing["rangeamount"])
     timeaction = TimeAction("importer.commit_ing 2", 10)
     if not (self.ing.has_key("position") and self.ing["position"]):
         self.ing["position"] = self.position
         self.position += 1
     timeaction.end()
     timeaction = TimeAction("importer.commit_ing 3", 10)
     if self.group:
         self.ing["inggroup"] = self.group
     timeaction.end()
     timeaction = TimeAction("importer.commit_ing 4", 10)
     self.added_ings.append(self.ing)
     self.ing = {}
     timeaction.end()
Example #24
0
 def apply_amt_convert (self,*args):
     to_unit = cb.cb_get_active_text(self.toUnitCombo)
     base_convert = self.nd.conv.converter('g',to_unit)
     if not base_convert:
         self.densities,self.extra_units = self.nd.get_conversions(self.ingkey)
         if self.extra_units.has_key(to_unit):
             base_convert = 1/self.extra_units[to_unit]
         else:
             # this is a density, we hope...
             if to_unit.find(' (')>0:
                 to_unit,describer = to_unit.split(' (')
                 describer = describer[0:-1]
                 density = self.densities[describer]
             else:
                 if not self.densities.has_key(None):
                     raise RuntimeError("Unable to make sense of conversion from %s %s"%(to_unit,self.ingkey))
                 density = self.densities[None]
             base_convert = self.nd.conv.converter('g',to_unit,density=density)
     to_amount = convert.frac_to_float(self.toAmountEntry.get_text())
     from_amount = convert.frac_to_float(self.fromAmountEntry.get_text())
     ratio = from_amount / to_amount
     factor = base_convert * ratio
     from_unit = self.fromUnit
     self.nd.set_conversion(self.ingkey,from_unit,factor)
Example #25
0
 def changed(self, *args):
     amt1 = convert.frac_to_float(self.amt1Entry.get_text())
     #amt2 = convert.frac_to_float(self.resultLabel.get_text())
     #amt2 = self.amt2
     unit1 = cb_get_active_text(self.unit1ComboBox)
     unit2 = cb_get_active_text(self.unit2ComboBox)
     if unit1 != self.last_unit1:
         self.get_possible_conversions()
     #self.unit2Model.refilter()
     if amt1 and unit2:
         self.convert(amt1, unit1, unit2)
     self.last_amt1 = amt1
     #self.last_amt2 = amt2
     self.last_unit1 = unit1
     self.last_unit2 = unit2
Example #26
0
 def changed (self, *args):
     amt1 = convert.frac_to_float(self.amt1Entry.get_text())
     #amt2 = convert.frac_to_float(self.resultLabel.get_text())
     #amt2 = self.amt2
     unit1 = cb_get_active_text(self.unit1ComboBox)
     unit2 = cb_get_active_text(self.unit2ComboBox)
     if unit1 != self.last_unit1:
         self.get_possible_conversions()
     #self.unit2Model.refilter()
     if amt1 and unit2:
         self.convert(amt1, unit1, unit2)
     self.last_amt1 = amt1
     #self.last_amt2 = amt2
     self.last_unit1 = unit1
     self.last_unit2 = unit2
Example #27
0
 def parse_yields (self, str):
     '''Parse number and field.'''
     m = re.match(r"(?P<prefix>\w+\s+)?(?P<num>[0-9/. ]+)(?P<unit>\s*\w+)?",str)
     if m:
         num = m.group('num')
         num = convert.frac_to_float(num)
         unit = (m.group('unit') or '').strip()
         prefix = (m.group('prefix') or '').strip()
         if not unit:
             if prefix in ['Serves','Feeds']:
                 unit = 'servings'
         elif prefix:
             if prefix not in ['Makes','Yields']:
                 print('Warning: parse_yields ignoring prefix, "%(prefix)s" in "%(str)s"'%locals())
         if not unit: unit='servings' # default/fallback
         return num,unit
     else:
         return None,None
Example #28
0
 def parse_yields (self, str):
     '''Parse number and field.'''
     m = re.match("(?P<prefix>\w+\s+)?(?P<num>[0-9/. ]+)(?P<unit>\s*\w+)?",str)
     if m:
         num = m.group('num')
         num = convert.frac_to_float(num)
         unit = (m.group('unit') or '').strip()
         prefix = (m.group('prefix') or '').strip()
         if not unit:
             if prefix in ['Serves','Feeds']:
                 unit = 'servings'
         elif prefix:
             if prefix not in ['Makes','Yields']:
                 print 'Warning: parse_yields ignoring prefix, "%(prefix)s" in "%(str)s"'%locals()
         if not unit: unit='servings' # default/fallback
         return num,unit
     else:
         return None,None
Example #29
0
 def editNutritionalInfoCB (self, *args):
     nid = nutritionDruid.NutritionInfoDruid(self.rg.nd, self.rg.prefs)
     mod,rows = self.treeview.get_selection().get_selected_rows()
     keys_to_update = {}
     for path in rows:
         itr = mod.get_iter(path)
         # Climb to the key-level for each selection -- we don't
         # care about anything else.
         parent = mod.iter_parent(itr)
         while parent:
             itr = parent
             parent = mod.iter_parent(itr)
         curkey = mod.get_value(itr,self.VALUE_COL)
         #if mod.get_value(itr,self.NUT_COL):
         #    print "We can't yet edit nutritional information..."
         #else:
         if True:
             keys_to_update[curkey]=[]
             child = mod.iter_children(itr)
             while child:
                 grandchild = mod.iter_children(child)
                 while grandchild:
                     # Grand children are units...
                     unit = mod.get_value(grandchild,self.VALUE_COL)
                     amounts = []
                     greatgrandchild = mod.iter_children(grandchild)
                     while greatgrandchild:
                         amount = mod.get_value(
                             greatgrandchild,
                             self.VALUE_COL
                             )
                         keys_to_update[curkey].append((convert.frac_to_float(amount),unit))
                         greatgrandchild = mod.iter_next(greatgrandchild)
                     grandchild = mod.iter_next(grandchild)
                 child = mod.iter_next(child)
             nid.add_ingredients(keys_to_update.items())
             nid.connect('finish',self.update_nutinfo)
             nid.show()
Example #30
0
 def editNutritionalInfoCB (self, *args):
     nid = nutritionDruid.NutritionInfoDruid(self.rg.nd, self.rg.prefs)
     mod,rows = self.treeview.get_selection().get_selected_rows()
     keys_to_update = {}
     for path in rows:
         itr = mod.get_iter(path)
         # Climb to the key-level for each selection -- we don't
         # care about anything else.
         parent = mod.iter_parent(itr)
         while parent:
             itr = parent
             parent = mod.iter_parent(itr)
         curkey = mod.get_value(itr,self.VALUE_COL)
         #if mod.get_value(itr,self.NUT_COL):
         #    print "We can't yet edit nutritional information..."
         #else:
         if True:
             keys_to_update[curkey]=[]
             child = mod.iter_children(itr)
             while child:
                 grandchild = mod.iter_children(child)
                 while grandchild:
                     # Grand children are units...
                     unit = mod.get_value(grandchild,self.VALUE_COL)
                     amounts = []
                     greatgrandchild = mod.iter_children(grandchild)
                     while greatgrandchild:
                         amount = mod.get_value(
                             greatgrandchild,
                             self.VALUE_COL
                             )
                         keys_to_update[curkey].append((convert.frac_to_float(amount),unit))
                         greatgrandchild = mod.iter_next(greatgrandchild)
                     grandchild = mod.iter_next(grandchild)
                 child = mod.iter_next(child)
             nid.add_ingredients(keys_to_update.items())
             nid.connect('finish',self.update_nutinfo)
             nid.show()
Example #31
0
 def get_value(self) -> float:
     return frac_to_float(self.get_text())
Example #32
0
 def find_completed_errors(self, text: str):
     if text and frac_to_float(text) is None:
         return self.error_message
Example #33
0
 def get_value(self):
     return convert.frac_to_float(self.get_text())
Example #34
0
 def find_completed_errors(self, txt):
     if txt and convert.frac_to_float(txt) == None:
         return self.error_message
Example #35
0
 def tree_edited (self, renderer, path_string, text, n, head):
     indices = path_string.split(':')
     path = tuple( map(int, indices))
     itr = self.treeModel.get_iter(path)
     curdic,field = self.get_dic_describing_iter(itr)
     value = curdic[field]
     if value == text: return
     if field=='ingkey':
         key = curdic['ingkey']
         if de.getBoolean(label=_('Change all keys "%s" to "%s"?')%(key,text),
                          sublabel=_("You won't be able to undo this action. If there are already ingredients with the key \"%s\", you won't be able to distinguish between those items and the items you are changing now."%text)
                          ):
             self.rd.update_by_criteria(
                 self.rd.ingredients_table,
                 curdic,
                 {'ingkey':text}
                 )
             self.rd.delete_by_criteria(
                 self.rd.keylookup_table,
                 {'ingkey':key}
                 )
     elif field=='item':
         if de.getBoolean(label=_('Change all items "%s" to "%s"?')%(curdic['item'],text),
                          sublabel=_("You won't be able to undo this action. If there are already ingredients with the item \"%s\", you won't be able to distinguish between those items and the items you are changing now.")%text
                          ):
             self.rd.update_by_criteria(
                 self.rd.ingredients_table,
                 curdic,
                 {'item':text}
                 ) 
     elif field=='unit':
         unit = curdic['unit']; key = curdic['ingkey']; item = curdic['item']
         val = de.getRadio(label='Change unit',
                             options=[
             [_('Change _all instances of "%(unit)s" to "%(text)s"')%locals(),1],
             [_('Change "%(unit)s" to "%(text)s" only for _ingredients "%(item)s" with key "%(key)s"')%locals(),2],
             ],
                           default = 2,
                           )
         if val==1:
             self.rd.update_by_criteria(
                 self.rd.ingredients_table,
                 {'unit':unit},
                 {'unit':text},
                 )
         elif val==2:
             self.rd.update_by_criteria(
                 self.rd.ingredients_table,
                 curdic,
                 {'unit':text}
                 )
     elif field=='amount':
         amount = curdic['amount']; unit = curdic['unit']; key = curdic['ingkey']; item = curdic['item']
         try:
             new_amount = convert.frac_to_float(text)
         except:
             de.show_amount_error(text)
             return
         val = de.getRadio(label='Change amount',
                     options=[
             [_('Change _all instances of "%(amount)s" %(unit)s to %(text)s %(unit)s')%locals(),1],
             [_('Change "%(amount)s" %(unit)s to "%(text)s" %(unit)s only _where the ingredient key is %(key)s')%locals(),2],
             [_('Change "%(amount)s" %(unit)s to "%(text)s" %(unit)s only where the ingredient key is %(key)s _and where the item is %(item)s')%locals(),3],
             ],
             default=3,
                           )
         if val == 1:
             cond = {'unit':unit,'amount':amount}
         elif val == 2:
             cond = {'unit':unit,'amount':amount,'ingkey':key}
         elif val == 3:
             cond = curdic
         self.rd.update_by_criteria(
             self.rd.ingredients_table,
             {'unit':unit,'amount':convert.frac_to_float(amount)},
             {'unit':unit,'amount':new_amount}
             )
     else:
         return
     self.treeModel.set_value(itr, n, text)
     return
Example #36
0
 def find_completed_errors (self, txt):
     if txt and convert.frac_to_float(txt)==None:
         return self.error_message
Example #37
0
 def get_value (self):
     return convert.frac_to_float(self.get_text())
Example #38
0
 def tree_edited(self, renderer, path_string, text, n, head):
     indices = path_string.split(':')
     path = tuple(map(int, indices))
     itr = self.treeModel.get_iter(path)
     curdic, field = self.get_dic_describing_iter(itr)
     value = curdic[field]
     if value == text: return
     if field == 'ingkey':
         key = curdic['ingkey']
         if de.getBoolean(
                 label=_('Change all keys "%s" to "%s"?') % (key, text),
                 sublabel=_(
                     "You won't be able to undo this action. If there are already ingredients with the key \"%s\", you won't be able to distinguish between those items and the items you are changing now."
                     % text)):
             self.rd.update_by_criteria(self.rd.ingredients_table, curdic,
                                        {'ingkey': text})
             self.rd.delete_by_criteria(self.rd.keylookup_table,
                                        {'ingkey': key})
     elif field == 'item':
         if de.getBoolean(
                 label=_('Change all items "%s" to "%s"?') %
             (curdic['item'], text),
                 sublabel=
                 _("You won't be able to undo this action. If there are already ingredients with the item \"%s\", you won't be able to distinguish between those items and the items you are changing now."
                   ) % text):
             self.rd.update_by_criteria(self.rd.ingredients_table, curdic,
                                        {'item': text})
     elif field == 'unit':
         unit = curdic['unit']
         key = curdic['ingkey']
         item = curdic['item']
         val = de.getRadio(
             label='Change unit',
             options=[
                 [
                     _('Change _all instances of "%(unit)s" to "%(text)s"')
                     % locals(), 1
                 ],
                 [
                     _('Change "%(unit)s" to "%(text)s" only for _ingredients "%(item)s" with key "%(key)s"'
                       ) % locals(), 2
                 ],
             ],
             default=2,
         )
         if val == 1:
             self.rd.update_by_criteria(
                 self.rd.ingredients_table,
                 {'unit': unit},
                 {'unit': text},
             )
         elif val == 2:
             self.rd.update_by_criteria(self.rd.ingredients_table, curdic,
                                        {'unit': text})
     elif field == 'amount':
         amount = curdic['amount']
         unit = curdic['unit']
         key = curdic['ingkey']
         item = curdic['item']
         try:
             new_amount = convert.frac_to_float(text)
         except:
             de.show_amount_error(text)
             return
         val = de.getRadio(
             label='Change amount',
             options=[
                 [
                     _('Change _all instances of "%(amount)s" %(unit)s to %(text)s %(unit)s'
                       ) % locals(), 1
                 ],
                 [
                     _('Change "%(amount)s" %(unit)s to "%(text)s" %(unit)s only _where the ingredient key is %(key)s'
                       ) % locals(), 2
                 ],
                 [
                     _('Change "%(amount)s" %(unit)s to "%(text)s" %(unit)s only where the ingredient key is %(key)s _and where the item is %(item)s'
                       ) % locals(), 3
                 ],
             ],
             default=3,
         )
         if val == 1:
             cond = {'unit': unit, 'amount': amount}
         elif val == 2:
             cond = {'unit': unit, 'amount': amount, 'ingkey': key}
         elif val == 3:
             cond = curdic
         self.rd.update_by_criteria(self.rd.ingredients_table, {
             'unit': unit,
             'amount': convert.frac_to_float(amount)
         }, {
             'unit': unit,
             'amount': new_amount
         })
     else:
         return
     self.treeModel.set_value(itr, n, text)
     return
Example #39
0
def string_to_rating (s):
    m = simple_matcher.match(s)
    if m:
        top=float(convert.frac_to_float(m.groups()[0]))
        bottom = float(convert.frac_to_float(m.groups()[2]))
        return int(top/bottom * 10)
Example #40
0
def string_to_rating (s):
    m = simple_matcher.match(s)
    if m:
        top=float(convert.frac_to_float(m.groups()[0]))
        bottom = float(convert.frac_to_float(m.groups()[2]))
        return int(top/bottom * 10)