Example #1
0
def test_timestamps():
    col = getEmptyCol()
    assert len(col.models.all_names_and_ids()) == len(get_stock_notetypes(col))
    for i in range(100):
        addBasicModel(col)
    assert len(
        col.models.all_names_and_ids()) == 100 + len(get_stock_notetypes(col))
Example #2
0
def Collection(path, lock=True, server=False, sync=True):
    "Open a new or existing collection. Path must be unicode."
    assert path.endswith(".anki2")
    path = os.path.abspath(path)
    create = not os.path.exists(path)
    if create:
        base = os.path.basename(path)
        for c in ("/", ":", "\\"):
            assert c not in base
    # connect
    db = DB(path)
    if create:
        ver = _createDB(db)
    else:
        ver = _upgradeSchema(db)
    db.execute("pragma temp_store = memory")
    if sync:
        db.execute("pragma cache_size = 10000")
        db.execute("pragma journal_mode = wal")
    else:
        db.execute("pragma synchronous = off")
    # add db to col and do any remaining upgrades
    col = _Collection(db, server)
    if ver < SCHEMA_VERSION:
        _upgrade(col, ver)
    elif create:
        # add in reverse order so basic is default
        addClozeModel(col)
        addForwardOptionalReverse(col)
        addForwardReverse(col)
        addBasicModel(col)
        col.save()
    if lock:
        col.lock()
    return col
Example #3
0
    def ensureNotEmpty(self) -> Optional[bool]:
        if not self.models:
            from anki.stdmodels import addBasicModel

            addBasicModel(self.col)
            return True
        return None
Example #4
0
def Collection(path, lock=True, server=False, sync=True):
    "Open a new or existing collection. Path must be unicode."
    assert path.endswith(".anki2")
    path = os.path.abspath(path)
    create = not os.path.exists(path)
    if create:
        base = os.path.basename(path)
        for c in ("/", ":", "\\"):
            assert c not in base
    # connect
    db = DB(path)
    if create:
        ver = _createDB(db)
    else:
        ver = _upgradeSchema(db)
    db.execute("pragma temp_store = memory")
    if sync:
        db.execute("pragma cache_size = 10000")
        db.execute("pragma journal_mode = wal")
    else:
        db.execute("pragma synchronous = off")
    # add db to col and do any remaining upgrades
    col = _Collection(db, server)
    if ver < SCHEMA_VERSION:
        _upgrade(col, ver)
    elif create:
        # add in reverse order so basic is default
        addClozeModel(col)
        addBasicModel(col)
        col.save()
    if lock:
        col.lock()
    return col
Example #5
0
def Collection(path: str,
               lock: bool = True,
               server: Optional[ServerData] = None,
               log: bool = False) -> _Collection:
    "Open a new or existing collection. Path must be unicode."
    assert path.endswith(".anki2")
    (media_dir, media_db) = media_paths_from_col_path(path)
    log_path = ""
    if not server:
        log_path = path.replace(".anki2", "2.log")
    backend = RustBackend(path, media_dir, media_db, log_path)
    path = os.path.abspath(path)
    create = not os.path.exists(path)
    if create:
        base = os.path.basename(path)
        for c in ("/", ":", "\\"):
            assert c not in base
    # connect
    db = DB(path)
    db.setAutocommit(True)
    if create:
        ver = _createDB(db)
    else:
        ver = _upgradeSchema(db)
    db.execute("pragma temp_store = memory")
    db.execute("pragma cache_size = 10000")
    if not isWin:
        db.execute("pragma journal_mode = wal")
    db.setAutocommit(False)
    # add db to col and do any remaining upgrades
    col = _Collection(db, backend=backend, server=server, log=log)
    if ver < SCHEMA_VERSION:
        _upgrade(col, ver)
    elif ver > SCHEMA_VERSION:
        raise Exception("This file requires a newer version of Anki.")
    elif create:
        # add in reverse order so basic is default
        addClozeModel(col)
        addBasicTypingModel(col)
        addForwardOptionalReverse(col)
        addForwardReverse(col)
        addBasicModel(col)
        col.save()
    if lock:
        try:
            col.lock()
        except:
            col.db.close()
            raise
    return col
