refactor: move Anki API interactions to separate anki.py module
This commit is contained in:
parent
35df3eaab8
commit
9a29db84ef
56
anki.py
Normal file
56
anki.py
Normal file
@ -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
|
49
main.py
49
main.py
@ -16,8 +16,9 @@ logger = logging.getLogger("flashcard-creator")
|
|||||||
|
|
||||||
class FlashcardCreator:
|
class FlashcardCreator:
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
# AnkiConnect configuration
|
# Anki configuration
|
||||||
self.anki_connect_url = "http://127.0.0.1:8765"
|
from anki import AnkiConnect
|
||||||
|
self.anki = AnkiConnect()
|
||||||
|
|
||||||
# File picker
|
# File picker
|
||||||
self.file_picker = ft.FilePicker()
|
self.file_picker = ft.FilePicker()
|
||||||
@ -640,49 +641,11 @@ class FlashcardCreator:
|
|||||||
|
|
||||||
def get_anki_decks(self) -> List[str]:
|
def get_anki_decks(self) -> List[str]:
|
||||||
"""Get the list of decks from Anki using AnkiConnect."""
|
"""Get the list of decks from Anki using AnkiConnect."""
|
||||||
try:
|
return self.anki.get_decks()
|
||||||
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 []
|
|
||||||
|
|
||||||
def create_anki_cards(self, deck: str, cards: List[Dict[str, str]]) -> bool:
|
def create_anki_cards(self, deck: str, cards: List[Dict[str, str]]) -> bool:
|
||||||
"""Create flashcards in Anki using AnkiConnect."""
|
"""Create flashcards in Anki using Anki-connect."""
|
||||||
try:
|
return self.anki.create_cards(deck, cards)
|
||||||
# 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
|
|
||||||
|
|
||||||
def export_as_yaml(self, e):
|
def export_as_yaml(self, e):
|
||||||
"""Export the flashcards as a YAML file."""
|
"""Export the flashcards as a YAML file."""
|
||||||
|
Loading…
Reference in New Issue
Block a user