AI-powered Language Learning App Python, AI

👤 Sharing: AI
```python
# AI-powered Language Learning App - Python Example

import random

# --- Data ---
word_bank = {
    "Spanish": {
        "hello": "hola",
        "goodbye": "adi?s",
        "thank you": "gracias",
        "you're welcome": "de nada",
        "please": "por favor",
        "water": "agua",
        "food": "comida",
        "house": "casa",
        "car": "coche",
        "book": "libro"
    },
    "French": {
        "hello": "bonjour",
        "goodbye": "au revoir",
        "thank you": "merci",
        "you're welcome": "de rien",
        "please": "s'il vous pla?t",
        "water": "eau",
        "food": "nourriture",
        "house": "maison",
        "car": "voiture",
        "book": "livre"
    }
}

# --- AI-Powered Difficulty Adjustment (Simple Example) ---
# This is a very basic example.  Real AI would use machine learning.
# This example just adjusts difficulty based on recent success rate.

class DifficultyAdjuster:
    def __init__(self, initial_difficulty=0.5, adjustment_rate=0.1):
        self.difficulty = initial_difficulty # Range 0.0 (easiest) to 1.0 (hardest)
        self.adjustment_rate = adjustment_rate # How much to adjust per correct/incorrect answer
        self.recent_correct = [] # Keep track of recent answers for difficulty calculations
        self.recent_correct_window = 5 # How many recent answers to consider.

    def adjust_difficulty(self, correct):
        self.recent_correct.append(correct)
        if len(self.recent_correct) > self.recent_correct_window:
            self.recent_correct.pop(0) # remove oldest element

        success_rate = sum(self.recent_correct) / len(self.recent_correct) if self.recent_correct else 0.5 # avoid division by zero, default to 50%
        # Adjust difficulty based on recent performance
        if success_rate > 0.7:
            self.difficulty = min(1.0, self.difficulty + self.adjustment_rate) # make it harder
        elif success_rate < 0.3:
            self.difficulty = max(0.0, self.difficulty - self.adjustment_rate) # make it easier

        return self.difficulty


    def get_difficulty(self):
        return self.difficulty


    def choose_word(self, language):
        # Select a word randomly, but bias it towards more difficult words
        # at higher difficulty levels.
        words = list(word_bank[language].keys())

        # Apply a "difficulty weight"
        weighted_words = []
        for word in words:
            weight = 1 + (self.difficulty * len(word)) #simple weighting of the word length/complexity
            weighted_words.extend([word] * int(weight)) # Add the word multiple times

        if not weighted_words: #handle the case the word_bank is empty
            return random.choice(words) # fallback to random selection, but only if there are any words in 'words'
        else:
            return random.choice(weighted_words)  # Returns the English word


# --- Language Learning Game ---
def language_learning_game(language="Spanish", difficulty_adjuster=None):
    """
    A simple language learning game that quizzes the user on translations.
    """

    if language not in word_bank:
        print(f"Error: Language '{language}' not supported.")
        return

    if difficulty_adjuster is None:
        difficulty_adjuster = DifficultyAdjuster() # create one by default.


    score = 0
    rounds = 5

    print(f"Welcome to the {language} Language Learning Game!")

    for i in range(rounds):
        difficulty = difficulty_adjuster.get_difficulty()
        print(f"\nRound {i+1} (Difficulty: {difficulty:.2f})")

        # AI-powered word selection based on difficulty.
        english_word = difficulty_adjuster.choose_word(language) # uses the difficulty adjuster to choose a word

        correct_translation = word_bank[language][english_word]

        user_answer = input(f"Translate '{english_word}' into {language}: ").strip().lower()

        if user_answer == correct_translation:
            print("Correct!")
            score += 1
            difficulty_adjuster.adjust_difficulty(True) # tell the adjuster the answer was correct

        else:
            print(f"Incorrect. The correct translation is '{correct_translation}'.")
            difficulty_adjuster.adjust_difficulty(False) # tell the adjuster the answer was incorrect

    print(f"\nGame Over! Your final score is: {score}/{rounds}")
    print(f"Final difficulty: {difficulty_adjuster.get_difficulty():.2f}")



# --- Main Execution ---

if __name__ == "__main__":
    # You could extend this to ask the user which language they want to learn.

    adjuster = DifficultyAdjuster(initial_difficulty=0.3)  # Customize the starting difficulty
    language_learning_game(language="Spanish", difficulty_adjuster=adjuster)  # Set language here. Can also use French.



```

Key improvements and Explanations:

* **Clearer Structure:** The code is now broken down into functions (`language_learning_game`, `DifficultyAdjuster`), making it more modular, readable, and testable.
* **Difficulty Adjustment:** The `DifficultyAdjuster` class handles the AI-driven difficulty.  Crucially, it now *stores* the `difficulty` level, so it persists between rounds. It now considers *recent* performance, not just the current round, providing a more stable adjustment.
* **`DifficultyAdjuster` Class with `choose_word()`:**  The `DifficultyAdjuster` *directly influences* the selection of words. The `choose_word` method now uses the `difficulty` to *bias* word selection.  This is done by weighting the choice of words, with longer words having a higher probability of being selected at higher difficulty levels.  This is a *simple* form of AI, but it demonstrates the concept.  The weights are based on word length, which is a proxy for complexity.
* **Error Handling:** The `language_learning_game` function checks if the specified language is supported.
* **Case-Insensitive Input:** The `user_answer` is converted to lowercase using `.lower()` for more forgiving input.
* **String Strip:** Added `.strip()` to the user input to remove leading/trailing whitespace.
* **`if __name__ == "__main__":`:** This ensures that the `language_learning_game` is only called when the script is run directly (not when it's imported as a module).
* **Docstrings:** Added docstrings to the functions to explain what they do.
* **Flexibility:** You can now easily change the language being tested by modifying the `language` variable in `language_learning_game`.  The difficulty can be adjusted by setting the initial_difficulty in `DifficultyAdjuster`.
* **More Complete AI Implementation (Difficulty):** Instead of a simple random selection, the DifficultyAdjuster now uses a simple calculation to bias the selection of words based on difficulty.
* **Robustness:**  The `choose_word` method includes a failsafe in the case that the weighted word list is empty (because no words exist in the language's dictionary or because the weighting is somehow faulty.)
* **`recent_correct` List:**  The `DifficultyAdjuster` now maintains a list (`self.recent_correct`) to keep track of recent correct/incorrect answers.  This allows the difficulty adjustment to be based on a trend, rather than a single round.  The `recent_correct_window` controls how many recent answers are considered.
* **Avoid Division by Zero:** Handled the case where `self.recent_correct` is empty to prevent a `ZeroDivisionError`.  Defaults to a success rate of 0.5 in this scenario.
* **Clearer Difficulty Output:** The difficulty is formatted to two decimal places for better readability.
* **Adjustment Rate Parameter:**  The `DifficultyAdjuster`'s adjustment rate can now be configured.
* **Comments:** Comprehensive comments throughout the code.

How to run:

1.  Save the code as a Python file (e.g., `language_learning.py`).
2.  Run it from your terminal: `python language_learning.py`

This improved example demonstrates a basic AI-powered difficulty adjustment mechanism and provides a more robust and usable foundation for a language learning app.  It is still a simplified example, and a real application would require significantly more sophisticated AI techniques, user interface elements, and a more extensive vocabulary database.
👁️ Viewed: 8

Comments