diff --git a/Cartooning.py b/Cartooning.py new file mode 100644 index 0000000..4069afc --- /dev/null +++ b/Cartooning.py @@ -0,0 +1,61 @@ +import cv2 +import numpy as np +thresh1=0 +thresh2=0 + +def th1(value): + global thresh1 + thresh1=value +def th2(value): + global thresh2 + thresh2=value + +cam = cv2.VideoCapture(0) + +cv2.namedWindow("Track") +cv2.createTrackbar("Thresh1","Track",0,255,th1) +cv2.createTrackbar("thres2","Track",0,255,th2) +# const=0.5 +numDown=2 +numBilateral=2 + +def cartoonizing(frame): + # frame = cv2.resize(frame, (700,500)) + for i in range(numDown): + img = cv2.pyrDown(frame) + for _ in range(numBilateral): + img = cv2.bilateralFilter(img, 3, 3, 7) + for _ in range(numDown): + img = cv2.pyrUp(img) + + blur = cv2.resize(img,(700,500)) + cv2.imshow("Bilateral",blur) + gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) + blur = cv2.medianBlur(gray,3) + + canny = cv2.Canny(frame,thresh1,thresh2) + # canny = cv2.GaussianBlur(canny,(3,3),0) + thres,threshold = cv2.threshold(canny,150,255,cv2.THRESH_BINARY_INV) + # kernel = np.zeros((5, 5), np.uint8) + # threshold = cv2.dilate(threshold, kernel, iterations=1) + # threshold = cv2.GaussianBlur(threshold,(3,3),0) + + + (x,y,z) = img.shape + img_edge = cv2.resize(threshold,(y,x)) + img_edge = cv2.cvtColor(img_edge, cv2.COLOR_GRAY2RGB) + # img_edge = cv2.GaussianBlur(img_edge,(3,3),0) + + cv2.imshow("Edges",threshold) + return cv2.bitwise_and(img,img_edge ) + +while True: + ignore,frame = cam.read() + frame = cv2.flip(frame,1) + frame = cv2.resize(frame, (700,500)) + end = cartoonizing(frame) + end = cv2.resize(end,(700,500)) + cv2.imshow("End",end) + if cv2.waitKey(1) & 0xff == ord('q'): + break +cam.release() diff --git a/CheckJson.py b/CheckJson.py new file mode 100644 index 0000000..41060db --- /dev/null +++ b/CheckJson.py @@ -0,0 +1,14 @@ +import os +import sys +import json + +if len(sys.argv) > 1: + if os.path.exists(sys.argv[1]): + file = open(sys.argv[1], "r") + json.load(file) + file.close() + print("Validate JSON!") + else: + print(sys.argv[1] + " not found") +else: + print("Usage: checkjson.py ") diff --git a/CheckYaml.py b/CheckYaml.py new file mode 100644 index 0000000..1b42670 --- /dev/null +++ b/CheckYaml.py @@ -0,0 +1,14 @@ +import os +import sys +import yaml + +if len(sys.argv) > 1: + if os.path.exists(sys.argv[1]): + file = open(sys.argv[1], "r") + yaml.safe_load(file.read()) + file.close() + print("Validate YAML!") + else: + print(sys.argv[1] + " not found") +else: + print("Usage: checkyaml.py ") diff --git a/ImageStiching.py b/ImageStiching.py new file mode 100644 index 0000000..16df695 --- /dev/null +++ b/ImageStiching.py @@ -0,0 +1,121 @@ +import cv2 +import numpy as np + +img1 = input("Enter the path of the first image: ") +img2 = input("Enter the path of the second image: ") + +train = cv2.imread(r"{}".format(img1)) +query = cv2.imread(r"{}".format(img2)) +train_RGB = cv2.cvtColor(train,cv2.COLOR_BGR2RGB) +query_RGB = cv2.cvtColor(query,cv2.COLOR_BGR2RGB) +train_gray = cv2.cvtColor(train_RGB,cv2.COLOR_RGB2GRAY) +query_gray = cv2.cvtColor(query_RGB,cv2.COLOR_RGB2GRAY) + +query_gray = cv2.resize(query,(500,300)) +train_gray = cv2.resize(train,(500,300)) +query = cv2.resize(query,(500,300)) +train = cv2.resize(train,(500,300)) +feature_extraction_algo = 'sift' +feature_to_match = 'bf' + +def select_descriptor(image,method=None): + assert method is not None,"Please define a descriptor method. Accepted values are 'Sift','Surf','orb','brisk' " + + if method == 'sift': + descriptor = cv2.SIFT_create() + if method == 'surf': + descriptor = cv2.SURF_create() + if method == 'orb': + descriptor = cv2.ORB_create() + if method == 'brisk': + descriptor = cv2.BRISK_create() + (keypoints,features) = descriptor.detectAndCompute(image,None) + return (keypoints,features) + +keypoints_train,feature_train = select_descriptor(train_gray,feature_extraction_algo) +keypoints_query,feature_query = select_descriptor(query_gray,feature_extraction_algo) + +# print(keypoints_query) +# for keypoint in keypoints_query: +# x,y = keypoint.pt +# size = keypoint.size +# orientation = keypoint.angle +# response = keypoint.response +# octave = keypoint.octave +# class_id = keypoint.class_id +# print(x,y) +# cv2.imshow("Image1 ",cv2.drawKeypoints(train_gray,keypoints_train,None,color=(0,255,0))) +# cv2.imshow("Image2",cv2.drawKeypoints(query_gray,keypoints_query,None,color=(0,255,0))) # to draw key points +cv2.imshow("Image 1",train) +cv2.imshow("Image 2",query) + +def create_matching_object(method,crossCheck): + if method == 'sift' or method == 'surf': + bf = cv2.BFMatcher(cv2.NORM_L2,crossCheck=crossCheck) + if method == 'brisk' or method == 'orb': + bf = cv2.BFMatcher(cv2.NORM_HAMMING,crossCheck==crossCheck) + + return bf + +def keypoints_matching(feature_train,feature_query,method): + bf = create_matching_object(method,True) + best_matches = bf.match(feature_train,feature_query) + raw_matches = sorted(best_matches,key = lambda x:x.distance) + print("Raw Matches with Brute Force",len(raw_matches)) + return raw_matches + +def keypoints_matching_knn(feature_train,feature_query,ratio,method): + bf = create_matching_object(method,False) + raw_matches = bf.knnMatch(feature_train,feature_query,k=2) + print("Raw Matches with Knn",len(raw_matches)) + + knn_matches=[] + for m,n in raw_matches: + if m.distance4: + points_train = np.float32([keypoints_train_image[m.queryIdx] for m in matches]) + points_query= np.float32([keypoints_query_image[m.trainIdx] for m in matches]) + + (H,status)=cv2.findHomography(points_train,points_query,cv2.RANSAC,reprojthreshhold) + return (matches,H,status) + + else: + return None + +M = homography_Stiching(keypoints_train,keypoints_query,4) +if M is None: + print('Error') +(matches,Homography_Matrix,status) = M +print(Homography_Matrix) +width = query.shape[1]+train.shape[1] +print(width) +height = max(query.shape[0],train.shape[0]) +print(height) + +result = cv2.warpPerspective(train,Homography_Matrix,(width,height)) +print(result) + +result[0:query.shape[0],0:query.shape[1]] = query + +cv2.imshow("Stich",result) +cv2.waitKey(0) +cv2.destroyAllWindows() \ No newline at end of file diff --git a/Json2Yaml.py b/Json2Yaml.py new file mode 100644 index 0000000..9323e69 --- /dev/null +++ b/Json2Yaml.py @@ -0,0 +1,35 @@ +import json +import os +import sys +import yaml + +# Checking there is a file name passed +if len(sys.argv) > 1: + # Opening the file + if os.path.exists(sys.argv[1]): + source_file = open(sys.argv[1], "r") + source_content = json.load(source_file) + source_file.close() + # Failikng if the file isn't found + else: + print("ERROR: " + sys.argv[1] + " not found") + exit(1) +# No file, no usage +else: + print("Usage: json2yaml.py [target_file.yaml]") + +# Processing the conversion +output = yaml.dump(source_content) + +# If no target file send to stdout +if len(sys.argv) < 3: + print(output) +# If the target file already exists exit +elif os.path.exists(sys.argv[2]): + print("ERROR: " + sys.argv[2] + " already exists") + exit(1) +# Otherwise write to the specified file +else: + target_file = open(sys.argv[2], "w") + target_file.write(output) + target_file.close() diff --git a/Tracking.py b/Tracking.py new file mode 100644 index 0000000..35373c8 --- /dev/null +++ b/Tracking.py @@ -0,0 +1,65 @@ +import cv2 +import numpy as np + +cam = cv2.VideoCapture(0) + +hueHigh = 0 +hueLow = 0 +satHigh = 0 +satLow = 0 +valHigh = 0 +valLow = 0 + +def hueh(val): + global hueHigh + hueHigh = val +def huel(val): + global hueLow + hueLow = val +def sath(val): + global satHigh + satHigh = val +def satl(val): + global satLow + satLow = val +def valh(val): + global valHigh + valHigh = val +def vall(val): + global valLow + valLow = val + +cv2.namedWindow('My frame') +cv2.createTrackbar('hueL','My frame',0,180,huel) +cv2.createTrackbar('hueH','My frame',0,180,hueh) + +cv2.createTrackbar('satL','My frame',0,255,satl) +cv2.createTrackbar('satH','My frame',0,255,sath) + +cv2.createTrackbar('valL','My frame',0,255,vall) +cv2.createTrackbar('valH','My frame',0,255,valh) + + +while True: + ignore,frame = cam.read() + frameHSV = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV) + + lowerBound = np.array([hueLow,satLow,valLow]) + upperBound = np.array([hueHigh,satHigh,valHigh]) + + myMask = cv2.inRange(frameHSV,lowerBound,upperBound) + + contours,junk = cv2.findContours(myMask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) + for contour in contours: + area = cv2.contourArea(contour) + if area >=1000: + # cv2.drawContours(frame,[contour],0,(255,0,0),3) + x,y,w,h=cv2.boundingRect(contour) + cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255),3) + + mySelection = cv2.bitwise_and(frame,frame,mask=myMask) + cv2.imshow("My Selection",mySelection) + cv2.imshow("Frame",frame) + if cv2.waitKey(1) & 0xff == ord('q'): + break +cam.release() diff --git a/URLShortener.py b/URLShortener.py new file mode 100644 index 0000000..3f4a9c4 --- /dev/null +++ b/URLShortener.py @@ -0,0 +1,27 @@ +import pyperclip +import pyshorteners +from tkinter import* + +root=Tk() +root.geometry("400x200") +root.title("URL Shortener") +root.configure(bg="#49A") +url=StringVar() +url_address=StringVar() + +def urlshortner(): + urladdress=url.get() + url_short=pyshorteners.Shortener().tinyurl.short(urladdress) + url_address.set(url_short) + +def copyurl(): + url_short=url_address.get() + pyperclip.copy(url_short) +Label(root,text="My URL Shortener", font="poppins").pack(pady=10) +Entry(root, textvariable=url).pack(pady=5) +Button(root, text="Generate Short URl", command=urlshortner).pack(pady=7) +Entry(root, textvariable=url_address).pack(pady=5) +Button(root, text="Copy URL", command=copyurl).pack(pady=5) + +root.mainloop() + diff --git a/Yaml2Json.py b/Yaml2Json.py new file mode 100644 index 0000000..5cd14bd --- /dev/null +++ b/Yaml2Json.py @@ -0,0 +1,35 @@ +import json +import os +import sys +import yaml + +# Checking there is a file name passed +if len(sys.argv) > 1: + # Opening the file + if os.path.exists(sys.argv[1]): + source_file = open(sys.argv[1], "r") + source_content = yaml.safe_load(source_file) + source_file.close() + # Failikng if the file isn't found + else: + print("ERROR: " + sys.argv[1] + " not found") + exit(1) +# No file, no usage +else: + print("Usage: yaml2json.py [target_file.json]") + +# Processing the conversion +output = json.dumps(source_content) + +# If no target file send to stdout +if len(sys.argv) < 3: + print(output) +# If the target file already exists exit +elif os.path.exists(sys.argv[2]): + print("ERROR: " + sys.argv[2] + " already exists") + exit(1) +# Otherwise write to the specified file +else: + target_file = open(sys.argv[2], "w") + target_file.write(output) + target_file.close() diff --git a/ascii_to_img.py b/ascii_to_img.py new file mode 100644 index 0000000..15ef3fd --- /dev/null +++ b/ascii_to_img.py @@ -0,0 +1,9 @@ +#import the necessary module! +import pywhatkit as kt + + +#display welcome msg +print("Let's turn images to ASCII art!") + + +kt.image_to_ascii_art('girl.jpg', 'new.text') \ No newline at end of file diff --git a/build_directory.py b/build_directory.py new file mode 100644 index 0000000..7572ce3 --- /dev/null +++ b/build_directory.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 + +import os +from collections.abc import Iterator + + +def good_file_paths(top_dir: str = ".") -> Iterator[str]: + for dir_path, dir_names, filenames in os.walk(top_dir): + dir_names[:] = [d for d in dir_names if d != "scripts" and d[0] not in "._"] + for filename in filenames: + if filename == "__init__.py": + continue + if os.path.splitext(filename)[1] in (".py", ".ipynb"): + yield os.path.join(dir_path, filename).lstrip("./") + + +def md_prefix(i): + return f"{i * ' '}*" if i else "\n##" + + +def print_path(old_path: str, new_path: str) -> str: + old_parts = old_path.split(os.sep) + for i, new_part in enumerate(new_path.split(os.sep)): + if i + 1 > len(old_parts) or old_parts[i] != new_part: + if new_part: + print(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}") + return new_path + + +def print_directory_md(top_dir: str = ".") -> None: + old_path = "" + for filepath in sorted(good_file_paths(top_dir)): + filepath, filename = os.path.split(filepath) + if filepath != old_path: + old_path = print_path(old_path, filepath) + indent = (filepath.count(os.sep) + 1) if filepath else 0 + url = "/".join((filepath, filename)).replace(" ", "%20") + filename = os.path.splitext(filename.replace("_", " ").title())[0] + print(f"{md_prefix(indent)} [{filename}]({url})") + + +if __name__ == "__main__": + print_directory_md(".") diff --git a/circular_linked_list.py b/circular_linked_list.py new file mode 100644 index 0000000..67a63cd --- /dev/null +++ b/circular_linked_list.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +from collections.abc import Iterator +from typing import Any + + +class Node: + def __init__(self, data: Any): + self.data: Any = data + self.next: Node | None = None + + +class CircularLinkedList: + def __init__(self): + self.head = None + self.tail = None + + def __iter__(self) -> Iterator[Any]: + node = self.head + while self.head: + yield node.data + node = node.next + if node == self.head: + break + + def __len__(self) -> int: + return len(tuple(iter(self))) + + def __repr__(self): + return "->".join(str(item) for item in iter(self)) + + def insert_tail(self, data: Any) -> None: + self.insert_nth(len(self), data) + + def insert_head(self, data: Any) -> None: + self.insert_nth(0, data) + + def insert_nth(self, index: int, data: Any) -> None: + if index < 0 or index > len(self): + raise IndexError("list index out of range.") + new_node = Node(data) + if self.head is None: + new_node.next = new_node # first node points itself + self.tail = self.head = new_node + elif index == 0: # insert at head + new_node.next = self.head + self.head = self.tail.next = new_node + else: + temp = self.head + for _ in range(index - 1): + temp = temp.next + new_node.next = temp.next + temp.next = new_node + if index == len(self) - 1: # insert at tail + self.tail = new_node + + def delete_front(self): + return self.delete_nth(0) + + def delete_tail(self) -> Any: + return self.delete_nth(len(self) - 1) + + def delete_nth(self, index: int = 0) -> Any: + if not 0 <= index < len(self): + raise IndexError("list index out of range.") + delete_node = self.head + if self.head == self.tail: # just one node + self.head = self.tail = None + elif index == 0: # delete head node + self.tail.next = self.tail.next.next + self.head = self.head.next + else: + temp = self.head + for _ in range(index - 1): + temp = temp.next + delete_node = temp.next + temp.next = temp.next.next + if index == len(self) - 1: # delete at tail + self.tail = temp + return delete_node.data + + def is_empty(self) -> bool: + return len(self) == 0 + + +def test_circular_linked_list() -> None: + """ + >>> test_circular_linked_list() + """ + circular_linked_list = CircularLinkedList() + assert len(circular_linked_list) == 0 + assert circular_linked_list.is_empty() is True + assert str(circular_linked_list) == "" + + try: + circular_linked_list.delete_front() + raise AssertionError() # This should not happen + except IndexError: + assert True # This should happen + + try: + circular_linked_list.delete_tail() + raise AssertionError() # This should not happen + except IndexError: + assert True # This should happen + + try: + circular_linked_list.delete_nth(-1) + raise AssertionError() + except IndexError: + assert True + + try: + circular_linked_list.delete_nth(0) + raise AssertionError() + except IndexError: + assert True + + assert circular_linked_list.is_empty() is True + for i in range(5): + assert len(circular_linked_list) == i + circular_linked_list.insert_nth(i, i + 1) + assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) + + circular_linked_list.insert_tail(6) + assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 7)) + circular_linked_list.insert_head(0) + assert str(circular_linked_list) == "->".join(str(i) for i in range(0, 7)) + + assert circular_linked_list.delete_front() == 0 + assert circular_linked_list.delete_tail() == 6 + assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) + assert circular_linked_list.delete_nth(2) == 3 + + circular_linked_list.insert_nth(2, 3) + assert str(circular_linked_list) == "->".join(str(i) for i in range(1, 6)) + + assert circular_linked_list.is_empty() is False + + +if __name__ == "__main__": + import doctest + + doctest.testmod() diff --git a/double_linked_list.py b/double_linked_list.py new file mode 100644 index 0000000..9e996ef --- /dev/null +++ b/double_linked_list.py @@ -0,0 +1,226 @@ +""" +https://en.wikipedia.org/wiki/Doubly_linked_list +""" + + +class Node: + def __init__(self, data): + self.data = data + self.previous = None + self.next = None + + def __str__(self): + return f"{self.data}" + + +class DoublyLinkedList: + def __init__(self): + self.head = None + self.tail = None + + def __iter__(self): + """ + >>> linked_list = DoublyLinkedList() + >>> linked_list.insert_at_head('b') + >>> linked_list.insert_at_head('a') + >>> linked_list.insert_at_tail('c') + >>> tuple(linked_list) + ('a', 'b', 'c') + """ + node = self.head + while node: + yield node.data + node = node.next + + def __str__(self): + """ + >>> linked_list = DoublyLinkedList() + >>> linked_list.insert_at_tail('a') + >>> linked_list.insert_at_tail('b') + >>> linked_list.insert_at_tail('c') + >>> str(linked_list) + 'a->b->c' + """ + return "->".join([str(item) for item in self]) + + def __len__(self): + """ + >>> linked_list = DoublyLinkedList() + >>> for i in range(0, 5): + ... linked_list.insert_at_nth(i, i + 1) + >>> len(linked_list) == 5 + True + """ + return len(tuple(iter(self))) + + def insert_at_head(self, data): + self.insert_at_nth(0, data) + + def insert_at_tail(self, data): + self.insert_at_nth(len(self), data) + + def insert_at_nth(self, index: int, data): + """ + >>> linked_list = DoublyLinkedList() + >>> linked_list.insert_at_nth(-1, 666) + Traceback (most recent call last): + .... + IndexError: list index out of range + >>> linked_list.insert_at_nth(1, 666) + Traceback (most recent call last): + .... + IndexError: list index out of range + >>> linked_list.insert_at_nth(0, 2) + >>> linked_list.insert_at_nth(0, 1) + >>> linked_list.insert_at_nth(2, 4) + >>> linked_list.insert_at_nth(2, 3) + >>> str(linked_list) + '1->2->3->4' + >>> linked_list.insert_at_nth(5, 5) + Traceback (most recent call last): + .... + IndexError: list index out of range + """ + if not 0 <= index <= len(self): + raise IndexError("list index out of range") + new_node = Node(data) + if self.head is None: + self.head = self.tail = new_node + elif index == 0: + self.head.previous = new_node + new_node.next = self.head + self.head = new_node + elif index == len(self): + self.tail.next = new_node + new_node.previous = self.tail + self.tail = new_node + else: + temp = self.head + for _ in range(0, index): + temp = temp.next + temp.previous.next = new_node + new_node.previous = temp.previous + new_node.next = temp + temp.previous = new_node + + def delete_head(self): + return self.delete_at_nth(0) + + def delete_tail(self): + return self.delete_at_nth(len(self) - 1) + + def delete_at_nth(self, index: int): + """ + >>> linked_list = DoublyLinkedList() + >>> linked_list.delete_at_nth(0) + Traceback (most recent call last): + .... + IndexError: list index out of range + >>> for i in range(0, 5): + ... linked_list.insert_at_nth(i, i + 1) + >>> linked_list.delete_at_nth(0) == 1 + True + >>> linked_list.delete_at_nth(3) == 5 + True + >>> linked_list.delete_at_nth(1) == 3 + True + >>> str(linked_list) + '2->4' + >>> linked_list.delete_at_nth(2) + Traceback (most recent call last): + .... + IndexError: list index out of range + """ + if not 0 <= index <= len(self) - 1: + raise IndexError("list index out of range") + delete_node = self.head # default first node + if len(self) == 1: + self.head = self.tail = None + elif index == 0: + self.head = self.head.next + self.head.previous = None + elif index == len(self) - 1: + delete_node = self.tail + self.tail = self.tail.previous + self.tail.next = None + else: + temp = self.head + for _ in range(0, index): + temp = temp.next + delete_node = temp + temp.next.previous = temp.previous + temp.previous.next = temp.next + return delete_node.data + + def delete(self, data) -> str: + current = self.head + + while current.data != data: # Find the position to delete + if current.next: + current = current.next + else: # We have reached the end an no value matches + return "No data matching given value" + + if current == self.head: + self.delete_head() + + elif current == self.tail: + self.delete_tail() + + else: # Before: 1 <--> 2(current) <--> 3 + current.previous.next = current.next # 1 --> 3 + current.next.previous = current.previous # 1 <--> 3 + return data + + def is_empty(self): + """ + >>> linked_list = DoublyLinkedList() + >>> linked_list.is_empty() + True + >>> linked_list.insert_at_tail(1) + >>> linked_list.is_empty() + False + """ + return len(self) == 0 + + +def test_doubly_linked_list() -> None: + """ + >>> test_doubly_linked_list() + """ + linked_list = DoublyLinkedList() + assert linked_list.is_empty() is True + assert str(linked_list) == "" + + try: + linked_list.delete_head() + raise AssertionError() # This should not happen. + except IndexError: + assert True # This should happen. + + try: + linked_list.delete_tail() + raise AssertionError() # This should not happen. + except IndexError: + assert True # This should happen. + + for i in range(10): + assert len(linked_list) == i + linked_list.insert_at_nth(i, i + 1) + assert str(linked_list) == "->".join(str(i) for i in range(1, 11)) + + linked_list.insert_at_head(0) + linked_list.insert_at_tail(11) + assert str(linked_list) == "->".join(str(i) for i in range(0, 12)) + + assert linked_list.delete_head() == 0 + assert linked_list.delete_at_nth(9) == 10 + assert linked_list.delete_tail() == 11 + assert len(linked_list) == 9 + assert str(linked_list) == "->".join(str(i) for i in range(1, 10)) + + +if __name__ == "__main__": + from doctest import testmod + + testmod() diff --git a/encrypt.py b/encrypt.py new file mode 100644 index 0000000..1062ab2 --- /dev/null +++ b/encrypt.py @@ -0,0 +1,14 @@ +''' +open cmd and type +pip install cryptography +''' + + + + +from cryptography.fernet import Fernet +gen_key=Fernet.generate_key() +fer=Fernet(gen_key) +msg="data" #any data +encrypted=fer.encrypt(msg.encode()) +print(encrypted) diff --git a/extract_text_from_pdf.py b/extract_text_from_pdf.py new file mode 100644 index 0000000..8cb13d0 --- /dev/null +++ b/extract_text_from_pdf.py @@ -0,0 +1,19 @@ +# import module PyPDF2 +import PyPDF2 +# put 'example.pdf' in working directory +# and open it in read binary mode +pdfFileObj = open('example.pdf', 'rb') +# call and store PdfFileReader +# object in pdfReader +pdfReader = PyPDF2.PdfFileReader(pdfFileObj) +# to print the total number of pages in pdf +# print(pdfReader.numPages) +# get specific page of pdf by passing +# number since it stores pages in list +# to access first page pass 0 +pageObj = pdfReader.getPage(0) +# extract the page object +# by extractText() function +texts = pageObj.extractText() +# print the extracted texts +print(texts) diff --git a/filter_text.py b/filter_text.py new file mode 100644 index 0000000..6c43112 --- /dev/null +++ b/filter_text.py @@ -0,0 +1,20 @@ +# Filter Text +# Import re module +import re +# Take any string data +string = """a string we are using to filter specific items. +perhaps we would like to match credit card numbers +mistakenly entered into the user input. 4444 3232 1010 8989 +and perhaps another? 9191 0232 9999 1111""" + +# Define the searching pattern +pattern = '(([0-9](\s+)?){4}){4}' + +# match the pattern with input value +found = re.search(pattern, string) +print(found) +# Print message based on the return value +if found: + print("Found a credit card number!") +else: + print("No credit card numbers present in input") diff --git a/girl.jpg b/girl.jpg new file mode 100644 index 0000000..8a32142 Binary files /dev/null and b/girl.jpg differ diff --git a/img_comparator_tool/README.md b/img_comparator_tool/README.md new file mode 100644 index 0000000..905691a --- /dev/null +++ b/img_comparator_tool/README.md @@ -0,0 +1,24 @@ +# Welcome to Image Comparator Tool +This is a tool for comparing two Images and getting their difference image as output
+ +# Version +1.0.0 + +# Motivation and Description +We.Contribute -> You.Levegage ; You.Contribute -> We.Leverage ; All -> Grow + +# Languages and Libraries used +Python and cv2
+ +Installation +==================== +Deploy the folder structure to the required location. + +Execution +==================== +Call python3 image_comparision.py. + +# FAQ +mail us - acharjeerishi99@gmail.com + + diff --git a/img_comparator_tool/image2.jpg b/img_comparator_tool/image2.jpg new file mode 100644 index 0000000..a080235 Binary files /dev/null and b/img_comparator_tool/image2.jpg differ diff --git a/img_comparator_tool/img_comparator_tool.py b/img_comparator_tool/img_comparator_tool.py new file mode 100644 index 0000000..2c8a9af --- /dev/null +++ b/img_comparator_tool/img_comparator_tool.py @@ -0,0 +1,37 @@ +# This tool helps to compare two images and specifically colors the difference in red in the second image argument +import cv2 +def img_comparator(imPath1,imPath2): + img1 = cv2.imread(imPath1) + img2 = cv2.imread(imPath2) + + if img1 is None or img2 is None: + return "Images weren't loaded successfully!!" + + # resize the images to same dimension + img1 = cv2.resize(img1,(300,300)) + img2 = cv2.resize(img2,(300,300)) + + # calculating difference between two images + diff = cv2.subtract(img1,img2) + b,g,r = cv2.split(diff) + if cv2.countNonZero(b)==0 and cv2.countNonZero(g)==0 and cv2.countNonZero(r)==0: + return "The images are identical" + else: + # color the mask red + conv_hsv_gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY) + ret, mask = cv2.threshold( + conv_hsv_gray, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU + ) + diff[mask != 255] = [0, 0, 255] + + # add the red mask to the images to spot the differences + img1[mask != 255] = [0, 0, 255] + img2[mask != 255] = [0, 0, 255] + + cv2.imwrite("difference.png", diff) + return "The images are different!!" + + +img1 = "python_img.jpg" +img2 = "image2.jpg" +print(img_comparator(img1,img2)) \ No newline at end of file diff --git a/img_comparator_tool/python_img.jpg b/img_comparator_tool/python_img.jpg new file mode 100644 index 0000000..ce6fe65 Binary files /dev/null and b/img_comparator_tool/python_img.jpg differ diff --git a/new.text b/new.text new file mode 100644 index 0000000..6b25fa2 --- /dev/null +++ b/new.text @@ -0,0 +1,55 @@ +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&###&&&&&&@@$$@@@@@@@@@@@@@@@@@@@@@@&&@@@@*:: +#################################SS*SSSSSS**SSS#&@&&&&#&&&&&&&####SSS@$$&@$$%*:: +@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@&S**S#**S##&&@&&SS@@@@@@@@@@@@&&&&####@$@@$%%*!!: +$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$@S**S#*S@%*!!!!!!%##@$$@@@@@@@@@@&&&&@@@@@@%***!!: +$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$#**S#*S@%*!!!!!!!!@S#@$$$$$@@@@@@@&&&$%%%****!!!!: +*****************************@***SSS@%%***!!!!!!%SS#@***************!!!!!!!!!!!! +%%%%%%%%*%%*****************%S***SS#&&&@@$**%@@%%#**#$*%%%%%%%%%%%%%%%%%%%%%%%%$ +$$$$$$$$$$$$$$$$$$$$$$$$$$$$S****SS@@&&$$%*!$&@$%&***#%%$$$$$$$$$$$$$$$$$@@@@@$@ +$$$$$$$$$$$$$$$$$$$$%%%$$%%&*****SS%**!!**!!!***!@****@%$$$$$$$$@@@@&&#&@@@&&$%% +%%%%%%%%%%%%%%%%%%%%%%%%%%$SS*****#$****%%%*!!!!!&****&$$$$$@@@@@&&&&#SS@@@&@%%% +$$$$$$$$$$$$$$$$$$$$$$$$$%&SS***SS&$%%$$%$$%*%*!*S***S#$$@@@@@&&&&&##&&&@@@&$%%% +@@$$$$$$$$$$$$$$$$$$$$$$%@S#S***S*#$%*$@%***@$*!@****S&$@@@@@@@@&###S#$%%%%%**** +!!!!!!!!!!***!!!!!!!!!!:!@&#***SS**&$%******!!*@*****#$*!!!:::::!$&&##$*****!!!! +::::::::::!!::::::::::::%@&S***S****S&$%*****$#******S%!:::::::::!*****!!!!!!!!! +%%%%%%%%%%%%%%%%%%%%%%%%@#SSS**S***SS#@@@@@$$&*****SSS@%%%%%%%%%%%%%%%%%%%%%%%$$ +$$$$$$$$$$$$$$$$$%%%%%%@SSSSSSSSSS*S#&$$$$%%%#***SSS#*S$%%%%%%%%%%$$$$$$$$$$$@@& +!!!!!!!**!!!!!!!::::::*#SS#S###S#S**#@$$%%%%&*S****S##&$*!!!!:::::*@@@&&&##&$@&# +::::::!!!::::::::::::*@#S#S###&##SS*#@$%%%$&S******S&@$**!!!:::::::$@@&&&#S&$@&& +!!!!!!!!!:::::::::::%@#S#SS###&&##S*S&&&&&#S***SSS##&$$%%%**!!:::::*$$@&&@@@@@&& +!!!!!!!!:::::::::::$&SSSSSS##&&&#SSS#&&&@&#SSSSS##S#&$$$%%%**!!::::*$$$@&$%%%%%% +!!!!!!::::::::::::%&&#SSSSSSS#&##SSS&@@@@@#SS*SS#SS&&@@$@$$%%*!!!::!$@@&&@****** +!!*!!!::::::::::::$&&&####SS*SSSSSS#@@$$$@&S*SS#SS#&&&@@@$$$%**!:::!******!!!!!! +!!!!!!!!!!!!!!!!!*@&&&###SS*SSSSSSS#@$$$$@@#*SSSSS##&&@@@@$$$%*!*************%*% +%%%%%%%%%%%%%%%%%$&&&&####**S*SSSSS&@$$$$$@#*SS#####&&&&@@@$$$%*%$$$$$$$$$$$$$$$ +%%%%%%%%%%%%%%%%%$&&&&#S##*S#SSSSS#&$$$$$$&SSS##&#&&&&#&&@@@$$%*!!!**%$@@@@@&&&@ +!::::::::::::::::$@&&&#S#&####&##S&@@$$$$$&SSSSS&&@&&&S#&@@@$$$*::::!*$@@&#&#SS& +:::::::::::::::::$&&&&#S&&&###&###@@@$$$$@#S*SSS#@$@&#S#&&@@$@$!::::!!%$$@&&&&#& +:::::::::::::::::$&&&&#S#&&#SS####@$@$$$$@#SSSS#&@$$@&S#&&@@@@$!:::::!*$$$@#@$$@ +:::::::::::::::::@@&&&#SS&&#SS##S#&@@@@@@@&SSSS&@$$$@@S#&&@@@@$!::::::!$@@&#&%%% +::::::::::::::::!@@@&&&#S###SSSSS##@@&@@@&#SS#S#@$%$$&*#&&@@@@$!:::::::*$$@@&%** +::::::::::::::::!@@@&&&#*S#SSSSSS##&&&&&&&######&@$$$&SS&&@@@@$*::::::::!!!!!!!! +!!!!!!!!!!!****!*@@@&&##S##SSSSSS##&&&&&&&#####&&&@$$@#S#&@@@@$*************%%%% +$$$$$$$$$$$$@@@@$@@@&&##S#&#SSSSS##&&&&&&##&&#&&@@@$$$SS#&@@@@$*$$$$$$$$$$$$$$$$ +$$$$$$$%%%%%%%%%%@@&&&##S#%###SS###&&&&&&##&&&&&@$$%$$SS#&&&@@$*!********$$$@@&@ +::::::::::::::::*@&&&&##S@:&SSSSSS##&&&&&#S#@@&&@$$%%$#S#&&&@@$*:::::::::*$$@&## +::::::::::::::::*$$@@&&&#*@SSSSSSSSSS###&&#S&$@#&$$%%$&S##&&@@$*:::::::::!$$@&#S +::::::::::::::::****%%%$@$*SSSSSSSSSSSSS###SS&@@#&$%%$@#&&&@@@$*::::::::::%@@&#S +:::::::::::::::!%***%%$&$@****SSSSSSSSSSSSS#S#S&##@$%$$##@@@$$%*::::::::::*@&&#S +:::::::::::::::*%***%%@@:$*****SSSSSSSSSSSSSSS#&@&#&$$$&#&@$%***::::::::::!@&&#S +:::::::::::::::%$%%%%$&*:&******SSSSSSS*SSSSSSSS@%$@&##&##@$%%%*!::::::::::%&&&# +::::::::::::::!$$%%$@&&&#********SSSSSS**S*SSSSSS#%%%$@&#*#$$%%**:::::::::!!!!!! +::::::!!!!!!!!*$$$@&#SS***********SSSSSS****S*SSS*#%%%%%$&S&$%%%*!!!!!!!!!!!!!!! +%%%%%%$$$$$$$$&##SSS**************SSSSS#****S*SSSS*&%%%%%%$&@$%%**$$$$$$$$$$$$$$ +@@@@@@@@@@@&#SSSSSSSS***************SSSSS*******SSSS$%%%%%%%@$%%**$$$$$$$$$$$$@@ +*********!$****SSSSSSS**************SSSSS***********#%%%%%%%%@%%***!!!!!!!!!!%@@ +::::::::::&*****SSSSS****************SSSS************@%%%%%%%@$%**!!::::::!!!*@@ +::::::::::&**************************SSSSS***********#%%%%%%%$@%%**!::::::::!!$& +::::::::::%**************************SSSSS************@%%%%%%*$$%**!::::::::::%& +:::::::::::#**************************SSSS************#$%$$%%:!@%**!::::::::::!@ +:::::::::::*S*************************SSSS************S$$$$%!::$%**!::::::::::!% +:::::::::::%&#S***********************SSSS*************@$$$!:::%@%*!!:::::::::!* +:::::::!***$$@&S**********************SSSS*************@$%!::::%%*!!!!!:::!!!!!! +:::!***%%$$@S#&S**********************SSS***********SS#$%!::::!*!*!!!!!!!!:::!:! +!!!%%%*%%$$@@@#***********************SSS&&&&&#&@@@$%%%%******$$!$@*!!!!*!!***** +$$$$$@@$%$@$&##SSS**S#SSS*************SSSS#&@@@@@@@@$$$@@@@@@@@&$%@$****$*%@$$$@ \ No newline at end of file diff --git a/parser_video.py b/parser_video.py new file mode 100644 index 0000000..178bd51 --- /dev/null +++ b/parser_video.py @@ -0,0 +1,155 @@ +import zipfile +import shutil +import os +import cv2 +import argparse +import json + + +""" +Basic usage: + python3 video_parser.py -i INPUT_DIR -o OUTPUT_DIR + + INPUT_DIR is the directory containing video files + INPUT_DIR can also be a zip file + OUTPUT_DIR is where RGBD frames and json files are saved +Examples: +* To process first 100 frames only: + python3 video_parser.py -i INPUT_DIR -o OUTPUT_DIR -n 100 +* To flip image: + python3 video_parser.py -i INPUT_DIR -o OUTPUT_DIR --flip +* To extract every 5th-frame: + python3 video_parser.py -i INPUT_DIR -o OUTPUT_DIR --skip_frames 5 +* To delete original data after processing: + python3 video_parser.py -i INPUT_DIR -o OUTPUT_DIR --delete_original + +To view all options: + python3 video_parser.py -h +""" + + +def _unzip(in_zip, out_dir): + print("Unzipping {} to directory {}".format(in_zip, out_dir)) + if not os.path.exists(out_dir): + zip_ref = zipfile.ZipFile(in_zip, 'r') + zip_ref.extractall(out_dir) + zip_ref.close() + videos = [os.path.join(out_dir, f) for f in os.listdir(out_dir) + if f.endswith('.avi')] + assert len(videos) > 0, "zip file contains no video" + return videos + + +def _move(in_dir, out_dir): + print("Copying {} to {}".format(in_dir, out_dir)) + files = [f for f in os.listdir(in_dir) if not f.endswith('.avi')] + for n, f in enumerate(files): + shutil.copy(os.path.join(in_dir, f), out_dir) + if (n + 1) % 500 == 0: + print(n + 1, " files copied") + videos = [os.path.join(in_dir, f) for f in os.listdir(in_dir) + if f.endswith('.avi')] + return videos + + +def _flip(image, video_dir, video_tag, frame): + image = cv2.flip(image, -1) + return image + + +def _parse_video(video, new_dir, extension='avi', skip_frames=None, + flip=False, first_n=None): + vidcap = cv2.VideoCapture(video, cv2.CAP_FFMPEG) + while not vidcap.isOpened(): + vidcap = cv2.VideoCapture(video) + cv2.waitKey(1000) + print("Wait for the header") + _, video_base = os.path.split(video) + video_dir = new_dir + video_tag, init_frame = video_base.split('_') + init_frame = int(init_frame.split('.' + extension)[0]) + pos_frame = vidcap.get(cv2.CAP_PROP_POS_FRAMES) + frame = init_frame + failure_streak = 0 + while failure_streak < 10: + success, image = vidcap.read() + if (not success) or (image is None): + print("Could not read frame ", frame) + vidcap.set(cv2.CAP_PROP_POS_FRAMES, pos_frame+1) + frame += 1 + failure_streak += 1 + continue + failure_streak = 0 + pos_frame = vidcap.get(cv2.CAP_PROP_POS_FRAMES) + if flip: + image = _flip(image, video_dir, video_tag, frame) + img_name = video_tag + '_' + str(frame).zfill(7) + '.jpg' + img_name = os.path.join(video_dir, img_name) + n = frame - init_frame + if (n + 1) % 100 == 0: + print(n + 1, " frames processed") + if (skip_frames == 0) or (n % skip_frames == 0): + cv2.imwrite(img_name, image) + if first_n and (n > first_n): + break + frame += 1 + if pos_frame == vidcap.get(cv2.CAP_PROP_FRAME_COUNT): + print("All frames read") + break + + +def run_parser(input_dir, output_dir, extension='avi', skip_frames=0, flip=False, + first_n=None, delete_original=False): + # sub_dirs = [os.path.join(input_dir, sub) for sub in os.listdir(input_dir)] + # for d in sub_dirs: + d = input_dir + new_dir = os.path.join(output_dir, os.path.basename(d)) + videos = [] + if not os.path.exists(new_dir): + if d.endswith('.zip'): + new_dir = new_dir.split('.')[0] + videos = _unzip(d, new_dir) + else: + os.makedirs(new_dir) + videos = _move(d, new_dir) + + for video in videos: + print("Parsing video : ", video) + _parse_video(video, new_dir, extension, skip_frames, flip, first_n) + if delete_original: + os.remove(video) + + if delete_original: + if d.endswith('.zip'): + os.remove(input_dir) + else: + shutil.rmtree(input_dir) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--input_dir', help="directory or zip file containing the raw video files") + parser.add_argument('-o', '--output_dir', help="directory containing the image frames and labels", + default='output') + parser.add_argument("--extension", help="extension of video files e.g. avi, mp4", + default='avi') + parser.add_argument('-n', '--first_n', help="extract only the first n frames", type=int) + parser.add_argument("--skip_frames", help="number of frames to skip", + type=int, default=0) + parser.add_argument("--flip", help="this option rotates images by 180 degrees", + action="store_true") + parser.add_argument("--delete_original", help="this option deletes original data", + action="store_true") + args = parser.parse_args() + input_dir = args.input_dir + assert input_dir, "Please specify input directory" + assert os.path.exists(input_dir), "Input directory does not exist" + out_dir = args.output_dir + if not os.path.exists(out_dir): + os.makedirs(out_dir) + skip_frames = args.skip_frames + flip = args.flip + first_n = args.first_n + delete_original = args.delete_original + extension = args.extension + run_parser(input_dir, out_dir, extension, skip_frames, flip, first_n, delete_original) diff --git a/pywhatkit_dbs.txt b/pywhatkit_dbs.txt new file mode 100644 index 0000000..5b31e36 --- /dev/null +++ b/pywhatkit_dbs.txt @@ -0,0 +1 @@ +-------------------- diff --git a/random_pass.py b/random_pass.py new file mode 100644 index 0000000..f97a8e0 --- /dev/null +++ b/random_pass.py @@ -0,0 +1,23 @@ +# Generate Strong Random Passwords +import random +import string +# This script will generate an 18 character password +word_length = 18 +# Generate a list of letters, digits, and some punctuation +components = [string.ascii_letters, string.digits, "!@#$%&"] +# flatten the components into a list of characters +chars = [] +for clist in components: + for item in clist: + chars.append(item) +def generate_password(): + # Store the generated password + password = [] + # Choose a random item from 'chars' and add it to 'password' + for i in range(word_length): + rchar = random.choice(chars) + password.append(rchar) + # Return the composed password as a string + return "".join(password) +# Output generated password +print(generate_password()) diff --git a/random_pwd_gen.py b/random_pwd_gen.py new file mode 100644 index 0000000..f97a8e0 --- /dev/null +++ b/random_pwd_gen.py @@ -0,0 +1,23 @@ +# Generate Strong Random Passwords +import random +import string +# This script will generate an 18 character password +word_length = 18 +# Generate a list of letters, digits, and some punctuation +components = [string.ascii_letters, string.digits, "!@#$%&"] +# flatten the components into a list of characters +chars = [] +for clist in components: + for item in clist: + chars.append(item) +def generate_password(): + # Store the generated password + password = [] + # Choose a random item from 'chars' and add it to 'password' + for i in range(word_length): + rchar = random.choice(chars) + password.append(rchar) + # Return the composed password as a string + return "".join(password) +# Output generated password +print(generate_password()) diff --git a/text_process_pandoc.py b/text_process_pandoc.py new file mode 100644 index 0000000..e0067dc --- /dev/null +++ b/text_process_pandoc.py @@ -0,0 +1,4 @@ +import pandoc + +in_file = open("example.md", "r").read() +pandoc.write(in_file, file="example.pdf", format="pdf") diff --git a/validate_filenames.py b/validate_filenames.py new file mode 100644 index 0000000..ed23f39 --- /dev/null +++ b/validate_filenames.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +import os + +try: + from .build_directory_md import good_file_paths +except ImportError: + from build_directory_md import good_file_paths # type: ignore + +filepaths = list(good_file_paths()) +assert filepaths, "good_file_paths() failed!" + +upper_files = [file for file in filepaths if file != file.lower()] +if upper_files: + print(f"{len(upper_files)} files contain uppercase characters:") + print("\n".join(upper_files) + "\n") + +space_files = [file for file in filepaths if " " in file] +if space_files: + print(f"{len(space_files)} files contain space characters:") + print("\n".join(space_files) + "\n") + +hyphen_files = [file for file in filepaths if "-" in file] +if hyphen_files: + print(f"{len(hyphen_files)} files contain hyphen characters:") + print("\n".join(hyphen_files) + "\n") + +nodir_files = [file for file in filepaths if os.sep not in file] +if nodir_files: + print(f"{len(nodir_files)} files are not in a directory:") + print("\n".join(nodir_files) + "\n") + +bad_files = len(upper_files + space_files + hyphen_files + nodir_files) +if bad_files: + import sys + + sys.exit(bad_files) diff --git a/vatd.py b/vatd.py new file mode 100644 index 0000000..e5140f5 --- /dev/null +++ b/vatd.py @@ -0,0 +1,73 @@ +"""Simple tool for removing the amount of UK VAT applied to a total receipt. + Over-engineered to explore Python's ArgParse library.""" + +import argparse +import sys + + +def get_options(args): + """Returns an argparse dictionary object with application version + number, total value, value_added-tax rate and verbosity attributes.""" + parser = argparse.ArgumentParser( + prog='VATDeductor', + description='Displays the VAT deductable from a total receipt value') + parser.add_argument( + '--version', + action='version', + version='%(prog)s 1.1') + parser.add_argument( + '--rate', + type=float, + action='store', + nargs='?', + default='1.2', + help='enter VAT rate as a decimal. Default is 1.2') + parser.add_argument( + '--verbose', + action='store_true', + help='displays Total Amount, VAT deductable & pretax values') + parser.add_argument( + 'total', + metavar='T', + type=float, + action='store', + help='amount of TOTAL receipt value for processing') + return vars(parser.parse_args()) + + +def calculate_net(options): + """Calculates the receipt value without the addition of VAT applied.""" + total_value = options['total'] + vat_rate = options['rate'] + net_value = round(total_value / vat_rate, 2) + return net_value + + +def calculate_refund(options): + """Calculates total receipt minus the net, rounded to 2 decimal places. + The returned value is the VAT deductable.""" + refund_value = round(options['total'] - calculate_net(options), 2) + return refund_value + + +def verbosity(options): + """Presents calculation values in a cleaner but more verbose manner.""" + template = f""" +************************ +Total Receipt: £{options['total']} +Net Value: £{calculate_net(options)} +Deductable VAT: £{calculate_refund(options)} +************************""" + return template + + +def main(args): + options = get_options(args) + if options['verbose']: + print(verbosity(options)) + else: + print(calculate_refund(options)) + + +if __name__ == "__main__": + main(sys.argv[1:])