Example #6
0
def Collection(path: str,
               lock: bool = True,
               server: Optional[ServerData] = None,
               log: bool = False) -> _Collection:
    "Open a new or existing collection. Path must be unicode."
    backend = Backend(path)
    # fixme: this call is temporarily here to ensure the brige is working
    # on all platforms, and should be removed in a future beta
    assert backend.plus_one(5) == 6
    assert path.endswith(".anki2")
    path = os.path.abspath(path)
    create = not os.path.exists(path)
    if create:
        base = os.path.basename(path)
        for c in ("/", ":", "\\"):
            assert c not in base
    # connect
    db = DB(path)
    db.setAutocommit(True)
    if create:
        ver = _createDB(db)
    else:
        ver = _upgradeSchema(db)
    db.execute("pragma temp_store = memory")
    db.execute("pragma cache_size = 10000")
    if not isWin:
        db.execute("pragma journal_mode = wal")
    db.setAutocommit(False)
    # add db to col and do any remaining upgrades
    col = _Collection(db, backend=backend, server=server, log=log)
    if ver < SCHEMA_VERSION:
        _upgrade(col, ver)
    elif ver > SCHEMA_VERSION:
        raise Exception("This file requires a newer version of Anki.")
    elif create:
        # add in reverse order so basic is default
        addClozeModel(col)
        addBasicTypingModel(col)
        addForwardOptionalReverse(col)
        addForwardReverse(col)
        addBasicModel(col)
        col.save()
    if lock:
        try:
            col.lock()
        except:
            col.db.close()
            raise
    return col
Example #7
0
File: mnemo.py Project: zjulyx/anki
 def _addFrontBacks(self, notes):
     m = addBasicModel(self.col)
     m["name"] = "Mnemosyne-FrontBack"
     mm = self.col.models
     t = mm.newTemplate("Back")
     t["qfmt"] = "{{Back}}"
     t["afmt"] = t["qfmt"] + "\n\n<hr id=answer>\n\n{{Front}}"  # type: ignore
     mm.addTemplate(m, t)
     self._addFronts(notes, m)
Example #8
0
 def _addFrontBacks(self, notes):
     m = addBasicModel(self.col)
     m['name'] = "Mnemosyne-FrontBack"
     mm = self.col.models
     t = mm.newTemplate("Back")
     t['qfmt'] = "{{Back}}"
     t['afmt'] = t['qfmt'] + "\n\n<hr id=answer>\n\n{{Front}}"
     mm.addTemplate(m, t)
     self._addFronts(notes, m)
Example #9
0
def Collection(path, lock=True, server=False, log=False):
    """Open a new or existing collection. Path must be unicode.

    server -- always False in anki without add-on.
    log -- Boolean stating whether log must be made in the file, with same name than the collection, but ending in .log.
    """
    assert path.endswith(".anki2")
    path = os.path.abspath(path)
    create = not os.path.exists(path)
    if create:
        base = os.path.basename(path)
        for c in ("/", ":", "\\"):
            assert c not in base
    # connect
    db = DB(path)
    db.setAutocommit(True)
    if create:
        ver = _createDB(db)
    else:
        ver = _upgradeSchema(db)
    db.execute("pragma temp_store = memory")
    db.execute("pragma cache_size = 10000")
    if not isWin:
        db.execute("pragma journal_mode = wal")
    db.setAutocommit(False)
    # add db to col and do any remaining upgrades
    col = _Collection(db, server, log)
    if ver < SCHEMA_VERSION:
        _upgrade(col, ver)
    elif ver > SCHEMA_VERSION:
        raise Exception("This file requires a newer version of Anki.")
    elif create:
        # add in reverse order so basic is default
        addClozeModel(col)
        addBasicTypingModel(col)
        addForwardOptionalReverse(col)
        addForwardReverse(col)
        addBasicModel(col)
        col.save()
    if lock:
        col.lock()
    return col
Example #10
0
def Collection(path, lock=True, server=False, log=False):
    "Open a new or existing collection. Path must be unicode."
    assert path.endswith(".anki2")
    path = os.path.abspath(path)
    create = not os.path.exists(path)
    if create:
        base = os.path.basename(path)
        for c in ("/", ":", "\\"):
            assert c not in base
    # connect
    db = DB(path)
    db.setAutocommit(True)
    if create:
        ver = _createDB(db)
    elif db.scalar("select ver from col") > 11:
        db.setAutocommit(False)
        raise Exception("invalidColVersion")
    else:
        ver = _upgradeSchema(db)
    db.execute("pragma temp_store = memory")
    db.execute("pragma cache_size = 10000")
    if not isWin:
        db.execute("pragma journal_mode = wal")
    db.setAutocommit(False)
    # add db to col and do any remaining upgrades
    col = _ExtCollection(db, server, log)
    if ver < SCHEMA_VERSION:
        _upgrade(col, ver)
    elif ver > SCHEMA_VERSION:
        raise Exception("This file requires a newer version of Anki.")
    elif create:
        # add in reverse order so basic is default
        addClozeModel(col)
        addBasicTypingModel(col)
        addForwardOptionalReverse(col)
        addForwardReverse(col)
        addBasicModel(col)
        col.save()
    if lock:
        col.lock()
    return col
Example #11
0
def Collection(
    path: str,
    backend: Optional[RustBackend] = None,
    server: Optional[ServerData] = None,
    log: bool = False,
) -> _Collection:
    "Open a new or existing collection. Path must be unicode."
    assert path.endswith(".anki2")
    if backend is None:
        backend = RustBackend(server=server is not None)

    (media_dir, media_db) = media_paths_from_col_path(path)
    log_path = ""
    should_log = not server and log
    if should_log:
        log_path = path.replace(".anki2", "2.log")
    path = os.path.abspath(path)

    # connect
    backend.open_collection(path, media_dir, media_db, log_path)
    db = DBProxy(weakref.proxy(backend), path)

    # initial setup required?
    create = db.scalar("select models = '{}' from col")
    if create:
        initial_db_setup(db)

    # add db to col and do any remaining upgrades
    col = _Collection(db, backend=backend, server=server, log=should_log)
    if create:
        # add in reverse order so basic is default
        addClozeModel(col)
        addBasicTypingModel(col)
        addForwardOptionalReverse(col)
        addForwardReverse(col)
        addBasicModel(col)
        col.save()
    else:
        db.begin()
    return col
Example #12
0
def Collection(path, lock=True, server=False, log=False):
    "Open a new or existing collection. Path must be unicode."
    assert path.endswith(".anki2")
    path = os.path.abspath(path)
    create = not os.path.exists(path)
    if create:
        base = os.path.basename(path)
        for c in ("/", ":", "\\"):
            assert c not in base
    # connect
    db = DB(path)
    db.setAutocommit(True)
    if create:
        ver = _createDB(db)
    else:
        ver = _upgradeSchema(db)
    db.execute("pragma temp_store = memory")
    db.execute("pragma cache_size = 10000")
    if not isWin:
        db.execute("pragma journal_mode = wal")
    db.setAutocommit(False)
    # add db to col and do any remaining upgrades
    col = _Collection(db, server, log)
    if ver < SCHEMA_VERSION:
        _upgrade(col, ver)
    elif ver > SCHEMA_VERSION:
        raise Exception("This file requires a newer version of Anki.")
    elif create:
        # add in reverse order so basic is default
        addClozeModel(col)
        addBasicTypingModel(col)
        addForwardOptionalReverse(col)
        addForwardReverse(col)
        addBasicModel(col)
        col.save()
    if lock:
        col.lock()
    return col
Example #13
0
    def __init__(self, *args):
        """Initialize internal varables.
        Pameters to be exposed to GUI are stored in self.META"""
        NoteImporter.__init__(self, *args)
        m = addBasicModel(self.col)
        m['name'] = "Supermemo"
        self.col.models.save(m)
        self.initMapping()

        self.lines = None
        self.numFields = int(2)

        # SmXmlParse VARIABLES
        self.xmldoc = None
        self.pieces = []
        self.cntBuf = []  # to store last parsed data
        self.cntElm = []  # to store SM Elements data
        self.cntCol = []  # to store SM Colections data

        # store some meta info related to parse algorithm
        # SmartDict works like dict / class wrapper
        self.cntMeta = SmartDict()
        self.cntMeta.popTitles = False
        self.cntMeta.title = []

        # META stores controls of import scritp, should be
        # exposed to import dialog. These are default values.
        self.META = SmartDict()
        self.META.resetLearningData = False  # implemented
        self.META.onlyMemorizedItems = False  # implemented
        self.META.loggerLevel = 2             # implemented
        # 0no,1info,2error,3debug
        self.META.tagAllTopics = True
        # path patterns to be tagged - in gui entered like 'Advanced
        # English 97|My Vocablary'
        self.META.pathsToBeTagged = ['English for begginers',  # sic
                                     'Advanced English 97',
                                     'Phrasal Verbs']
        self.META.tagMemorizedItems = True              # implemented
        self.META.logToStdOutput = False              # implemented

        self.notes = []
Example #14
0
    def __init__(self, col: Collection, file: str) -> None:
        """Initialize internal varables.
        Pameters to be exposed to GUI are stored in self.META"""
        NoteImporter.__init__(self, col, file)
        m = addBasicModel(self.col)
        m["name"] = "Supermemo"
        self.col.models.save(m)
        self.initMapping()

        self.lines = None
        self.numFields = int(2)

        # SmXmlParse VARIABLES
        self.xmldoc = None
        self.pieces = []
        self.cntBuf = []  # to store last parsed data
        self.cntElm = []  # to store SM Elements data
        self.cntCol = []  # to store SM Colections data

        # store some meta info related to parse algorithm
        # SmartDict works like dict / class wrapper
        self.cntMeta = SmartDict()
        self.cntMeta.popTitles = False
        self.cntMeta.title = []

        # META stores controls of import scritp, should be
        # exposed to import dialog. These are default values.
        self.META = SmartDict()
        self.META.resetLearningData = False  # implemented
        self.META.onlyMemorizedItems = False  # implemented
        self.META.loggerLevel = 2  # implemented 0no,1info,2error,3debug
        self.META.tagAllTopics = True
        self.META.pathsToBeTagged = [
            "English for begginers",
            "Advanced English 97",
            "Phrasal Verbs",
        ]  # path patterns to be tagged - in gui entered like 'Advanced English 97|My Vocablary'
        self.META.tagMemorizedItems = True  # implemented
        self.META.logToStdOutput = False  # implemented

        self.notes = []
Example #15
0
 def _addFronts(self, notes, model=None, fields=("f", "b")):
     data = []
     for orig in notes:
         # create a foreign note object
         n = ForeignNote()
         n.fields = []
         for f in fields:
             n.fields.append(orig.get(f, ''))
         n.tags = orig['tags']
         n.cards = orig.get('cards', {})
         data.append(n)
     # add a basic model
     if not model:
         model = addBasicModel(self.col)
     model['name'] = "Mnemosyne-FrontOnly"
     mm = self.col.models
     mm.save(model)
     mm.setCurrent(model)
     self.model = model
     self._fields = len(model['flds'])
     self.initMapping()
     # import
     self.importNotes(data)
