├── CHATBOT WITH RULE-BASED RESPONSES.py ├── README.md ├── IMAGE CAPTIONING.py └── TIC-TAC-TOE AI.py /CHATBOT WITH RULE-BASED RESPONSES.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def simple_chatbot(user_input): 4 | # Convert user input to lowercase for case-insensitivity 5 | user_input = user_input.lower() 6 | 7 | # Define rules and responses 8 | rules = { 9 | 'hello': 'Hi there! How can I help you?', 10 | 'how are you': 'I am just a computer program, but I am doing well. How about you?', 11 | 'goodbye': 'Goodbye! Have a great day!', 12 | 'name': 'I am a chatbot. You can call me ChatGPT.', 13 | 'default': 'I'm sorry, I don't understand that. Can you please rephrase or ask something else?' 14 | } 15 | 16 | # Check user input against rules 17 | for pattern, response in rules.items(): 18 | if re.search(pattern, user_input): 19 | return response 20 | 21 | # Default response if no match is found 22 | return rules['default'] 23 | 24 | # Simple loop to run the chatbot 25 | while True: 26 | # Get user input 27 | user_input = input("You: ") 28 | 29 | # Check for exit condition 30 | if user_input.lower() == 'exit': 31 | print("Chatbot: Goodbye!") 32 | break 33 | 34 | # Get and print the chatbot's response 35 | response = simple_chatbot(user_input) 36 | print("Chatbot:", response) 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Projects 2 | This repository contains various Python projects that demonstrate different applications, including a rule-based chatbot, image captioning using deep learning, and an AI-powered Tic-Tac-Toe game. 3 | 4 | ## Projects: 5 | 1. CHATBOT WITH RULE-BASED RESPONSES 6 | 2. IMAGE CAPTIONING 7 | 3. TIC-TAC-TOE AI 8 | 9 | 10 | 11 | ### CHATBOT WITH RULE-BASED RESPONSES 12 | This is a simple chatbot that responds to user inputs based on predefined rules. The chatbot uses pattern matching techniques to identify specific keywords or phrases in the user's input and generates appropriate responses accordingly. 13 | Features: 14 | Rule-based responses based on keyword matching 15 | Easily customizable rules 16 | Supports multiple input patterns 17 | File: chatbot_rule_based.py 18 | 19 | ### IMAGE CAPTIONING 20 | Description: 21 | This project implements an image captioning system using deep learning techniques. The model takes an image as input and generates descriptive captions based on the contents of the image. It utilizes Convolutional Neural Networks (CNNs) for image feature extraction and Recurrent Neural Networks (RNNs) for caption generation. 22 | Features: 23 | Uses a pre-trained CNN for image feature extraction 24 | RNN-based caption generation 25 | Can be extended to use different datasets 26 | File: image_captioning.py 27 | 28 | ### TIC-TAC-TOE AI 29 | Description: 30 | This is an implementation of the classic Tic-Tac-Toe game with an AI opponent. The AI uses the Minimax algorithm to calculate the best possible moves and plays optimally, ensuring that it never loses. 31 | Features: 32 | Play Tic-Tac-Toe against a computer AI 33 | AI uses the Minimax algorithm for optimal play 34 | Simple command-line interface 35 | File: tic_tac_toe_ai.py 36 | Navigate to the TIC-TAC-TOE AI folder. 37 | -------------------------------------------------------------------------------- /IMAGE CAPTIONING.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import torchvision.transforms as transforms 4 | from torch.autograd import Variable 5 | from torchvision.models import resnet50 6 | from PIL import Image 7 | import matplotlib.pyplot as plt 8 | import nltk 9 | from nltk.tokenize import word_tokenize 10 | from nltk.corpus import stopwords 11 | 12 | # Download NLTK data 13 | nltk.download('punkt') 14 | nltk.download('stopwords') 15 | 16 | # Define the image captioning model 17 | class ImageCaptioningModel(nn.Module): 18 | def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1): 19 | super(ImageCaptioningModel, self).__init__() 20 | self.embed = nn.Embedding(vocab_size, embed_size) 21 | self.lstm = nn.LSTM(embed_size, hidden_size, num_layers, batch_first=True) 22 | self.linear = nn.Linear(hidden_size, vocab_size) 23 | 24 | def forward(self, features, captions): 25 | embeddings = self.embed(captions) 26 | embeddings = torch.cat((features.unsqueeze(1), embeddings), 1) 27 | lstm_out, _ = self.lstm(embeddings) 28 | outputs = self.linear(lstm_out) 29 | return outputs 30 | 31 | # Load pre-trained ResNet model 32 | resnet = resnet50(pretrained=True) 33 | resnet = nn.Sequential(*list(resnet.children())[:-1]) 34 | for param in resnet.parameters(): 35 | param.requires_grad = False 36 | 37 | # Define the image preprocessing pipeline 38 | transform = transforms.Compose([ 39 | transforms.Resize((224, 224)), 40 | transforms.ToTensor(), 41 | ]) 42 | 43 | # Define the image captioning model parameters 44 | embed_size = 256 45 | hidden_size = 512 46 | vocab_size = 10000 # Change based on your vocabulary size 47 | num_layers = 1 48 | 49 | # Initialize the image captioning model 50 | model = ImageCaptioningModel(embed_size, hidden_size, vocab_size, num_layers) 51 | 52 | # Load pre-trained weights (you can train the model on your dataset) 53 | # model.load_state_dict(torch.load('image_captioning_model.pth')) 54 | model.eval() 55 | 56 | # Load the vocabulary 57 | with open('vocab.txt', 'r') as f: 58 | vocab = f.read().splitlines() 59 | 60 | # Remove stopwords from the vocabulary 61 | stop_words = set(stopwords.words('english')) 62 | vocab = [word for word in vocab if word not in stop_words] 63 | 64 | # Function to preprocess and extract image features 65 | def get_image_features(image_path): 66 | image = Image.open(image_path).convert('RGB') 67 | image = transform(image).unsqueeze(0) 68 | image_features = resnet(Variable(image)).squeeze(2).squeeze(2) 69 | return image_features 70 | 71 | # Function to generate captions for the given image 72 | def generate_caption(image_path, max_len=20): 73 | image_features = get_image_features(image_path) 74 | sampled_ids = [] 75 | inputs = torch.LongTensor([vocab.index('')]) 76 | 77 | for i in range(max_len): 78 | outputs = model(image_features, inputs) 79 | _, predicted = outputs.max(2) 80 | sampled_ids.append(predicted.item()) 81 | inputs = predicted.squeeze(1) 82 | 83 | if sampled_ids[-1] == vocab.index(''): 84 | break 85 | 86 | caption = [vocab[i] for i in sampled_ids] 87 | return ' '.join(caption[1:-1]) # Exclude and 88 | 89 | # Test the image captioning model 90 | image_path = 'example.jpg' # Replace with your image path 91 | caption = generate_caption(image_path) 92 | print(f"Image Caption: {caption}") 93 | 94 | # Display the image 95 | image = Image.open(image_path) 96 | plt.imshow(image) 97 | plt.axis('off') 98 | plt.show() 99 | -------------------------------------------------------------------------------- /TIC-TAC-TOE AI.py: -------------------------------------------------------------------------------- 1 | import math 2 | import random 3 | 4 | # Function to print the Tic-Tac-Toe board 5 | def print_board(board): 6 | for row in board: 7 | print(" ".join(row)) 8 | print() 9 | 10 | # Function to check if a player has won 11 | def check_winner(board, player): 12 | # Check rows and columns 13 | for i in range(3): 14 | if all(board[i][j] == player for j in range(3)) or all(board[j][i] == player for j in range(3)): 15 | return True 16 | 17 | # Check diagonals 18 | if all(board[i][i] == player for i in range(3)) or all(board[i][2 - i] == player for i in range(3)): 19 | return True 20 | 21 | return False 22 | 23 | # Function to check if the board is full 24 | def is_board_full(board): 25 | return all(board[i][j] != ' ' for i in range(3) for j in range(3)) 26 | 27 | # Function to evaluate the current state of the board 28 | def evaluate(board): 29 | if check_winner(board, 'X'): 30 | return -1 31 | elif check_winner(board, 'O'): 32 | return 1 33 | elif is_board_full(board): 34 | return 0 35 | else: 36 | return None 37 | 38 | # Minimax algorithm with Alpha-Beta Pruning 39 | def minimax(board, depth, maximizing_player, alpha, beta): 40 | result = evaluate(board) 41 | 42 | if result is not None: 43 | return result 44 | 45 | if maximizing_player: 46 | max_eval = float('-inf') 47 | for i in range(3): 48 | for j in range(3): 49 | if board[i][j] == ' ': 50 | board[i][j] = 'O' 51 | eval = minimax(board, depth + 1, False, alpha, beta) 52 | board[i][j] = ' ' 53 | max_eval = max(max_eval, eval) 54 | alpha = max(alpha, eval) 55 | if beta <= alpha: 56 | break 57 | return max_eval 58 | else: 59 | min_eval = float('inf') 60 | for i in range(3): 61 | for j in range(3): 62 | if board[i][j] == ' ': 63 | board[i][j] = 'X' 64 | eval = minimax(board, depth + 1, True, alpha, beta) 65 | board[i][j] = ' ' 66 | min_eval = min(min_eval, eval) 67 | beta = min(beta, eval) 68 | if beta <= alpha: 69 | break 70 | return min_eval 71 | 72 | # Function to find the best move for the AI using Minimax with Alpha-Beta Pruning 73 | def find_best_move(board): 74 | best_val = float('-inf') 75 | best_move = (-1, -1) 76 | 77 | for i in range(3): 78 | for j in range(3): 79 | if board[i][j] == ' ': 80 | board[i][j] = 'O' 81 | move_val = minimax(board, 0, False, float('-inf'), float('inf')) 82 | board[i][j] = ' ' 83 | 84 | if move_val > best_val: 85 | best_move = (i, j) 86 | best_val = move_val 87 | 88 | return best_move 89 | 90 | # Function to play Tic-Tac-Toe 91 | def play_tic_tac_toe(): 92 | board = [[' ' for _ in range(3)] for _ in range(3)] 93 | current_player = 'X' 94 | 95 | while True: 96 | print_board(board) 97 | 98 | if current_player == 'X': 99 | row, col = map(int, input("Enter your move (row and column): ").split()) 100 | if board[row][col] == ' ': 101 | board[row][col] = 'X' 102 | else: 103 | print("Invalid move. Try again.") 104 | continue 105 | else: 106 | row, col = find_best_move(board) 107 | print(f"AI's move: {row} {col}") 108 | board[row][col] = 'O' 109 | 110 | winner = evaluate(board) 111 | 112 | if winner is not None: 113 | print_board(board) 114 | if winner == -1: 115 | print("You won!") 116 | elif winner == 1: 117 | print("AI won!") 118 | else: 119 | print("It's a draw!") 120 | break 121 | 122 | current_player = 'O' if current_player == 'X' else 'X' 123 | 124 | if __name__ == "__main__": 125 | play_tic_tac_toe() 126 | --------------------------------------------------------------------------------