Tuesday, December 24, 2024

Christmas tree and star in Python

def draw_tree(height):

  for i in range(1, height + 1):

    for j in range(height - i):

      print(" ", end="")

    for j in range(2 * i - 1):

      print("*", end="")

    print()

  for ctr in range(height // 2):

    print("*".center(height * 2))


h = int(input("Enter height of tree: "))

draw_tree(h)

==========================================================

import turtle as t

import time


win = t.Screen()

t.width(3)

t.ht()

t.speed(10)


fgColors = ['red', 'green', 'black', 'gold', 'blue']

bgColors = ['white', 'black', 'gold', 'black', 'black']


t.pu()

t.bk(100)

t.pd()


for i in range(5):

  t.color(fgColors[i])

  t.bgcolor(bgColors[i])

  for j in range(5):

    t.forward(200)

    t.right(144)

  t.write("   Happy Christmas", font=("Verdana", 15, "normal"))

  time.sleep(1.5)

  t.clear()


Display .mp4 using Python

import cv2


video = cv2.VideoCapture('Video.mp4')  # Replace with your video file path

while True:

    ret, frame = video.read()  # Read each frame

    if not ret:

        break  # Exit if no more frames

    cv2.imshow('Video', frame)  # Display frame in a window

    if cv2.waitKey(25) & 0xFF == ord('q'):    # Press 'q' to exit

        break

video.release()  # Release video object

cv2.destroyAllWindows()  # Close all windows

Saturday, October 12, 2024

Text to Speech using Python (doesn't save, but good performance)

import pyttsx3


def text_to_speech(text):

    engine = pyttsx3.init()                     # Initialize engine

    engine.setProperty('rate', 300)             # Speed of speech


    voices = engine.getProperty('voices')

    engine.setProperty('voice', voices[1].id)  # 0 male, 1 female


    engine.say(text)

    engine.runAndWait()


text = '''



'''

text_to_speech(text)


Wednesday, September 25, 2024

Controlling key movements in VS Code

// Key bindings to take cursor to Terminal

// C:/Users/student/AppData/Roaming/Code/User/keybindings.json

[   {   "key": "ctrl+down",

        "command": "workbench.action.terminal.focus"

    },

    {   "key": "ctrl+up",

        "command": "workbench.action.focusActiveEditorGroup",

        "when": "terminalFocus"

    }

]


// Key bindings to take cursor to Output

// C:/Users/student/AppData/Roaming/Code/User/keybindings.json

[   {   "key": "ctrl+down",

        "command": "workbench.action.output.toggleOutput",

        "when": "!terminalFocus"

    },

    {   "key": "ctrl+up",

        "command": "workbench.action.focusActiveEditorGroup",

        "when": "editorTextFocus || panelFocus"

    }

]

Tuesday, September 17, 2024

Zipping files

import os

from datetime import datetime

from zipfile import ZipFile


today = datetime.now() # set file name and time of creation

file_name = 'zipper_' + today.strftime('%Y.%m.%dh%H%M') + '.zip'

dir_name = 'To Zip'  # update path

def zipdir(path, zip):

  for root, dirs, files in os.walk(path):

    for file in files:

      zip.write(os.path.join(root, file))


if __name__ == '__main__':

  zipfile = ZipFile(file_name, 'w')

  zipdir(dir_name, zipfile)

  zipfile.close()

Finding execution time

import time, random

class ExecutionTime:

  def __init__(self):

    self.start_time = time.time()

  def duration(self):

    return time.time() - self.start_time


timer = ExecutionTime()

L = [random.randint(1, 888898) for i in range(1, 10_000_000)]

print(f'Finished in {timer.duration()} seconds.')


Renaming files in a folder

import os, glob

for file in glob.glob("*.*"):

  file_name = os.path.splitext(file)[0]

  extension = os.path.splitext(file)[1]

  new_file = file_name[:10] + extension # Choose new filename pattern

  try:

    os.rename(file, new_file)

  except OSError as e:

    print(e)

  else:

    print(f"Renamed {file} to {new_file}")


Find all links on a webpage

import requests, re

url = "https://medium.com/@binoythomas1108/understanding-classification-metrics-through-fairy-tales-5434213aa441"

website = requests.get(url)

html = website.text # read html

links = re.findall('"((http|ftp)s?://.*?)"', html) # re.findall grabs links

for i, link in enumerate(links): # output links

  print(i+1, link[0], "\n")

Monday, August 19, 2024

GUI based Sudoku Solver

import tkinter as tk

from tkinter import messagebox


def is_valid(board, row, col, num):

  for i in range(9):

    if board[row][i] == num or board[i][col] == num:

      return False

  

  start_row, start_col = 3 * (row // 3), 3 * (col // 3)

  for i in range(start_row, start_row + 3):

    for j in range(start_col, start_col + 3):

      if board[i][j] == num:

        return False

  

  return True


def solve_sudoku(board):

  for row in range(9):

    for col in range(9):

      if board[row][col] == 0:

        for num in range(1, 10):

          if is_valid(board, row, col, num):

            board[row][col] = num

            if solve_sudoku(board):

              return True

            board[row][col] = 0

        return False

  return True


def extract_values():

  board = []

  for i in range(9):

    row = []

    for j in range(9):

      val = entries[i][j].get()

      if val == "":

        row.append(0)

      else:

        try:

          row.append(int(val))

        except ValueError:

          messagebox.showerror("Invalid input", f"Invalid value at row {i+1}, column {j+1}. Please enter numbers 1-9.")

          return None

    board.append(row)

  return board


def display_solution(board):

  for i in range(9):

    for j in range(9):

      entries[i][j].delete(0, tk.END)

      entries[i][j].insert(0, str(board[i][j]))


def solve():

  board = extract_values()

  if board:

    if solve_sudoku(board):

      display_solution(board)

    else:

      messagebox.showinfo("No solution", "This Sudoku puzzle has no solution.")


def clear_board():

  for i in range(9):

    for j in range(9):

      entries[i][j].delete(0, tk.END)


# Initialize GUI window

root = tk.Tk()

root.title("Sudoku Solver")


# Create 9x9 grid of Entry widgets

entries = []

for i in range(9):

  row_entries = []

  for j in range(9):

    entry = tk.Entry(root, width=3, font=("Arial", 18), justify="center")

    entry.grid(row=i, column=j, padx=5, pady=5)

    row_entries.append(entry)

  entries.append(row_entries)


solve_button = tk.Button(root, text="Solve", command=solve, font=("Arial", 14))

solve_button.grid(row=9, column=3, columnspan=3, pady=10)


clear_button = tk.Button(root, text="Clear", command=clear_board, font=("Arial", 14))

clear_button.grid(row=10, column=3, columnspan=3, pady=10)


root.mainloop()


Text based Sudoku Solver

def is_valid(board, row, col, num):

  for i in range(9): # Number repeated in row?

    if board[row][i] == num:

      return False

  

  for i in range(9): # Number repeated in column?

    if board[i][col] == num:

      return False

  

  # Is number repeated in 3x3 subgrid

  start_row, start_col = 3 * (row // 3), 3 * (col // 3)

  for i in range(start_row, start_row + 3):

    for j in range(start_col, start_col + 3):

      if board[i][j] == num:

        return False


  return True


def solve_sudoku(board):

  for row in range(9):

    for col in range(9):

      if board[row][col] == 0:

        for num in range(1, 10):

          if is_valid(board, row, col, num):

            board[row][col] = num

            if solve_sudoku(board):

              return True

            board[row][col] = 0

        return False

  return True


def print_board(board):

  for row in board:

    print(" ".join(str(num) for num in row))


grid = [[5, 3, 0, 0, 7, 0, 0, 0, 0],

        [6, 0, 0, 1, 9, 5, 0, 0, 0],

        [0, 9, 8, 0, 0, 0, 0, 6, 0],

        [8, 0, 0, 0, 6, 0, 0, 0, 3],

        [4, 0, 0, 8, 0, 3, 0, 0, 1],

        [7, 0, 0, 0, 2, 0, 0, 0, 6],

        [0, 6, 0, 0, 0, 0, 2, 8, 0],

        [0, 0, 0, 4, 1, 9, 0, 0, 5],

        [0, 0, 0, 0, 8, 0, 0, 7, 9]

       ]


if solve_sudoku(grid):

  print("Sudoku Solved:")

  print_board(grid)

else:

  print("No solution exists.")


Sunday, August 18, 2024

Convert each pixel of one color to another color

# Convert each pixel of one color to another color

# Error value allows pixels +- that error value to also be converted


from PIL import Image


img = Image.open("Just.png")

img = img.convert("RGB")

pixels = img.load()


target_color = (237, 238, 247)

replacement_color = (255, 255, 255)


width, height = img.size

error = 10 # Allowing for variation in pixel value


for x in range(width):

  for y in range(height):

    if pixels[x, y][0] >= target_color[0] - error and pixels[x, y][0] <= target_color[0] + error:

      if pixels[x, y][1] >= target_color[1] - error and pixels[x, y][1] <= target_color[1] + error:

        if pixels[x, y][2] >= target_color[2] - error and pixels[x, y][2] <= target_color[2] + error:

          pixels[x, y] = replacement_color


img.save("Converted.png")

img.show()


Friday, August 2, 2024

Download Youtube videos

# pip install yt-dlp


import yt_dlp


def download_youtube_video(url, save_path='.'):

  ydl_opts = {'outtmpl': f'{save_path}/%(title)s.%(ext)s', 'format': 'best'

  }

  try:

    with yt_dlp.YoutubeDL(ydl_opts) as ydl:

      ydl.download([url])

    print("Download completed!")

  except Exception as e:

    print(f"An error occurred: {e}")


video_url = "https://www.youtube.com/watch?v=-5ef7epnR60"

download_youtube_video(video_url)


Sunday, July 28, 2024

Merge PDF (Merging to new document)

# pip install pypdf


def mergePDFs(inFile1, inFile2, outFile):

  writer = PdfWriter()


  reader1 = PdfReader(inFile1)

  for page in reader1.pages:

    writer.add_page(page)


  reader2 = PdfReader(inFile2)

  for page in reader2.pages:

    writer.add_page(page)


  with open(outFile, 'wb') as output:

    writer.write(output)


inFile1 = 'Business_Proposal.pdf'

inFile2 = 'Some_New_Doc.pdf'

outFile = 'Merged.pdf'


mergePDFs(inFile1, inFile2, outFile)


Display PDF text on Python terminal

# pip install pypdf


def extractFromPage1(innFile, pageNumbers):

    reader = PdfReader(innFile)

    for pageNumber in pageNumbers:

      if pageNumber < len(reader.pages):

        page = reader.pages[pageNumber]

        text = page.extract_text()

        print(text)

        input("Press any key to continue\n")

      else: # If page does not exist

        print(f"page {pageNumber} does not exist")

        input("Press any key to continue\n")


innFile = 'US_Declaration.pdf'

extractFromPage1(innFile, [7, 2]) # Page 7 does not exist in file

Convert PDF to Word

# pip install pdf2docx


from pdf2docx import Converter


def pdf_to_word(inputFile, outputFile):

  cv = Converter(inputFile)

  cv.convert(outputFile, start=0, end=None)

  cv.close()


innputFile = 'US_Declaration.pdf'

outputFile = 'US_Declaration.docx'

pdf_to_word(innputFile, outputFile)


Extract pages from PDF using Python

# This code was suggested by Gemini and runs on Colab

!pip install PyPDF2==3.0.1

from PyPDF2 import PdfReader, PdfWriter

def extract_pages(input_pdf, output_pdf, pages):
    pdf_reader = PdfReader(input_pdf)
    pdf_writer = PdfWriter()

    for page_num in pages:
        page = pdf_reader.pages[page_num]
        pdf_writer.add_page(page)

    with open(output_pdf, 'wb') as out_file:
        pdf_writer.write(out_file)

input_pdf_file = '/content/sample_data/Emp Skills IX.pdf'
output_pdf_file = '/content/sample_data/Green IX.pdf'
#                              +5,   +6
pages_to_extract = list(range(175, 206))

extract_pages(input_pdf_file, output_pdf_file, pages_to_extract)

===========================================================================

# This code suggested by ChatGPT & had problems on IDLE

# pip install pypdf

from PyPDF2 import PdfReader, PdfWriter


def extract_pages(inputFile, outputFile, pages):

  reader = PdfReader(inputFile)

  writer = PdfWriter()

  for page_number in pages:

    writer.add_page(reader.pages[page_number])

  with open(outputFile, 'wb') as out:

    writer.write(out)


innFile = 'US_Declaration.pdf'

outFile = 'US_Declaration1.pdf'

pages = [i for i in range(2)] # [0, 1]

extract_pages(innFile, outFile, pages)


Tuesday, April 30, 2024

Save / Saving file to Drive programatically, using Colab

import csv

out = open("/content/drive/MyDrive/My Data Files/Data.csv", 'a', newline='')
W = csv.writer(out)
W.writerow(["Binoy", 57])
out.close()

inn = open("/content/drive/MyDrive/My Data Files/Data.csv")
R = csv.reader(inn)
print(next(R))
L = list(R)
for row in L:
  print(row)
inn.close()

!cp Data.csv "/content/drive/MyDrive/My Data Files"