├── PlayVideos.py ├── TTS.py ├── Qrcodes.py ├── sftp.py ├── EdgeDetection.py ├── TextRecognition.py ├── AttachToProcesses.py ├── ScreenRecorder.py ├── FindSubdomains.py ├── GetImages.py ├── CompressImageAndWatermark.py ├── SecurePassword.py ├── TransferFiles.py ├── Dir_Size.py ├── files └── known_hosts ├── NetworkGraphs.py ├── TransferFilesServer.py ├── Spracherkennung.py ├── FaceRecognition.py ├── 2FA - One Time Passwords.py ├── SavePasswords.py ├── TorRequests.py ├── Automate WhatsApp.py ├── EncryptPasswords.py ├── ftp.py ├── CleanText.py ├── PdfsInPython.py ├── Feather.py ├── EncryptFiles.py ├── ProcessMonitor.py ├── SysInfo.py └── Snake.py /PlayVideos.py: -------------------------------------------------------------------------------- 1 | from moviepy.editor import * 2 | import pygame 3 | 4 | pygame.display.set_mode((0,0), 0, 32) 5 | clip = VideoFileClip('audio/output.mp4').resize((1920,1080)) 6 | clip.preview() 7 | pygame.quit() -------------------------------------------------------------------------------- /TTS.py: -------------------------------------------------------------------------------- 1 | from gtts import gTTS 2 | from playsound import playsound 3 | 4 | language = 'de' 5 | tts = gTTS(text="Hallo Welt, abonnier mich!", 6 | lang=language, 7 | slow=False) 8 | tts.save("audio/tts.mp3") 9 | playsound("audio/tts.mp3") -------------------------------------------------------------------------------- /Qrcodes.py: -------------------------------------------------------------------------------- 1 | # Generate 2 | import pyqrcode 3 | 4 | url = pyqrcode.create("https://the-morpheus.de", error='H') 5 | url.png("audio/qrcode.png", module_color=(0, 255, 0, 255), background=(0, 0, 0, 255), scale=10) 6 | 7 | # Decode 8 | from PIL import Image 9 | from pyzbar.pyzbar import decode 10 | 11 | data = decode(Image.open("audio/qrcode.png")) 12 | print(data) 13 | -------------------------------------------------------------------------------- /sftp.py: -------------------------------------------------------------------------------- 1 | import pysftp 2 | 3 | cnopts = pysftp.CnOpts(knownhosts='files/known_hosts') 4 | with pysftp.Connection('host', port=22, username='demo', password='password', cnopts=cnopts) as sftp: 5 | print(sftp.listdir()) 6 | 7 | with pysftp.Connection('host', port=22, username='morpheus', private_key=r'C:\Users\mykey.priv', private_key_pass='password') as sftp: 8 | print(sftp.listdir()) -------------------------------------------------------------------------------- /EdgeDetection.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | cam = cv2.VideoCapture(0) 4 | 5 | while True: 6 | _, image = cam.read() 7 | gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) 8 | edges = cv2.Canny(gray, 30, 100) 9 | 10 | cv2.imshow("LiveVideo", image) 11 | cv2.imshow("Edges", edges) 12 | if cv2.waitKey(1) == ord("q"): 13 | break 14 | 15 | cam.release() 16 | cv2.destroyAllWindows() -------------------------------------------------------------------------------- /TextRecognition.py: -------------------------------------------------------------------------------- 1 | #Get tesseract from here: https://github.com/UB-Mannheim/tesseract/wiki 2 | 3 | import pytesseract 4 | pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe' 5 | import cv2 6 | import matplotlib.pyplot as plt 7 | from PIL import Image 8 | 9 | image = cv2.imread("files/1984_image.PNG") 10 | #image = Image.open("files/1984_image.PNG") 11 | 12 | string = pytesseract.image_to_string(image) 13 | print(string) -------------------------------------------------------------------------------- /AttachToProcesses.py: -------------------------------------------------------------------------------- 1 | import pymem 2 | import os 3 | import subprocess 4 | 5 | notepad = subprocess.Popen(['notepad.exe']) 6 | 7 | mem = pymem.Pymem('notepad.exe') 8 | mem.inject_python_interpreter() 9 | path = os.path.join(os.path.abspath('audio'), 'injected.txt') 10 | path = path.replace("\\", "\\\\") 11 | shellcode = """ 12 | f = open("{}", "w+") 13 | f.write("Hello I'm injected") 14 | f.close() 15 | """.format(path) 16 | mem.inject_python_shellcode(shellcode) 17 | -------------------------------------------------------------------------------- /ScreenRecorder.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | import pyautogui 4 | 5 | screen = (3840,2160) 6 | fourcc = cv2.VideoWriter_fourcc(*"MP4V") 7 | output = cv2.VideoWriter("output.mp4", fourcc, 30, screen) 8 | 9 | for i in range(30*5): 10 | img = pyautogui.screenshot() #TODO region 11 | frame = np.array(img) 12 | frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) 13 | output.write(frame) 14 | #TODO: Track Time and sleep for exact 30fps 15 | 16 | output.release() -------------------------------------------------------------------------------- /FindSubdomains.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | domain = "google.com" 4 | file = open("files/subdomains.txt") 5 | subdomains = [] 6 | for i in file.readlines(): 7 | subdomains.append(i.replace('\n', '')) 8 | 9 | print(f"------- CHECKING {len(subdomains)} Subdomains -------") 10 | found = [] 11 | for sub in subdomains: 12 | url = f'http://{sub}.{domain}' 13 | try: 14 | requests.get(url) 15 | except requests.ConnectionError: 16 | pass 17 | else: 18 | found.append(sub) 19 | print(f"[+++] FOUND: {sub}") 20 | -------------------------------------------------------------------------------- /GetImages.py: -------------------------------------------------------------------------------- 1 | from bs4 import BeautifulSoup as bs 2 | import requests 3 | import os 4 | 5 | URL = "https://the-morpheus.de/" 6 | 7 | soup = bs(requests.get(URL).content, "html.parser") 8 | img_urls = [] 9 | for img in soup.find_all("img"): 10 | img_url = URL + img.attrs.get("src") 11 | img_urls.append(img_url) 12 | 13 | for url in img_urls: 14 | response = requests.get(url) 15 | size = int(response.headers.get("Content-Length", 0)) 16 | name = os.path.join("imgs", url.split("/")[-1]) 17 | with open(name, "wb") as f_out: 18 | f_out.write(response.content) -------------------------------------------------------------------------------- /CompressImageAndWatermark.py: -------------------------------------------------------------------------------- 1 | import PIL 2 | from PIL import Image, ImageFont, ImageDraw 3 | 4 | 5 | def save_compressed(img): 6 | img.save("./imgs/thumb.jpg", "JPEG", optimize=True, quality=80) #1080, JPG 7 | 8 | 9 | def watermark(img): 10 | watermarked = ImageDraw.Draw(img) 11 | watermarked.text((5, 2), "The Morpheus") 12 | watermarked.bitmap((12, 9), Image.open("./imgs/MO-logo_quadratisch.png").resize((50, 50))) 13 | 14 | 15 | 16 | if __name__ == "__main__": 17 | img = Image.open("./imgs/anonymous-438427_640.jpg") 18 | watermark(img) 19 | save_compressed(img) 20 | -------------------------------------------------------------------------------- /SecurePassword.py: -------------------------------------------------------------------------------- 1 | import secrets 2 | import string 3 | 4 | print(secrets.choice("ab")) 5 | print(secrets.token_bytes()) 6 | print(secrets.token_urlsafe()) 7 | chars = string.digits + string.ascii_letters + string.punctuation 8 | print(len(chars)) # Entropie: 6,555, Min: 100 Bit 9 | print(''.join(secrets.choice(chars) for _ in range(40))) 10 | 11 | #Standard vom BSI: https://www.bsi.bund.de/SharedDocs/Downloads/DE/BSI/Publikationen/TechnischeRichtlinien/TR02102/BSI-TR-02102.pdf?__blob=publicationFile 12 | #Entropie pro Zeichen: https://en.wikipedia.org/wiki/Password_strength#Entropy_as_a_measure_of_password_strength 13 | -------------------------------------------------------------------------------- /TransferFiles.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import os 3 | 4 | file = r"G:\Tuts\Archive\Python LetsCodes\audio\long.wav" 5 | host = "192.168.0.244" 6 | sep = "#SEP#" 7 | port = 1337 8 | buffer = 1024 9 | 10 | file_size = os.path.getsize(file) 11 | if sep in file: 12 | print("WARNING! INVALID FILENAME!") 13 | exit(-1) 14 | s = socket.socket() 15 | s.connect((host, port)) 16 | s.send(f"{file}{sep}{file_size}".encode()) 17 | 18 | with open(file, "rb") as f: 19 | while True: 20 | file_bytes = f.read(buffer) 21 | if not file_bytes: 22 | break 23 | s.sendall(file_bytes) 24 | s.close() 25 | 26 | -------------------------------------------------------------------------------- /Dir_Size.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | def get_dir_size(dir): 5 | sum = 0 6 | try: 7 | for i in os.scandir(dir): 8 | if i.is_file(): 9 | sum += i.stat().st_size 10 | elif i.is_dir(): 11 | sum += get_dir_size(i.path) 12 | except Exception: 13 | return 0 14 | return sum 15 | 16 | 17 | def get_size(byte): 18 | for i in ["", "K", "M", "G", "T", "P"]: 19 | if byte < 1024: 20 | return f"{byte:.2f}{i}B" 21 | byte /= 1024 22 | return f"{byte:.2f}EB" 23 | 24 | 25 | folder = r"G:\Tuts" 26 | size = get_dir_size(folder) 27 | print(f"{folder} hat {get_size(size)}") 28 | -------------------------------------------------------------------------------- /files/known_hosts: -------------------------------------------------------------------------------- 1 | test.rebex.net ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQEAkRM6RxDdi3uAGogR3nsQMpmt43X4WnwgMzs8VkwUCqikewxqk4U7EyUSOUeT3CoUNOtywrkNbH83e6/yQgzc3M8i/eDzYtXaNGcKyLfy3Ci6XOwiLLOx1z2AGvvTXln1RXtve+Tn1RTr1BhXVh2cUYbiuVtTWqbEgErT20n4GWD4wv7FhkDbLXNi8DX07F9v7+jH67i0kyGm+E3rE+SaCMRo3zXE6VO+ijcm9HdVxfltQwOYLfuPXM2t5aUSfa96KJcA0I4RCMzA/8Dl9hXGfbWdbD2hK1ZQ1pLvvpNPPyKKjPZcMpOznprbg+jIlsZMWIHt7mq2OJXSdruhRrGzZw== 2 | test.rebex.net ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBLZcZopPvkxYERubWeSrWOSHpxJdR14WFVES/Q3hFguTn6L+0EANqYcbRXhGBUV6SjR7SaxZACXSxOzgCtG4kwc= 3 | test.rebex.net ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOdXzF+Jx/wvEBun5fxi8FQK30miLZFND0rxkYwNcYlE 4 | -------------------------------------------------------------------------------- /NetworkGraphs.py: -------------------------------------------------------------------------------- 1 | import networkx as nx 2 | 3 | G = nx.Graph() 4 | 5 | G.add_node(1) 6 | G.add_nodes_from([2, 3]) 7 | G.add_nodes_from([ 8 | (4, {"color": "green"}), 9 | (5, {"color": "red"}) 10 | ]) 11 | 12 | H = nx.Graph() 13 | H.add_node(6) 14 | H.add_node(7) 15 | H.add_edge(6, 7) 16 | G.add_nodes_from(H) 17 | 18 | G.add_edge(1, 2) 19 | G.add_edges_from([(2, 3), (1, 3)]) 20 | G.add_edges_from(H.edges) 21 | G.add_edges_from([(3, 6), (4, 6), (5, 4)]) 22 | 23 | I = nx.Graph() 24 | I.add_weighted_edges_from([(1, 2, 0.9123), (1, 3, 0.5), (2, 4, 0.25), (3, 4, 0.5)]) 25 | for (u,v,w) in I.edges.data("weight"): 26 | print(w) 27 | 28 | print(nx.shortest_path(I, 1, 4, "weight")) 29 | -------------------------------------------------------------------------------- /TransferFilesServer.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import os 3 | 4 | host = "0.0.0.0" 5 | port = 1337 6 | buffer = 1024 7 | sep = "#SEP#" 8 | 9 | s = socket.socket() 10 | s.bind((host, port)) 11 | s.listen(5) 12 | print("Server open...") 13 | client_socket, address = s.accept() 14 | print(f"{address} just connected...") 15 | file, file_size = client_socket.recv(buffer).decode().split(sep) 16 | 17 | file_name = os.path.basename(file) 18 | file_size = int(file_size) 19 | with open(file_name, "wb") as f: 20 | bytes_recv = client_socket.recv(buffer) 21 | while bytes_recv: 22 | f.write(bytes_recv) 23 | bytes_recv = client_socket.recv(buffer) 24 | client_socket.close() 25 | s.close() -------------------------------------------------------------------------------- /Spracherkennung.py: -------------------------------------------------------------------------------- 1 | import speech_recognition as sr 2 | 3 | file_name = "audio/long.wav" 4 | speech_engine = sr.Recognizer() 5 | 6 | def from_file(file_name): 7 | with sr.AudioFile(file_name) as f: 8 | data = speech_engine.record(f) 9 | text = speech_engine.recognize_google(data, language="de-DE") 10 | return text 11 | 12 | def from_microphone(): 13 | with sr.Microphone() as micro: 14 | print("Recording...") 15 | audio = speech_engine.record(micro, duration=5) 16 | print("Recognition...") 17 | text = speech_engine.recognize_google(audio, language="de-DE") 18 | return text 19 | 20 | print(from_file(file_name)) 21 | print(from_microphone()) -------------------------------------------------------------------------------- /FaceRecognition.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | 3 | capture = cv2.VideoCapture(0) 4 | cascade = cv2.CascadeClassifier("files/haarcascade_frontalface_default.xml") 5 | # https://raw.githubusercontent.com/opencv/opencv/master/data/haarcascades/haarcascade_frontalface_default.xml 6 | while True: 7 | _, im = capture.read() 8 | im_gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY) 9 | faces = cascade.detectMultiScale(im_gray) # [(0,0,500,500), (650, 700, 500,500)] 10 | for x, y, width, height in faces: 11 | cv2.rectangle(im, (x, y), (x + width, y + height), color=(0, 0, 255), thickness=5) 12 | cv2.imshow("Kamera", im) 13 | if cv2.waitKey(1) == ord("q"): 14 | break 15 | 16 | capture.release() 17 | cv2.destroyAllWindows() 18 | -------------------------------------------------------------------------------- /2FA - One Time Passwords.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | import pyotp 4 | 5 | 6 | def gen_key(): 7 | return pyotp.random_base32() 8 | 9 | 10 | def gen_url(key: str): 11 | return pyotp.totp.TOTP(key).provisioning_uri(name='Morpheus', issuer_name='My 2fa App') 12 | 13 | 14 | def generate_code(key: str): 15 | totp = pyotp.TOTP(key) 16 | return totp.now() 17 | 18 | 19 | def verify_code(key: str, code: str): 20 | totp = pyotp.TOTP(key) 21 | return totp.verify(code) 22 | 23 | 24 | key = gen_key() # Put in Database 25 | print(key) 26 | uri = gen_url(key) 27 | print(uri) 28 | 29 | code = generate_code(key) 30 | print(code) 31 | time.sleep(30) 32 | code2 = generate_code(key) 33 | 34 | print(verify_code(key, code)) 35 | print(verify_code(key, code2)) -------------------------------------------------------------------------------- /SavePasswords.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import bcrypt 3 | import hashlib 4 | 5 | def gen_password_hash(password: str): 6 | password = password.encode("utf-8") 7 | password = base64.b64encode(hashlib.sha256(password).digest()) 8 | print(password) 9 | hashed = bcrypt.hashpw( 10 | password, 11 | bcrypt.gensalt(12) 12 | ) 13 | return hashed.decode() 14 | 15 | def check_password(password: str, hash: str): 16 | password = password.encode('utf-8') 17 | password = base64.b64encode(hashlib.sha256(password).digest()) 18 | hash = hash.encode('utf-8') 19 | if bcrypt.checkpw(password, hash): 20 | return True 21 | else: 22 | return False 23 | 24 | password = "0123456789"*8 #BAD PASSWORD, DO NOT USE!!! 25 | hash = gen_password_hash(password) 26 | print(hash) 27 | print(check_password(password, hash)) 28 | -------------------------------------------------------------------------------- /TorRequests.py: -------------------------------------------------------------------------------- 1 | from torpy import TorClient 2 | from torpy.utils import recv_all 3 | from torpy.http import requests 4 | from torpy.http.adapter import TorHttpAdapter 5 | 6 | host = "ifconfig.me" 7 | with TorClient() as tor: 8 | with tor.create_circuit(3) as circ: 9 | with circ.create_stream((host, 80)) as stream: 10 | stream.send(b'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host.encode()) 11 | ret = recv_all(stream).decode() 12 | print(ret) 13 | 14 | host2 = 'https://www.facebookcorewwwi.onion/' 15 | with TorClient() as tor: 16 | with tor.get_guard() as guard: 17 | adapter = TorHttpAdapter(guard, 3) 18 | with requests.Session() as sess: 19 | sess.headers.update({'User-Agent': 'Mozilla/5.0'}) 20 | sess.mount('http://', adapter) 21 | sess.mount('https://', adapter) 22 | 23 | resp = sess.get("http://" + host, timeout=15) 24 | print(resp.text) 25 | 26 | resp = sess.get(host2) 27 | print(resp.text) -------------------------------------------------------------------------------- /Automate WhatsApp.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import queue 3 | import pywhatkit 4 | 5 | 6 | def get_input(msg, chn): 7 | resp = input(msg + "\n") 8 | chn.put(resp) 9 | 10 | 11 | def notfall_protokoll(): 12 | phone_number = "" 13 | print("Initialisiere Notfallprotokoll...") 14 | pywhatkit.sendwhatmsg(phone_number, "Hey, ich wurde gerade entführt. Kannst du mich eventuell retten?", 15 | time_hour=13, time_min=22) 16 | 17 | 18 | def timeout_input(msg, timeout): 19 | chn = queue.Queue() 20 | thread = threading.Thread(target=get_input, args=(msg, chn)) 21 | thread.daemon = True 22 | thread.start() 23 | try: 24 | resp = chn.get(True, timeout) 25 | return resp 26 | except queue.Empty: 27 | print("Nicht rechtzeitig geantwortet!") 28 | notfall_protokoll() 29 | return "" 30 | 31 | 32 | if __name__ == "__main__": 33 | if "abcde" == timeout_input("Gib das Passwort ein:", 5): 34 | print("Richtig!") 35 | else: 36 | notfall_protokoll() 37 | -------------------------------------------------------------------------------- /EncryptPasswords.py: -------------------------------------------------------------------------------- 1 | from Crypto.PublicKey import RSA 2 | from Crypto.Cipher import PKCS1_OAEP 3 | from Crypto.Hash import SHA256 4 | 5 | def generate_sk(): 6 | key = RSA.generate(16384) 7 | with open("secret_key.pem", "wb") as f_out: 8 | f_out.write(key.export_key(format='PEM')) 9 | return key 10 | 11 | def import_key(file_name): 12 | with open(file_name, 'rb') as f_in: 13 | key = RSA.import_key(f_in.read()) 14 | return key 15 | 16 | def generate_pk(sk): 17 | pk = sk.publickey() 18 | with open("public_key.pem", "wb") as f_out: 19 | f_out.write(pk.export_key(format='PEM')) 20 | return pk 21 | 22 | def encrypt(pk_receiver, message): 23 | cipher = PKCS1_OAEP.new(pk_receiver) 24 | c = cipher.encrypt(message) 25 | return c 26 | 27 | def decrypt(sk, c): 28 | cipher = PKCS1_OAEP.new(sk) 29 | m = cipher.decrypt(c) 30 | return m 31 | 32 | def footprint(pk): 33 | hasher = SHA256.new(pk) 34 | return hasher.digest() 35 | 36 | #key = generate_sk() 37 | key = import_key('secret_key.pem') 38 | pk = generate_pk(key) 39 | c = encrypt(pk, b"Hallo Welt") 40 | print(c) 41 | m = decrypt(key, c) 42 | print(m) 43 | print(footprint(pk.export_key(format='PEM'))) -------------------------------------------------------------------------------- /ftp.py: -------------------------------------------------------------------------------- 1 | import ftplib 2 | import os 3 | from datetime import datetime 4 | 5 | FTP_HOST = "" 6 | FTP_USER = "" 7 | FTP_PASS = "" 8 | 9 | def get_size(n, suffix="B"): 10 | for u in ["", "K", "M", "G", "T", "P"]: 11 | if n < 1024: 12 | return f"{n:.3f}{u}{suffix}" 13 | n /= 1024 14 | 15 | def save_file_binary(data): 16 | with open("out.pdf", "ab") as out: 17 | out.write(data) 18 | 19 | ftp = ftplib.FTP(FTP_HOST, FTP_USER, FTP_PASS) 20 | ftp.encoding = "utf-8" 21 | print(ftp.getwelcome()) 22 | home = "/" 23 | 24 | ftp.dir() 25 | ftp.cwd(home) 26 | dirs = [] 27 | files = [] 28 | for d in ftp.nlst(): 29 | if d == "." or d == "..": 30 | continue 31 | try: 32 | ftp.cwd(d) 33 | dirs.append(d) 34 | print(f"Success: {d}") 35 | except: 36 | files.append(d) 37 | print(f"Error: {d}") 38 | ftp.cwd(home) 39 | 40 | print(files) 41 | print(dirs) 42 | 43 | if len(files) > 0: 44 | ftp.retrbinary(f'RETR {files[0]}', save_file_binary) 45 | 46 | upload_file = open(r"G:\Tuts\Archive\Python LetsCodes\files\1984_image.PNG", "rb") 47 | ftp.storbinary("STOR 1984_image.PNG", upload_file) 48 | upload_file.close() 49 | 50 | ftp.quit() 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /CleanText.py: -------------------------------------------------------------------------------- 1 | import re 2 | import string 3 | 4 | text = """ 5 | ACHTUNG!Warnsignal 6 | Es geht eine neue SMS Spam Welle um. Der Text geht in dieser Richtung. 7 | '1 Neue Spnachnachricht(en) empfadgen: [bösartiger Link]'Ѧ 8 | #Spam 9 | @TheMorpheusTuts Hallo Welt 10 | https://twitter.com/TheMorpheusTuts/status/1416103913355366400 Hallo Welt 11 | Zu erkennen am schlechten Deutsch, aber sowas sollte generell nicht per SMS kommen, ohne, dass ihr wisst von wem. 12 | """ 13 | 14 | 15 | def clean(text, *, allow_none=False, duplicate_whitespace=False, remove_linebreaks_with='\n', to_ascii=True, allow_mentions=True, allow_urls=True, allow_digits=True, allow_punctuation=True): 16 | if text is None: 17 | if allow_none: 18 | return None 19 | return '' 20 | 21 | text = str(text) 22 | 23 | if not allow_mentions: 24 | text = re.sub("@\S+", "", text) 25 | if not allow_urls: 26 | text = re.sub("https?:\/\/\S*", "", text) 27 | if not allow_digits: 28 | text = re.sub("\d+", "", text) 29 | if not allow_punctuation: 30 | for c in string.punctuation: 31 | text = text.replace(c, "") 32 | 33 | text = re.sub('\n', remove_linebreaks_with, text) 34 | 35 | if not duplicate_whitespace: 36 | text = re.sub(' +', ' ', text).strip() 37 | 38 | if to_ascii: 39 | text = text.encode('ascii', 'ignore').decode() 40 | 41 | return text 42 | 43 | 44 | print(clean(text, allow_digits=False, allow_punctuation=False, duplicate_whitespace=False, remove_linebreaks_with='\n', allow_mentions=False, allow_urls=False)) 45 | -------------------------------------------------------------------------------- /PdfsInPython.py: -------------------------------------------------------------------------------- 1 | from PyPDF2 import PdfFileReader, PdfFileWriter, PdfFileMerger 2 | 3 | def get_meta(path): 4 | with open(path, 'rb') as f: 5 | pdf = PdfFileReader(f) 6 | info = pdf.getDocumentInfo() 7 | nop = pdf.getNumPages() 8 | print(info) 9 | print(nop) 10 | 11 | def extract_text(path): 12 | with open(path, 'rb') as f: 13 | pdf = PdfFileReader(f) 14 | page_one = pdf.getPage(1) 15 | print(page_one) 16 | print(type(page_one)) 17 | text = page_one.extractText() 18 | print(text) 19 | 20 | def split_pdf(path): 21 | with open(path, 'rb') as f: 22 | pdf = PdfFileReader(f) 23 | for page in range(pdf.getNumPages()): 24 | writer = PdfFileWriter() 25 | writer.addPage(pdf.getPage(page)) 26 | with open(f"{page}.pdf", "wb") as f_out: 27 | writer.write(f_out) 28 | 29 | def merge_pdf(input_paths, output_path): 30 | writer = PdfFileWriter() 31 | for i in input_paths: 32 | pdf_reader = PdfFileReader(i) 33 | for page in range(pdf_reader.getNumPages()): 34 | writer.addPage(pdf_reader.getPage(page)) 35 | with open(output_path, "wb") as f_out: 36 | writer.write(f_out) 37 | 38 | def lazy_merge(input_paths, output_path): 39 | pdf_merger = PdfFileMerger() 40 | for i in input_paths: 41 | pdf_merger.append(i) 42 | with open(output_path, "wb") as f_out: 43 | pdf_merger.write(f_out) 44 | 45 | if __name__ == '__main__': 46 | path = r"G:\Tuts\Uploaded\Algorithmen und Datenstrukturen\Bonus\Radix_LSD_Sort.pdf" 47 | lazy_merge(["2.pdf", "1.pdf"], "out.pdf") -------------------------------------------------------------------------------- /Feather.py: -------------------------------------------------------------------------------- 1 | import feather 2 | import numpy as np 3 | import pandas as pd 4 | import timeit 5 | 6 | def create_df(): 7 | size = 10000000 8 | df = pd.DataFrame({ 9 | 'a': np.random.rand(size), 10 | 'b': np.random.rand(size), 11 | 'c': np.random.rand(size), 12 | 'd': np.random.rand(size) 13 | }) 14 | return df 15 | 16 | def save_to_feather(df): 17 | df.to_feather('files/large.feather') 18 | 19 | def save_to_csv(df): 20 | df.to_csv("files/large.csv") 21 | 22 | def read_feather(): 23 | df = pd.read_feather('files/large.feather') 24 | return df 25 | 26 | def read_csv(): 27 | df = pd.read_csv('files/large.csv') 28 | return df 29 | 30 | duration_feather = 0 31 | duration_csv = 0 32 | duration_read_feather = 0 33 | duration_read_csv = 0 34 | runs = 1000 35 | for i in range(runs): 36 | df = create_df() 37 | start = timeit.default_timer() 38 | save_to_feather(df) 39 | duration_feather += timeit.default_timer() - start 40 | 41 | start = timeit.default_timer() 42 | save_to_csv(df) 43 | duration_csv += timeit.default_timer() - start 44 | 45 | start = timeit.default_timer() 46 | df = read_feather() 47 | duration_read_feather += timeit.default_timer() - start 48 | 49 | start = timeit.default_timer() 50 | df2 = read_csv() 51 | duration_read_csv += timeit.default_timer() - start 52 | 53 | print(f"Current stats for writing feather: {duration_feather / (i+1)}") 54 | print(f"Current stats for writing csv: {duration_csv / (i+1)}") 55 | print(f"Current stats for reading feather: {duration_read_feather / (i+1)}") 56 | print(f"Current stats for reading csv: {duration_read_csv / (i+1)}") 57 | 58 | print(duration_feather / runs) 59 | print(duration_csv / runs) 60 | print(duration_read_feather / runs) 61 | print(duration_read_csv / runs) 62 | -------------------------------------------------------------------------------- /EncryptFiles.py: -------------------------------------------------------------------------------- 1 | import os 2 | from Crypto import Random 3 | from Crypto.Cipher import AES 4 | from Crypto.Hash import SHA256 5 | 6 | chunks = 32 * 1024 7 | 8 | def encrypt(key, filename): 9 | out_file_name = "encrypted-" + os.path.basename(filename) 10 | file_size = str(os.path.getsize(filename)).zfill(16) # 0000000000032001 11 | IV = Random.new().read(16) 12 | encryptor = AES.new(key, AES.MODE_CFB, IV) 13 | with open(filename, 'rb') as f_input: 14 | with open(out_file_name, 'wb') as f_output: 15 | f_output.write(file_size.encode('utf-8')) 16 | f_output.write(IV) 17 | while True: 18 | chunk = f_input.read(chunks) 19 | if len(chunk) == 0: 20 | break 21 | if len(chunk) % 16 != 0: 22 | chunk += b' ' * (16 - (len(chunk) % 16)) 23 | f_output.write(encryptor.encrypt(chunk)) 24 | 25 | def decrypt(key, filename): 26 | out_file_name = filename.split("-")[-1] 27 | with open(filename, 'rb') as f_input: 28 | filesize = int(f_input.read(16)) 29 | IV = f_input.read(16) 30 | decryptor = AES.new(key, AES.MODE_CFB, IV) 31 | with open(out_file_name, 'wb') as f_output: 32 | while True: 33 | chunk = f_input.read(chunks) 34 | if len(chunk) == 0: 35 | break 36 | f_output.write(decryptor.decrypt(chunk)) 37 | f_output.truncate(filesize) 38 | 39 | def get_key(password): 40 | hashing = SHA256.new(password.encode('utf-8')) 41 | return hashing.digest() 42 | 43 | if __name__ == "__main__": 44 | file_name = "/run/media/morpheus/Volume/Tuts/Archive/Python LetsCodes/audio/long.wav" 45 | password = input("Password: ") 46 | encrypt(get_key(password), file_name) 47 | decrypt(get_key(password), "/run/media/morpheus/Volume/Tuts/Archive/Python LetsCodes/encrypted-long.wav") -------------------------------------------------------------------------------- /ProcessMonitor.py: -------------------------------------------------------------------------------- 1 | import datetime 2 | import psutil 3 | from tabulate import tabulate 4 | import os 5 | import time 6 | 7 | def get_processes(): 8 | procs = [] 9 | for p in psutil.process_iter(): 10 | with p.oneshot(): 11 | pid = p.pid 12 | if pid == 0: 13 | continue 14 | name = p.name() 15 | try: 16 | create_time = datetime.datetime.fromtimestamp(p.create_time()) 17 | except OSError: 18 | create_time = datetime.datetime.fromtimestamp(psutil.boot_time()) 19 | cpu_usage = p.cpu_percent() 20 | try: 21 | cpu_affinity = len(p.cpu_affinity()) 22 | except psutil.AccessDenied: 23 | cpu_affinity = 0 24 | status = p.status() 25 | try: 26 | memory = p.memory_full_info().uss 27 | except psutil.AccessDenied: 28 | memory = 0 29 | try: 30 | user = p.username() 31 | except psutil.AccessDenied: 32 | user = "N/A" 33 | procs.append({ 34 | 'pid': pid, 35 | 'name': name, 36 | 'create_time': create_time, 37 | 'cpu_usage': cpu_usage, 38 | 'cpu_affinity': cpu_affinity, 39 | 'status': status, 40 | 'memory': get_size(memory), 41 | 'user': user 42 | }) 43 | return procs 44 | 45 | def get_size(bytes): 46 | for i in ['', 'K', 'M', 'G', 'T', 'P', 'E']: 47 | if bytes < 1024: 48 | return f"{bytes:.2f}{i}B" 49 | bytes /= 1024 50 | 51 | def print_processes(ps): 52 | print(tabulate(ps, headers="keys", tablefmt='github')) 53 | 54 | procs = get_processes() 55 | while True: 56 | print_processes(procs) 57 | time.sleep(1) 58 | procs = get_processes() 59 | if "nt" in os.name: 60 | os.system("cls") 61 | else: 62 | os.system("clear") 63 | 64 | 65 | -------------------------------------------------------------------------------- /SysInfo.py: -------------------------------------------------------------------------------- 1 | import psutil 2 | import platform 3 | from datetime import datetime 4 | 5 | print("-"*40, "Sys Info", "-"*40) 6 | uname = platform.uname() 7 | print(f"System: {uname.system}") 8 | print(f"Node Name: {uname.node}") 9 | print(f"Release: {uname.release}") 10 | print(f"Version: {uname.version}") 11 | print(f"Machine: {uname.machine}") 12 | print(f"Processor: {uname.processor}") 13 | 14 | print("-"*40, "Boot Time", "-"*40) 15 | boot_time_timestamp = psutil.boot_time() 16 | bt = datetime.fromtimestamp(boot_time_timestamp) 17 | print(f"Boot Time: {bt.day}.{bt.month}.{bt.year} {bt.hour}:{bt.minute}:{bt.second}") 18 | 19 | print("-"*40, "CPU Info", "-"*40) 20 | print("Actual Cores:", psutil.cpu_count(logical=False)) 21 | print("Logical Cores:", psutil.cpu_count(logical=True)) 22 | print(f"Max Frequency: {psutil.cpu_freq().max:.1f}Mhz") 23 | print(f"Current Frequency: {psutil.cpu_freq().current:.1f}Mhz") 24 | print(f"CPU Usage: {psutil.cpu_percent()}%") 25 | print("CPU Usage/Core:") 26 | for i, perc in enumerate(psutil.cpu_percent(percpu=True, interval=1)): 27 | print(f"Core {i}: {perc}%") 28 | 29 | def adjust_size(size): 30 | factor = 1024 31 | for i in ["B", "KiB", "MiB", "GiB", "TiB"]: 32 | if size > factor: 33 | size = size / factor 34 | else: 35 | return f"{size:.3f}{i}" 36 | 37 | print("-"*40, "RAM Info", "-"*40) 38 | virtual_mem = psutil.virtual_memory() 39 | print(f"Total: {adjust_size(virtual_mem.total)}") 40 | print(f"Available: {adjust_size(virtual_mem.available)}") 41 | print(f"Used: {adjust_size(virtual_mem.used)}") 42 | print(f"Percentage: {virtual_mem.percent}%") 43 | print("-"*40, "SWAP", "-"*40) 44 | swap = psutil.swap_memory() 45 | print(f"Total: {adjust_size(swap.total)}") 46 | print(f"Free: {adjust_size(swap.free)}") 47 | print(f"Used: {adjust_size(swap.used)}") 48 | print(f"Percentage: {swap.percent}%") 49 | 50 | print("-"*40, "Disk Information", "-"*40) 51 | partitions = psutil.disk_partitions() 52 | for p in partitions: 53 | print(f"Device: {p.device}") 54 | print(f"\tMountpoint: {p.mountpoint}") 55 | print(f"\tFile system type: {p.fstype}") 56 | try: 57 | partition_usage = psutil.disk_usage(p.mountpoint) 58 | except PermissionError: 59 | continue 60 | print(f" Total Size: {adjust_size(partition_usage.total)}") 61 | print(f" Used: {adjust_size(partition_usage.used)}") 62 | print(f" Free: {adjust_size(partition_usage.free)}") 63 | print(f" Percentage: {partition_usage.percent}%") 64 | disk_io = psutil.disk_io_counters() 65 | print(f"Read since boot: {adjust_size(disk_io.read_bytes)}") 66 | print(f"Written since boot: {adjust_size(disk_io.write_bytes)}") 67 | 68 | print("-"*40, "GPU Details", "-"*40) 69 | import GPUtil 70 | gpus = GPUtil.getGPUs() 71 | for gpu in gpus: 72 | print(f"ID: {gpu.id}, Name: {gpu.name}") 73 | print(f"\tLoad: {gpu.load*100}%") 74 | print(f"\tFree Mem: {gpu.memoryFree}MB") 75 | print(f"\tUsed Mem: {gpu.memoryUsed}MB") 76 | print(f"\tTotal Mem: {gpu.memoryTotal}MB") 77 | print(f"\tTemperature: {gpu.temperature} °C") 78 | 79 | print("-"*40, "Network Information", "-"*40) 80 | if_addrs = psutil.net_if_addrs() 81 | for interface_name, interface_addresses in if_addrs.items(): 82 | for address in interface_addresses: 83 | print(f"Interface: {interface_name}") 84 | if str(address.family) == 'AddressFamily.AF_INET': 85 | print(f" IP Address: {address.address}") 86 | print(f" Netmask: {address.netmask}") 87 | print(f" Broadcast IP: {address.broadcast}") 88 | elif str(address.family) == 'AddressFamily.AF_PACKET': 89 | print(f" MAC Address: {address.address}") 90 | print(f" Netmask: {address.netmask}") 91 | print(f" Broadcast MAC: {address.broadcast}") 92 | net_io = psutil.net_io_counters() 93 | print(f"Total Bytes Sent: {adjust_size(net_io.bytes_sent)}") 94 | print(f"Total Bytes Received: {adjust_size(net_io.bytes_recv)}") 95 | -------------------------------------------------------------------------------- /Snake.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | import pygame 4 | from enum import Enum 5 | import random 6 | 7 | 8 | class Direction(Enum): 9 | UP = 1 10 | DOWN = 2 11 | RIGHT = 3 12 | LEFT = 4 13 | 14 | 15 | speed = 10 16 | 17 | window_width = 1080 18 | window_height = 720 19 | 20 | scale = 20 21 | 22 | pygame.init() 23 | pygame.display.set_caption("Snakeus") 24 | window = pygame.display.set_mode((window_width, window_height)) 25 | 26 | refresh_controller = pygame.time.Clock() 27 | 28 | snake_position = [250, 250] 29 | snake_body = [[250, 250], 30 | [240, 250], 31 | [230, 250]] 32 | 33 | food_position = [0, 0] 34 | food_position[0] = random.randint(5, ((window_width - 2) // scale)) * scale 35 | food_position[1] = random.randint(5, ((window_height - 2) // scale)) * scale 36 | 37 | global score 38 | score = 0 39 | 40 | 41 | def handle_keys(direction): 42 | new_direction = direction 43 | for event in [e for e in pygame.event.get() if e.type == pygame.KEYDOWN]: 44 | if event.key == pygame.K_UP and direction != Direction.DOWN: 45 | new_direction = Direction.UP 46 | if event.key == pygame.K_DOWN and direction != Direction.UP: 47 | new_direction = Direction.DOWN 48 | if event.key == pygame.K_RIGHT and direction != Direction.LEFT: 49 | new_direction = Direction.RIGHT 50 | if event.key == pygame.K_LEFT and direction != Direction.RIGHT: 51 | new_direction = Direction.LEFT 52 | return new_direction 53 | 54 | 55 | def move_snake(direction): 56 | if direction == Direction.UP: 57 | snake_position[1] -= scale 58 | if direction == Direction.DOWN: 59 | snake_position[1] += scale 60 | if direction == Direction.LEFT: 61 | snake_position[0] -= scale 62 | if direction == Direction.RIGHT: 63 | snake_position[0] += scale 64 | snake_body.insert(0, list(snake_position)) 65 | 66 | 67 | def generate_new_food(): 68 | food_position[0] = random.randint(5, ((window_width - 2) // scale)) * scale 69 | food_position[1] = random.randint(5, ((window_height - 2) // scale)) * scale 70 | 71 | 72 | def get_food(): 73 | global score 74 | print(food_position) 75 | if abs(snake_position[0] - food_position[0]) < 20 and abs(snake_position[1] - food_position[1]) < 20: 76 | score += 10 77 | generate_new_food() 78 | else: 79 | snake_body.pop() 80 | 81 | 82 | def repaint(): 83 | window.fill(pygame.Color(0, 0, 0)) 84 | for body in snake_body: 85 | pygame.draw.circle(window, pygame.Color(0, 255, 0), (body[0], body[1]), scale / 2) 86 | pygame.draw.rect(window, pygame.Color(255, 0, 0), 87 | pygame.Rect(food_position[0] - scale / 2, food_position[1] - scale / 2, scale, scale)) 88 | 89 | 90 | def game_over_message(): 91 | font = pygame.font.SysFont('Arial', scale * 3) 92 | render = font.render(f"Score: {score}", True, pygame.Color(255, 255, 255)) 93 | rect = render.get_rect() 94 | rect.midtop = (window_width / 2, window_height / 2) 95 | window.blit(render, rect) 96 | pygame.display.flip() 97 | time.sleep(5) 98 | pygame.quit() 99 | exit(0) 100 | 101 | 102 | def game_over(): 103 | if snake_position[0] < 0 or snake_position[0] > window_width - 10: 104 | game_over_message() 105 | if snake_position[1] < 0 or snake_position[1] > window_height - 10: 106 | game_over_message() 107 | for blob in snake_body[1:]: 108 | if snake_position[0] == blob[0] and snake_position[1] == blob[1]: 109 | game_over_message() 110 | 111 | 112 | def paint_hud(): 113 | font = pygame.font.SysFont("Arial", scale * 2) 114 | render = font.render(f"Score: {score}", True, pygame.Color(255, 255, 255)) 115 | rect = render.get_rect() 116 | window.blit(render, rect) 117 | pygame.display.flip() 118 | 119 | 120 | def game_loop(): 121 | direction = Direction.RIGHT 122 | while True: 123 | direction = handle_keys(direction) 124 | move_snake(direction) 125 | get_food() 126 | repaint() 127 | game_over() 128 | paint_hud() 129 | pygame.display.update() 130 | refresh_controller.tick(speed) 131 | time.sleep(0.1) 132 | 133 | 134 | if __name__ == "__main__": 135 | game_loop() 136 | --------------------------------------------------------------------------------