Sunday, July 28, 2024

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)


Merge PDF

# 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 & works 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"

Sunday, November 12, 2023

Automate Bingo game using Python

                

                         189 x 126                 86 x 87


https://www.blogger.com/blog/post/edit/preview/705067943936137407/8237077484565746551 is the link to creating Bingo cards. Here, we simulate the game play.


from tkinter import *

from random import shuffle


win = Tk()

win.config(bg="white")

win.title("B C R S  Children's Day B I N G O")


scrWidth = win.winfo_screenwidth()

scrHeight = win.winfo_screenheight()

winWidth, winHeight = 1200, 680

x = scrWidth//2 - winWidth//2

y = scrHeight//2 - winHeight//2 - 40

win.geometry("%dx%d+%d+%d" % (winWidth, winHeight, x, y))


ctr = 0

L = [i for i in range(1, 91)]

shuffle(L)


def Next():

  global ctr

  num = L[ctr]  # Next number to call

  txt1['state'] = NORMAL

  txt2['state'] = NORMAL


  if num < 10:

    lbl2.config(text=('  ' + str(num)))

  else:

    lbl2.config(text=(' ' + str(num)))


  if num < 10:

    txt1.insert(END, ' ' + str(num) + '   ')

  else:

    txt1.insert(END, str(num) + '  ')


  L1 = sorted(L[:ctr+1])

  txt2.delete("0.0", END)

  for i in range(len(L1)):

    if L1[i] < 10:

      txt2.insert(END, ' ' + str(L1[i]) + '   ')

    else:

      txt2.insert(END, str(L1[i]) + '  ')


  if ctr < 89:

    ctr += 1

  txt1['state'] = DISABLED

  txt2['state'] = DISABLED

  if ctr == 90:

    btn1['state'] = DISABLED


pic1 = PhotoImage(file="Bingo.png")

lbl1 = Label(win, image=pic1, border=0)

lbl1.place(x=500, y=545)


lbl2 = Label(win, font=("Verdana", 32, "bold"), bg="yellow", width=3,

             relief="raised", borderwidth=3, anchor="w", border=2)

lbl2.place(x=150, y=580)


txt1 = Text(win, font=("Verdana", 26, "bold"), width=47, bg="blue",

            fg="white", height=6, undo=False)

txt1.place(x=10, y=10)


txt2 = Text(win, font=("Verdana", 26, "bold"), width=47, bg="green",

            fg="white", height=6, undo=False)

txt2.place(x=10, y=280)


pic2 = PhotoImage(file="Bingo Next.png")

btn1 = Button(win, image=pic2, command=Next) 

btn1.place(x=950, y=550)


win.mainloop()


Wednesday, November 8, 2023

Testing Internet speed


from tkinter import *
import speedtest

root=Tk()
root.geometry("320x250")
root.resizable(False,False)
root.title("Internet Speed Test")
root.config(bg='#E6E6FA')

Label(root,text="Internet Speed Test",font=("Arial,bold",22),bg='#8B8386',fg='White',width=30).pack(pady=10)
l1=Label(root,text="Download Speed :",font=("Arial,bold",15),bg='#E6E6FA')
l1.place(x=10,y=80)
ldspd=Label(root,text="",font=("Arial,bold",15),bg='#E6E6FA',fg='#089927')
ldspd.place(x=180,y=80)
l2=Label(root,text="Upload Speed :",font=("Arial,bold",15),bg='#E6E6FA')
l2.place(x=10,y=130)
luspd=Label(root,text="",font=("Arial,bold",15),bg='#E6E6FA',fg='#089927')
luspd.place(x=180,y=130)

def check():
  spd=speedtest.Speedtest()
  spd.get_servers()
  dspd=str(round(spd.download() / (10**6),3)) + " Mbps"
  uspd=str(round(spd.upload() / (10**6),3)) + " Mbps"
  ldspd.config(text=dspd)
  luspd.config(text=uspd)

btn=Button(root,text="Check",font=('Arial,bold',15),bd=5,bg='#8B8386',fg='White',activebackground='#8B8386',activeforeground='White',command=check)
btn.place(x=125,y=190)

root.mainloop()

Sunday, October 15, 2023

Automate SQL Table Creation/Insertion using Python

def createTable():

  global fields, table

  table = input("Enter table name: ")

  s = "CREATE TABLE " + table + "(\n"

  while True:

    attr = input("Enter attribute: ") # Enter empty string to quit

    if attr == '':

      break

    dtype = input("Enter type: ").upper()

    fields[attr] = dtype

    s += '  ' + attr + ' ' + dtype + ',\n'

  s += ');'

  s = s[:-4] + s[-2:]

  print(s)

  out = open("TempTable.txt", 'w')

  out.write(s) # Write CREATE TABLE commands to TempTable.txt

  out.close()


def addRecords():

  global table, fields

  out = open("TempRecords.txt", 'w')

  while True:

    choice = input("Continue inserting? ") # Enter empty string to quit

    if choice == '':

      break

    rec = "INSERT INTO " + table + " VALUES("

    for key in fields.keys():

      s = "Enter " + key + " - " + fields[key] + ": "

      val = input(s)

      dtype = fields[key].upper()[:3]

      if dtype != "INT" and dtype != "DEC" and dtype != "BOO":

        val = "'" + val + "'"

      rec += val + ', '

    rec = rec[:-2] + ");\n"

    out.write(rec) # Write INSERT INTO commands to TempRecords.txt

  out.close()


table, fields = "", {}

while True:

  print("1. CREATE TABLE")

  print("2. INSERT INTO")

  print("0. Exit")

  choice = input("Enter choice: ")

  if choice == '1':

    createTable()

  elif choice == '2':

    addRecords()

  elif choice == '0':

    break

  else:

    print("Wrong choice\n")