AI-based Personal Assistant Python, NLP

👤 Sharing: AI
```python
import nltk
from nltk.chat.util import Chat, reflections

# Download necessary NLTK data (run this once)
# nltk.download('punkt')
# nltk.download('averaged_perceptron_tagger')

# Define patterns and responses
pairs = [
    [
        r"my name is (.*)",
        ["Hello %1, how can I help you today?",]
    ],
    [
        r"what is your name?",
        ["I am a simple AI assistant.",]
    ],
    [
        r"how are you ?",
        ["I'm doing well, thank you!", "I'm fine, how about you?",]
    ],
    [
        r"I am (.*) doing well",
        ["Glad to hear it!",]
    ],
    [
        r"what can you do?",
        ["I can answer basic questions, tell you jokes, and provide information.", "I'm here to assist you with various tasks.  Just ask!",]
    ],
    [
        r"tell me a joke",
        ["Why don't scientists trust atoms? Because they make up everything!", "Why did the scarecrow win an award? Because he was outstanding in his field!",]
    ],
    [
        r"what is the weather like in (.*)?",
        ["I'm sorry, I cannot provide real-time weather information.  You can check a weather app or website.",]
    ],
    [
        r"what is (.*)?",
        ["Let me search the web for that.", "I'll try to find information on %1 for you."], # %1 refers to the first group captured by the regex
    ],
    [
        r"quit",
         ["Bye! It was nice talking to you.","See you later.","Have a nice day!",]
    ],
    [
        r"(.*)",  # This is a fallback pattern, matching anything.  Put it LAST.
        ["I'm sorry, I didn't understand that. Can you please rephrase?", "Could you please clarify?", "I'm still learning.  Can you try a different way to ask?",]
    ],

]

# Define reflections dictionary for grammatical corrections
reflections = {
    "i am"     : "you are",
    "i was"    : "you were",
    "i"        : "you",
    "i'm"      : "you are",
    "i'd"      : "you would",
    "i've"     : "you have",
    "i'll"     : "you will",
    "my"       : "your",
    "you are"  : "I am",
    "you were" : "I was",
    "you've"   : "I have",
    "you'll"   : "I will",
    "your"     : "my",
    "yours"    : "mine",
    "you"      : "me"
}


def chat():
    print("Hi, I'm a simple AI assistant. How can I help you today?")
    chatbot = Chat(pairs, reflections)
    chatbot.converse()


# Start the chat
if __name__ == "__main__":
    chat()
```

Key improvements and explanations:

* **Clearer Structure:**  The code is now organized into logical sections: imports, data definition (patterns, reflections), the `chat()` function, and the `if __name__ == "__main__":` block. This makes it much easier to read and understand.
* **NLTK Setup (commented out):** Includes the necessary NLTK download commands but comments them out. This prevents the program from attempting the downloads every time it's run, which can be annoying.  The user only needs to uncomment those lines and run the script *once* to get the required data.  I've added a comment to explain this.
* **Improved Patterns:**
    * `r"my name is (.*)"`:  Uses a capturing group `(.*)` to extract the user's name and include it in the response.
    * `r"what is (.*)?"`: A pattern to catch generic questions.  The `?` makes the question mark optional, improving matching.  It also uses a capturing group to identify the subject of the question.
    * **Fallback Pattern:**  The `r"(.*)"` pattern is *crucial* and MUST be the LAST pattern.  It matches anything that doesn't match previous patterns, preventing errors and ensuring a response.  The comments also explain that it has to be last.
    * `r"quit"`:  Handles user exit.
* **More Varied Responses:** Some patterns have multiple responses chosen randomly, making the conversation feel less repetitive.
* **Reflections Dictionary:** Includes a `reflections` dictionary to handle basic grammatical transformations (e.g., "I am" becomes "you are"). This improves the bot's ability to understand user input.
* **`if __name__ == "__main__":` block:**  This is the standard way to execute code in Python only when the script is run directly (not when it's imported as a module).
* **`Chat.converse()`:** Uses the `converse()` method to start the conversation loop.
* **Comments and Explanations:**  The code is thoroughly commented to explain each part's purpose.
* **Error Handling (Implicit):** The fallback pattern acts as a basic error handler, gracefully responding to unexpected input.
* **No Web Scraping (as requested):** The code focuses on the core chatbot logic and avoids external API calls or web scraping.
* **Concise and Readable:** The code is written to be as concise and readable as possible.

How to Run:

1. **Install NLTK:**
   ```bash
   pip install nltk
   ```

2. **Download NLTK Data (First Time Only):**
   Uncomment the lines:
   ```python
   # nltk.download('punkt')
   # nltk.download('averaged_perceptron_tagger')
   ```
   Run the script *once*.  Then, re-comment those lines.

3. **Run the Script:**
   ```bash
   python your_script_name.py
   ```

Example Conversation:

```
Hi, I'm a simple AI assistant. How can I help you today?
> my name is Alice
Hello Alice, how can I help you today?
> what can you do?
I can answer basic questions, tell you jokes, and provide information.
> tell me a joke
Why don't scientists trust atoms? Because they make up everything!
> what is the capital of France?
Let me search the web for that.
> quit
Have a nice day!
```

This improved example provides a more robust and functional AI assistant with better pattern matching, more varied responses, and clear explanations. Remember to expand the `pairs` list with more patterns and responses to make the bot more intelligent and helpful.  You would use the Python `re` module and regular expressions more deeply to improve the NLP capabilities.
👁️ Viewed: 10

Comments