API Reference.md - himent12/FlashGenie GitHub Wiki

📚 FlashGenie API Reference

Complete technical documentation for FlashGenie's classes, methods, and interfaces. This reference provides comprehensive coverage of the public API for developers building integrations, extensions, or contributing to the core codebase.

🎯 API Overview

FlashGenie's API is organized into several key modules:


🧠 Core Classes

Flashcard

The fundamental unit of learning in FlashGenie.

from flashgenie.core.flashcard import Flashcard

Constructor

Flashcard(
    question: str,
    answer: str,
    tags: Optional[List[str]] = None,
    difficulty: float = 1.0,
    metadata: Optional[Dict[str, Any]] = None
)

Parameters:

  • question (str): The question text
  • answer (str): The answer text
  • tags (List[str], optional): List of tags for categorization
  • difficulty (float, optional): Difficulty level (0.1-5.0), defaults to 1.0
  • metadata (Dict[str, Any], optional): Additional metadata

Properties

Property Type Description
id str Unique identifier
question str Question text
answer str Answer text
tags List[str] Associated tags
difficulty float Current difficulty level
created_at datetime Creation timestamp
updated_at datetime Last update timestamp
review_count int Number of times reviewed
correct_count int Number of correct answers
last_reviewed datetime Last review timestamp

Methods

add_tag(tag: str) -> None

Add a tag to the flashcard.

remove_tag(tag: str) -> bool

Remove a tag from the flashcard. Returns True if tag was found and removed.

update_difficulty(new_difficulty: float) -> None

Update the difficulty level (clamped between 0.1 and 5.0).

record_review(correct: bool) -> None

Record a review attempt and update statistics.

get_success_rate() -> float

Calculate the success rate as a percentage.

to_dict() -> Dict[str, Any]

Convert flashcard to dictionary representation.

from_dict(data: Dict[str, Any]) -> Flashcard

Create flashcard from dictionary (class method).


Deck

Container for managing collections of flashcards.

from flashgenie.core.deck import Deck

Constructor

Deck(
    name: str,
    description: str = "",
    flashcards: Optional[List[Flashcard]] = None,
    metadata: Optional[Dict[str, Any]] = None
)

Properties

Property Type Description
id str Unique identifier
name str Deck name
description str Deck description
flashcards List[Flashcard] List of flashcards
created_at datetime Creation timestamp
updated_at datetime Last update timestamp
total_cards int Total number of cards
tags Set[str] All unique tags in deck

Methods

add_card(flashcard: Flashcard) -> None

Add a flashcard to the deck.

remove_card(card_id: str) -> bool

Remove a flashcard by ID. Returns True if found and removed.

get_card(card_id: str) -> Optional[Flashcard]

Retrieve a flashcard by ID.

get_cards_by_tag(tag: str) -> List[Flashcard]

Get all cards with a specific tag.

get_cards_by_difficulty(min_diff: float, max_diff: float) -> List[Flashcard]

Get cards within a difficulty range.

shuffle_cards() -> None

Randomly shuffle the order of flashcards.

get_statistics() -> Dict[str, Any]

Get comprehensive deck statistics.


🤖 Smart Features

QuizEngine

Manages quiz sessions and intelligent question selection.

from flashgenie.core.quiz_engine import QuizEngine, QuizSession

Constructor

QuizEngine(
    difficulty_analyzer: Optional[DifficultyAnalyzer] = None,
    spaced_repetition: Optional[SpacedRepetitionAlgorithm] = None
)

Methods

start_session(deck: Deck, config: Optional[QuizConfig] = None) -> QuizSession

Start a new quiz session.

resume_session(session_id: str) -> QuizSession

Resume a previously saved session.


QuizSession

Represents an active quiz session.

Properties

Property Type Description
session_id str Unique session identifier
deck Deck Associated deck
current_card Optional[Flashcard] Current flashcard
score int Current score
total_questions int Total questions answered
correct_answers int Number of correct answers
start_time datetime Session start time

Methods

get_next_card() -> Optional[Flashcard]

Get the next card based on intelligent selection.

submit_answer(answer: str, confidence: float = 1.0) -> bool

Submit an answer and get correctness feedback.

skip_card() -> None

Skip the current card.

end_session() -> Dict[str, Any]

End the session and return summary statistics.


DifficultyAnalyzer

Analyzes performance and adjusts card difficulty intelligently.

from flashgenie.core.difficulty_analyzer import DifficultyAnalyzer

Methods

analyze_performance(card: Flashcard, responses: List[Dict]) -> Dict[str, float]

Analyze performance metrics for a card.

suggest_difficulty_adjustment(performance: Dict[str, float]) -> float

Suggest difficulty adjustment based on performance.

update_card_difficulty(card: Flashcard, performance: Dict[str, float]) -> None

Update card difficulty based on analysis.


SpacedRepetitionAlgorithm

Implements the SM-2 spaced repetition algorithm.

from flashgenie.core.spaced_repetition import SpacedRepetitionAlgorithm

Methods

calculate_next_review(card: Flashcard, quality: int) -> datetime

Calculate when a card should next be reviewed.

update_card_schedule(card: Flashcard, quality: int) -> None

Update the card's review schedule.


💾 Data Management

DataStorage

Handles persistence and data management.

from flashgenie.data.storage import DataStorage

Methods

save_deck(deck: Deck) -> bool

Save a deck to persistent storage.

load_deck(deck_id: str) -> Optional[Deck]

Load a deck from storage.

list_decks() -> List[Dict[str, str]]

List all available decks.

delete_deck(deck_id: str) -> bool

Delete a deck from storage.

backup_data(backup_path: str) -> bool

Create a backup of all data.

restore_data(backup_path: str) -> bool

