Automatically Creating Flashcards with Python Code and AnkiConnect not working

Hello everyone,

I have been trying for hours to program a code that accesses an Excel file, gets the values of certain cells and uses them to create new flashcards based on them. The interaction with Anki is supposed to happen via the add-on AnkiConnect. The specific code I am using is posted down below. I inserted checks in it that should print error messages if any of the steps it carries out fail. It does not show any errors and prints that new flashcards are created just as I want them to. I also checked whether AnkiConnect is installed and enabled, and it is. Here is the log I get when running the code:

Excel file loaded successfully.
AnkiConnect is installed and running.

Flashcard created: Liebe, Lieben → love
Flashcard created: Ferien → holidays, vacation (from school or university)
Flashcard created: Familie, Familien → family
Flashcard created: Burg, Burgen → castle
Flashcard created: Monster, Monster → monster
Flashcard created: England → England
Finished creating flashcards.

Still, the anki decks that I have tried it with never feature any new cards after I run the code. Does anyone have an idea why this could be? I have become so desperate that I opened the collection.anki2 file to check whether running the code changes anything, but I am not a computer guy and dont understand anything in there :smiley:

Here is the code I am using. I am running it in a jupyter notebook

import pandas as pd
import requests

Load your Excel data

excel_file_path = r’C:\Users\Brenda Elisa\Desktop\iLearnLang\Word Sheet.xlsx’

try:
df = pd.read_excel(excel_file_path)
print(“Excel file loaded successfully.”)
except Exception as e:
print(f"Error loading Excel file: {e}")
raise

Define the range of rows to process (e.g., rows 5 to 10)

start_row = 5
end_row = 40
df = df.iloc[start_row - 1:end_row] # Adjust indices to start from 0

Specify the AnkiConnect API endpoint

anki_connect_url = “(http)://localhost:8765”

try:
# Check AnkiConnect
response = requests.get(f"{anki_connect_url}/version")
response.raise_for_status()
print(“AnkiConnect is installed and running.”)
except Exception as e:
print(f"AnkiConnect is not installed or running: {e}")
raise

Specify the deck name where you want to add flashcards

deck_name = ‘test’

Iterate through rows in your Excel file

for index, row in df.iterrows():
# Extract data from the Excel columns
word = row[‘Word’]
extra1 = row[‘Extra1’]
extra2 = row[‘Extra2’]
extra3 = row[‘Extra3’]
translation = row[‘Translation’]

# Concatenate non-empty values with a comma
extras = ', '.join([extra for extra in [extra1, extra2, extra3] if pd.notna(extra)])

# Concatenate "Word" with "Extras" if "Extras" is not empty
if extras:
    word = f'{word}, {extras}'

# Create Anki flashcard with the concatenated string as the front and translation as the back
note = {
    "deckName": deck_name,
    "modelName": "Basic",
    "fields": {
        "Front": word,
        "Back": translation
    },
    "tags": []
}

try:
    # Add the note to Anki using AnkiConnect
    response = requests.post(f"{anki_connect_url}/addNote", json=note)
    response.raise_for_status()
    print(f"Flashcard created: {word} -> {translation}")
except Exception as e:
    print(f"Error creating flashcard: {e}")
    raise

print(“Finished creating flashcards.”)

Had a whole night to think about it, and here are some of the ideas I have why it might not work:

  • None of the words I tried has all three Extra slots full. Could it be that the concatenation of the “front” field fails and is not printed, leading to the cards not being created?

  • I created this whole thing with chatGPT, which has last been updated in 2021. Maybe something has chaged in the meantime? For example, is there even a functionality called “addnote” that can be used to add new notes to the collection?

  • Is the format of the note wrong?

I will try to find a solution and write what I find in here. If anyone has another idea, please feel free to comment :slight_smile:

Hello again!

I have somewhat narrowed down what the error could be:

The printed messages meant to display whether flashcards have been created were faulty. I changed it to interact more closely with Anki and now it shows the following:

“Request to create new flashcard sent successfully”, and
“Failed to create a new note”

This measn that the error is indeed in the creation of new notes. Now I need to find out why. I want to create cards of the “Basic” type like this:

note = {
“deckName”: deck_name,
“modelName”: “Basic”,
“fields”: {
“Front”: word,
“Back”: translation
},
“tags”:
}

What could be going wrong?

Further Update:
I tried other things that require the AnkiConnect functionality, and it worked. I could use AnkiConnect to create a new deck, for instance. But for some reason, the new notes are not created. I implemented a request to retrieve the new note’s ID, and it returns an empty “” and that no such note was found. I tried it on another PC as well, and it did not work…
Really do not know what to do now, and slowly starting to think that I will make the 5000 Flashcards by hand

Create a CSV generator using Python for the content and import it. It’s better than doing it manually

1 Like

Hello!
Just came back to tell people that I worked arounf the problem in a similar way. I created a google apps script that converted my original google sheet into a correctly formated CSV file and just imported it from there. Was 10x easier and should have done so from the start. Thanks anway :slight_smile:

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.