Extending the Anki Cloze Anything script for language learners

It’s possible to use cloze deletion cards within standard Anki note types using the Anki Cloze Anything setup. But additional scripts are required to allow it to function seamlessly in a typical language-learning environment. I’ll show you how to flexibly display a sentence with or without Anki Cloze Anything markup and also not break AwesomeTTS.

Anki’s built-in cloze deletion system

The built-in cloze deletion feature in Anki is an excellent way for language learners to actively test their recall. For example, a cloze deletion note type with the following content requires the learner to supply the missing word:

This will render the front side as:

and the reverse side will be rendered as:

But the greatest weakness of the built-in cloze deletion feature is that the only way to generate cloze deletion cards is to use the cloze deletion note type; and it is not possible to generate cloze deletion cards from other note types. This introduces an inefficiency for language learners. Often we use example sentences in straight vocabulary notes as an aid to using the word in context. I use example sentences that appear on the back side of the card. It would be ideal if I could create a card type within my standard vocabulary notes that generates a cloze card with the example sentence. Otherwise, I am forced to create a separate cloze deletion note for my example sentence if I want to also test on that sentence. This is the problem that Anki Cloze Anything solves.

Anki Cloze Anything

In its simplest form, this is a script that allows you to use cloze deletion card types in a regular note. Instead of Anki’s typical {{c1:somecloze}} markup, it uses ((c1::somecloze)) style markup, but in most respects works the same as the built-in system. Anki Cloze Anything also has an add-on that addresses some workflow efficiency needs; but it will work just fine with only the Javascript on the card template.

However, because Anki Cloze Anything requires that I use a particular markup for the sentences, I can no longer display the same sentence on another card type. Using the example above, if I have a vocabulary card for перевязать then I’d like to have an illustrative sentence on the back of my card, Она перевяза́ла упако́вку шпагатом. . But Anki Cloze Anything requires me to commit to something like: Она ((c1::перевяза́ла)) упако́вку шпагатом. if I also want to use the same sentence in a cloze-type note. Unless I modify my standard card template, then my sentence will display with the Anki Cloze Anything markup.

Essentially, what Anki Cloze Anything does for me is that it allows me to use a single illustrative sentence as both an example sentence on the back of a standard vocabulary card and to be a cloze sentence at the same time. It saves time by not requiring me to add sentences twice (once to my standard vocabulary card and again to a cloze deletion card.)

But this idea only works if I can display (and pronounce) the sentence in the correct way on the correct card. This is where the two-fold solution described below comes into play.

Enhancing the Anki Cloze Anything template

If I want to display a sentence containing Anki Cloze Anything markup on a standard (non-cloze) card type, then I have to strip out the markup. Fortunately, jQuery makes this easy. Assume I have the following on my standard card template:

<!-- if an example sentence is available, show it -->
{{#sentence_ru}}
   <hr/>
   <div style="padding-left:10px;, padding-right:10px;">
      <span class="rusentence">
         {{sentence_ru}}
      </span> - <span class="ensentence smaller">{{sentence_en}}</span>
   </div>
{{/sentence_ru}}

If the span class rusentence contains a sentence with Anki Cloze Anything markup, then I need to strip away the markup when the standard card displays; so I just need a script to address that:

$('span.rusentence').each(function() {
   var text = $(this).text();
   text = text.replace(/\({2}c\d::([^\0]+)\){2}/g, "$1");
   text = text.replace(new RegExp('`', 'g'),"")
   $(this).text(text);
});

If you enclose this between <script>...</script> tags in the standard note template, then the sentence will display normally, while still allowing you to use the same sentence in a different Anki Cloze Anything card type.

But what about AwesomeTTS

Many language learners use AwesomeTTS, an add-on that provides text-to-speech capabilities to Anki cards. However, using AwesomeTTS on an Anki Cloze Anything card doesn’t work as intendeded, because it just reads the text with the markup. How to fix this?

Fortunately, AwesomeTTS has a text preprocessor that allows you to apply regular expressions (regex) to the text before it feeds the text to the TTS service. The functionality is at Toos → AwesomeTTS → Configuration → Text → Advanced. From there, add a text replacement rule:

The rule \({2}c\d::(.+)\){2} → \1 is very similar to the Javascript we used above in the template. With this text-replacement rule in place, AwesomeTTS now reads the sentence correctly even if it contains Anki Cloze Anything markup.

Caveats

The regex described here doesn’t account for the hint markup feature of Anki Cloze Anything. I’ll have to work on that at some point.

References

Complete fix for broken Knowclip .apkg files

I think this is the last word on fixing Knowclip .apkg files. I’ve developed this in bits and pieces; but hopefully this is the last word on the subject. See my previous articles, here and here, for the details.

This issue, again, is that Knowclip gives these notes and cards sequential id values starting at 1. But Anki uses the note.id and the card.id as the creation date. I logged it as an issue on Github, but as of 2021-04-15 no action has been taken.

This version takes the .apkg path as the script parameter and then does this rest. Instead of asking the user for the date and time for the first note (and card) it takes that information from the creation time of the .apkg file. Note that this has been tested only on macOS. Undoubtedly you will have to adapt this on other platforms.

#!/usr/bin/env python3

import sqlite3
import time
import datetime
import zipfile
import os
import sys

def create_holding_dir(parent_path, name):
   path = os.path.join(parent_path, name)
   os.mkdir(path)
   return path

def delete_rogue_macosx_dir(target_dir):
   path = os.path.join(target_dir, '__MACOSX')
   os.rmdir(path)

def collection_path(target_dir):
   path = os.path.join(target_dir, 'collection.anki2')
   return path

def open_collection_db(target_dir):
   try:
      conn = sqlite3.connect(collection_path(target_dir))
      cursor = conn.cursor()
   except:
      exit("__UNABLE TO OPEN COLLECTION DB__")
   return (conn, cursor)

def restore_apkg(apkg_path, basename_with_path):
   # give apkg_path a unique name
   components = os.path.split(apkg_path)
   os.rename(basename_with_path, os.path.join(components[0], f'_{components[1]}'))

   # sys.argv[1] is the apkg to expand
try:
   apkg_path = sys.argv[1]
except:
   exit("__NO APKG PATH SPECIFIED__")
basename_with_extension = os.path.basename(os.path.normpath(apkg_path))
basename = basename_with_extension.rsplit( ".", 1 )[ 0 ]
basename_with_zip = basename + '.zip'
parent_dir = os.path.split(apkg_path)[0]
basename_with_path = os.path.join(parent_dir, basename_with_zip)
parent_path = os.path.abspath(os.path.join(basename_with_path, '..'))

# create a directory to hold the unzipped files
target_dir = create_holding_dir(parent_path, basename)

try:
   os.rename(apkg_path, basename_with_path)
except:
   print('ERROR - unable to rename file')
with zipfile.ZipFile(basename_with_path, 'r') as zip_ref:
   zip_ref.extractall(target_dir)

delete_rogue_macosx_dir(target_dir)
(conn, cursor) = open_collection_db(target_dir)

new_epoch = int(1000 * os.path.getctime(basename_with_path))

print(f'Will begin create date with epoch ms {new_epoch}.')

q = 'SELECT id FROM notes'
cursor.execute(q)
note_rows = cursor.fetchall()
note_chg_sql_cmds = []
for note_row in note_rows:
   qn = f'UPDATE notes SET id = {new_epoch} WHERE id = {note_row[0]}'
   note_chg_sql_cmds.append(qn)
   qc = f'UPDATE cards SET nid = {new_epoch}, id = {new_epoch} WHERE nid = {note_row[0]}'
   new_epoch = new_epoch + 100
   cursor.execute(qc)
conn.commit()
qc = f'UPDATE cards SET id = nid +10'
cursor.execute(qc)
conn.commit()
for sql in note_chg_sql_cmds:
   cursor.execute(sql)
conn.commit()
conn.close()

# save a backup copy of the original apkg name
restore_apkg(apkg_path, basename_with_path)

# compress the altered collection directory into a zip
# and rename it as an .apkg file for Anki
dest_zip_file_path = os.path.join(parent_path, basename+'.zip')
zf = zipfile.ZipFile(dest_zip_file_path, 'w', zipfile.ZIP_DEFLATED)
for root, dirs, files in os.walk(target_dir):
   for file_name in files:
      zf.write(os.path.join(root, file_name))
os.rename(basename_with_path, apkg_path)