Restore data from a backup.


Importers

CSVImporter

from flashgenie.data.importers.csv_importer import CSVImporter
import_from_file(file_path: str, config: Optional[Dict] = None) -> List[Flashcard]

Import flashcards from CSV file.

TXTImporter

from flashgenie.data.importers.txt_importer import TXTImporter
import_from_file(file_path: str, config: Optional[Dict] = None) -> List[Flashcard]

Import flashcards from text file.


Exporters

CSVExporter

from flashgenie.data.exporters.csv_exporter import CSVExporter
export_deck(deck: Deck, file_path: str) -> bool

Export deck to CSV format.

JSONExporter

from flashgenie.data.exporters.json_exporter import JSONExporter
export_deck(deck: Deck, file_path: str) -> bool

Export deck to JSON format.


🎯 Usage Examples

Basic Usage

from flashgenie import Flashcard, Deck, QuizEngine, DifficultyAnalyzer

# Create flashcards
card1 = Flashcard("What is Python?", "A programming language")
card2 = Flashcard("What is ML?", "Machine Learning")

# Create deck
deck = Deck("Programming Basics", flashcards=[card1, card2])

# Initialize quiz engine
analyzer = DifficultyAnalyzer()
quiz_engine = QuizEngine(analyzer)

# Start quiz session
session = quiz_engine.start_session(deck)

# Quiz loop
while session.has_more_cards():
    card = session.get_next_card()
    print(f"Question: {card.question}")
    
    user_answer = input("Your answer: ")
    is_correct = session.submit_answer(user_answer)
    
    print("Correct!" if is_correct else f"Wrong. Answer: {card.answer}")

# Get session results
results = session.end_session()
print(f"Score: {results['score']}/{results['total']}")

Advanced Usage with Smart Features

from flashgenie import (
    Deck, QuizEngine, DifficultyAnalyzer,
    TagManager, SmartCollectionManager
)

# Create deck with tagged cards
deck = Deck("Advanced Topics")
deck.add_card(Flashcard("Define polymorphism", "...", tags=["OOP", "concepts"]))
deck.add_card(Flashcard("Explain inheritance", "...", tags=["OOP", "basics"]))

# Initialize smart features
tag_manager = TagManager()
collection_manager = SmartCollectionManager()
analyzer = DifficultyAnalyzer()

# Auto-categorize cards
tag_manager.auto_tag_deck(deck)

# Create smart collections
collection_manager.create_collection("Struggling Cards", {
    "difficulty_min": 3.0,
    "success_rate_max": 0.6
})

# Use smart collections
struggling_cards = collection_manager.get_collection("Struggling Cards")
cards = collection_manager.get_collection_cards(struggling_cards, deck)
print(f"Found {len(cards)} struggling cards")

Data Management

from flashgenie.data.storage import DataStorage
from flashgenie.data.importers.csv_importer import CSVImporter

# Initialize storage
storage = DataStorage()

# Import from CSV
importer = CSVImporter()
cards = importer.import_from_file("my_cards.csv")

# Create and save deck
deck = Deck("Imported Deck", flashcards=cards)
storage.save_deck(deck)

# List all decks
decks = storage.list_decks()
for deck_info in decks:
    print(f"Deck: {deck_info['name']} ({deck_info['card_count']} cards)")

🔧 Configuration

Environment Variables

Variable Description Default
FLASHGENIE_DATA_DIR Data directory path ./data
FLASHGENIE_LOG_LEVEL Logging level INFO
FLASHGENIE_CONFIG_FILE Config file path ./config.json

Configuration File

{
  "spaced_repetition": {
    "initial_interval": 1,
    "easy_factor": 2.5,
    "minimum_factor": 1.3
  },
  "quiz": {
    "max_questions_per_session": 50,
    "case_sensitive": false
  },
  "ui": {
    "use_colors": true,
    "clear_screen": true
  }
}

🚨 Error Handling

Custom Exceptions

from flashgenie.utils.exceptions import (
    FlashGenieError,
    DeckNotFoundError,
    CardNotFoundError,
    ImportError,
    ExportError
)

FlashGenieError

Base exception for all FlashGenie errors.

DeckNotFoundError

Raised when a requested deck cannot be found.

CardNotFoundError

Raised when a requested card cannot be found.

ImportError

Raised when import operations fail.

ExportError

Raised when export operations fail.


🔌 Extension Points

FlashGenie is designed for extensibility. Key extension points include:

Custom Algorithms

from flashgenie.core.difficulty_analyzer import DifficultyAnalyzer

class MyCustomAnalyzer(DifficultyAnalyzer):
    def analyze_performance(self, card, responses):
        # Your custom analysis logic
        return performance_metrics

    def suggest_difficulty_adjustment(self, performance):
        # Your custom adjustment logic
        return difficulty_change

Custom Importers

from flashgenie.data.importers.base_importer import BaseImporter

class MyCustomImporter(BaseImporter):
    def import_from_file(self, file_path, config=None):
        # Your custom import logic
        return flashcards

Custom Exporters

from flashgenie.data.exporters.base_exporter import BaseExporter

class MyCustomExporter(BaseExporter):
    def export_deck(self, deck, file_path):
        # Your custom export logic
        return success

📊 Performance Considerations

Memory Usage

  • Decks are loaded entirely into memory
  • Large decks (>10,000 cards) may impact performance
  • Consider pagination for very large datasets

Storage

  • Data is stored in JSON format by default
  • File I/O operations are synchronous
  • Consider async operations for large datasets

Optimization Tips

  • Use smart collections to filter large decks
  • Implement custom algorithms for specific use cases
  • Cache frequently accessed data

This API reference is automatically updated with each release. For the latest version, see the GitHub repository.