Example #16
0
 def _addFronts(self, notes, model=None, fields=("f", "b")):
     data = []
     for orig in notes:
         # create a foreign note object
         n = ForeignNote()
         n.fields = []
         for f in fields:
             n.fields.append(orig.get(f, ''))
         n.tags = orig['tags']
         n.cards = orig.get('cards', {})
         data.append(n)
     # add a basic model
     if not model:
         model = addBasicModel(self.col)
     model['name'] = "Mnemosyne-FrontOnly"
     mm = self.col.models
     mm.save(model)
     mm.setCurrent(model)
     self.model = model
     self._fields = len(model['flds'])
     self.initMapping()
     # import
     self.importNotes(data)
Example #17
0
 def _addFronts(self, notes, model=None, fields=("f", "b")):
     data = []
     for orig in notes:
         # create a foreign note object
         n = ForeignNote()
         n.fields = []
         for f in fields:
             fld = self._mungeField(orig.get(f, ""))
             n.fields.append(fld)
         n.tags = orig["tags"]
         n.cards = orig.get("cards", {})
         data.append(n)
     # add a basic model
     if not model:
         model = addBasicModel(self.col)
         model["name"] = "Mnemosyne-FrontOnly"
     mm = self.col.models
     mm.save(model)
     mm.set_current(model)
     self.model = model
     self._fields = len(model["flds"])
     self.initMapping()
     # import
     self.importNotes(data)
Example #18
0
 def ensureNotEmpty(self):
     if not self.models:
         from anki.stdmodels import addBasicModel
         addBasicModel(self.col)
         return True
Example #19
0
    sys.exit()

if args.output == "file":
    collection_fn = os.path.join(directory, "..", "..", "output", "leetcode",
                                 "leetcode.anki2")
    collection_fn = os.path.abspath(collection_fn)
elif args.output == "desktop":
    collection_fn = util_anki.get_default_collection()
col = Collection(collection_fn, log=True)
my_sol_folder = os.path.join(directory, "..", "..", "output", "raw",
                             "leetcode", "my_solution")

modelBasic = col.models.byName('Basic')
if modelBasic is None:
    # 新安装的 Anki 桌面端会存在为空的情况
    modelBasic = addBasicModel(col)
modelBasic["css"] = conf.DEFAULT_CSS_N_ALIGN + "\n" + conf.HIGHLIGHT_CSS
modelBasic["tmpls"][0]["qfmt"] = "{{Front}}" + conf.JS_TEMPLATE
modelBasic["tmpls"][0][
    "afmt"] = "{{FrontSide}}\n\n<hr id=answer>\n\n{{Back}}" + conf.JS_TEMPLATE
col.models.save(modelBasic)

# 建立新 deck
deck_name = "leetcode"
did = col.decks.id(deck_name)
col.decks.select(did)
col.decks.current()['mid'] = modelBasic['id']
deck = col.decks.byName(deck_name)

base_folder = os.path.join(directory, "..", "..", "output", "raw", "leetcode")
lang = "CN"
Example #20
0
def test_timestamps():
    deck = getEmptyCol()
    assert len(deck.models.models) == len(models)
    for i in range(100):
        addBasicModel(deck)
    assert len(deck.models.models) == 100 + len(models)
Example #21
0
File: models.py Project: dae/anki
 def ensureNotEmpty(self):
     if not self.models:
         from anki.stdmodels import addBasicModel
         addBasicModel(self.col)
         return True
Example #22
0
def test_timestamps():
    deck = getEmptyDeck()
    assert len(deck.models.models) == 2
    for i in range(100):
        addBasicModel(deck)
    assert len(deck.models.models) == 102
Example #23
0
def test_timestamps():
    deck = getEmptyCol()
    assert len(deck.models.models) == len(models)
    for i in range(100):
        addBasicModel(deck)
    assert len(deck.models.models) == 100 + len(models)
Example #24
0
def test_timestamps():
    deck = getEmptyDeck()
    assert len(deck.models.models) == 2
    for i in range(100):
        addBasicModel(deck)
    assert len(deck.models.models) == 102