示例#1
0
 def compile_regexps(self):
     testtimer = TimeAction('mealmaster_importer.compile_regexps', 10)
     debug("start compile_regexps", 5)
     plaintext_importer.TextImporter.compile_regexps(self)
     self.start_matcher = re.compile(mm_start_pattern)
     self.end_matcher = re.compile("^[M-][M-][M-][M-][M-]\s*$")
     self.group_matcher = re.compile(
         "^\s*([M-][M-][M-][M-][M-])-*\s*([^-]+)\s*-*|^\s*---\s*([^-]+)\s*---\s*$",
         re.IGNORECASE)
     self.ing_cont_matcher = re.compile("^\s*[-;]")
     self.ing_opt_matcher = re.compile("(.+?)\s*\(?\s*optional\)?\s*$",
                                       re.IGNORECASE)
     self.ing_or_matcher = re.compile("^[- ]*[Oo][Rr][- ]*$", re.IGNORECASE)
     self.variation_matcher = re.compile(
         "^\s*(VARIATION|HINT|NOTES?)(:.*)?", re.IGNORECASE)
     # a crude ingredient matcher -- we look for two numbers,
     # intermingled with spaces followed by a space or more,
     # followed by a two digit unit (or spaces)
     c = convert.get_converter()
     self.ing_num_matcher = re.compile(
         "^\s*%s+\s+([a-z ]{1,2}|%s)\s+.*\w+.*" %
         (convert.NUMBER_REGEXP,
          '(' + '|'.join(filter(lambda x: x, c.unit_dict.keys())) + ')'),
         re.IGNORECASE)
     self.amt_field_matcher = re.compile("^(\s*%s\s*)$" %
                                         convert.NUMBER_REGEXP)
     # we build a regexp to match anything that looks like
     # this: ^\s*ATTRIBUTE: Some entry of some kind...$
     self.mmf = mmf
     attrmatch = "^\s*("
     for k in self.mmf.recattrs.keys():
         attrmatch += "%s|" % re.escape(k)
     attrmatch = "%s):\s*(.*)\s*$" % attrmatch[0:-1]
     self.attr_matcher = re.compile(attrmatch)
     testtimer.end()
 def compile_regexps (self):
     testtimer = TimeAction('mealmaster_importer.compile_regexps',10)
     debug("start compile_regexps",5)
     plaintext_importer.TextImporter.compile_regexps(self)
     self.start_matcher = re.compile(mm_start_pattern)
     self.end_matcher = re.compile("^[M-][M-][M-][M-][M-]\s*$")
     self.group_matcher = re.compile("^\s*([M-][M-][M-][M-][M-])-*\s*([^-]+)\s*-*|^\s*---\s*([^-]+)\s*---\s*$",re.IGNORECASE)
     self.ing_cont_matcher = re.compile("^\s*[-;]")
     self.ing_opt_matcher = re.compile("(.+?)\s*\(?\s*optional\)?\s*$",re.IGNORECASE)
     self.ing_or_matcher = re.compile("^[- ]*[Oo][Rr][- ]*$",re.IGNORECASE)
     self.variation_matcher = re.compile("^\s*(VARIATION|HINT|NOTES?)(:.*)?",re.IGNORECASE)
     # a crude ingredient matcher -- we look for two numbers,
     # intermingled with spaces followed by a space or more,
     # followed by a two digit unit (or spaces)
     c = convert.get_converter()
     self.ing_num_matcher = re.compile(
         "^\s*%s+\s+([a-z ]{1,2}|%s)\s+.*\w+.*"%(
             convert.NUMBER_REGEXP,
             '('+'|'.join(filter(lambda x: x, c.unit_dict.keys()))+')'
             ),
         re.IGNORECASE)
     self.amt_field_matcher = re.compile("^(\s*%s\s*)$"%convert.NUMBER_REGEXP)
     # we build a regexp to match anything that looks like
     # this: ^\s*ATTRIBUTE: Some entry of some kind...$
     self.mmf = mmf
     attrmatch="^\s*("
     for k in self.mmf.recattrs.keys():
         attrmatch += "%s|"%re.escape(k)
     attrmatch="%s):\s*(.*)\s*$"%attrmatch[0:-1]
     self.attr_matcher = re.compile(attrmatch)
     testtimer.end()
