Copied to Clipboard
Project Avatar

Peer-2-Peer File Transfer

Project Avatar

WebAuth

None

View on GitHub

2FA Web Authenticator

Simple Django App that lets you scan 2FA QR codes to generate TOTP codes

Uses Django User Authentication

TODO

  • Make even more secure
  • Make it prettier
Project Avatar

ft_retro

Ascii based shooting game made in Python(Curses) AND again in C++(SDL2)

View on GitHub

ft_retro

Space Invaders clone written in C++ using the SDL 2 library And in python using the curses library

The python is much more developed than the C++ version for now

Python verion:

There are no additional dependacies needed but if you're on windows you'll have to install the python curses library https://www.lfd.uci.edu/~gohlke/pythonlibs/#curses

To Run

python src/main.py

Space -> Shoot Arrow keys -> Move Enter -> AFK Mode

C++ version:

Requires SDL2 libraries to compile and is an early version of the game, since then a lot of changes have been made

TODO

Animations Another graphics display Ai alien invaders game logic Shop Sound Upgrades Move based on algo Ship Builder

Strech Goal

Add Moonbase Game

Project Avatar

Binary Encoder and Compressor

An idea to compress a file by finding pairs of binary data, its an advanced version of the Run Length …

View on GitHub View Demo

Pattern Compressor

I have an idea, want to try it out and see if it'll work
I'm trying to compress files at the cost of all your computers memory, GG

The inspiration for this project was from a video explaining how compression of pokemon sprites where done for the Game Boy
Here's the video

After doing this project, I found a small improvement to compress files
At most I would get a 10% reduction in size
And found that files which already have good compression algorithms where worse
Sometimes this algorithm resulted in the file being a bit larger

Method

I've implemented a program that takes advantage of 2 algorithms,
Delta Encoding and Run Length Encoding

I then run these algorithms on the binary data of files because theres more chance of patterns appearing between 1's and 0's rather than hex's 16 different characters,
Though because of theres not much room to store additional data about how it was compressed we're forced to only compress 1 pair of binary data, 00 pairs

Run Length Encoding

So you want to implement binary Run Length Encoding?
Binary RLE works by taking 00 pairs and replacing them with a counter which says how many 00 pairs where there
The rest of the binary pairs are ignored: 01 10 11

Steps to decode: - Read the first bit, if its a 0 that means its an RLE packet - Continue reading until you get a 0, your read bits tell you how many more bits to read - Take the first of the read bits and add the second read bits, then add 1 - The result will tell you how many 0 pairs there are - You will know then that a data packet follows and you can keep reading until you reach the terminator which is a 00 - After that another RLE packet follows

Delta Encoding

The RLE algorithm works well with 00 pairs and Delta Encoding eliminates sequences of 11 pairs
This is because DE records the difference between data not the data itself,
reducing the comlexety of the data and may help it compress better

If a bit is the same as the one before it, encode it as a 0 else a 1
An imaginary first bit is assumed to be 0 which is used to decode it back

eg.
11111111
Would be saved as
10000000

Project Avatar

MyLibs

Libraires: SLD Wraper: Speed up the time to make projects using SDL "libft.a": Implementation of Unix C Standard Library

View on GitHub

Libraires:

SLD Wraper: Speed up the time to make projects using SDL

Libft: Implementation of Unix C Standard Library

Project Avatar

KNearest

Algorithm created to make machine learning like decisions

View on GitHub

K-Nearst Machine Learning Algorithm

I want to make an ML program that makes predictions based on the closest point across multi-dimensions

Given an n amount of inputs use that to place the output in the dimension using the inputs as a co-ordinate,

A prediction will be made by getting the distance of all points and taking the result of all K points

The more K points with the same value the higher the confidence of the prediction

distance = √(βˆ‘(n2 - n1)^)

Pic to Asscii

Made my own simple implementation converting an image to asscii

Copy to Clipboard
"""
Pic to Asscii
Made my own simple implementation converting an image to asscii
"""
import sys, random, argparse 
import numpy as np 
import math 
  
from PIL import Image 
  
# gray scale level values from:  
# http://paulbourke.net/dataformats/asciiart/ 
  
# 70 levels of gray 
gscale1 = "$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. "
  
# 10 levels of gray 
gscale2 = '@%#*+=-:. '
  
def getAverageL(image): 
  
    """ 
    Given PIL Image, return average value of grayscale value 
    """
    # get image as numpy array 
    im = np.array(image) 
  
    # get shape 
    w,h = im.shape 
  
    # get average 
    return np.average(im.reshape(w*h)) 
  
