Saturday, May 29, 2021

Sending text / chat messages

# https://www.youtube.com/watch?v=3QiPPX-KeSc

# Server.py

import socket, threading

HEADER = 64
SERVER = socket.gethostbyname(socket.gethostname())
PORT = 5050
ADDR = (SERVER, PORT)
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "!DISCONNECT"

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(ADDR)

def handle_client(conn, addr):
  print(f"[NEW CONNECTION] {addr} connected.")
  connected = True
  while connected:
    msg_length = conn.recv(HEADER).decode(FORMAT)
    if msg_length:
      msg_length = int(msg_length)
      msg = conn.recv(msg_length).decode(FORMAT)
      if msg == DISCONNECT_MESSAGE:
        connected = False
      print(f"[{addr}] {msg}")
      conn.send("Msg received".encode(FORMAT))
  conn.close()

def start():
  server.listen()
  print(f"[LISTENING] Server is listening on {SERVER}")
  while True:
    conn, addr = server.accept()
    thread = threading.Thread(target=handle_client, args=(conn, addr))
    thread.start()
    print(f"[ACTIVE CONNECTIONS] {threading.activeCount()-1}")
    

print("[STARTING] Server is starting ...")
start()


# Client.py

import socket

HEADER = 64
PORT = 5050
FORMAT = "utf-8"
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = socket.gethostbyname(socket.gethostname())
ADDR = (SERVER, PORT)

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)

def send(msg):
  message = msg.encode(FORMAT)
  msg_length = len(message)
  send_length = str(msg_length).encode(FORMAT)
  send_length += b' ' * (HEADER - len(send_length))
  client.send(send_length)
  client.send(message)
  print(client.recv(2048).decode(FORMAT))

send("Hello World!")
send("Hello All")
send("Hello Binoy!")
send(DISCONNECT_MESSAGE)

Chatting application in python

https://www.youtube.com/watch?v=zHUUTGQWjrM

# Server.py

import socket


ser = socket.socket()

ser.bind(("localhost", 999))

ser.listen(3)


while True:

  c, add = ser.accept()

  print(c.recv(1024).decode())

  while True:

    mes = "Server: " + input("Me: ")

    c.send(bytes(mes, "utf-8"))

    print(" " + c.recv(1024).decode())


c.close()



# Client.py

import socket

soc = socket.socket()
soc.connect(("localhost", 999))

while True:
  mess = "Client: " + input("Me: ")
  soc.send(bytes(mess, "utf-8"))
  print(soc.recv(1024).decode())

soc.close()

Create audiobooks in Python

import pyttsx3, PyPDF2


with open("Hello! Python ~ Briggs.pdf", "rb") as book:

  full_text = ""

  reader = PyPDF2.PdfFileReader(book)

  audio_reader = pyttsx3.init()

  audio_reader.setProperty("rate", 300)

  for page in range(reader.numPages):

    next_page = reader.getPage(page)

    content = next_page.extractText()

    full_text += content


  audio_reader.save_to_file(content, "Hello Python.mp3")

  audio_reader.runAndWait()


Animating matplotlib

# https://www.youtube.com/watch?v=7RgoHTMbp4A

# Draw Scatter Diagram & Regression Line

import matplotlib.pyplot as plt

import numpy as np

from sklearn.linear_model import LinearRegression

import random


reg = LinearRegression()

x_values, y_values = [], []

plt.xlim(0, 100)

plt.ylim(0, 100)


for i in range(95):

  plt.clf()

  x_values.append(random.randint(0, 100))

  y_values.append(random.randint(0, 100))

  x = np.array(x_values)

  x = x.reshape(-1, 1)

  y = np.array(y_values)

  y = y.reshape(-1, 1)


  if i % 5 == 0 or i == 94:

    reg.fit(x, y)

    plt.scatter(x_values, y_values, color='brown')

    plt.plot(list(range(100)), reg.predict(np.array([x for x in range(100)]).reshape(-1, 1))) 

    plt.pause(0.0001)