示例#3
0
    def __init__(
        self,
        rd=None,  # OBSOLETE
        total=0,
        prog=None,  # OBSOLETE
        do_markup=True,
        conv=None,
        rating_converter=None,
        name="importer",
    ):
        """rd is our recipeData instance.

        Total is used to keep track of progress.

        do_markup should be True if instructions and modifications
        come to us unmarked up (i.e. if we need to escape < and &,
        etc. -- this might be False if importing e.g. XML).
        """

        timeaction = TimeAction("importer.__init__", 10)
        if not conv:
            self.conv = convert.get_converter()
        self.id_converter = {}  # a dictionary for tracking named IDs
        self.total = total
        if prog or rd:
            import traceback

            traceback.print_stack()
            if prog:
                print "WARNING: ", self, "handed obsolete parameter prog=", prog
            if rd:
                print "WARNING: ", self, "handed obsolete parameter rd=", rd
        self.do_markup = do_markup
        self.count = 0
        self.rd = get_recipe_manager()
        self.rd_orig_ing_hooks = self.rd.add_ing_hooks
        self.added_recs = []
        self.added_ings = []
        # self.rd_orig_hooks = self.rd.add_hooks
        self.rd.add_ing_hooks = []
        # self.rd.add_hooks = []
        self.position = 0
        self.group = None
        # allow threaded calls to pause
        self.suspended = False
        # allow threaded calls to be terminated (this
        # has to be implemented in subclasses).
        self.terminated = False
        # Our rating converter -- if we've been handed a class, we
        # assume our caller will handle doing the
        # conversion. Otherwise we do it ourselves.
        if rating_converter:
            self.rating_converter = rating_converter
            self.do_conversion = False
        else:
            self.rating_converter = RatingConverter()
            self.do_conversion = True
        self.km = keymanager.get_keymanager()
        timeaction.end()
        SuspendableThread.__init__(self, name=name)
示例#4
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
示例#5
0
    def __init__(
            self,
            rd=None,  # OBSOLETE
            total=0,
            prog=None,  # OBSOLETE
            do_markup=True,
            conv=None,
            rating_converter=None,
            name='importer'):
        """rd is our recipeData instance.

        Total is used to keep track of progress.

        do_markup should be True if instructions and modifications
        come to us unmarked up (i.e. if we need to escape < and &,
        etc. -- this might be False if importing e.g. XML).
        """

        timeaction = TimeAction('importer.__init__', 10)
        if not conv: self.conv = convert.get_converter()
        self.id_converter = {}  # a dictionary for tracking named IDs
        self.total = total
        if prog or rd:
            import traceback
            traceback.print_stack()
            if prog:
                print('WARNING: ', self, 'handed obsolete parameter prog=',
                      prog)
            if rd:
                print('WARNING: ', self, 'handed obsolete parameter rd=', rd)
        self.do_markup = do_markup
        self.count = 0
        self.rd = get_recipe_manager()
        self.rd_orig_ing_hooks = self.rd.add_ing_hooks
        self.added_recs = []
        self.added_ings = []
        #self.rd_orig_hooks = self.rd.add_hooks
        self.rd.add_ing_hooks = []
        #self.rd.add_hooks = []
        self.position = 0
        self.group = None
        # allow threaded calls to pause
        self.suspended = False
        # allow threaded calls to be terminated (this
        # has to be implemented in subclasses).
        self.terminated = False
        # Our rating converter -- if we've been handed a class, we
        # assume our caller will handle doing the
        # conversion. Otherwise we do it ourselves.
        if rating_converter:
            self.rating_converter = rating_converter
            self.do_conversion = False
        else:
            self.rating_converter = RatingConverter()
            self.do_conversion = True
        self.km = keymanager.get_keymanager()
        timeaction.end()
        SuspendableThread.__init__(self, name=name)
