Thursday, December 16, 2021

Cartoonize



import cv2


img = cv2.imread('Binoy.jpg')

grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

grayimg  = cv2.medianBlur(grayimg, 5)

edges = cv2.Laplacian(grayimg , cv2.CV_8U, ksize=5)

r,mask =cv2.threshold(edges,100,255,cv2.THRESH_BINARY_INV)

img2 = cv2.bitwise_and(img, img, mask=mask)

img2 = cv2.medianBlur(img2, 5)

cv2.imwrite("cartooned.jpg", mask)

Thursday, December 2, 2021

Array of radiobuttons

from tkinter import *


win = Tk()

win.geometry("300x300")


def Select(i):

  print(i)  


n = 3

rbn, I = list(range(n)), IntVar()


for i in range(n):

  rbn[i] = Radiobutton(win, value=i+1, variable=I, command=lambda I=i:Select(I))

  rbn[i].place(x=i*50, y=100)


win.mainloop()


Friday, October 22, 2021

Phone number locator using phonenumbers module

import phonenumbers

from phonenumbers import geocoder

from phonenumbers import carrier


n = input("Enter number: ")


cn = phonenumbers.parse(n, "CH")

print(geocoder.description_for_number(cn, "en"))


sn = phonenumbers.parse(n, "RO")

print(carrier.name_for_number(sn, "en"))


Use pyfiglet to create ASCII Art

import pyfiglet

  

result = pyfiglet.figlet_format("Geeks  For  Geeks")

print(result)


result = pyfiglet.figlet_format("Geeks  For  Geeks", font="slant")

print(result)


result = pyfiglet.figlet_format("G e e k", font="3-d")

print(result)


result = pyfiglet.figlet_format("G e e k", font="3x5")

print(result)


result = pyfiglet.figlet_format("G e e k", font="5lineoblique")

print(result)


result = pyfiglet.figlet_format("G e e k", font="alphabet")

print(result)


result = pyfiglet.figlet_format("Geeks", font="banner3-D")

print(result)


result = pyfiglet.figlet_format("Geek", font="doh")

print(result)


result = pyfiglet.figlet_format("Geeks", font="isometric1")

print(result)


result = pyfiglet.figlet_format("Geeks", font="letters")

print(result)


result = pyfiglet.figlet_format("G e e k", font="alligator")

print(result)


result = pyfiglet.figlet_format("Geeks", font="dotmatrix")

print(result)


result = pyfiglet.figlet_format("Geeks For Geeks", font="bubble")

print(result)


result = pyfiglet.figlet_format("Geeks For Geeks", font="bulbhead")

print(result)


result = pyfiglet.figlet_format("Geeks For Geeks", font="digital")

print(result)


Thursday, September 23, 2021

Difference between for and while loop, using microwave tkinter program


 Dimensions:                     442 x 281                                    59 x 16            62 x 30          44 x 42 


from tkinter import *

from tkinter import simpledialog

from playsound import playsound

from time import sleep

from random import randint


win = Tk()

win.geometry("450x300+800+50")


picMW = PhotoImage(file="Microwave.png")

lblMW = Label(win, image=picMW)

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


S = StringVar()                           # Change in font size here     

lblCtr = Label(win, textvariable=S, font=("Helvetica", 22, "bold"),

               width=3, anchor="c", bg="black", fg="yellow")

lblCtr.place(x=370, y=45)  # Change here


def setTime(e):

  S.set("")

  secs = simpledialog.askinteger("Input", "How many seconds?", parent=win)

  for i in range(secs, -1, -1):

    S.set(str(i))

    if i < 10:

      S.set("  " + str(i))

    win.update_idletasks()

    sleep(1)


picBtn1 = PhotoImage(file="TimeButton.png")

lblBtn1 = Label(win, image=picBtn1, bd=0)

lblBtn1.place(x=380, y=173)

lblBtn1.bind("<Button-1>", setTime)


state = False

