Created
April 2, 2021 10:48
-
-
Save vonHartz/741eb0a393e53df140b504f87cdb6d56 to your computer and use it in GitHub Desktop.
Auto create Anki cards from batch images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Inspired by https://www.reddit.com/r/Anki/comments/1xfpbe/how_to_make_a_deck_out_of_a_folder_of_images_one/cfaylv0?utm_source=share&utm_medium=web2x&context=3 | |
Added a header column for my own card style, fixed sorting and added media import. | |
""" | |
import sys | |
import os | |
import uuid | |
from shutil import copyfile | |
image_formats = ('jpg', 'png') | |
blacklisted_file_formats = ('tsv', 'py') | |
home_dir = os.path.expanduser("~") | |
anki_suffix = r".local/share/Anki2/Benutzer 1/collection.media/" | |
anki_dir = os.path.join(home_dir, anki_suffix) | |
uid = uuid.uuid4().hex | |
if __name__ == '__main__': | |
file_path = os.getcwd() | |
if len(sys.argv) > 1: | |
file_path = sys.argv[1] | |
files = [x for x in sorted(os.listdir(file_path)) if not x.endswith(blacklisted_file_formats)] | |
if len(files) % 2 != 0: | |
print("Odd number of files in directory %s, results might be off." % (file_path)) | |
pairs = zip(files[1::2], files[0::2]) | |
with open('anki_cards.tsv', 'w') as output_file: | |
for pair in pairs: | |
header = ('.').join(pair[0].split('.')[:-1]) | |
if pair[0].endswith(image_formats): | |
img_file = uid + '-' + pair[0] | |
dst = os.path.join(anki_dir, img_file) | |
copyfile(pair[0], dst) | |
question = "<img src='%s' />" % img_file if pair[0].endswith(image_formats) else open(pair[0], 'r').read().strip('\n') | |
if pair[1].endswith(image_formats): | |
img_file = uid + '-' + pair[1] | |
dst = anki_dir + img_file | |
copyfile(pair[1], dst) | |
answer = '<img src="%s" />' % img_file if pair[1].endswith(image_formats) else open(pair[1], 'r').read().strip('\n') | |
output_file.write('%s\t%s\t%s%s' % (header, question, answer, os.linesep)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment