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