def covertImageToAscii(fileName, cols, scale, moreLevels): 
    """ 
    Given Image and dims (rows, cols) returns an m*n list of Images  
    """
    # declare globals 
    global gscale1, gscale2 
  
    # open image and convert to grayscale 
    image = Image.open(fileName).convert('L') 
  
    # store dimensions 
    W, H = image.size[0], image.size[1] 
    print("input image dims: %d x %d" % (W, H)) 
  
    # compute width of tile 
    w = W/cols 
  
    # compute tile height based on aspect ratio and scale 
    h = w/scale 
  
    # compute number of rows 
    rows = int(H/h) 
      
    print("cols: %d, rows: %d" % (cols, rows)) 
    print("tile dims: %d x %d" % (w, h)) 
  
    # check if image size is too small 
    if cols > W or rows > H: 
        print("Image too small for specified cols!") 
        exit(0) 
  
    # ascii image is a list of character strings 
    aimg = [] 
    # generate list of dimensions 
    for j in range(rows): 
        y1 = int(j*h) 
        y2 = int((j+1)*h) 
  
        # correct last tile 
        if j == rows-1: 
            y2 = H 
  
        # append an empty string 
        aimg.append("") 
  
        for i in range(cols): 
  
            # crop image to tile 
            x1 = int(i*w) 
            x2 = int((i+1)*w) 
  
            # correct last tile 
            if i == cols-1: 
                x2 = W 
  
            # crop image to extract tile 
            img = image.crop((x1, y1, x2, y2)) 
  
            # get average luminance 
            avg = int(getAverageL(img)) 
  
            # look up ascii char 
            if moreLevels: 
                gsval = gscale1[int((avg*69)/255)] 
            else: 
                gsval = gscale2[int((avg*9)/255)] 
  
            # append ascii char to string 
            aimg[j] += gsval 
      
    # return txt image 
    return aimg 
  
# main() function 
def main(): 
    # create parser 
    descStr = "This program converts an image into ASCII art."
    parser = argparse.ArgumentParser(description=descStr) 
    # add expected arguments 
    parser.add_argument('--file', dest='imgFile', required=True) 
    parser.add_argument('--scale', dest='scale', required=False) 
    parser.add_argument('--out', dest='outFile', required=False) 
    parser.add_argument('--cols', dest='cols', required=False) 
    parser.add_argument('--morelevels',dest='moreLevels',action='store_true') 
  
    # parse args 
    args = parser.parse_args() 
    
    imgFile = args.imgFile 
  
    # set output file 
    outFile = 'out.txt'
    if args.outFile: 
        outFile = args.outFile 
  
    # set scale default as 0.43 which suits 
    # a Courier font 
    scale = 0.43
    if args.scale: 
        scale = float(args.scale) 
  
    # set cols 
    cols = 80
    if args.cols: 
        cols = int(args.cols) 
  
    print('generating ASCII art...') 
    # convert image to ascii txt 
    aimg = covertImageToAscii(imgFile, cols, scale, args.moreLevels) 
  
    # open file 
    f = open(outFile, 'w') 
  
    # write to file 
    for row in aimg: 
        f.write(row + '\n') 
  
    # cleanup 
    f.close() 
    print("ASCII art written to %s" % outFile) 
  
# call main 
if __name__ == '__main__': 
    main()

Extract Text from Image

Simple script uses pytesseract to pull text from an image.

Copy to Clipboard
"""
Extract Text from Image
Simple script uses pytesseract to pull text from an image. 
"""
import pytesseract
from PIL import Image
import json

def pro(n):
    image = Image.open('1.png')
    return pytesseract.image_to_string(image)

t = []
for i in range(1, 13):
    print("Doing: ", i)
    t.append(pro(i))

open('out', 'w+').write(json.dumps(t))

Find Duplicate Images

Script to try find duplicate images regardless of file type. Converts them into their encoding hash to compare other images.

Copy to Clipboard
"""
Find Duplicate Images
Script to try find duplicate images regardless of file type.
Converts them into their encoding hash to compare other images. 
"""

from PIL import Image
import imagehash
import os
from pathlib import Path
from imagededup.methods import PHash

phasher = PHash()
# Generate hashes for all images in the folder
encodings = phasher.encode_images(image_dir='D:\My Drive\Shared\Whiteriver')

# Find duplicates
duplicates = phasher.find_duplicates(encoding_map=encodings, min_similarity_threshold=0.9)

# Print the results
for key, value in duplicates.items():
    if value:
        print(f"{key} is a duplicate of {value}")

# def find_duplicates(directory):
#     hashes = {}
#     for root, dirs, files in os.walk(directory):
#         for f in files:
#             filename = os.path.join(root, f)
#             if filename.endswith(('png', 'jpg', 'jpeg', 'gif', 'avif')):
#                 img = Image.open(filename)
#                 img_hash = imagehash.phash(img)  # pHash for similarity detection

#                 if img_hash in hashes:
#                     print(f"Duplicate found: {filename} and {hashes[img_hash]}")
#                 else:
#                     hashes[img_hash] = filename

# find_duplicates('D:\My Drive\Shared\Whiteriver')

Convert Images to the AVIF format

AVIF is a lot smaller as well as other benifits. Specifically this script was used on my Google Drive root folder finding all images and converting them to avif.

Copy to Clipboard
"""
Convert Images to the AVIF format
AVIF is a lot smaller as well as other benifits.
Specifically this script was used on my Google Drive root folder
finding all images and converting them to avif.
"""

import requests
from pathlib import Path
import os
import concurrent.futures
from tqdm import tqdm  # Install with: pip install tqdm
from threading import Lock
import shutil
from time import sleep
import json
import psutil

api_url = 'http://localhost:8080/api'
input_dir = 'D:\My Drive\Shared'
output_dir = Path('C:\Processed')
image_extensions = [
    ".jpeg", ".jpg", ".png", ".gif", ".bmp", ".tiff", ".tif",
    ".webp", ".heif", ".heic", ".ico", ".svg",
    ".cr2", ".cr3", ".nef", ".arw", ".raf", ".orf", ".rw2", ".dng"
]
lock = Lock()


def convert(filepath):
    suf = Path(filepath).suffix.lower()
    if suf in image_extensions:
        try:
            output_name = str(filepath).split(suf)[0] + '.avif'

            with open(filepath, 'rb') as f:
                r = requests.post(api_url, data={'quality': 80}, files={'file': f})
            if r.status_code == requests.codes.ok and r.headers.get('Content-Type') == 'image/avif':
                with open(output_name, 'wb') as f:
                    f.write(r.content)
                
                full_output_dir = output_dir / '/'.join(filepath.parts[1:-1])
                full_output_dir.mkdir(parents=True, exist_ok=True)
                shutil.move(filepath, full_output_dir)
            else:
                print('Error with:', filepath)
        except Exception as e:
            print(f'Error {e} with:', filepath)


def list_files_and_folders(directory):
    # Collect all file and folder paths
    items = []
    for root, dirs, files in os.walk(directory):
        items.extend([Path(os.path.join(root, f)) for f in files])

    total_items = len(items)
    if total_items == 0:
        print("No files or folders found.")
        return

    # Use tqdm to display a progress bar
    with tqdm(total=total_items, desc="Processing", unit="item") as pbar:
        with concurrent.futures.ThreadPoolExecutor() as executor:
            futures = [executor.submit(convert, item) for item in items]

            # Update the progress bar as each task completes
            for future in concurrent.futures.as_completed(futures):
                with lock:
                    pbar.update(1)  # Increment the progress bar by 1

list_files_and_folders(input_dir)

I have my own web server and like to run a few projects.

  • Home

    Home Page of my server and domain. 🌐 I'm always updating this page since I use it to test out whatever new thing I'm working on.

  • Planka

    Self-hosted Planka, an alternative to Trello / Jira. πŸ—‚οΈ I use it to plan my side projects, create cards, and keep track of progress.

  • Jellyfin

    Self-hosted Jellyfin, an alternative to Plex. 🎢 Makes it easy to access my music from any device.

  • VS Code Web

    Self-hosted VS Code Editor πŸ’» Runs on my server so I can code and manage it from anywhere, on any device.

  • Excalidraw

    Self-hosted Excalidraw ✏️ A draw.io alternative, great for sketching out project ideas and designs.

  • TOTP Authenticator

    Side project πŸ” I built my own 2FA Authenticator after losing my phone and getting locked out of everything. This way I add my own security and access it from the web instead of being tied to a device.

  • Peer-to-Peer File Transfer

    Side project πŸ“€ Transfers files directly between devices without storing them on the server.

  • Paste Room

    Side project πŸ“ A simple way to share text between devices (like my PC and laptop). Create a 'room' by changing the URL, and it becomes your unique space for shared text.

  • Media Gallery

    I wanted an easy way to show off pictures without filling up my phone storage. πŸ“Έ This site displays media from any folder I choose, and I can share it with anyone via ngrok.

  • Suika Game Clone

    I made a Suika Game clone in Godot πŸ‰ β€” simple but fun!

  • EagleCraft

    Minecraft in your browser! ⛏️ I used to run a dedicated server, but if it’s offline you can always connect to another public server.