def setTemp(e):

  global state

  state = True

  S.set("")


  currentTemp = randint(30, 40)

  while state == True:

    inc = randint(1, 2)

    currentTemp += inc

    sleep(.1)

    S.set(str(currentTemp))

    win.update_idletasks()


picBtn2 = PhotoImage(file="TempButton.png")

lblBtn2 = Label(win, image=picBtn2, bd=0)

lblBtn2.place(x=374, y=85)

lblBtn2.bind("<Button-1>", setTemp)


def stopTemp(e):

  global state

  state = False


picBtn3 = PhotoImage(file="StopButton.png")

lblBtn3 = Label(win, image=picBtn3, bd=0)

lblBtn3.place(x=374, y=135)

lblBtn3.bind("<Button-1>", stopTemp)


win.mainloop()


Tuesday, September 7, 2021

Transliteration tool (googletrans) - Contributed by Mathew Tharakan

from googletrans import Translator

from tkinter import *

from tkinter import messagebox


root = Tk()

root.geometry('300x100')


print('''\

'af': 'afrikaans',  'sq': 'albanian',     'am': 'amharic',   'ar': 'arabic',

'hy': 'armenian',   'az': 'azerbaijani',  'eu': 'basque',    'be': 'belarusian',

'bn': 'bengali',    'bs': 'bosnian',      'bg': 'bulgarian', 'ca': 'catalan',

'ceb': 'cebuano',   'ny': 'chichewa',     'zh-cn': 'chinese (simplified)',

'zh-tw': 'chinese (traditional)',         'co': 'corsican',  'hr': 'croatian',

'cs': 'czech',      'da': 'danish',       'nl': 'dutch',     'en': 'english',

'eo': 'esperanto',  'et': 'estonian',     'tl': 'filipino',  'fi': 'finnish',

'fr': 'french',     'fy': 'frisian',      'gl': 'galician',  'ka': 'georgian',

'de': 'german',     'el': 'greek',        'gu': 'gujarati',  'ht': 'haitian',

'ha': 'hausa',      'haw': 'hawaiian',    'iw': 'hebrew',    'he': 'hebrew',

'hi': 'hindi',      'hmn': 'hmong',       'hu': 'hungarian', 'is': 'icelandic',

'ig': 'igbo',       'id': 'indonesian',   'ga': 'irish',     'it': 'italian',

'ja': 'japanese',   'jw': 'javanese',     'kn': 'kannada',   'kk': 'kazakh',

'km': 'khmer',      'ko': 'korean',       'ku': 'kurdish',   'ky': 'kyrgyz',

'lo': 'lao',        'la': 'latin',        'lv': 'latvian',   'lt': 'lithuanian',

'lb': 'luxembourg', 'mk': 'macedonian',   'mg': 'malagasy',  'ms': 'malay',

'ml': 'malayalam',  'mt': 'maltese',      'mi': 'maori',     'mr': 'marathi',

'mn': 'mongolian',  'my': 'myanmar',      'ne': 'nepali',    'no': 'norwegian',

'or': 'odia',       'ps': 'pashto',       'fa': 'persian',   'pl': 'polish',

'pt': 'portuguese', 'pa': 'punjabi',      'ro': 'romanian',  'ru': 'russian',

'sm': 'samoan',     'gd': 'scots gaelic', 'sr': 'serbian',   'st': 'sesotho',

'sn': 'shona',      'sd': 'sindhi',       'si': 'sinhala',   'sk': 'slovak',

'sl': 'slovenian',  'so': 'somali',       'es': 'spanish',   'su': 'sundanese',

'sw': 'swahili',    'sv': 'swedish',      'tg': 'tajik',     'ta': 'tamil',

'te': 'telugu',     'th': 'thai',         'tr': 'turkish',   'uk': 'ukrainian',

'ur': 'urdu',       'ug': 'uyghur',       'uz': 'uzbek',     'vi': 'vietnamese',

'cy': 'welsh',      'xh': 'xhosa',        'yi': 'yiddish',   'yo': 'yoruba',

'zu': 'zulu' ''')