示例#6
0
def convert_times(recipe):
    conv = convert.get_converter()
    for t in ['preptime', 'cooktime']:
        if t in recipe and type(recipe[t]) != int:
            secs = conv.timestring_to_seconds(recipe[t])
            if secs != None:
                recipe[t] = secs
            else:
                del recipe[t]
示例#7
0
    def __init__(
        self,
        rd,
        r,
        out,
        conv=None,
        imgcount=1,
        order=["image", "attr", "ings", "text"],
        attr_order=DEFAULT_ATTR_ORDER,
        text_attr_order=DEFAULT_TEXT_ATTR_ORDER,
        do_markup=True,
        use_ml=False,
        convert_attnames=True,
        fractions=convert.FRACTIONS_ASCII,
    ):
        """Instantiate our exporter.

        conv is a preexisting convert.converter() class
        imgcount is a number we use to start counting our exported images.
        order is a list of our core elements in order: 'image','attr','text' and 'ings'
        attr_order is a list of our attributes in the order we should export them:
                   title, category, cuisine, servings, source, rating, preptime, cooktime
        text_attr_order is a list of our text attributes.
        do_markup is a flag; if true, we interpret tags in text blocks by calling
                  self.handle_markup to e.g. to simple plaintext renderings of tags.
        use_ml is a flag; if true, we escape strings we output to be valid *ml
        convert_attnames is a flag; if true, we hand write_attr a translated attribute name
                         suitable for printing or display. If not, we just hand it the standard
                         attribute name (this is a good idea if a subclass needs to rely on the
                         attribute name staying consistent for processing, since converting attnames
                         will produce locale specific strings.
        """
        self.attr_order = attr_order
        self.text_attr_order = text_attr_order
        self.out = out
        self.r = r
        self.rd = rd
        self.do_markup = do_markup
        self.fractions = fractions
        self.use_ml = use_ml
        self.convert_attnames = convert_attnames
        if not conv:
            conv = convert.get_converter()
        self.conv = conv
        self.imgcount = imgcount
        self.images = []
        self.order = order
        Pluggable.__init__(self, [BaseExporterPlugin])
        SuspendableThread.__init__(self, self.name)
示例#8
0
    def __init__(
        self,
        rd,
        r,
        out,
        conv=None,
        imgcount=1,
        order=['image', 'attr', 'ings', 'text'],
        attr_order=DEFAULT_ATTR_ORDER,
        text_attr_order=DEFAULT_TEXT_ATTR_ORDER,
        do_markup=True,
        use_ml=False,
        convert_attnames=True,
        fractions=convert.FRACTIONS_ASCII,
    ):
        """Instantiate our exporter.

        conv is a preexisting convert.converter() class
        imgcount is a number we use to start counting our exported images.
        order is a list of our core elements in order: 'image','attr','text' and 'ings'
        attr_order is a list of our attributes in the order we should export them:
                   title, category, cuisine, servings, source, rating, preptime, cooktime
        text_attr_order is a list of our text attributes.
        do_markup is a flag; if true, we interpret tags in text blocks by calling
                  self.handle_markup to e.g. to simple plaintext renderings of tags.
        use_ml is a flag; if true, we escape strings we output to be valid *ml
        convert_attnames is a flag; if true, we hand write_attr a translated attribute name
                         suitable for printing or display. If not, we just hand it the standard
                         attribute name (this is a good idea if a subclass needs to rely on the
                         attribute name staying consistent for processing, since converting attnames
                         will produce locale specific strings.
        """
        self.attr_order = attr_order
        self.text_attr_order = text_attr_order
        self.out = out
        self.r = r
        self.rd = rd
        self.do_markup = do_markup
        self.fractions = fractions
        self.use_ml = use_ml
        self.convert_attnames = convert_attnames
        if not conv: conv = convert.get_converter()
        self.conv = conv
        self.imgcount = imgcount
        self.images = []
        self.order = order
        Pluggable.__init__(self, [BaseExporterPlugin])
        SuspendableThread.__init__(self, self.name)
示例#9
0
    def __init__ (self, unitModel=None):
        debug("Opening PriceAdder screen",2)
        self.ui = gtk.Builder()
        self.ui.add_from_file(os.path.join(current_path,'priceAdder.ui'))
        self.window = self.ui.get_object("window1")
        self.window.show()

        signals = {"on_add_clicked": self.add_ingredient,
                   "on_cancel_clicked": self.cancel}
        self.ui.connect_signals(signals)
                
        converter=convert.get_converter()

        if unitModel: 
            self.unitModel = unitModel
        else: 
            self.unitModel = gourmet.GourmetRecipeManager.UnitModel(converter)  
        
        self.comboboxUnit = self.ui.get_object("comboboxUnit")
        self.comboboxUnit.set_model(self.unitModel)
        self.comboboxUnit.set_wrap_width(3)
        self.comboboxUnit.set_wrap_width(3)   
示例#10
0
def hash_recipe(rec, rd, conv=None):
    if not conv: conv = convert.get_converter()
    rechash = get_recipe_hash(rec)
    inghash = get_ingredient_hash(rd.get_ings(rec), conv)
    return rechash, inghash
示例#11
0
 def setUp(self):
     self.c = convert.get_converter()
示例#12
0
 def __init__ (self, conv=None):
     if not conv: self.conv = convert.get_converter()
     else: self.conv = conv
     validatingEntry.ValidatingEntry.__init__(self)
     self.entry.get_value = self.get_value
     self.entry.set_value = self.set_value
示例#13
0
 def __init__ (self, converter=convert.get_converter(),
               unitModel=None,
               amt1=None, unit1=None, item=None,
               okcb=None
               ):
     self.possible_conversions = None
     self.ui = gtk.Builder()
     self.ui.add_from_file(os.path.join(current_path,'converter.ui'))
     self.conv = converter
     self.changing_item = False
     self.okcb = okcb
     self.widget_names = ['window','amt1Entry', 'amt2Label', 'unit1ComboBox', 'unit2ComboBox',
                'itemComboBox', 'densitySpinButton', 'useDensityCheckButton', 'statusbar','expander1','messageLabel']
     # grab all our widgets
     for w in self.widget_names:
         setattr(self,w,self.ui.get_object(w))
     # HACK FOR READABILITY w/o glade change
     self.resultLabel = self.amt2Label
     self.resultLabel.set_use_markup(True)
     self.resultLabel.set_line_wrap(True)
     if unitModel: self.unitModel=unitModel
     else: self.unitModel=gourmet.GourmetRecipeManager.UnitModel(self.conv)
     #self.unit2Model = self.unitModel.filter_new()
     self.unit1ComboBox.set_model(self.unitModel)
     self.unit1ComboBox.set_wrap_width(3)
     self.unit2ComboBox.set_wrap_width(3)
     #self.unit2Model.set_visible_func(self.unit_filter)
     #self.unit2ComboBox.set_model(self.unit2Model)
     self.unit2ComboBox.set_model(self.unitModel)
     for combobox in [self.unit1ComboBox, self.unit2ComboBox]:
         cell = gtk.CellRendererText()
         combobox.pack_start(cell, True)
         combobox.add_attribute(cell, 'text', 1)
         setup_typeahead(combobox)
     #self.itemComboBox.append_text('None')
     ikeys = self.conv.density_table.keys()
     ikeys.sort()
     for itm in ikeys:
         self.itemComboBox.append_text(itm)
     if len(self.conv.density_table.keys()) > 8:
         self.itemComboBox.set_wrap_width(3)
     setup_typeahead(self.itemComboBox)
     if amt1:
         self.amt1Entry=self.conv.float_to_frac(amt1)
     self.ui.connect_signals({
         'amt1changed':self.changed,
         'unit1changed':self.changed,
         'unit2changed':self.changed,
         'itemChanged':self.density_itm_changed,
         'densitySpinChanged':self.density_spin_changed,
         'densityChecked':self.density_toggled,
         'close':self.close,
         })
     self.last_amt1 = None
     self.last_amt2 = None
     self.last_unit1 = None
     self.last_unit2 = None
     if unit1 and self.conv.unit_dict.has_key[unit1]:
         u = self.conv.unit_dict[unit1]
         cb_set_active_text(self.unit1ComboBox,u)
     if amt1: self.amt1Entry.set_text("%s"%amt1)
     if item: cb_set_active_text(self.itemComboBox,item)
