Not long ago I ran across this post detailing a method for opening and inspecting the Anki database using Python outside the Anki application environment. However, the approach requires linking to the Anki code base which is inaccessible on mac OS since the Python code is packaged into a Mac app on this platform.
The solution I’ve found is inelegant; but just involves downloading the Anki code base to a location on your file system where you can link to it in your code. You can find the Anki code here on github.
Once that’s done, you’re ready to load an Anki collection. First, the preliminaries:
#!/usr/bin/pythonimportsys# pathsANKI_PATH='path to where you downloaded the anki codebase'COLLECTION_PATH="path to the Anki collection"sys.path.append(ANKI_PATH)fromankiimportCollection
Now we’re ready to open the collection:
col=Collection(COLLECTION_PATH)
And execute a simple query to print out the total number of cards in the collection:
query="""SELECT COUNT(id) from cards"""totalCards=col.db.scalar(query)print'There are {:.5g} total cards.'.format(totalCards)
Then close the collection:
col.close()
That’s it. Ideally, we’d be able to link to the Anki code bundled with the Mac application. Maybe there’s a way. In the meanwhile, here’s the entire little app:
#!/usr/bin/pythonimportsys# pathsANKI_PATH='/Users/alan/Documents/dev/projects/PersonalProjects/anki'COLLECTION_PATH="/Users/alan/Documents/Anki/Alan - Russian/collection.anki2"sys.path.append(ANKI_PATH)fromankiimportCollectioncol=Collection(COLLECTION_PATH)query="""SELECT COUNT(id) from cards"""totalCards=col.db.scalar(query)print'There are {:.5g} total cards.'.format(totalCards)col.close()
For the last two years, I’ve been working through a 10,000 word Russian vocabulary ordered by frequency. I have a goal of finishing the list before the end of 2019. This requires not only stubborn persistence but an efficient process of collecting the information that goes onto my Anki flash cards.
My manual process has been to work from a Numbers spreadsheet. As I collect information about each word from several websites, I log it in this table.
For each word, I do the following:
From Open Russian I obtain an example sentence or two.
From Wiktionary I obtain, the definition, more example phrases, any particular grammatical information I need, and audio of the pronunciation if it is available. I also capture the URL from this site onto my flash card.
From the Russian National Corpus I capture the frequency according to their listing in case I want to reorder my frequency list in the future.
This involves lots of cutting, pasting and tab-switching. So I devised an automated approach to loading up this information. This most complicated part was downloading the Russian pronunciation from Wiktionary. I did this with Python.
Downloading pronunciation files from Wiktionary
classWikiPage(object):"""Wiktionary page - source for the extraction"""def__init__(self,ruWord):super(WikiPage,self).__init__()self.word=ruWordself.baseURL=u'http://en.wiktionary.org/wiki/'self.anchor=u'#Russian'defurl(self):returnself.baseURL+self.word+self.anchor
First, we initialize a WikiPage object by building the main page URL using the Russian word we want to capture. We can capture the page source and look for the direct link to the audio file that we want:
The function audioLink returns a link to the .ogg file that we want to download. Now we just have to download the file:
defdownloadAudio(self):path=join(expanduser("~"),'Downloads',self.word+'.ogg')try:mp3file=urllib2.urlopen(self.fullAudioLink())exceptAttributeError:print"There appears to be no audio."notify("No audio","Wiktionary has no pronunciation","Pronunciation is not available for download.",sound=True)else:withopen(path,'wb')asoutput:output.write(mp3file.read())
Now to kick-off the process, we just have to get the word from the mac OS pasteboard, instantiate a WikiPage object and call downloadAudio on it:
There we grab the word off the clipboard and build the URL for both sites. Next we’ll look for a tab that contains the Russian National Corpus site and execute a page search for our target word. That way I can easily grab the word frequency from the page.
tellapplication"Google Chrome"toactivate-- initiate the word find process in dict.ruslang.rutellapplication"Google Chrome"-- find the tab with the frequency listsetito0repeatwithtin(everytabofwindow1)setitoi+1setsearchURLTextto(URLoft)as textifsearchURLTextbegins with"http://dict.ruslang.ru/"thensetactivetabindexofwindow1toiexitrepeatendifendrepeatendtelldelay1tellapplication"System Events"tellprocess"Google Chrome"keystroke"f"usingcommanddowndelay0.5keystroke"V"usingcommanddowndelay0.5key code36endtellendtell
Then we need to load the word definition pages using the URLs that we built earlier:
-- load word definitionstellapplication"Google Chrome"activatesetito0settabListtoeverytabofwindow1repeatwiththeTabintabListsetitoi+1settextURLto(URLoftheTab)as text-- load the word in open russianiftextURLbegins with"https://en.openrussian.org"thensetURLoftheTabtoopenRussianURLendif-- load the word in wiktionaryiftextURLbegins with"https://en.wiktionary.org"thensetURLoftheTabtowiktionaryURL-- make the wiktionary tab the active tabsetactivetabindexofwindow1toiendifendrepeatendtell
Finally, using do shell script we can fire off the Python script to download the audio. Actually, I have the AppleScript do that first to allow time to process the audio as I’ve described previously. Finally, I create a Quicksilver trigger to start the entire process from a single keystroke.
Granted, I have a very specific use case here, but hopefully you’ve been able to glean something useful about process automation of Chrome and using Python to download pronunciation files from Wiktionary. Cheers.
I wrote a piece previously about using JavaScript in Anki cards. Although I haven’t found many uses for employing this idea, it does come up from time-to-time including a recent use-case I’m writing about now.
After downloading a popular French frequency list deck for my daughter to use, I noticed that it omits the gender of nouns in the French prompt. In school, I was always taught to memorize the gender along with the noun.
He was supposed to be a great maker of things, but he was mostly a breaker.
This is a brutal piece by Rebecca Solnit on the privilege and cravenness of Donald Trump. Should be read by all Americans.
Spurious sensor data can wreak havoc in an otherwise finely-tuned home automation system. I use temperature data from an Aeotech Multisensor 6 to monitor the environment in our greenhouse. Living in Canada, I cannot rely solely on passive systems to maintain the temperature, particularly at night. So, using the temperature and humidity measurements transmitted back to the controller over Z-wave, I control devices inside the greenhouse that heat and humidify the environment.
With Trump the usual advice of “Follow the money.” doesn’t work because Congress refuses to force him to disclose his conflicts of interest. As enormous and material as those conflicts must be, I’m just going to focus on what I can see with my own eyes, the man’s apparent intent.
In his public life, Donald Trump has never done anything that did not personally and directly benefit him. Most of us, as we go through life, assemble a collection of acts that are variously self-serving and other-serving.
In an effort to strip protesters of their legitimacy, Trump and Fox News claim that protesters are simply there because they’re paid by powerful oppositional interests. Never mind that Trump has no evidence for his claim; he has no evidence for practically anything that emerges from his loud mouth. What is more interesting to me is that if money delegitimizes authenticity then presumably we can use this effect to come to additional conclusions.
Someday, when I have time to burn, I’m going to write a Twitter bot that takes all of Trump’s vacuous tweets and translate them into Russian. It’ll look like this:
There’s something ludicrous about the idea of the Trump, who is distractible, impatient, and incurious being able to learn Russian, an incredibly difficult language.
marking time,eyes glazed, pupils constrictedto the head of a pinfrom facing the blue white sterile lightfor too longa zombie tribenumbering in the millionsif not morewaits.this throng, agitatedin a subdued anesthetizedway,crowns one of its owna clown of sortsknowing little of the pastless of the presentand practically nothingof the future.“why not? it could be worse.“in a strange unrealitya vaudeville show becomesits own rehearsal,a dreamish state from whichonly an atomic flashcan awaken a person.
On January 1, 2016 we packed up all our earthly goods and headed south to Canada. (Yes, it’s true. When you live in Minnesota, it’s possible to move south to Canada. Look at the map!) Having lived here for a little over a year, here are some thoughts about living here, in no particular order:
“Sorry” is more of a greeting than just an apology.