Created
April 15, 2023 17:34
-
-
Save htlin222/2e17d07363f98ab20b304fe6506782b9 to your computer and use it in GitHub Desktop.
python script to watch all images in current directory and use AnkiConnect API to create new card to a Anki Deck
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
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
# date: "2023-04-12" | |
import os | |
import requests | |
import base64 | |
folder_path = "." | |
done_folder_path = "./done" | |
def add_card(deck_name, front, back): | |
# Define the Anki Connect API endpoint | |
endpoint = "http://localhost:8765" | |
with open(front, 'rb') as img_file: | |
encoded_img = base64.b64encode(img_file.read()) | |
html_front = f"<img src='{front}'>" | |
print(html_front) | |
# Define the API request | |
request = { | |
"action": "multi", | |
"params": { | |
"actions": [ | |
{ | |
"action": "storeMediaFile", | |
"params": { | |
"filename": front, | |
"data": encoded_img.decode() | |
} | |
}, | |
{ | |
"action": "addNote", | |
"params": { | |
"note": { | |
"deckName": deck_name, | |
"modelName": "Basic", | |
"fields": { | |
"Front": html_front, | |
"Back": back | |
}, | |
"tags": ['screenshot'] | |
} | |
} | |
} | |
] | |
} | |
} | |
# Send the API request | |
response = requests.post(endpoint, json=request).json() | |
# Check the response for errors | |
print(response) | |
def main(deckname): | |
extensions = [".png", ".PNG", ".JPG", ".JPEG", ".jpg", "jpeg"] | |
for file in os.listdir(folder_path): | |
if any(file.endswith(ext) for ext in extensions): | |
add_card(deckname, file, file) | |
src = os.path.join(folder_path, file) | |
dst = os.path.join(done_folder_path, file) | |
os.rename(src, dst) | |
if __name__ == '__main__': | |
main("YOUR_DECK_NAME") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
install plugin AnkiConnect
2055492159