Exemplo n.º 1
0
 def createFact(self, attrs):
     """Makes a new Anki fact from an entry."""
     model = self.models[attrs["et"]]
     self.f = Fact(model)
     # process attributes
     for attr in ["a1", "a2" "a3", "a4"]:
         if attr in attrs.keys():
             self.f.__setitem__(
                 self.typeAttributes[attrs["et"] + "_" + attr],
                 self.attributeItems[attrs[attr]])
     # process tags. Unit, Category plus entry type name
     tagString = unicode(self.unitCategories[attrs["u"]] + " " +
                         self.unitCategories[attrs["c"]] + " " + model.tags)
     self.f.tags = tagString
Exemplo n.º 2
0
def doAddURL():
    # get URL from clipboard
    url = str(QApplication.clipboard().mimeData().text())
    try:
        # download HTML file with urllib
        html = opener.open(url).read()
    except ValueError:
        utils.showInfo("Please copy a URL to clipboard first.")
        return
    # parse HTML and find images
    xml = libxml2.htmlParseDoc(html, 'utf-8')
    context = xml.xpathNewContext()
    # find correct nodes via XPath
    count = 0
    for img in context.xpathEval('//img'):
        # get src attribute
        attr = img.get_properties()
        imgurl = None
        while attr:
            if attr.name == 'src':
                _replaceImageSrc(url, attr)
                count += 1
                break
            attr = attr.get_next()

    # add new fact
    fact = Fact(mw.deck.currentModel)
    val = tidyHTML(xml.serialize(encoding='utf-8').decode('utf-8', 'replace'))
    fact.fields[0].value = val
    mw.deck.addFact(fact, reset=True)
    utils.showInfo(
        "URL successfully added as new fact (%d pictures downloaded)" % count)
Exemplo n.º 3
0
class DingsBumsHandler(ContentHandler):
    def __init__(self, deck):
        self.eid = "0"
        self.attributeItems = {}
        self.unitCategories = {}
        self.attributes = {}
        self.currentContent = ""
        self.labels = {}
        self.labels[
            "pro"] = u"Pronunciation"  # the user cannot change this label and therefore not in xml-file
        self.labels["rel"] = u"Relation"
        self.visibility = {}
        self.models = {}
        self.typeAttributes = {
        }  # mapping of entry type and attribute name (e.g. "ET8_A1", "ET8_A2", ...)
        self.deck = deck
        self.f = None  # the current fact
        self.countFacts = 0

    def startElement(self, name, attrs):
        """Implements SAX interface"""
        if name in ["etai", "unit", "category"]:
            self.eid = attrs["eid"]
        elif "eta" == name:
            self.attributes[attrs["eid"]] = attrs["n"]
        elif "entrytype" == name:
            self.createModel(attrs)
        elif "e" == name:
            self.createFact(attrs)

    def endElement(self, name):
        """Implements SAX interface"""
        if "vocabulary" == name:
            self.deck.updateProgress()
        elif name.endswith("label"):
            self.labels[name.replace("label", "")] = self.currentContent
        elif name.startswith("vis"):
            self.visibility[name.replace("vis", "")] = self.currentContent
        elif "etai" == name:
            self.attributeItems[self.eid] = self.currentContent
        elif "etattributes" == name:
            self.deck.updateProgress()
        elif "entrytypes" == name:
            self.deck.updateProgress()
        elif "name" == name:
            self.unitCategories[self.eid] = self.prepareTag(
                self.currentContent)
        elif "units" == name:
            self.deck.updateProgress()
        elif "categories" == name:
            self.deck.updateProgress()
        elif "entries" == name:
            self.deck.updateProgress()
        elif "e" == name:
            self.deck.addFact(self.f)
            self.countFacts += 1
        # there is a not logical mapping between the tags for fields and names in VocabInfo
        # See net.vanosten.dings.consts.Constants.XML_*
        elif "o" == name:
            self.f.__setitem__(self.labels["b"], self.currentContent)
        elif "d" == name:
            self.f.__setitem__(self.labels["t"], self.currentContent)
        elif "ep" == name:
            self.f.__setitem__(self.labels["exp"], self.currentContent)
        elif "ea" == name:
            self.f.__setitem__(self.labels["ex"], self.currentContent)
        elif "p" == name:
            self.f.__setitem__(self.labels["pro"], self.currentContent)
        elif "r" == name:
            self.f.__setitem__(self.labels["rel"], self.currentContent)

    def characters(self, content):
        """Implements SAX interface"""
        self.currentContent = content.strip()

    def createModel(self, attrs):
        """Makes a new Anki (fact) model from an entry type.
        The card models are made each time from scratch in order that evt. model specific fields (attributes) can make part."""
        m = Model(attrs["n"])
        # field model for standard fields
        m.addFieldModel(
            FieldModel(self.labels["b"], True,
                       False))  #there is no uniqueness check in DingsBums?!
        m.addFieldModel(FieldModel(self.labels["t"], True, False))
        for aField in ["exp", "ex", "pro", "rel"]:
            if self.visibility[aField] in "012":
                m.addFieldModel(FieldModel(self.labels[aField], False, False))
        # field models for attributes
        for attr in ["a1", "a2" "a3", "a4"]:
            if attr in attrs.keys():
                m.addFieldModel(
                    FieldModel(self.attributes[attrs[attr]], False, False))
                self.typeAttributes[attrs["eid"] + "_" +
                                    attr] = self.attributes[attrs[attr]]

        # card model for front
        frontStrings = ["%(" + self.labels["b"] + ")s"]
        backStrings = ["%(" + self.labels["t"] + ")s"]
        for aField in ["exp", "ex", "pro", "rel"]:
            if self.visibility[aField] in "01":
                frontStrings.append("%(" + self.labels[aField] + ")s")
            if self.visibility[aField] in "02":
                backStrings.append("%(" + self.labels[aField] + ")s")
        m.addCardModel(
            CardModel(u'Forward', "<br>".join(frontStrings),
                      "<br>".join(backStrings)))
        # card model for back
        m.addCardModel(
            CardModel(u'Reverse', unicode("%(" + self.labels["t"] + ")s"),
                      unicode("%(" + self.labels["b"] + ")s")))
        # tags is just the name without spaces
        m.tags = self.prepareTag(m.name)

        # link
        self.models[attrs["eid"]] = m
        self.deck.addModel(m)

    def createFact(self, attrs):
        """Makes a new Anki fact from an entry."""
        model = self.models[attrs["et"]]
        self.f = Fact(model)
        # process attributes
        for attr in ["a1", "a2" "a3", "a4"]:
            if attr in attrs.keys():
                self.f.__setitem__(
                    self.typeAttributes[attrs["et"] + "_" + attr],
                    self.attributeItems[attrs[attr]])
        # process tags. Unit, Category plus entry type name
        tagString = unicode(self.unitCategories[attrs["u"]] + " " +
                            self.unitCategories[attrs["c"]] + " " + model.tags)
        self.f.tags = tagString

    def prepareTag(self, stringWithSpace):
        parts = stringWithSpace.split()
        return "_".join(parts)