示例#14
0
 def __init__(self,
              converter=convert.get_converter(),
              unitModel=None,
              amt1=None,
              unit1=None,
              item=None,
              okcb=None):
     self.possible_conversions = None
     self.ui = gtk.Builder()
     self.ui.add_from_file(os.path.join(current_path, 'converter.ui'))
     self.conv = converter
     self.changing_item = False
     self.okcb = okcb
     self.widget_names = [
         'window', 'amt1Entry', 'amt2Label', 'unit1ComboBox',
         'unit2ComboBox', 'itemComboBox', 'densitySpinButton',
         'useDensityCheckButton', 'statusbar', 'expander1', 'messageLabel'
     ]
     # grab all our widgets
     for w in self.widget_names:
         setattr(self, w, self.ui.get_object(w))
     # HACK FOR READABILITY w/o glade change
     self.resultLabel = self.amt2Label
     self.resultLabel.set_use_markup(True)
     self.resultLabel.set_line_wrap(True)
     if unitModel: self.unitModel = unitModel
     else:
         self.unitModel = gourmet.GourmetRecipeManager.UnitModel(self.conv)
     #self.unit2Model = self.unitModel.filter_new()
     self.unit1ComboBox.set_model(self.unitModel)
     self.unit1ComboBox.set_wrap_width(3)
     self.unit2ComboBox.set_wrap_width(3)
     #self.unit2Model.set_visible_func(self.unit_filter)
     #self.unit2ComboBox.set_model(self.unit2Model)
     self.unit2ComboBox.set_model(self.unitModel)
     for combobox in [self.unit1ComboBox, self.unit2ComboBox]:
         cell = gtk.CellRendererText()
         combobox.pack_start(cell, True)
         combobox.add_attribute(cell, 'text', 1)
         setup_typeahead(combobox)
     #self.itemComboBox.append_text('None')
     ikeys = self.conv.density_table.keys()
     ikeys.sort()
     for itm in ikeys:
         self.itemComboBox.append_text(itm)
     if len(self.conv.density_table.keys()) > 8:
         self.itemComboBox.set_wrap_width(3)
     setup_typeahead(self.itemComboBox)
     if amt1:
         self.amt1Entry = self.conv.float_to_frac(amt1)
     self.ui.connect_signals({
         'amt1changed': self.changed,
         'unit1changed': self.changed,
         'unit2changed': self.changed,
         'itemChanged': self.density_itm_changed,
         'densitySpinChanged': self.density_spin_changed,
         'densityChecked': self.density_toggled,
         'close': self.close,
     })
     self.last_amt1 = None
     self.last_amt2 = None
     self.last_unit1 = None
     self.last_unit2 = None
     if unit1 and self.conv.unit_dict.has_key[unit1]:
         u = self.conv.unit_dict[unit1]
         cb_set_active_text(self.unit1ComboBox, u)
     if amt1: self.amt1Entry.set_text("%s" % amt1)
     if item: cb_set_active_text(self.itemComboBox, item)
示例#15
0
 def init_converter(self):
     self.cnv = convert.get_converter()
示例#16
0
 def __init__(self, conv=None):
     if not conv: self.conv = convert.get_converter()
     else: self.conv = conv
     validatingEntry.ValidatingEntry.__init__(self)
     self.entry.get_value = self.get_value
     self.entry.set_value = self.set_value
示例#17
0
 def init_converter(self):
     #self.cnv = DatabaseConverter(self.db)
     if not self.cnv:
         self.cnv = convert.get_converter()