plt.show()


# Draw histogram

import matplotlib.pyplot as plt

import random


values = [0] * 50

plt.xlim(0, 50)

plt.ylim(0, 100)


for i in range(50):

  values[i] = random.randint(0, 100)

  plt.bar(list(range(50)), values)

  plt.pause(0.0001)

plt.show()


# Draw histogram of heads and tails in 100000 throws

import matplotlib.pyplot as plt
import random

heads_tails = [0, 0]

for i in range(100000):
  if i % 50 == 0:
    heads_tails[random.randint(0, 1)] += 1
    #print(heads_tails)
    plt.bar([0, 1], heads_tails, color=("blue", "red"))
    plt.pause(0.0001)

plt.show()


# Draw histogram to simulate throw of die 100000 times

import matplotlib.pyplot as plt
import random

dice = [0, 0, 0, 0, 0, 0]

for i in range(100000):
  if i % 50 == 0:
    dice[random.randint(0, 5)] += 1
    plt.bar([1, 2, 3, 4, 5, 6], dice, color=("blue", "red"))
    plt.pause(0.0001)

plt.show()

Thursday, May 27, 2021

Timing Python script using timeit

from timeit import timeit


def whileLoop(n = 100_000):

  i, s = 0, 0

  while i < n:

    s += i

    i += 1

  return s


def forLoop(n = 100_000):

  s = 0

  for i in range(n):

    s += i

  return s


print("While loop", timeit(whileLoop, number=1))

print("For   loop", timeit(forLoop,   number=1))


*************** OUTPUT ***********************

While loop 0.0387066
For   loop 0.00698

Sunday, May 23, 2021

Ticker in Python tkinter




BCRS.png        Dimensions: 1440 x 960

Screenshot.png

from tkinter import *

from time import sleep


win = Tk()

win.geometry("1355x800-10+0")


pic2 = PhotoImage(file="BCRS.png")

lblSchoolPhoto = Label(win, image=pic2)

lblSchoolPhoto.place(x=0, y=0)


dummyStr = "*" * 200  # To provide background

lblBackground4Ticker = Label(win, text=dummyStr, bg="yellow", fg="yellow", font=("Helvetica", 40, "bold"))

lblBackground4Ticker.place(x=0, y=630)


s = "WELCOME  TO  THE  VIRTUAL  OPENING  OF  BCRS  CLASS  XI,  2021-22"

lblTicker = Label(win, bg="yellow", text=s, font=("Helvetica", 40, "bold"))


while True:

  X = 1400

  while X > -1900:

    lblTicker.place(x=X, y=630)

    sleep(.05)

    win.update()

    X -= 5


win.mainloop()


Monday, May 10, 2021

Chatbot

########## Intents.json ##############

{"intents": [

  {"tag": "greetings", 

   "patterns":["hello", "hey", "hi", "good day", "greetings", "what's u?", "howdy"],

   "responses": ["Hello!", "Hey!", "What can I do for you?"]

  },

  {"tag": "goodbye", 

   "patterns":["cya", "see you later", "goodbye", "i am leaving",

               "have a good day", "bye", "ciao", "tata", "farewell"],

   "responses": ["Sad to see you go :(", "Talk to you later", "Goodbye", "So long ..." ]

  },

  {"tag": "age", 

   "patterns":["how old", "how old is binoy", "what is your age", "how old are you", "age?"],

   "responses": ["My owner Binoy is 54 years young!", "54 years", "He has seen 54 summers"]

  },

  {"tag": "name", 

   "patterns":["what is your name?", "what should I call you?", "whats your name?", "who are you?", "can you tell me your name?", "please tell me your name"],

   "responses": ["You can call me Neural", "I'm Neural", "I'm Neural, the assistant to Binoy"]

  },

  {"tag": "shop", 

   "patterns":["I'd like to buy something", "what do you sell?", "what are your products?", "what do you recommend?", "what are you selling", "what's for sale", "what can I buy?"],

   "responses": ["You can buy a snazzy car", "We have cars of all makes and models", "Wanna see our range of cars?"]

  },

  {"tag": "hours", 

   "patterns":["when are you open", "what are your hours", "hours of operation", "timing", "opening time", "closing time", "working hours"],

   "responses": ["24/7"]

  },

  {"tag": "stocks", 

   "patterns":["what stocks do I own?", "how are my shares?", "what companies am I investing in?", "what am I doing with my savings"],

   "responses": ["You own the following shares: RIL & Tata Motors on the BSE and FB, MS & Intel on the NYSE"]

  },

  {"tag": "shutdown", 

   "patterns":["", "", "", "", "", "", ""],

   "responses": ["", "", ""]

  }

]}



############ Chatbot.py ############

import random, json, pickle, nltk, numpy as np
from nltk.stem import WordNetLemmatizer
from tensorflow.keras.models import load_model

bot_name = "Discoverer"
lemmatizer = WordNetLemmatizer()
intents = json.loads(open("Intents.json").read())

words = pickle.load(open("Words.pkl", "rb"))
classes = pickle.load(open("Classes.pkl", "rb"))
model = load_model("ChatbotModel.h5")

def clean_up_sentence(sentence):
  sentence_words = nltk.word_tokenize(sentence)
  sentence_words = [lemmatizer.lemmatize(word) for word in sentence_words]
  return sentence_words

def bag_of_words(sentence):
  sentence_words = clean_up_sentence(sentence)
  bag = [0] * len(words)
  for w in sentence_words:
    for i, word in enumerate(words):
      if word == w:
        bag[i] = 1
  return np.array(bag)

def predict_class(sentence):
  bow = bag_of_words(sentence)
  res = model.predict(np.array([bow]))[0]
  ERROR_THRESHOLD = 0.25
  results = [[i, r] for i, r in enumerate(res) if r > ERROR_THRESHOLD]

  results.sort(key=lambda x: x[1], reverse=True)
  return_list = []
  for r in results:
    return_list.append({'intent': classes[r[0]], 'probability': str(r[1])})
  return return_list

def get_response(intents_list, intents_json):
  tag = intents_list[0]['intent']
  list_of_intents = intents_json['intents']
  for i in list_of_intents:
    if i['tag'] == tag:
      result = random.choice(i['responses'])
      break
  return result


############ Training.py ############

# https://youtu.be/1lwddP0KUEg

''' Run the following from the IDLE prompt
>> nltk.download("punkt")
>> nltk.download("wordnet")
'''
import random, json, pickle, numpy as np, nltk
from nltk.stem import WordNetLemmatizer
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Activation, Dropout
from tensorflow.keras.optimizers import SGD

lemmatizer = WordNetLemmatizer()
intents = json.loads(open("Intents.json").read())

words, classes, documents, ignore_letters = [], [], [], ['?', '.', ',', '!']

for intent in intents['intents']:
  for pattern in intent['patterns']:
    word_list = nltk.word_tokenize(pattern)
    words.extend(word_list)
    documents.append((word_list, intent['tag']))
    if intent["tag"] not in classes:
      classes.append(intent['tag'])

words = [lemmatizer.lemmatize(word) for word in words if word not in ignore_letters]
words = sorted(set(words))

ckasses = sorted(set(classes))

pickle.dump(words, open("Words.pkl", "wb"))
pickle.dump(classes, open("Classes.pkl", "wb"))

training = []
output_empty = [0] * len(classes)

for document in documents:
  bag = []
  word_patterns = document[0]
  word_patterns = [lemmatizer.lemmatize(word.lower()) for word in word_patterns]
  for word in words:
    bag.append(1) if word in word_patterns else bag.append(0)

  output_row = list(output_empty)
  output_row[classes.index(document[1])] = 1
  training.append([bag, output_row])

random.shuffle(training)
training = np.array(training, dtype=object)

train_x = list(training[:, 0])
train_y = list(training[:, 1])

model = Sequential()
model.add(Dense(128, input_shape=(len(train_x[0]),), activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(len(train_y[0]), activation='softmax'))

sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy'])

hist = model.fit(np.array(train_x), np.array(train_y), epochs=200, batch_size=5, verbose=1)
model.save("ChatbotModel.h5", hist)
print("Done")



######### UI.py ###########

# https://www.youtube.com/watch?v=RNEcewpVZUQ

from ChatBot import *
from tkinter import *
from random import choice

BG_GRAY, BG_COLOR, TEXT_COLOR = "#ABB2B9", "#17202A", "#EAECEE"
FONT, FONT_BOLD = "Helvetica 14", "Helvetica 13 bold"

win = Tk()
win.geometry("470x550")
win.resizable(0, 0)
win.title("Chat")
win.config(bg=BG_COLOR)

head_label = Label(win, bg=BG_COLOR, fg=TEXT_COLOR, text="Welcome", font=FONT_BOLD, pady=0)
head_label.place(relwidth=1)

line = Label(win, width=450, bg=BG_GRAY)
line.place(relwidth=1, rely=0.045, relheight=0.012)

txt = Text(win, width=20, height=2, bg=BG_COLOR, fg=TEXT_COLOR, font=FONT, padx=5, pady=5, bd=3)
txt.place(relheight=0.8, relwidth=1, rely=0.06)
txt.config(cursor="arrow", state=DISABLED)

scrollbar = Scrollbar(txt)
scrollbar.place(relheight=1, relx=0.974)
scrollbar.configure(command=txt.yview)

bottom_label = Label(win, bg=BG_GRAY, height=80)
bottom_label.place(relwidth=1, rely=0.825)

def insert_message(msg, sender):
  if not msg:
    return

  ent.delete(0, END)
  msg1 = f"{sender}: {msg}\n\n"
  txt.config(state=NORMAL)
  txt.insert(END, msg1)
  txt.config(state=DISABLED)

  ints = predict_class(msg)
  res = get_response(ints, intents)
  sorry_responses = ["Sorry, I don't understand", "Pardon me ...", "Can you be more specific?"]
  if res == "":
    res = choice(sorry_responses)
  msg2 = f"{bot_name}: {res}\n\n"
  txt.config(state=NORMAL)
  txt.insert(END, msg2)
  txt.config(state=DISABLED)

  txt.see(END)

def send():
  msg = ent.get().lower()
  insert_message(msg, "You")
  ent.focus()

ent = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
ent.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.0)
ent.focus()

btn = Button(bottom_label, text="SEND", font=FONT_BOLD, command=send)
btn.place(relx=0.77, rely=0.02, relheight=0.04, relwidth=0.22)

win.mainloop()














Colour using Colorama

 


from colorama import Back, Fore, Style, init


init(autoreset=True)


print(Fore.RED + "Hello World")

print(Back.GREEN + "Hello World")


print(f"{Fore.RED}H{Fore.YELLOW}E{Fore.GREEN}L{Fore.CYAN}L{Fore.MAGENTA}O")

print(f"{Fore.RED}W{Fore.YELLOW}O{Fore.GREEN}R{Fore.CYAN}L{Fore.MAGENTA}D")


print(f"{Fore.BLACK}{Back.RED}H{Back.YELLOW}E{Back.GREEN}L{Back.CYAN}L{Back.MAGENTA}O")

print(f"{Fore.BLACK}{Back.RED}W{Back.YELLOW}O{Back.GREEN}R{Back.CYAN}L{Back.MAGENTA}D")


print(f"{Fore.RED}{Back.BLACK}{Style.BRIGHT}Hello World")

print(f"{Fore.RED}{Back.BLACK}{Style.NORMAL}Hello World")

print(f"{Fore.RED}{Back.BLACK}{Style.DIM}Hello World")