def translate():

  try:

    translater = Translator()

    out = translater.translate(e1.get(), dest=e2.get())

    messagebox.showinfo('Translation', out.text)

    print(out.text)

  except:

    messagebox.showinfo('Translation', "Sorry couldn't translate")


l1 = Label(root, text='Text')

l1.grid(row=1, column=0)


e1 = Entry(root, width=30, font=("Helvetica", 16, "bold"))

e1.grid(row=1, column=1)


l2 = Label(root, text='language')

l2.grid(row=2, column=0)


e2 = Entry(root, width=30, font=("Helvetica", 16, "bold"))

e2.grid(row=2, column=1)


btn = Button(root, text="Translate", command=translate)

btn.grid(row=3, column=1)


root.mainloop()

Thursday, August 26, 2021

Roulette Rotate Canvas











import tkinter as tk

from PIL import ImageTk, Image

from random import randint


win = tk.Tk()

win.geometry("452x485+0+0")


class SimpleApp(object):

  def __init__(self, master, filename):

    self.master = master

    self.filename = filename

    self.canvas = tk.Canvas(master, bg="black", width=450, height=500)

    self.canvas.place(x=0, y=10)

    self.angle = 0


  def draw(self):

    self.image = Image.open(self.filename)

    self.turn = randint(30, 390)

    self.canvas_obj = None

    self.master.after(100, self.rotate)

  

  def rotate(self):

    if self.turn > 0:

      if self.canvas_obj:

        self.canvas.delete(self.canvas_obj)

      self.tkimage = ImageTk.PhotoImage(self.image.rotate(self.angle))

      self.canvas_obj = self.canvas.create_image(227, 250, image=self.tkimage)

      self.angle = (self.angle - 1) % 360

      self.turn -= 1

      self.master.after_idle(self.rotate)


app = SimpleApp(win, '10C.png')


pic = ImageTk.PhotoImage(file="Stick.png")

lblStick = tk.Label(win, image=pic);    lblStick.place(x=0, y=0)


btn = tk.Button(win, text="Rotate", command=app.draw)

btn.place(x=400, y=450)


win.mainloop()


Tuesday, August 3, 2021

Internet Speed Test

# https://youtu.be/sPq8a1MUgr0


import speedtest


test = speedtest.Speedtest()


print("Loading server list ...")

test.get_servers() # Get list of servers available for speedtests


print("Choosing best server ...")

best = test.get_best_server()

print("Found:", best["host"], "located in", best["country"])


print("Performing download test ...")

download_result = test.download() / 1024 / 1024

print("Performing upload test ...")

upload_result = test.upload() / 1024 / 1024

ping_result = test.results.ping


print("Download speed: %.2s MBits per second" % download_result)

print("Upload speed:   %.2s MBits per second" % upload_result)

print(ping_result, "ms")


Monday, August 2, 2021

Colorize Grayscale Images / Colorise Greyscale Images

# Support files @ https://drive.google.com/drive/folders/1VftER_oapccpYpxhDOl0j_14CL0Z9Nvz?usp=sharing

# Libraries from: https://drive.google.com/drive/folders/1FaDajjtAsntF_Sw5gqF0WyakviA5l8-a

# Code from: https://www.codespeedy.com/automatic-colorization-of-black-and-white-images-using-ml-in-python/



import numpy as np

import cv2


prototxt = "colorization_deploy_v2.prototxt"

caffe_model = "colorization_release_v2.caffemodel"

pts_npy = "pts_in_hull.npy"


inputImage = "Cat.jpg"

outputImage = "CatColored.jpg"


net = cv2.dnn.readNetFromCaffe(prototxt, caffe_model) # Load model

pts = np.load(pts_npy)

 

layer1 = net.getLayerId("class8_ab")

layer2 = net.getLayerId("conv8_313_rh")

pts = pts.transpose().reshape(2, 313, 1, 1)

net.getLayer(layer1).blobs = [pts.astype("float32")]

net.getLayer(layer2).blobs = [np.full([1, 313], 2.606, dtype="float32")]


inputImage = cv2.imread(inputImage)

inputImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2GRAY) # To grayscale

inputImage = cv2.cvtColor(inputImage, cv2.COLOR_GRAY2RGB) # To RGB

cv2.imshow("GrayScale", inputImage)


# Converting the RGB image into LAB format

# Normalizing the image

normalized = inputImage.astype("float32") / 255.0

lab_image = cv2.cvtColor(normalized, cv2.COLOR_RGB2LAB) # To LAB format

resized = cv2.resize(lab_image, (224, 224))

L = cv2.split(resized)[0]  # Extract value of L for LAB image

L -= 50


# Setting input

net.setInput(cv2.dnn.blobFromImage(L))

# Finding the values of 'a' and 'b'

ab = net.forward()[0, :, :, :].transpose((1, 2, 0))

ab = cv2.resize(ab, (inputImage.shape[1], inputImage.shape[0]))


# Combining L, a, and b channels

L = cv2.split(lab_image)[0]

LAB_colored = np.concatenate((L[:, :, np.newaxis], ab), axis=2)# Combining L,a,b


RGB_colored = cv2.cvtColor(LAB_colored,cv2.COLOR_LAB2RGB)  # LAB to RGB

RGB_colored = np.clip(RGB_colored, 0, 1)  # Limit values in array

# Changing pixel intensity back to [0,255] as we scaled during pre-processing and converted pixel intensity to [0,1]

RGB_colored = (255 * RGB_colored).astype("uint8")


RGB_BGR = cv2.cvtColor(RGB_colored, cv2.COLOR_RGB2BGR)

cv2.imshow("Colorized", RGB_BGR)

cv2.imwrite(outputImage, RGB_BGR)


Monday, July 26, 2021

clrprint to print color in IDLE

# pip install clrprint


from clrprint import clrprint, clrinput


clrprint("Big data", clr='b')           # Print single value

clrprint("Big", "data", clr=['y', 'd']) # Print multiple values


x = 5

clrprint("x =", x, clr=['g', 'p'])      # Print variable


name = clrinput('\nEnter name:  ', clr=['r', 'd'])  # Accept input

clrprint('You entered', name, clr=['p', 'b'])     # print input value




Sunday, July 18, 2021

Bingo

BINGO

from tkinter import *

from random import shuffle, randint

from tkinter import messagebox as mb


win = Tk()

scrWidth = win.winfo_screenwidth()

scrHeight = win.winfo_screenheight()

win.geometry(f'{scrWidth}x{scrHeight}+0+0')

win.title("B I N G O")


labels = list()

nRows, nCols = 34, 15

names = ["Chacha", "Mummy", "Moni", "Susan", "Bijoy", "Joyce", "Binoy",

         "Omana", "Vijay", "Karuna", "Vinny", "Shawn", "Namitha", "Thejus",

         "Aambo", "Bambo", "Chambo",

         "Chacha1", "Mummy1", "Moni1", "Susan1", "Bijoy1", "Joyce1", "Binoy1",

         "Omana1", "Vijay1", "Karuna1", "Vinny1", "Shawn1", "Namitha1", "Thejus1",

         "Aambo1", "Bambo1", "Chambo1"

        ] # len(names) must be >= nRows


L = []                    # Insert 2D list of numbers in L during real game

for i in range(nRows):

  l = []

  for j in range(nCols):  # Randomly select numbers for players

    num = randint(0, 99)

    l.append(num)

  l.sort()

  l.insert(0, names[i])   # Name will be 0th element of each row of L

  L.append(l)

  #print(l)


players = []

for i in range(nRows):

  players.append(L[i])


rangeOfNums = 100

         

L = list(range(rangeOfNums))

shuffle(L)

clickNo, called, winners = 0, [], []

tallied = []

for i in range(nRows):

  tallied.append(0)


def click():

  global clickNo

  num = L[clickNo]

  called.append(num)

  clickNo += 1

  rows = []

  for l in range(nRows):

    for m in range(1, nCols+1):

      val = players[l][m]

      if val == num:

        labelList[l][m-1].config(bg="lime green")

        tallied[l] += 1

  print(L[:clickNo], "\n")

  msgCalled.config(text=str(L[:clickNo]))

  

  for a in range(nRows):

    if tallied[a] == nCols:

      winners.append(players[a][0])


  if len(winners) > 0:

    btnCheck["state"] = DISABLED

    s = "WINNER(S): "

    for i in range(len(winners)):

      s = s + winners[i] + ", "

    mb.showinfo("OUTCOME", s[:-2] + " " + str(clickNo))


for i in range(nRows):

  X, Y = 0, 10

  if i > 16:

    X = 666

  lblName = Label(win, text=players[i][0], width=10, font=("Helvetica", 16, "bold"), anchor="e").place(x=X, y=Y+(i%17)*36)


labelList = []

for j in range(nRows):

  row = []

  for k in range(1, nCols+1):

    X, Y = 100, 10

    if j > 16:

      X = 770

    lblNums = Label(win, text=str(players[j][k]), font=("Helvetica", 16, "bold"), bg="yellow", width=2)

    lblNums.place(x=X+k*35, y=Y+(j%17)*36)

    row.append(lblNums)

  labelList.append(row)


S = StringVar()

msgCalled = Message(win, font=("Helvetica", 16, "bold"), width=1200, bg="light blue")

msgCalled.place(x=0, y=620)


btnCheck = Button(win, text="CHECK", bg="pink", font=("Helvetica", 16, "bold"), command=click)

btnCheck.place(x=1240, y=640)


win.mainloop()


Tuesday, June 15, 2021

Number of days between 2 dates

from datetime import date


a = date(2021, 4, 1)

b = date(2021, 6, 24)


print((b - a).days, "days")

##########################
Output: 84 days

Sunday, June 13, 2021

Web scraping with Beautiful Soup

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

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = "https://webscraper.io/test-sites/tables"
html_code = urlopen(url).read().decode("utf-8")
#print(html_code)

start = html_code.find("<h1>") + len("<h1>")
end = html_code.find("</h1>")
#print(html_code[start:end])

soup = BeautifulSoup(html_code, "lxml")
headings_2 = soup.find_all("h2")
#print(headings_2)

images = soup.find_all("img")
#print(images[1]["src"])
#print(images[1]["alt"])

first_table = soup.find("table")
rows = first_table.findAll("tr")[1:]
last_names = []
for row in rows:
  last_names.append(row.findAll("td")[2].get_text())
#print(last_names)

######################################

url = "https://en.wikipedia.org/wiki/Python_(programming_language)"
html_code = urlopen(url).read().decode("utf-8")
soup = BeautifulSoup(html_code, "lxml")

type_table = soup.find(class_="wikitable")
body = type_table.find("tbody")
rows = body.find_all("tr")[1:]
mutable_types, immutable_types = [], []
for row in rows:
  data = row.find_all("td")
  if data[1].get_text() == "mutable\n":
    mutable_types.append(data[0].get_text())
  else:
    immutable_types.append(data[0].get_text())

#print(f"Mutable Types: {mutable_types}")
#print(f"Immutable Types: {immutable_types}")

thumb_box = soup.find(class_="thumb")
thumb_img_src = thumb_box.find("img")["src"]
#print(thumb_img_src)

toc = soup.find(class_="toc")
toc_text = [a.get_text() for a in toc.find_all("a")]
print(toc_text)

Tuesday, June 8, 2021

Merging multiple video files

"C:\Program Files (x86)\VideoLAN\VLC\vlc.exe" 1.mp4 2.mp4 3.mp4 --sout "#gather:std{access=file,dst=final.mp4}" --sout-keep


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")


Friday, April 16, 2021

Google Assistant program sent by Blessen Eby & Aaron Mohan Varghese

import pyttsx3

import speech_recognition as sr

import datetime

import wikipedia

import webbrowser

import os

import smtplib

import pywhatkit

import pyjokes


engine = pyttsx3.init('sapi5')

voices = engine.getProperty('voices')

engine.setProperty('voice', voices[0].id)


def speak(audio):

  engine.say(audio)

  engine.runAndWait()


def wishMe():

  hour = int(datetime.datetime.now().hour)

  if hour>=0 and hour<12:

    speak("Good Morning!")

  elif hour>=12 and hour<18:

    speak("Good Afternoon!")

  elif hour==12:

    speak('Sir,its mid day. Would you like me to help you with something')

  else:

    speak("Good Evening!")

  speak("I am Dracore. Please tell me how may I help you, Sir")


def takeCommand():

  r = sr.Recognizer()

  with sr.Microphone() as source:

    print("Listening...")

    r.pause_threshold = 1

    audio = r.listen(source)

  try:

    print("Recognizing...")

    query = r.recognize_google(audio, language='en-uk')

    print(f"User said: {query}\n")

  except Exception as e:

    # print(e)

    print("Say that again please...")

    return "None"

  return query


def sendEmail(to, content):

  server = smtplib.SMTP('smtp.gmail.com', 587)

  server.ehlo()

  server.starttls()

  gmail, pword = "", ""

  server.login(gmail, pword)

  server.sendmail('binoythomas1108@gmail.com', to, content)

  server.close()


if __name__ == "__main__":

  wishMe()

  while True:

    query = takeCommand().lower()

    if 'wikipedia' in query:

      try:

        speak('Searching Wikipedia...')

        query = query.replace("wikipedia", "")

        results = wikipedia.summary(query, sentences=2)

        speak("According to Wikipedia")

        print(results)

        speak(results)

      except:

        speak('Sorry, this result does not exist')

    elif 'who is' in query:

      try:

        speak('Searching in Wikipedia ...')

        query = query.replace("who is", "")

        results = wikipedia.summary(query, sentences=3)

        speak("According to Wikipedia")

        print(results)

        speak(results)

      except:

        speak('sorry, this person does not exist')

    elif 'open youtube' in query:

      webbrowser.open("youtube.com")

    elif 'open google' in query:

      webbrowser.open("google.com")

    elif 'open stackoverflow' in query:

      webbrowser.open("stackoverflow.com")

    elif 'music please' in query:

      music_dir = 'G:/Music'

      songs = os.listdir(music_dir)

      print(songs)

      os.startfile(os.path.join(music_dir, songs[0]))

    elif 'the time' in query:

      strTime = datetime.datetime.now().strftime("%H:%M:%S %p")

      speak(f"Sir, the time is {strTime}")

    elif 'open code' in query:

      codePath = "C:/Users/user/Desktop"

      os.startfile(codePath)

    elif 'joke'in query:

      speak(pyjokes.get_joke())

      print(pyjokes.get_joke())

    elif 'send an email' in query:

      try:

        speak("What should I say?")

        content = takeCommand()

        to = 'binoythomas1108@gmail.com'

        sendEmail(to, content)

        speak("Email has been sent!")

      except Exception as e:

        print(e)

        speak("Sorry . I am not able to send this email")

    elif 'play' in query:

      video = query.replace('play','')

      speak('playing....'+video)

      pywhatkit.playonyt(video)

    elif 'hello' in query:

      speak('hi Sir ,Is there anything you need')

    elif 'exit listening' in query:

      speak('see you later sir')

      exit()

    elif 'what is your name' in query:

      speak('my name is dracore')

    elif 'search' in query:

      query = query.replace('search','')

      pywhatkit.search(query)