Skip to content

Instantly share code, notes, and snippets.

@flee2free
Created April 22, 2021 09:56
Show Gist options
  • Save flee2free/08eeec8b9fdb9c449d92243c697e0666 to your computer and use it in GitHub Desktop.
Save flee2free/08eeec8b9fdb9c449d92243c697e0666 to your computer and use it in GitHub Desktop.
Export the randomly generated study card as a PDF
import json
import os
import sqlite3
import zipfile
import glob
import re
import shutil
'''Renaming the ANKI media file with its original filename, once you rename upload these
to Google Drive - get the url mapped with file name and run tag_drive_path()'''
def rename(export_path, result):
resource_mapper = export_path + 'media.txt'
anki_sequence = None
mapper_original = None
try:
anki_sequence = json.loads(str(result[0][0]))
with open(resource_mapper) as resource:
mapper_original = json.load(resource)
except Exception as e:
print str(e)
if not anki_sequence or not mapper_original:
return
resources = ['media', 'renamed']
if os.path.exists('./data'):
shutil.rmtree('./data', ignore_errors=True)
for sub_folder in resources:
os.makedirs('./data/' + sub_folder)
res = [f for f in os.listdir(export_path + resources[0])]
for media in res:
if media in mapper_original:
original_file_name = mapper_original[media]
if original_file_name in anki_sequence:
source = export_path + resources[0] + '/' + media
sequenced_file = anki_sequence[original_file_name]
destination = "./data/renamed/" + "%02d" % sequenced_file + ".jpeg"
shutil.copyfile(source, destination)
def main():
export_path = '../../../../Downloads/_ANKI_EXPORT_/'
for apkg in glob.glob(export_path + '*.apkg'):
os.rename(apkg, export_path + 'export.zip')
with zipfile.ZipFile(export_path + 'export.zip', 'r') as zip_ref:
zip_ref.extractall(export_path)
os.rename(export_path + 'collection.anki2', export_path + 'collection.sqlite')
os.rename(export_path + 'media', export_path + 'media.txt')
os.mkdir(export_path + 'media')
res = [f for f in os.listdir(export_path) if re.search(r'[0-9]{1,2}', f)]
for media in res:
os.rename(export_path + media, export_path + 'media/' + media)
con = sqlite3.connect(export_path + 'collection.sqlite')
cur = con.cursor()
cur.execute("""\
SELECT json_group_object(trim(file_name), sequence_id) AS json_result
FROM (select substr(flds, instr(flds, '"') + 1, instr(flds, '>') - 12) as file_name,
t1.due, row_number() over (order by t1.due) as sequence_id
from cards t1 inner join (select id, flds, sfld, mid from notes) t2
on t1.nid = t2.id order by t1.due)""")
result = cur.fetchall()
rename(export_path, result)
os.system("cd data/renamed; image2pdf")
# ls | sort -n | rename -n 's/.+/our $i; sprintf("%02d.jpeg", 1+$i++)/e'
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment