From 9a29db84efbe8ad02170cba3675ec04d2aaa52c5 Mon Sep 17 00:00:00 2001 From: "Yandrik (aider)" Date: Thu, 20 Mar 2025 11:28:59 +0100 Subject: [PATCH] refactor: move Anki API interactions to separate anki.py module --- anki.py | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ main.py | 49 ++++++------------------------------------------- 2 files changed, 62 insertions(+), 43 deletions(-) create mode 100644 anki.py diff --git a/anki.py b/anki.py new file mode 100644 index 0000000..15052e3 --- /dev/null +++ b/anki.py @@ -0,0 +1,56 @@ +import requests +import logging +from typing import List, Dict + +logger = logging.getLogger("flashcard-creator") + + +class AnkiConnect: + def __init__(self, url="http://127.0.0.1:8765"): + self.url = url + + def get_decks(self) -> List[str]: + """Get the list of decks from Anki using AnkiConnect.""" + try: + response = requests.post( + self.url, json={"action": "deckNames", "version": 6} + ) + data = response.json() + return data.get("result", []) + except Exception as e: + logger.error(f"Error getting Anki decks: {e}") + return [] + + def create_cards(self, deck: str, cards: List[Dict[str, str]]) -> bool: + """Create flashcards in Anki using AnkiConnect.""" + try: + # Prepare notes for addition + notes = [] + logger.info(f"Preparing to create {len(cards)} Anki cards in deck: {deck}") + for card in cards: + notes.append( + { + "deckName": deck, + "modelName": "Basic", # Using the basic model + "fields": {"Front": card["front"], "Back": card["back"]}, + "options": {"allowDuplicate": False}, + "tags": [f"{self.source_language}-{self.target_language}"], + } + ) + + # Add notes to Anki + logger.info("Sending request to AnkiConnect to add notes") + response = requests.post( + self.url, + json={"action": "addNotes", "version": 6, "params": {"notes": notes}}, + ) + data = response.json() + success = all(id is not None for id in data.get("result", [])) + if success: + logger.info("Successfully added all cards to Anki") + else: + logger.warning("Some cards failed to be added to Anki") + return success + except Exception as e: + logger.error(f"Error creating Anki cards: {e}") + return False diff --git a/main.py b/main.py index bbf7c8d..84dcec2 100644 --- a/main.py +++ b/main.py @@ -16,8 +16,9 @@ logger = logging.getLogger("flashcard-creator") class FlashcardCreator: def __init__(self): - # AnkiConnect configuration - self.anki_connect_url = "http://127.0.0.1:8765" + # Anki configuration + from anki import AnkiConnect + self.anki = AnkiConnect() # File picker self.file_picker = ft.FilePicker() @@ -640,49 +641,11 @@ class FlashcardCreator: def get_anki_decks(self) -> List[str]: """Get the list of decks from Anki using AnkiConnect.""" - try: - response = requests.post( - self.anki_connect_url, json={"action": "deckNames", "version": 6} - ) - data = response.json() - return data.get("result", []) - except Exception as e: - print(f"Error getting Anki decks: {e}") - return [] + return self.anki.get_decks() def create_anki_cards(self, deck: str, cards: List[Dict[str, str]]) -> bool: - """Create flashcards in Anki using AnkiConnect.""" - try: - # Prepare notes for addition - notes = [] - logging.info(f"Preparing to create {len(cards)} Anki cards in deck: {deck}") - for card in cards: - notes.append( - { - "deckName": deck, - "modelName": "Basic", # Using the basic model - "fields": {"Front": card["front"], "Back": card["back"]}, - "options": {"allowDuplicate": False}, - "tags": [f"{self.source_language}-{self.target_language}"], - } - ) - - # Add notes to Anki - logging.info("Sending request to AnkiConnect to add notes") - response = requests.post( - self.anki_connect_url, - json={"action": "addNotes", "version": 6, "params": {"notes": notes}}, - ) - data = response.json() - success = all(id is not None for id in data.get("result", [])) - if success: - logging.info("Successfully added all cards to Anki") - else: - logging.warning("Some cards failed to be added to Anki") - return success - except Exception as e: - logging.error(f"Error creating Anki cards: {e}") - return False + """Create flashcards in Anki using Anki-connect.""" + return self.anki.create_cards(deck, cards) def export_as_yaml(self, e): """Export the flashcards as a YAML file."""