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)