add a bunch of cool new stuff

This commit is contained in:
2026-07-09 01:05:56 +02:00
parent 9c9bcab59f
commit 2fa6ca798f
130 changed files with 5645 additions and 501 deletions

4
.gitignore vendored Normal file
View File

@@ -0,0 +1,4 @@
output
urls.txt
done.txt
processed

4
.obsidian/app.json vendored
View File

@@ -1,4 +0,0 @@
{
"alwaysUpdateLinks": true,
"showUnsupportedFiles": true
}

View File

@@ -1 +0,0 @@
{}

View File

@@ -1,33 +0,0 @@
{
"file-explorer": true,
"global-search": true,
"switcher": true,
"graph": true,
"backlink": true,
"canvas": true,
"outgoing-link": true,
"tag-pane": true,
"footnotes": false,
"properties": false,
"page-preview": true,
"daily-notes": true,
"templates": true,
"note-composer": true,
"command-palette": true,
"slash-command": false,
"editor-status": true,
"bookmarks": true,
"markdown-importer": false,
"zk-prefixer": false,
"random-note": false,
"outline": true,
"word-count": true,
"slides": false,
"audio-recorder": false,
"workspaces": false,
"file-recovery": true,
"publish": false,
"sync": true,
"bases": true,
"webviewer": false
}

View File

@@ -1,274 +0,0 @@
{
"main": {
"id": "c14fb7788bb86e58",
"type": "split",
"children": [
{
"id": "b277dc0ec57ac4e5",
"type": "tabs",
"children": [
{
"id": "bd0227a0bc51fda3",
"type": "leaf",
"pinned": true,
"state": {
"type": "markdown",
"state": {
"file": "rename-nested-file-to-parent.md",
"mode": "source",
"source": false
},
"pinned": true,
"icon": "lucide-file",
"title": "rename-nested-file-to-parent"
}
},
{
"id": "aad5fb65253dfe6f",
"type": "leaf",
"pinned": true,
"state": {
"type": "markdown",
"state": {
"file": "metadata-stuff.md",
"mode": "source",
"source": false
},
"pinned": true,
"icon": "lucide-file",
"title": "metadata-stuff"
}
},
{
"id": "1edaeb936a995d2c",
"type": "leaf",
"pinned": true,
"state": {
"type": "markdown",
"state": {
"file": "move-file-into-dir-with-same-name.md",
"mode": "source",
"source": false
},
"pinned": true,
"icon": "lucide-file",
"title": "move-file-into-dir-with-same-name"
}
},
{
"id": "50fc2c454baeec28",
"type": "leaf",
"state": {
"type": "markdown",
"state": {
"file": "bring-files-up-one-dir.md",
"mode": "source",
"source": false
},
"icon": "lucide-file",
"title": "bring-files-up-one-dir"
}
},
{
"id": "4c3684fe958a6ed9",
"type": "leaf",
"state": {
"type": "markdown",
"state": {
"file": "bulk-move.md",
"mode": "source",
"source": false
},
"icon": "lucide-file",
"title": "bulk-move"
}
},
{
"id": "b527262a94efda07",
"type": "leaf",
"state": {
"type": "markdown",
"state": {
"file": "move-file-into-dir-with-same-name.md",
"mode": "source",
"source": false
},
"icon": "lucide-file",
"title": "move-file-into-dir-with-same-name"
}
}
],
"currentTab": 1
}
],
"direction": "vertical"
},
"left": {
"id": "10ee71e8f52d892a",
"type": "split",
"children": [
{
"id": "63a8cd2db9e08095",
"type": "tabs",
"children": [
{
"id": "50dd7c7842ea0193",
"type": "leaf",
"state": {
"type": "file-explorer",
"state": {
"sortOrder": "alphabetical",
"autoReveal": false
},
"icon": "lucide-folder-closed",
"title": "Files"
}
},
{
"id": "96368e722c01fada",
"type": "leaf",
"state": {
"type": "search",
"state": {
"query": "",
"matchingCase": false,
"explainSearch": false,
"collapseAll": false,
"extraContext": false,
"sortOrder": "alphabetical"
},
"icon": "lucide-search",
"title": "Search"
}
},
{
"id": "ecb77e1599effc54",
"type": "leaf",
"state": {
"type": "bookmarks",
"state": {},
"icon": "lucide-bookmark",
"title": "Bookmarks"
}
}
]
}
],
"direction": "horizontal",
"width": 300
},
"right": {
"id": "cf899824f83d0bec",
"type": "split",
"children": [
{
"id": "5b1763d858d0e9ab",
"type": "tabs",
"children": [
{
"id": "5a0c75072484915d",
"type": "leaf",
"state": {
"type": "backlink",
"state": {
"file": "metadata-stuff.md",
"collapseAll": false,
"extraContext": false,
"sortOrder": "alphabetical",
"showSearch": false,
"searchQuery": "",
"backlinkCollapsed": false,
"unlinkedCollapsed": true
},
"icon": "links-coming-in",
"title": "Backlinks for metadata-stuff"
}
},
{
"id": "85c23228c3824809",
"type": "leaf",
"state": {
"type": "outgoing-link",
"state": {
"linksCollapsed": false,
"unlinkedCollapsed": true
},
"icon": "links-going-out",
"title": "Outgoing links"
}
},
{
"id": "b58ae060bc33155e",
"type": "leaf",
"state": {
"type": "tag",
"state": {
"sortOrder": "frequency",
"useHierarchy": true,
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-tags",
"title": "Tags"
}
},
{
"id": "502c9508500b0f41",
"type": "leaf",
"state": {
"type": "outline",
"state": {
"followCursor": false,
"showSearch": false,
"searchQuery": ""
},
"icon": "lucide-list",
"title": "Outline"
}
}
]
}
],
"direction": "horizontal",
"width": 300
},
"left-ribbon": {
"hiddenItems": {
"switcher:Open quick switcher": false,
"graph:Open graph view": false,
"canvas:Create new canvas": false,
"daily-notes:Open today's daily note": false,
"templates:Insert template": false,
"command-palette:Open command palette": false,
"bases:Create new base": false
}
},
"active": "aad5fb65253dfe6f",
"lastOpenFiles": [
"move-file-into-dir-with-same-name.md",
"metadata-stuff.md",
"bulk-move.md",
"find-short-videos.md",
"rename-nested-file-to-parent.md",
"bring-files-up-one-dir.md",
"remove-timestamps.md",
"ffmpeg.md",
"regex-stuff.md",
"add-prefix-to-file.md",
"usr-local-bin/setartist",
"usr-local-bin/getresauto",
"usr-local-bin/getres",
"usr-local-bin/cutto",
"usr-local-bin/cutfrom",
"usr-local-bin",
"remove-n-chars-from-name.md",
"remove-n-chars-from-name_handle-duplicates.md",
"recursively-extract-artist-from-filename.md",
"print-all-files-and-folders.md",
"print-all-files-and-folders-to-file.md",
"move-files-to-year-and-month-dirs.md",
"move-file-in-dir-with-same-name.md",
"filename-as-metadata-title.md",
"auto-fill-missing-artist-tags.md"
]
}

46
auto-curler/auto-curler.sh Executable file
View File

@@ -0,0 +1,46 @@
#!/bin/bash
if [ $# -eq 0 ]; then
echo "Usage: $0 file_with_urls.txt"
exit 1
fi
URL_FILE="$1"
OUTPUT_DIR="output"
mkdir -p "$OUTPUT_DIR"
while IFS= read -r url; do
if [ -z "$url" ]; then
continue
fi
domain=$(echo "$url" | awk -F[/:] '{print $4}')
filename=$(basename "$url")
sub_dir="$OUTPUT_DIR/$domain"
full_path="${sub_dir}/${filename}"
mkdir -p "$sub_dir"
if [ ! -f "$full_path" ]; then
echo "Downloading $url..."
echo "Subdir $sub_dir"
curl -o "$full_path" "$url"
last_modified=$(curl -sI $url | grep -i Last-Modified | awk '{print substr($0, index($0,$2))}')
echo "Modified: $last_modified"
touch -d "$last_modified" "$full_path"
echo "---"
else
echo "Skipping $url; file already exists."
fi
sleep 2
done < "$URL_FILE"
echo "Download complete."

30
auto-curler/file-replicator.sh Executable file
View File

@@ -0,0 +1,30 @@
#!/bin/bash
SOURCE_DIR="output"
TARGET_DIR="target"
replicate_structure() {
local source="$1"
local target="$2"
for item in "$source"/*; do
if [ -d "$item" ]; then
local dir_name=$(basename "$item")
mkdir -p "$target/$dir_name"
replicate_structure "$item" "$target/$dir_name"
elif [ -f "$item" ]; then
if [ -s "$item" ]; then
local file_name=$(basename "$item")
touch "$target/$file_name"
fi
fi
done
}
replicate_structure "$SOURCE_DIR" "$TARGET_DIR"
echo "Replication complete from $SOURCE_DIR to $TARGET_DIR"

View File

@@ -0,0 +1,56 @@
#!/bin/bash
set -euo pipefail
fetch_and_execute() {
local script_name=$1
shift # Shift the arguments so $@ contains the additional arguments to pass
local token_file=".gitea_token"
local gitea_user="user"
local gitea_repo="repo"
local gitea_domain="http://127.0.0.1:3333"
local gitea_access_token
if [[ -f "$token_file" ]]; then
gitea_access_token=$(<"$token_file")
else
echo "Cannot find the Gitea token file. Ensure it exists at $token_file."
exit 1
fi
echo "Fetching and executing ${script_name}..."
tmp_script="$(mktemp)"
if curl -fSL --show-error --header "Authorization: token $gitea_access_token" \
"${gitea_domain}/api/v1/repos/${gitea_user}/${gitea_repo}/raw/${script_name}" \
-o "$tmp_script"; then
chmod +x "$tmp_script"
mkdir -p ./log/homelab
logfile="./log/homelab/$(basename "$script_name").log"
if "$tmp_script" "$@" 2>&1 | tee "$logfile"; then
echo "Execution of ${script_name} was successful."
else
echo "Failed to execute ${script_name}. Log saved to $logfile"
rm -f "$tmp_script"
exit 2
fi
else
echo "Failed to download ${script_name}."
exit 1
fi
rm -f "$tmp_script"
}
# How to use in other scripts:
# path_to_fetch_script="fetch_and_execute.sh"
# source "$path_to_fetch_script"
# fetch_and_execute "name_of_script_to_fetch_and_run.sh" arg1 arg2 arg3

View File

@@ -0,0 +1,48 @@
#!/bin/bash
set -euo pipefail
umask 077
cat <<EOF > .gitea_token
REPLACE:gitea-token
EOF
fetch() {
local script_name=$1
local target=$2
local token_file=".gitea_token"
local gitea_user="user"
local gitea_repo="repo"
local gitea_domain="http://127.0.0.1:3333"
local gitea_access_token
if [[ -f "$token_file" ]]; then
gitea_access_token=$(<"$token_file")
else
echo "Cannot find the Gitea token file. Ensure it exists at $token_file."
exit 1
fi
echo "Fetching ${script_name}..."
mkdir -p "$(dirname "$target")"
if curl -fsSL \
--header "Authorization: token $gitea_access_token" \
"${gitea_domain}/api/v1/repos/${gitea_user}/${gitea_repo}/raw/${script_name}" \
-o "$target"; then
chmod +x "$target"
echo "Successfully fetched ${script_name} to ${target}."
else
echo "Failed to fetch ${script_name} from ${gitea_repo}."
exit 2
fi
}
fetch "script/fetch_and_execute.sh" "/usr/local/lib/fetch-and-execute.sh"
path_to_fetch_script="/usr/local/lib/fetch-and-execute.sh"
source "$path_to_fetch_script"
#fetch_and_execute "script/vm-setup/machine_setup.sh" REPLACE:generic-dev-machine

View File

@@ -0,0 +1,14 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] backup-cronjob-sudo"
echo
sudo crontab -l > "root-crontab-backup.txt"
echo
echo "[SCRIPT DONE] backup-cronjob-sudo"
echo
echo

View File

@@ -0,0 +1,14 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] backup-cronjob"
echo
crontab -l > "crontab-backup.txt"
echo
echo "[SCRIPT DONE] backup-cronjob"
echo
echo

View File

@@ -0,0 +1,17 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] rsync-docker-volumes-local"
echo
BACKUP_DIR="/var/lib/docker/volumes/"
REMOTE_DIR="/path/to/backup/folder"
rsync -avz --progress "$BACKUP_DIR" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR"
echo
echo "[SCRIPT DONE] rsync-docker-volumes-local"
echo
echo

View File

@@ -0,0 +1,20 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] rsync-docker-volumes-ssh"
echo
BACKUP_DIR="/var/lib/docker/volumes/"
REMOTE_USER="user"
REMOTE_HOST="127.0.0.1"
REMOTE_PORT="22"
REMOTE_DIR="/path/to/backup/folder"
rsync -avz -e "ssh -i /home/user/.ssh/id_rsa -p $REMOTE_PORT" --progress "$BACKUP_DIR" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR"
echo
echo "[SCRIPT DONE] rsync-docker-volumes-ssh"
echo
echo

View File

@@ -0,0 +1,21 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] configure-app-X"
echo
mkdir app-name
cd app-name
cat <<EOF | sudo tee -a docker-compose.yml
REPLACE:docker-compose
EOF
docker-compose up -d --build
echo
echo "[SCRIPT DONE] configure-app-X"
echo
echo

View File

@@ -0,0 +1,25 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] configure-apt-mirror"
echo
sudo cp /etc/apt/sources.list /etc/apt/sources.list.bak
sudo rm /etc/apt/sources.list
echo "[SCRIPT] Write new sources"
cat <<EOF | sudo tee -a /etc/apt/sources.list
deb http://127.0.0.1/archive.ubuntu.com/ubuntu/ jammy main restricted universe multiverse
deb http://127.0.0.1/archive.ubuntu.com/ubuntu/ jammy-updates main restricted universe multiverse
deb http://127.0.0.1/archive.ubuntu.com/ubuntu/ jammy-security main restricted universe multiverse
EOF
sudo apt update
echo
echo "[SCRIPT DONE] configure-apt-mirror"
echo
echo

View File

@@ -0,0 +1,14 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] configure-cronjob-sudo"
echo
sudo crontab "root-crontab-backup.txt"
echo
echo "[SCRIPT DONE] configure-cronjob-sudo"
echo
echo

View File

@@ -0,0 +1,14 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] configure-cronjob"
echo
crontab "crontab-backup.txt"
echo
echo "[SCRIPT DONE] configure-cronjob"
echo
echo

View File

@@ -0,0 +1,42 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] configure-docker"
echo
sudo apt update
sudo apt-get install ca-certificates curl gnupg -y
echo "[SCRIPT] Get key"
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL http://127.0.0.1/gpg/docker.gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg
echo "[SCRIPT] Add repository"
echo \
"deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] http://127.0.0.1/download.docker.com/linux/ubuntu \
"jammy" stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
echo "[SCRIPT] Install Docker"
sudo apt update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin
echo "[SCRIPT] Install docker-compose"
sudo curl -SL http://127.0.0.1/github/docker-compose/v2.27.0/docker-compose-linux-x86_64 -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
echo "[SCRIPT] Add user to docker group"
sudo usermod -aG docker ${USER}
echo
echo "[SCRIPT DONE] configure-docker"
echo
echo

View File

@@ -0,0 +1,21 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] configure-fstab"
echo
sudo mkdir /mnt/REPLACE:folder-name
cat <<EOF | sudo tee -a /etc/fstab
REPLACE:fstab config
EOF
sudo systemctl daemon-reload
sudo mount -a
echo
echo "[SCRIPT DONE] configure-fstab"
echo
echo

View File

@@ -0,0 +1,21 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] configure-netplan"
echo
sudo rm /etc/netplan/00-installer-config.yaml
cat <<EOF | sudo tee -a /etc/netplan/00-installer-config.yaml
REPLACE:netplan config
EOF
sudo chmod 600 /etc/netplan/00-installer-config.yaml
sudo netplan apply
echo
echo "[SCRIPT DONE] configure-netplan"
echo
echo

View File

@@ -0,0 +1,27 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] configure-nodejs"
echo
sudo apt-get update
sudo apt-get install -y ca-certificates curl gnupg
sudo mkdir -p /etc/apt/keyrings
curl -fsSL http://127.0.0.1/gpg/nodesource.gpg | \
sudo gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg
NODE_MAJOR=22
echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] \
http://127.0.0.1/deb.nodesource.com/node_$NODE_MAJOR.x \
nodistro main" | \
sudo tee /etc/apt/sources.list.d/nodesource.list
sudo apt-get update
sudo apt-get install nodejs -y
echo
echo "[SCRIPT DONE] configure-nodejs"
echo
echo

View File

@@ -0,0 +1,16 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] configure-packages"
echo
sudo apt update
sudo apt install REPLACE:name-of-package
echo
echo "[SCRIPT DONE] configure-packages"
echo
echo

View File

@@ -0,0 +1,38 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] configure-ungoogled-chromium"
echo
sudo apt update
sudo apt-get install -y ca-certificates curl gnupg
echo "[SCRIPT] Get key"
sudo install -m 0755 -d /etc/apt/keyrings
curl -fsSL http://127.0.0.1/gpg/xtradeb.gpg | \
sudo gpg --dearmor -o /etc/apt/keyrings/xtradeb.gpg
sudo chmod a+r /etc/apt/keyrings/xtradeb.gpg
echo "[SCRIPT] Add repository"
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/xtradeb.gpg] \
http://127.0.0.1/ppa.launchpadcontent.net/xtradeb/apps/ubuntu \
jammy main" | \
sudo tee /etc/apt/sources.list.d/xtradeb.list > /dev/null
echo "[SCRIPT] Update package lists"
sudo apt update
echo "[SCRIPT] Install ungoogled-chromium"
sudo apt-get install -y ungoogled-chromium
echo
echo "[SCRIPT DONE] configure-ungoogled-chromium"
echo
echo

View File

@@ -0,0 +1,17 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] execute"
echo
path_to_fetch_script="/usr/local/lib/fetch_and_execute.sh"
source "$path_to_fetch_script"
fetch_and_execute "script/vm-setup/machine/generic-dev-machine/restore/configure-apt-mirror.sh"
echo
echo "[SCRIPT DONE] execute"
echo
echo

View File

@@ -0,0 +1,34 @@
#!/bin/bash
set -euo pipefail
echo
echo
echo "[SCRIPT START] machine-setup"
echo
if [ -z "$1" ]; then
echo "Please provide a machine name as an argument. Usage: $0 <MACHINE_NAME>"
exit 1
fi
MACHINE_NAME=$1
path_to_fetch_script="/usr/local/lib/fetch_and_execute.sh"
source "$path_to_fetch_script"
case "$MACHINE_NAME" in
"generic-dev-machine")
fetch_and_execute "script/vm-setup/machine/generic-dev-machine/restore/execute.sh"
;;
*)
echo "Unknown machine name. Please provide a valid one."
exit 2
;;
esac
echo
echo "[SCRIPT DONE] machine-setup"
echo
echo

View File

@@ -0,0 +1,14 @@
echo
echo
echo "[SCRIPT START] configure-packages"
echo
sudo apt update
sudo apt install openssh-server
sudo apt install nfs-common
echo
echo "[SCRIPT DONE] configure-packages"
echo
echo

View File

@@ -0,0 +1,14 @@
echo
echo
echo "[SCRIPT START] execute"
echo
path_to_fetch_script="/usr/local/lib/fetch_and_execute.sh"
source "$path_to_fetch_script"
fetch_and_execute "script/vm-setup/machine/generic-dev-machine/restore/configure-packages.sh"
echo
echo "[SCRIPT DONE] execute"
echo
echo

View File

@@ -0,0 +1,8 @@
SETUP ON NEW MACHINE:
- Create "ground-zero.sh"
- Paste content
- Replace gitea token
- Replace machine name
- Make executable
$ ./ground-zero.sh

View File

@@ -0,0 +1,79 @@
const id = 'collectedAHref';
let collectedImgSrc = JSON.parse(localStorage.getItem(id)) || [];
function collectInitialSrc(targetNode) {
const elems = targetNode.querySelectorAll('a[href]');
elems.forEach(elem => {
if (!collectedImgSrc.includes(elem.href)) {
collectedImgSrc.push(elem.href);
localStorage.setItem(id, JSON.stringify(collectedImgSrc));
console.log(`🙄 Snagged an initial a.href: ${elem.href}`);
}
});
}
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((addedNode) => {
if (addedNode.nodeType === Node.ELEMENT_NODE) {
const elems = addedNode.querySelectorAll('a[href]');
elems.forEach((elem) => {
if (!collectedImgSrc.includes(elem.href)) {
collectedImgSrc.push(elem.href);
localStorage.setItem(id, JSON.stringify(collectedImgSrc));
console.log(`🙄 Added a.href: ${elem.href}`);
}
});
}
});
});
});
function waitForElement(selector, callback) {
if (document.querySelector(selector) != null) {
console.log("💠‍🌐 Target acquired. Commencing operation collect-a.srcs.");
callback(document.querySelector(selector));
} else {
setTimeout(() => waitForElement(selector, callback), 500);
}
}
collectInitialSrc(document.body);
const config = { childList: true, subtree: true };
observer.observe(document.body, config);
function downloadData(data, fileName, type = 'text/plain') {
const blob = new Blob([data], { type });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
URL.revokeObjectURL(url);
}
function stopObservingAHref() {
observer.disconnect();
console.log("💠‍🌐 I've ceased surveillance. Here's what I've collected in a.href:");
const data = JSON.parse(localStorage.getItem(id)).join('\n');
console.log(data);
downloadData(data, 'a-hrefs.txt');
}
function clearCollectedAHrefs() {
localStorage.removeItem(id);
collectedImgSrc = [];
console.log("💠‍🌐 Local storage cleared. The slate is wiped clean.");
}

View File

@@ -0,0 +1,28 @@
const scrollSpeed = 3;
const scrollDelay = 20;
let autoScrollInterval = null;
function startAutoScroll(){
if(autoScrollInterval) return;
autoScrollInterval = setInterval(() => {
window.scrollBy(0, scrollSpeed);
if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
/** Uncomment if you want to enable auto-stop on page end */
//stopAutoScroll();
//console.log("🙄 Reached bottom of page.");
}
}, scrollDelay);
console.log("💠‍🌐 Auto‑scroll engaged.");
}
function stopAutoScroll(){
clearInterval(autoScrollInterval);
autoScrollInterval = null;
console.log("💠‍🌐 Auto‑scroll disengaged.");
}
startAutoScroll();

View File

@@ -0,0 +1,20 @@
let magnets = [...document.querySelectorAll('a')].map(a => a.href).filter(href => href.startsWith('magnet:')).join('\n');
if (magnets.length > 0) {
let tempTextArea = document.createElement('textarea');
tempTextArea.value = magnets;
document.body.appendChild(tempTextArea);
tempTextArea.select();
try {
let successful = document.execCommand('copy');
let msg = successful ? 'Successfully copied to clipboard!' : 'Failed to copy to clipboard!';
console.log(msg);
} catch (err) {
console.error('Fallback: Oops, unable to copy', err);
}
document.body.removeChild(tempTextArea);
} else {
console.log('No magnet links found on this page.');
}

View File

@@ -0,0 +1,76 @@
let collectedHrefs = JSON.parse(localStorage.getItem('collectedHrefs')) || [];
function collectInitialHrefs(targetNode) {
const links = targetNode.querySelectorAll('a[href]');
links.forEach(link => {
if (!collectedHrefs.includes(link.href)) {
collectedHrefs.push(link.href);
localStorage.setItem('collectedHrefs', JSON.stringify(collectedHrefs));
console.log(`🙄 Snagged an initial href: ${link.href}`);
}
});
}
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((addedNode) => {
if (addedNode.nodeType === Node.ELEMENT_NODE) {
const links = addedNode.querySelectorAll('a[href]');
links.forEach((link) => {
if (!collectedHrefs.includes(link.href)) {
collectedHrefs.push(link.href);
localStorage.setItem('collectedHrefs', JSON.stringify(collectedHrefs));
console.log(`🙄 Added href: ${link.href}`);
}
});
}
});
});
});
function waitForElement(selector, callback) {
if (document.querySelector(selector) != null) {
console.log("💠‍🌐 Target acquired. Commencing operation collect-hrefs.");
callback(document.querySelector(selector));
} else {
setTimeout(() => waitForElement(selector, callback), 500);
}
}
waitForElement(".main-container", (targetNode) => {
collectInitialHrefs(targetNode);
const config = { childList: true, subtree: true };
observer.observe(targetNode, config);
});
function downloadData(data, fileName, type = 'text/plain') {
const blob = new Blob([data], { type });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
URL.revokeObjectURL(url);
}
function stopObserving() {
observer.disconnect();
console.log("💠‍🌐 I've ceased surveillance. Here's what I've collected:");
const data = JSON.parse(localStorage.getItem('collectedHrefs')).join('\n');
console.log(data);
downloadData(data, 'hrefs__reddit.txt');
}
function clearCollectedHrefs() {
localStorage.removeItem('collectedHrefs');
collectedHrefs = [];
console.log("💠‍🌐 Local storage cleared. The slate is wiped clean.");
}

View File

@@ -0,0 +1,31 @@
const delay = 300; // ms between clicks
const thumbs = Array.from(document.querySelectorAll("img"));
let i = 0;
console.log("💠‍🌐 Found " + thumbs.length + " images. Initiating click rampage.");
const clicker = setInterval(() => {
if (i >= thumbs.length) {
clearInterval(clicker);
console.log("🙄 Finished clicking everything.");
return;
}
const img = thumbs[i];
try {
img.scrollIntoView({ block: "center" });
img.dispatchEvent(new MouseEvent("click", {
bubbles: true,
cancelable: true,
view: window
}));
console.log("💠‍🌐 Clicked #" + i + " -> " + (img.src || "no-src"));
} catch (e) {}
i++;
}, delay);

View File

@@ -0,0 +1,79 @@
const id = 'collectedImgSrc';
let collectedImgSrc = JSON.parse(localStorage.getItem(id)) || [];
function collectInitialSrc(targetNode) {
const elems = targetNode.querySelectorAll('img[src]');
elems.forEach(elem => {
if (!collectedImgSrc.includes(elem.src)) {
collectedImgSrc.push(elem.src);
localStorage.setItem(id, JSON.stringify(collectedImgSrc));
console.log(`🙄 Snagged an initial img.src: ${elem.src}`);
}
});
}
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((addedNode) => {
if (addedNode.nodeType === Node.ELEMENT_NODE) {
const elems = addedNode.querySelectorAll('img[src]');
elems.forEach((elem) => {
if (!collectedImgSrc.includes(elem.src)) {
collectedImgSrc.push(elem.src);
localStorage.setItem(id, JSON.stringify(collectedImgSrc));
console.log(`🙄 Added img.src: ${elem.src}`);
}
});
}
});
});
});
function waitForElement(selector, callback) {
if (document.querySelector(selector) != null) {
console.log("💠‍🌐 Target acquired. Commencing operation collect-hrefs.");
callback(document.querySelector(selector));
} else {
setTimeout(() => waitForElement(selector, callback), 500);
}
}
collectInitialSrc(document.body);
const config = { childList: true, subtree: true };
observer.observe(document.body, config);
function downloadData(data, fileName, type = 'text/plain') {
const blob = new Blob([data], { type });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
URL.revokeObjectURL(url);
}
function stopObservingImgSrc() {
observer.disconnect();
console.log("💠‍🌐 I've ceased surveillance. Here's what I've collected in img.src:");
const data = JSON.parse(localStorage.getItem(id)).join('\n');
console.log(data);
downloadData(data, 'img-srcs.txt');
}
function clearCollectedImgSrcs() {
localStorage.removeItem(id);
collectedImgSrc = [];
console.log("💠‍🌐 Local storage cleared. The slate is wiped clean.");
}

View File

@@ -0,0 +1,75 @@
let collectedImgURL = JSON.parse(localStorage.getItem('collectedImgURL')) || [];
function collectInitialHrefs(targetNode) {
const links = targetNode.querySelectorAll('a[href*="img_url"]');
links.forEach(link => {
if (!collectedImgURL.includes(link.href)) {
collectedImgURL.push(link.href);
localStorage.setItem('collectedImgURL', JSON.stringify(collectedImgURL));
console.log(`🙄 Snagged an initial img url: ${link.href}`);
}
});
}
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((addedNode) => {
if (addedNode.nodeType === Node.ELEMENT_NODE) {
const links = addedNode.querySelectorAll('a[href*="img_url"]');
links.forEach((link) => {
if (!collectedImgURL.includes(link.href)) {
collectedImgURL.push(link.href);
localStorage.setItem('collectedImgURL', JSON.stringify(collectedImgURL));
console.log(`🙄 Added href: ${link.href}`);
}
});
}
});
});
});
function downloadData(data, fileName, type = 'text/plain') {
const blob = new Blob([data], { type });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.click();
URL.revokeObjectURL(url);
}
function waitForElement(selector, callback) {
if (document.querySelector(selector) != null) {
console.log("💠‍🌐 Target acquired. Commencing operation collect-hrefs.");
callback(document.querySelector(selector));
} else {
setTimeout(() => waitForElement(selector, callback), 500);
}
}
collectInitialHrefs(document.body);
const config = { childList: true, subtree: true };
observer.observe(document.body, config);
function stopObserving() {
observer.disconnect();
console.log("💠‍🌐 I've ceased surveillance. Here's what I've collected:");
const data = JSON.parse(localStorage.getItem('collectedImgURL')).join('\n');
console.log(data);
downloadData(data, 'images__yandex.txt');
}
function clearCollectedImgURL() {
localStorage.removeItem('collectedImgURL');
collectedImgURL = [];
console.log("💠‍🌐 Local storage cleared. The slate is wiped clean.");
}

View File

@@ -0,0 +1,79 @@
const MAGNET_STORAGE_KEY = 'nova_magnets';
function getStoredMagnets() {
const raw = localStorage.getItem(MAGNET_STORAGE_KEY);
if (!raw) return [];
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? parsed : [];
} catch {
return [];
}
}
function setStoredMagnets(magnets) {
const unique = Array.from(new Set(magnets));
localStorage.setItem(MAGNET_STORAGE_KEY, JSON.stringify(unique));
}
(function collectMagnets() {
const pageMagnets = [...document.querySelectorAll('a')]
.map(a => a.href)
.filter(href => href && href.startsWith('magnet:'));
if (pageMagnets.length === 0) {
console.log('No magnet links found on this page.');
return;
}
const stored = getStoredMagnets();
const combined = stored.concat(pageMagnets);
setStoredMagnets(combined);
console.log(`Stored ${pageMagnets.length} new magnet(s). Total in storage: ${getStoredMagnets().length}`);
})();
async function copyStoredMagnetsToClipboard() {
const magnets = getStoredMagnets();
if (magnets.length === 0) {
console.log('No stored magnets to copy.');
return;
}
const text = magnets.join('\n');
if (navigator.clipboard && navigator.clipboard.writeText) {
try {
await navigator.clipboard.writeText(text);
console.log('Successfully copied magnets to clipboard (navigator.clipboard).');
return;
} catch (err) {
console.warn('navigator.clipboard failed, falling back to execCommand:', err);
}
}
const tempTextArea = document.createElement('textarea');
tempTextArea.value = text;
document.body.appendChild(tempTextArea);
tempTextArea.select();
try {
const successful = document.execCommand('copy');
const msg = successful
? 'Successfully copied magnets to clipboard (execCommand fallback).'
: 'Failed to copy magnets to clipboard (execCommand fallback).';
console.log(msg);
} catch (err) {
console.error('Fallback: unable to copy magnets', err);
} finally {
document.body.removeChild(tempTextArea);
}
}
function clearStoredMagnets() {
localStorage.removeItem(MAGNET_STORAGE_KEY);
console.log('Cleared stored magnets.');
}

View File

@@ -0,0 +1,160 @@
#!/usr/bin/env bash
DRYRUN=0
TARGET="."
if [[ "${1:-}" == "--dry-run" ]]; then
DRYRUN=1
TARGET="${2:-.}"
else
TARGET="${1:-.}"
fi
LOGFILE="metadata_rename_log_$(date +%Y%m%d_%H%M%S).txt"
touch "$LOGFILE"
command -v ffprobe >/dev/null || {
echo "ffprobe not found. Install ffmpeg."
exit 1
}
sanitize() {
sed -E '
s/[\/:*?"<>|]//g;
s/[[:space:]]+/ /g;
s/^[[:space:]]+//;
s/[[:space:]]+$//
'
}
normalize_artists() {
tr ';' ',' |
sed -E '
s/[[:space:]]*,[[:space:]]*/, /g
s/[[:space:]]*&[[:space:]]*/, /g
s/[[:space:]]+feat\.?[[:space:]]+/, /Ig
s/[[:space:]]+ft\.?[[:space:]]+/, /Ig
' |
awk -F',' '
{
out=""
for(i=1;i<=NF;i++){
gsub(/^ +| +$/, "", $i)
if($i!=""){
if(out==""){out=$i}else{out=out" & "$i}
}
}
print out
}'
}
get_tag() {
local file=$1
local tag=$2
local val
val=$(ffprobe -v error \
-show_entries format_tags="$tag" \
-of default=nokey=1:noprint_wrappers=1 \
"$file" 2>/dev/null || true)
printf '%s\n' "$val" | head -n1
}
dedupe_target() {
local path="$1"
if [[ ! -e "$path" ]]; then
echo "$path"
return
fi
local dir
dir="$(dirname "$path")"
local base
base="$(basename "$path")"
local name="${base%.*}"
local ext="${base##*.}"
local n=1
local candidate
while true; do
candidate="$dir/$name.$n.$ext"
[[ -e "$candidate" ]] || break
((n++))
done
echo "$candidate"
}
for file in "$TARGET"/*; do
[[ -f "$file" ]] || continue
base="$(basename "$file")"
ext="${base##*.}"
artist="$(get_tag "$file" artist)"
artists="$(get_tag "$file" artists)"
album_artist="$(get_tag "$file" album_artist)"
title="$(get_tag "$file" title)"
artist_combined=""
if [[ -n "$artists" ]]; then
artist_combined="$artists"
elif [[ -n "$artist" ]]; then
artist_combined="$artist"
elif [[ -n "$album_artist" ]]; then
artist_combined="$album_artist"
fi
if [[ -z "$artist_combined" && -z "$title" ]]; then
echo "Skipped non-extracted $file"
continue
fi
artist_norm="$(echo "$artist_combined")"
title_norm="$(echo "$title")"
if [[ -z "$artist_norm" ]]; then
newname="$title_norm.$ext"
elif [[ -z "$title_norm" ]]; then
newname="$artist_norm.$ext"
else
newname="$artist_norm - $title_norm.$ext"
fi
target="$TARGET/$newname"
target="$(dedupe_target "$target")"
if [[ "$file" == "$target" ]]; then
echo "Skipped unchanged $file"
continue
fi
if [[ "$DRYRUN" == "1" ]]; then
echo "DRY:"
echo " OLD: $file"
echo " NEW: $target"
echo
else
if [[ -e "$target" ]]; then
echo "SKIP (exists): $target"
continue
fi
echo "Renaming"
echo " OLD: $file"
echo " NEW: $target"
echo
mv "$file" "$target"
echo "$file -> $target" >> "$LOGFILE"
fi
done

100
manage-music/group-by-artist.sh Executable file
View File

@@ -0,0 +1,100 @@
#!/usr/bin/env bash
set -euo pipefail
DRYRUN=0
TARGET="."
if [[ "$1" == "--dry-run" ]]; then
DRYRUN=1
TARGET="${2:-.}"
else
TARGET="${1:-.}"
fi
LOGFILE="grouping_log_$(date +%Y%m%d_%H%M%S).txt"
touch "$LOGFILE"
dedupe_target() {
local path="$1"
if [[ ! -e "$path" ]]; then
echo "$path"
return
fi
local dir
dir="$(dirname "$path")"
local base
base="$(basename "$path")"
local name="${base%.*}"
local ext="${base##*.}"
local n=1
local candidate
while true; do
candidate="$dir/$name.$n.$ext"
[[ -e "$candidate" ]] || break
((n++))
done
echo "$candidate"
}
#find "$TARGET" -type f -maxdepth 1 | while IFS= read -r file; do
for file in "$TARGET"/*; do
[[ -f "$file" ]] || continue
base="$(basename "$file")"
# skip if no artist-title pattern
[[ "$base" != *" - "* ]] && continue
artist="${base%% - *}"
# remove "feat." / "ft." sections
artist="$(sed -E 's/[[:space:]]+(feat|ft)\.?[[:space:]].*$//I' <<< "$artist")"
# split on common artist separators and keep first
artist="$(sed -E 's/[[:space:]]*(,|&| x | X u)[[:space:]]*.*$//' <<< "$artist")"
# trim whitespace
artist="$(sed 's/^[[:space:]]*//;s/[[:space:]]*$//' <<< "$artist")"
# lowercase
artist_lc="$(tr '[:upper:]' '[:lower:]' <<< "$artist")"
target_dir="$TARGET/$artist_lc"
target="$target_dir/$base"
# skip if artist extraction failed
[[ -z "$artist_lc" ]] && continue
target="$(dedupe_target "$target")"
if [[ "$target" != "$file" ]]; then
if [[ "$DRYRUN" == "1" ]]; then
echo "[DRY]"
echo " OLD: $file"
echo " NEW: $target"
echo
#Super lean dry run debug mode to spot leftovers
#echo "$target_dir"
else
mkdir -p "$target_dir"
echo "Renaming"
echo " OLD: $file"
echo " NEW: $target"
echo
mv -n "$file" "$target"
echo "$file -> $target" >> "$LOGFILE"
fi
fi
done

View File

@@ -0,0 +1,239 @@
#!/usr/bin/env bash
DRYRUN=0
TARGET="."
if [[ "$1" == "--dry-run" ]]; then
DRYRUN=1
TARGET="${2:-.}"
else
TARGET="${1:-.}"
fi
LOGFILE="rename_log_$(date +%Y%m%d_%H%M%S).txt"
touch "$LOGFILE"
clean_name() {
local name="$1"
# remove leading track numbers like "01 - ", "07 ", "003. "
name=$(echo "$name" | sed -E 's/^[0-9]{1,3}[[:space:]]*[-._][[:space:]]*//')
name=$(echo "$name" | sed -E 's/^[0-9]{1,3}[[:space:]]+//')
# remove youtube ids
name=$(echo "$name" | sed -E 's/\[[A-Za-z0-9_-]{11}\]//g')
# remove common youtube junk
name=$(echo "$name" | sed -E 's/\((official|official video|official music video|lyrics|lyric video|audio|visualizer|video)\)//ig')
name=$(echo "$name" | sed -E 's/\[lyric video\]//ig')
name=$(echo "$name" | sed -E 's/\(lyric video\)//ig')
name=$(echo "$name" | sed -E 's/\[(official|lyrics|audio|visualizer)\]//ig')
name=$(echo "$name" | sed -E 's/\[(official[^]]*)\]//ig')
name=$(echo "$name" | sed -E 's/\((official[^)]*)\)//ig')
name=$(echo "$name" | sed -E 's/[||][[:space:]]*official[^-]*//ig')
name=$(echo "$name" | sed -E 's/M.?V//ig')
name=$(echo "$name" | sed -E 's/\((music video)\)//ig')
name=$(echo "$name" | sed -E 's/\bOfficial( Music Video| Video| Audio)?\b//ig')
name=$(echo "$name" | sed -E 's/\[offizielles video\]//ig')
# quality markers
name=$(echo "$name" | sed -E 's/\b(4k|1080p|720p|hq|hd)\b//ig')
#remove director credits
name=$(echo "$name" | sed -E 's/\(directed by [^)]+\)//ig')
name=$(echo "$name" | sed -E 's/\(dir\.? by [^)]+\)//ig')
#remove producer bracket
name=$(echo "$name" | sed -E 's/\[prod\.? [^]]+\]//ig')
name=$(echo "$name" | sed -E 's/\(prod\.? [^)]+\)//ig')
name=$(echo "$name" | sed -E 's/\(prod\.? by [^)]+\)//ig')
# remove free download
name=$(echo "$name" | sed -E 's/\[free download\]//ig')
name=$(echo "$name" | sed -E 's/\(bass boost(ed)?\)//ig')
#remove quoting
name=$(echo "$name" | sed -E "s/'([^']+)'/\1/g")
#genres
name=$(echo "$name" | sed -E 's/^\[[^]]+\][[:space:]]*-?[[:space:]]*//')
name=$(echo "$name" | sed -E 's/\bDnB\b//ig')
name=$(echo "$name" | sed -E 's/\([A-Z ]{6,}\)//g')
name=$(echo "$name" | sed -E 's/\[(wave|phonk|liquid dubstep)[^]]*\]//ig')
name=$(echo "$name" | sed -E 's/\(tiktok\)//ig')
name=$(echo "$name" | sed -E 's/EP OUT NOW//ig')
name=$(echo "$name" | sed -E 's/VORBESTELLBAR//ig')
name=$(echo "$name" | sed -E 's/\+?.*beat by [^)]*\)//ig')
# remove copy artifacts
name=$(echo "$name" | sed -E 's/\((copy|kopie)\)//ig')
name=$(echo "$name" | sed -E 's/\((copy|kopie) *[0-9]+\)//ig')
name=$(echo "$name" | sed -E 's/\([0-9]+\. *(copy|kopie)\)//ig')
name=$(echo "$name" | sed -E 's/\((weitere )?kopie\)//ig')
# remove @prodby @mixtape like handles
name=$(echo "$name" | sed -E 's/_? *@[A-Za-z0-9_]+//g')
# remove numbered duplicates like "(1)" "(2)"
name=$(echo "$name" | sed -E 's/\([0-9]+\)//g')
# hashtags
name=$(echo "$name" | sed -E 's/#[A-Za-z0-9_]+//g')
#labels
name=$(echo "$name" | sed -E 's/\((free|copyright free|no copyright music)\)//ig')
name=$(echo "$name" | sed -E 's/\[(copyright free|no copyright music)[^]]*\]//ig')
# normalize separators
name=$(echo "$name" | sed -E 's/[–—]/-/g')
name=$(echo "$name" | sed -E 's/[|:]/-/g')
name=$(echo "$name" | sed -E 's/[::|]/-/g')
# remove quotes
name=$(echo "$name" | sed -E 's/[\"“”‘’]//g')
# clean weird punctuation leftovers
#name=$(echo "$name" | sed -E 's/[ ]+-[ ]+/-/g')
# collapse whitespace
name=$(echo "$name" | sed -E 's/[[:space:]]+/ /g')
# remove duplicate dashes
name=$(echo "$name" | sed -E 's/- -/-/g')
# ensure single space around dashes
name=$(echo "$name" | sed -E 's/[[:space:]]*-[[:space:]]*/ - /g')
#remove empty brackets
name=$(echo "$name" | sed -E 's/\(\s*\)//g')
name=$(echo "$name" | sed -E 's/\[\s*\]//g')
#vertical bar garbage
name=$(echo "$name" | sed -E 's/[||]+/ - /g')
# trailing dashes
name=$(echo "$name" | sed -E 's/[[:space:]]*-[[:space:]]*$//')
# trim
name=$(echo "$name" | sed -E 's/^ *//; s/ *$//')
# Specific removals
name=$(echo "$name" | sed -E 's/\[Monstercat Release\]//ig')
name=$(echo "$name" | sed -E 's/\[Monstercat[^]]*\]//ig')
name=$(echo "$name" | sed -E 's/\bNCS - Copyright Free Music\b//ig')
name=$(echo "$name" | sed -E 's/_ *League of Legends//ig')
name=$(echo "$name" | sed -E 's/\(wshh[^\)]*\)//ig')
name=$(echo "$name" | sed -E 's/\(WSHH[^\)]*//ig')
name=$(echo "$name" | sed -E 's/_ *Music Video *- *League of Legends//ig')
name=$(echo "$name" | sed -E 's/\(original soundtrack\)//ig')
name=$(echo "$name" | sed -E 's/\[NCS Release\]//ig')
# normalize featuring keywords
name=$(echo "$name" | sed -E 's/\b(ft|ft\.|feat|feat\.|featuring)\b/feat./ig')
# normalize separators inside features
name=$(echo "$name" | sed -E 's/feat\. ([^,-]+),/feat. \1 \&/g')
# convert "(feat X)" "[feat X]" -> "feat. X"
name=$(echo "$name" | sed -E 's/[\(\[]\s*feat\.? ([^\)\]]+)[\)\]]/feat. \1/ig')
# remove duplicate feat markers
name=$(echo "$name" | sed -E 's/feat\. feat\./feat./ig')
# collapse multiple dots
name=$(echo "$name" | sed -E 's/feat\.+/feat./g')
# convert [Remix] -> (Remix)
name=$(echo "$name" | sed -E 's/\[([^\]]*remix[^\]]*)\]/(\1)/ig')
# normalize spacing
name=$(echo "$name" | sed -E 's/\(([^)]*remix)\)/(\1)/ig')
# remove double brackets
name=$(echo "$name" | sed -E 's/\(\(([^)]*)\)\)/(\1)/g')
name=$(echo "$name" | sed -E 's/\[\s*\]//g')
echo "$name"
}
clean_loop() {
local name="$1"
local prev=""
for i in {1..3}; do
prev="$name"
name=$(clean_name "$name")
[[ "$name" == "$prev" ]] && break
done
echo "$name"
}
generate_unique() {
local filepath="$1"
local ext="${filepath##*.}"
local base="${filepath%.*}"
local i=2
local newpath="$filepath"
while [[ -e "$newpath" ]]; do
newpath="${base}.${i}.${ext}"
((i++))
done
echo "$newpath"
}
find "$TARGET" -type f -print0 | while IFS= read -r -d '' file; do
dir=$(dirname "$file")
base=$(basename "$file")
ext="${base##*.}"
name="${base%.*}"
cleaned=$(clean_loop "$name")
[[ -z "$cleaned" ]] && return
proposed="$dir/$cleaned.$ext"
if [[ "$proposed" != "$file" ]]; then
final="$proposed"
if [[ -e "$final" ]]; then
final=$(generate_unique "$proposed")
fi
if [[ "$DRYRUN" == "1" ]]; then
echo "[DRY]"
echo " OLD: $base"
echo " NEW: $(basename "$final")"
echo
#Super lean dry run debug mode to spot leftovers
#echo "$cleaned"
else
echo "Renaming"
echo " OLD: $base"
echo " NEW: $(basename "$final")"
echo
mv -n "$file" "$final"
echo "$file -> $final" >> "$LOGFILE"
fi
fi
done

View File

@@ -0,0 +1,15 @@
#!/usr/bin/env bash
library="$1"
for file in "$library"/*; do
[[ -f "$file" ]] || continue
comment=$(ffprobe -v quiet -show_entries format_tags=comment \
-of default=noprint_wrappers=1:nokey=1 "$file")
if echo "$comment" | grep -Eiq "(youtube\.com|youtu\.be)"; then
echo "$comment" | grep -Eo "https?://(www\.)?(youtube\.com|youtu\.be)[^ ]+"
fi
done

View File

@@ -0,0 +1,21 @@
#!/bin/bash
# Directory containing the MP4 files
DIRECTORY="input"
OUTPUT_DIRECTORY="output"
# Navigate to the directory
cd "$DIRECTORY"
# Loop through all MP4 files in the directory
for FILE in *.mp4; do
# Skip if the file does not exist (e.g., when the glob matches no files)
[ -f "$FILE" ] || continue
# Generate output file name with prefix
OUTPUT_FILE="$OUTPU_DIRECTORY/REDUCED_BITRATE $FILE"
# Apply the ffmpeg command to reduce bitrate
ffmpeg -i "$FILE" -c:v libx264 -preset medium -b:v 2500k -pass 1 -an -f null /dev/null && \
ffmpeg -i "$FILE" -c:v libx264 -preset medium -b:v 2500k -pass 2 -c:a aac -b:a 128k "$OUTPUT_FILE"
done

View File

@@ -0,0 +1,17 @@
#!/bin/bash
LOGS_DIR="logs"
TARGET_DIR="target"
# Loop through all log files
for log_file in "${LOGS_DIR}"/*.log; do
# Extract the base name without the log extension
base_name=$(basename "${log_file}" .log)
# Construct the name of the corresponding target file
target_file="${TARGET_DIR}/${base_name}.mp4"
# Check if the target file exists
if [ ! -f "${target_file}" ]; then
echo "Missing target file for log: ${log_file}"
fi
done

View File

@@ -0,0 +1,49 @@
#!/bin/bash
# Output file
output_csv="file_details.csv"
# CSV Header
echo "File Path,Resolution,Bitrate (kbps),Size (GB),Duration (Seconds)" > "$output_csv"
# Find all mp4 files and count them
total_files=$(find . -type f -name "*.mp4" ! -name "video*" | wc -l)
current_file=0
# Find and process mp4 files
find . -type f -name "*.mp4" ! -name "video*" -print0 | while IFS= read -r -d '' file; do
# Increment current file counter
((current_file++))
# Progress indicator
echo "$(date +"%Y-%m-%d %H:%M:%S"): Checking file $current_file/$total_files: $file"
# Extract file details with ffprobe
details=$(ffprobe -v error -select_streams v:0 -show_entries stream=width,height,bit_rate -of csv=p=0 "$file")
# Extract file duration with ffprobe
duration=$(ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 "$file")
duration=$(printf "%.0f\n" $(echo "$duration / 60" | bc -l))
# Read the details into an array
IFS=',' read -r width height bitrate <<< "$details"
# Convert bitrate to kilobits per second (kbps) if it's not N/A
if [[ "$bitrate" != "N/A" ]]; then
bitrate=$(awk "BEGIN {printf \"%.2f\", $bitrate/1000}") # Convert to kbps
else
bitrate="Unknown"
fi
# Calculate file size in GB TODO This seems to output MB for some strange reason
size=$(stat -c%s "$file" | awk '{ printf "%.3f", $1 / (1024^3) }') # Size in GB
# Format resolution
resolution="${width}x${height}"
# Write details to CSV
echo "\"$file\",\"$resolution\",\"$bitrate\",\"$size\",\"$duration\"" >> "$output_csv"
done
echo "Cataloging complete. Details saved in $output_csv"

View File

@@ -0,0 +1,35 @@
#!/bin/bash
export MIN_RES_WIDTH=1300
export MIN_RES_HEIGHT=800
SEARCH_DIR="/search/dir"
OUTPUT_DIR="."
mkdir -p "$OUTPUT_DIR"
export OUTPUT_FILE="$OUTPUT_DIR/low_res_videos.txt"
export OUTPUT_FILE_WITH_RESOLUTION="$OUTPUT_DIR/low_res_videos_with_res.txt"
check_resolution() {
local file="$1"
read width height < <(ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 "$file" | awk -F',' '{print $1, $2}')
echo "Checking $width x $height for $file"
if [[ $width -lt $MIN_RES_WIDTH || $height -lt $MIN_RES_HEIGHT ]]; then
echo "$file" >> "$OUTPUT_FILE"
echo "$width x $height | $file" >> "$OUTPUT_FILE_WITH_RESOLUTION"
fi
}
export -f check_resolution
find "$SEARCH_DIR" -type f \( -iname "*.mp4" -o -iname "*.avi" -o -iname "*.mkv" -o -iname "*.flv" -o -iname "*.mov" \) -exec bash -c 'check_resolution "$0"' {} \;
if [[ -s "$OUTPUT_FILE" ]]; then
echo "Low-resolution video files have been written to $OUTPUT_FILE"
else
echo "No low-resolution video files found."
fi

View File

@@ -0,0 +1,11 @@
#!/bin/bash
INPUT_FILE="low_res_videos.txt"
DESTINATION_DIR="/path/to/low-res"
while read -r dir; do
echo "Moving $dir"
mv "$dir" "$DESTINATION_DIR"
done < "$INPUT_FILE"
echo "All specified directories have been moved to '$DESTINATION_DIR'"

View File

@@ -0,0 +1,56 @@
#!/bin/bash
if [ -z "$1" ]; then
echo "Usage: $0 <top-level-directory>"
exit 1
fi
TOP_LEVEL_DIR="$1"
OUTPUT_FOLDER="./output"
UNSORTED_DIR_LIST="./unsorted_dir_list.txt"
THRESHOLD=55
mkdir -p "$OUTPUT_FOLDER"
process_directory() {
local sorted_dir=$1
local dir_name=$(basename "$sorted_dir")
echo "--------------------------"
echo "Processing dir '${dir_name}' (${sorted_dir})"
local output_file="${OUTPUT_FOLDER}/${dir_name}_similar_folders_detailed.txt"
local output_file_folder_name_only="${OUTPUT_FOLDER}/${dir_name}_similar_folders_folder_only.txt"
> "$output_file"
> "$output_file_folder_name_only"
while IFS= read -r -d '' sorted_folder_path; do
local sorted_name=$(basename "$sorted_folder_path")
echo "Checking '$sorted_name'"
while IFS= read -r unsorted_name; do
local levenshtein_distance=$(awk -f levenshtein.awk "$sorted_name" "$unsorted_name")
local len_sorted=${#sorted_name}
local len_unsorted=${#unsorted_name}
local max_length=$((len_sorted > len_unsorted ? len_sorted : len_unsorted))
local similarity=$((100 - (levenshtein_distance * 100 / max_length)))
if [ "$similarity" -ge "$THRESHOLD" ]; then
echo "\"$sorted_name\" <- \"$unsorted_name\": $similarity%"
echo "\"$sorted_name\" <- \"$unsorted_name\": $similarity%" >> "$output_file"
echo "$unsorted_name" >> "$output_file_folder_name_only"
fi
done < "$UNSORTED_DIR_LIST"
done < <(find "$sorted_dir" -mindepth 1 -maxdepth 1 -type d -print0)
echo "Similarity analysis for $sorted_dir complete. Results saved to $output_file and $output_file_folder_name_only."
}
for subdir in "$TOP_LEVEL_DIR"/*/; do
if [ -d "$subdir" ]; then
process_directory "$subdir"
fi
done
echo "All similarity analysis processes are complete."

View File

@@ -0,0 +1,34 @@
# levenshtein.awk
function levenshtein(a, b, len_a, len_b, cost, i, j, matrix) {
len_a = length(a);
len_b = length(b);
for (i = 0; i <= len_a; i++)
matrix[i, 0] = i;
for (j = 0; j <= len_b; j++)
matrix[0, j] = j;
for (i = 1; i <= len_a; i++) {
for (j = 1; j <= len_b; j++) {
cost = (substr(a, i, 1) != substr(b, j, 1));
matrix[i, j] = min(matrix[i-1, j] + 1, # deletion
matrix[i, j-1] + 1, # insertion
matrix[i-1, j-1] + cost); # substitution
}
}
return matrix[len_a, len_b];
}
function min(x, y, z) {
if (x < y && x < z) return x;
if (y < z) return y;
return z;
}
BEGIN {
if (ARGC != 3) {
print "Usage: levenshtein.awk <string1> <string2>";
exit 1;
}
print levenshtein(ARGV[1], ARGV[2]);
exit;
}

Binary file not shown.

View File

@@ -0,0 +1,93 @@
Copyright 2013 Google LLC
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

View File

@@ -0,0 +1,67 @@
Noto Emoji Variable Font
========================
This download contains Noto Emoji as both a variable font and static fonts.
Noto Emoji is a variable font with this axis:
wght
This means all the styles are contained in a single file:
NotoEmoji-VariableFont_wght.ttf
If your app fully supports variable fonts, you can now pick intermediate styles
that aren’t available as static fonts. Not all apps support variable fonts, and
in those cases you can use the static font files for Noto Emoji:
static/NotoEmoji-Light.ttf
static/NotoEmoji-Regular.ttf
static/NotoEmoji-Medium.ttf
static/NotoEmoji-SemiBold.ttf
static/NotoEmoji-Bold.ttf
Get started
-----------
1. Install the font files you want to use
2. Use your app's font picker to view the font family and all the
available styles
Learn more about variable fonts
-------------------------------
https://developers.google.com/web/fundamentals/design-and-ux/typography/variable-fonts
https://variablefonts.typenetwork.com
https://medium.com/variable-fonts
In desktop apps
https://theblog.adobe.com/can-variable-fonts-illustrator-cc
https://helpx.adobe.com/nz/photoshop/using/fonts.html#variable_fonts
Online
https://developers.google.com/fonts/docs/getting_started
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Fonts/Variable_Fonts_Guide
https://developer.microsoft.com/en-us/microsoft-edge/testdrive/demos/variable-fonts
Installing fonts
MacOS: https://support.apple.com/en-us/HT201749
Linux: https://www.google.com/search?q=how+to+install+a+font+on+gnu%2Blinux
Windows: https://support.microsoft.com/en-us/help/314960/how-to-install-or-remove-a-font-in-windows
Android Apps
https://developers.google.com/fonts/docs/android
https://developer.android.com/guide/topics/ui/look-and-feel/downloadable-fonts
License
-------
Please read the full license text (OFL.txt) to understand the permissions,
restrictions and requirements for usage, redistribution, and modification.
You can use them in your products & projects – print or digital,
commercial or otherwise.
This isn't legal advice, please consider consulting a lawyer and see the full
license for all details.

View File

@@ -0,0 +1,223 @@
#!/usr/bin/env bash
set -e
MODE="$1" # auto | manual
SEARCH_ROOT="${2:-.}"
CORNER="${3:-nw}" # nw ne sw se
FONT="./Noto_Emoji/static/NotoEmoji-Regular.ttf"
TMP="/tmp/jellyfin_tags_$"
mkdir -p "$TMP"
TAG_HEIGHT_RATIO=10
OFFSET_RATIO=40
PADDING_RATIO=3
declare -A TAG_COLOR
declare -A TAG_LABEL
TAG_COLOR[HDR]="#f5c542"
TAG_COLOR[TRASH]="#dc3545"
TAG_LABEL[HDR]="🌈 HDR"
TAG_LABEL[TRASH]="🗑 TRASH"
cleanup() {
rm -rf "$TMP"
}
trap cleanup EXIT
detect_hdr() {
FILE="$1"
ffprobe -v quiet \
-select_streams v:0 \
-show_entries stream=color_transfer \
-of default=nw=1:nk=1 "$FILE" 2>/dev/null |
grep -Eq "smpte2084|arib-std-b67" && echo "HDR"
}
make_tag_() {
TEXT="$1"
COLOR="$2"
OUT="$3"
convert \
-font "$FONT" \
-pointsize "$FONTSIZE" \
-background "$COLOR" \
-fill white \
label:" $TEXT " \
-gravity center \
-alpha set \
-channel A \
-evaluate set 100% \
-bordercolor "$COLOR" \
-border "$PADDING" \
"$OUT"
}
make_tag() {
TEXT="$1"
COLOR="$2"
OUT="$3"
convert -background none \
-font "$FONT" \
-pointsize "$FONTSIZE" \
label:"$TEXT" \
-bordercolor none -border "$PADDING" \
\( +clone \
-fill "$COLOR" \
-draw "roundrectangle 0,0 %[fx:w],%[fx:h] $RADIUS,$RADIUS" \
\) \
-compose DstOver -composite \
"$OUT"
}
combine_tags() {
OUT="$TMP/combined.png"
convert "$@" +append "$OUT"
echo "$OUT"
}
find_video() {
DIR="$1"
find "$DIR" -maxdepth 1 -type f \
\( -iname "*.mkv" -o -iname "*.mp4" -o -iname "*.m4v" \) |
head -n1
}
apply_tags() {
IMG="$1"
shift
TAGS=("$@")
[ "${#TAGS[@]}" -eq 0 ] && return
WIDTH=$(identify -format "%w" "$IMG")
TAGH=$((WIDTH / TAG_HEIGHT_RATIO))
FONTSIZE=$((TAGH / 2))
OFFSET=$((WIDTH / OFFSET_RATIO))
PADDING=$((TAGH / PADDING_RATIO))
TAG_FILES=()
for T in "${TAGS[@]}"; do
OUT="$TMP/tag_$T.png"
make_tag "${TAG_LABEL[$T]}" "${TAG_COLOR[$T]}" "$OUT"
TAG_FILES+=("$OUT")
done
COMBINED=$(combine_tags "${TAG_FILES[@]}")
BACKUP="${IMG}.bak"
cp "$IMG" "$BACKUP"
convert "$IMG" \
"$COMBINED" \
-gravity "$CORNER" \
-geometry +$OFFSET+$OFFSET \
-composite \
-quality 95 \
"$IMG"
echo "tagged: $IMG -> ${TAGS[*]}"
}
process_auto() {
find "$SEARCH_ROOT" -type f -iname "folder.jpg" | while read -r IMG; do
DIR=$(dirname "$IMG")
VIDEO=$(find_video "$DIR")
TAGS=()
if [ -n "$VIDEO" ]; then
HDR=$(detect_hdr "$VIDEO" || true)
[ "$HDR" == "HDR" ] && TAGS+=("HDR")
fi
apply_tags "$IMG" "${TAGS[@]}"
done
}
process_manual() {
IMG=$(find "$SEARCH_ROOT" -type f -iname "folder.jpg" |
fzf --preview 'convert {} -resize 300x jpg:- | display jpg:-')
[ -z "$IMG" ] && exit
DIR=$(dirname "$IMG")
VIDEO=$(find_video "$DIR")
TAGS=()
HDR=$(detect_hdr "$VIDEO" || true)
[ "$HDR" == "HDR" ] && TAGS+=("HDR")
SELECT=$(printf "TRASH\nnone" |
fzf --prompt="extra tag: ")
[ "$SELECT" != "none" ] && TAGS+=("$SELECT")
apply_tags "$IMG" "${TAGS[@]}"
}
case "$MODE" in
auto)
process_auto
;;
manual)
process_manual
;;
*)
echo "usage:"
echo "poster_tagger.sh auto [path] [nw|ne|sw|se]"
echo "poster_tagger.sh manual [path] [nw|ne|sw|se]"
;;
esac

View File

@@ -0,0 +1,220 @@
#!/bin/bash
ROOT="${1:-.}"
LOG="reencode.log"
PROGRESS="reencode.progress"
FAILED="reencode.failed"
SAFE_DIR="${SAFE_DIR:-}"
touch "$LOG"
touch "$PROGRESS"
ts() { date '+%F %T'; }
handler() {
echo "$(ts) INTERRUPTED by SIG$1 pid=$$ ppid=$PPID line=$LINENO cmd='$BASH_COMMAND'"
exit 1
}
trap 'handler INT' INT
trap 'handler TERM' TERM
count=0
find "$ROOT" -type f \( \
-iname "*.mp4" \
! -iname "*_delete" \
\) -print0 | while IFS= read -r -d '' f; do
count=$((count+1))
echo "----------------"
echo ""
if grep -Fxq "$f" "$PROGRESS"; then
echo "$(ts) [$count] SKIP file=$f reason=already_done"
continue
fi
echo "$(ts) [$count] START file=$f"
codec=$(ffprobe -v error -select_streams v:0 \
-show_entries stream=codec_name \
-of default=noprint_wrappers=1:nokey=1 "$f")
audio_codec=$(ffprobe -v error -select_streams a:0 \
-show_entries stream=codec_name \
-of default=noprint_wrappers=1:nokey=1 "$f")
sub_codec=$(ffprobe -v error -select_streams s:0 \
-show_entries stream=codec_name \
-of default=noprint_wrappers=1:nokey=1 "$f")
bitrate=$(ffprobe -v error -select_streams v:0 \
-show_entries stream=bit_rate \
-of default=noprint_wrappers=1:nokey=1 "$f")
video_streams=$(ffprobe -v error -select_streams v \
-show_entries stream=index \
-of csv=p=0 "$f" | wc -l)
echo "$(ts) [$count] INFO Codecs: v=$codec a=$audio_codec s=$sub_codec bitrate=$bitrate video_streams=$video_streams"
if [[ "$codec" == "hevc" || "$codec" == "av1" ]]; then
echo "$(ts) [$count] SKIP file=$f reason=codec_$codec" >> "$LOG"
echo "$(ts) [$count] SKIP file=$f reason=codec_$codec"
echo "$f" >> "$PROGRESS"
continue
fi
container="mp4"
case "$audio_codec" in
opus|vorbis|flac)
container="mkv"
;;
esac
case "$sub_codec" in
webvtt|ass|ssa)
container="mkv"
;;
esac
if (( video_streams > 1 )); then
container="mkv"
fi
echo "$(ts) [$count] INFO Selected container: $container"
if [[ -z "$bitrate" ]]; then
bitrate=0
fi
if (( bitrate > 20000000 )); then
crf=25
elif (( bitrate > 10000000 )); then
crf=24
elif (( bitrate > 5000000 )); then
crf=23
else
crf=22
fi
orig_size=$(stat -c%s "$f")
echo "$(ts) [$count] INFO CRF: $crf, Original Size: $orig_size"
base="${f%.*}"
if [[ -n "$SAFE_DIR" ]]; then
rel="${f#$ROOT/}"
out="$SAFE_DIR/${rel%.*}.reencode.tmp.$container"
mkdir -p "$(dirname "$out")"
else
out="${base}.reencode.tmp.$container"
fi
ffmpeg -nostdin -y -v error -stats \
-i "$f" \
-profile:v high \
-level 4.1 \
-map 0:v:0 \
-map 0:a? \
-map 0:s? \
-map 0:v:2? \
-c:v:0 libx264 \
-c:v:1 copy \
-c:a copy \
-c:s copy \
-c:t copy \
-pix_fmt yuv420p \
-crf "$crf" \
-preset slow \
-map_metadata 0 \
-map_chapters 0 \
-movflags use_metadata_tags+faststart \
-disposition:v:1 attached_pic \
-vsync vfr \
-maxrate 10M \
-bufsize 20M \
"$out"
ff_status=$?
if [ $ff_status -ne 0 ]; then
echo "$(ts) [$count] FAIL encode exit=$ff_status file=$f" >> "$LOG"
echo "$(ts) [$count] FAIL encode exit=$ff_status file=$f"
echo "$f" >> "$FAILED"
rm -f "$out"
continue
fi
if [[ ! -f "$out" ]]; then
echo "$(ts) [$count] FAIL empty_file file=$f" >> "$LOG"
echo "$(ts) [$count] FAIL empty_file file=$f"
echo "$f" >> "$FAILED"
continue
fi
duration=$(ffprobe -v error -show_entries format=duration \
-of default=noprint_wrappers=1:nokey=1 "$out")
if [[ -z "$duration" || "$duration" == "0.000000" ]]; then
echo "$(ts) [$count] FAIL zero_duration file=$f" >> "$LOG"
echo "$(ts) [$count] FAIL zero_duration file=$f"
echo "$f" >> "$FAILED"
rm -f "$out"
continue
fi
new_size=$(stat -c%s "$out")
if (( new_size >= orig_size )); then
rm -f "$out"
echo "$(ts) [$count] SKIP larger orig=$orig_size new=$new_size bitrate=$bitrate crf=$crf file=$f" >> "$LOG"
echo "$(ts) [$count] SKIP larger orig=$orig_size new=$new_size bitrate=$bitrate crf=$crf file=$f"
echo "$f" >> "$PROGRESS"
continue
fi
if [[ $? -eq 0 ]]; then
touch -r "$f" "$out"
if [[ "$container" == "mp4" ]]; then
mv "$out" "$f"
else
final="${base}.mkv"
mv "$out" "$final"
mv "$f" "${f}_delete"
fi
echo "$f" >> "$PROGRESS"
else
echo "$(ts) [$count] ERROR encoding failed for $f"
rm -f "$out"
fi
reduction=$(( (orig_size - new_size) * 100 / orig_size ))
echo "$(ts) [$count] DONE file=$f reduction=${reduction}%"
echo "$(ts) [$count] OK orig=$orig_size new=$new_size bitrate=$bitrate crf=$crf reduction=${reduction}% file=$f" >> "$LOG"
echo "$f" >> "$PROGRESS"
done
echo "done"

View File

@@ -0,0 +1,213 @@
#!/bin/bash
ROOT="${1:-.}"
LOG="reencode.log"
PROGRESS="reencode.progress"
FAILED="reencode.failed"
SAFE_DIR="${SAFE_DIR:-}"
touch "$LOG"
touch "$PROGRESS"
ts() { date '+%F %T'; }
handler() {
echo "$(ts) INTERRUPTED by SIG$1 pid=$$ ppid=$PPID line=$LINENO cmd='$BASH_COMMAND'"
exit 1
}
trap 'handler INT' INT
trap 'handler TERM' TERM
count=0
find "$ROOT" -type f \( \
-iname "*.mp4" \
! -iname "*_delete" \
\) -print0 | while IFS= read -r -d '' f; do
count=$((count+1))
echo "----------------"
echo ""
if grep -Fxq "$f" "$PROGRESS"; then
echo "$(ts) [$count] SKIP file=$f reason=already_done"
continue
fi
echo "$(ts) [$count] START file=$f"
codec=$(ffprobe -v error -select_streams v:0 \
-show_entries stream=codec_name \
-of default=noprint_wrappers=1:nokey=1 "$f")
audio_codec=$(ffprobe -v error -select_streams a:0 \
-show_entries stream=codec_name \
-of default=noprint_wrappers=1:nokey=1 "$f")
sub_codec=$(ffprobe -v error -select_streams s:0 \
-show_entries stream=codec_name \
-of default=noprint_wrappers=1:nokey=1 "$f")
bitrate=$(ffprobe -v error -select_streams v:0 \
-show_entries stream=bit_rate \
-of default=noprint_wrappers=1:nokey=1 "$f")
video_streams=$(ffprobe -v error -select_streams v \
-show_entries stream=index \
-of csv=p=0 "$f" | wc -l)
echo "$(ts) [$count] INFO Codecs: v=$codec a=$audio_codec s=$sub_codec bitrate=$bitrate video_streams=$video_streams"
if [[ "$codec" == "hevc" || "$codec" == "av1" ]]; then
echo "$(ts) [$count] SKIP file=$f reason=codec_$codec" >> "$LOG"
echo "$(ts) [$count] SKIP file=$f reason=codec_$codec"
echo "$f" >> "$PROGRESS"
continue
fi
container="mp4"
case "$audio_codec" in
opus|vorbis|flac)
container="mkv"
;;
esac
case "$sub_codec" in
webvtt|ass|ssa)
container="mkv"
;;
esac
if (( video_streams > 1 )); then
container="mkv"
fi
echo "$(ts) [$count] INFO Selected container: $container"
if [[ -z "$bitrate" ]]; then
bitrate=0
fi
if (( bitrate > 15000000 )); then
crf=27
else
crf=26
fi
orig_size=$(stat -c%s "$f")
echo "$(ts) [$count] INFO CRF: $crf, Original Size: $orig_size"
base="${f%.*}"
if [[ -n "$SAFE_DIR" ]]; then
rel="${f#$ROOT/}"
out="$SAFE_DIR/${rel%.*}.reencode.tmp.$container"
mkdir -p "$(dirname "$out")"
else
out="${base}.reencode.tmp.$container"
fi
ffmpeg -nostdin -y \
-i "$f" \
-x265-params log-level=error:aq-mode=3:qcomp=0.7:psy-rd=2.0:cutree=1:pools=12 \
-map 0:v:0 \
-map 0:v:2? \
-map 0:a? \
-map 0:s? \
-c:v:0 libx265 \
-c:v:1 copy \
-c:a copy \
-c:s copy \
-c:t copy \
-crf "$crf" \
-preset slow \
-map_metadata 0 \
-map_chapters 0 \
-movflags use_metadata_tags+faststart \
-disposition:v:1 attached_pic \
-fflags +bitexact \
"$out"
ff_status=$?
if [ $ff_status -ne 0 ]; then
echo "$(ts) [$count] FAIL encode exit=$ff_status file=$f" >> "$LOG"
echo "$(ts) [$count] FAIL encode exit=$ff_status file=$f"
echo "$f" >> "$FAILED"
rm -f "$out"
continue
fi
if [[ ! -f "$out" ]]; then
echo "$(ts) [$count] FAIL empty_file file=$f" >> "$LOG"
echo "$(ts) [$count] FAIL empty_file file=$f"
echo "$f" >> "$FAILED"
continue
fi
duration=$(ffprobe -v error -show_entries format=duration \
-of default=noprint_wrappers=1:nokey=1 "$out")
if [[ -z "$duration" || "$duration" == "0.000000" ]]; then
echo "$(ts) [$count] FAIL zero_duration file=$f" >> "$LOG"
echo "$(ts) [$count] FAIL zero_duration file=$f"
echo "$f" >> "$FAILED"
rm -f "$out"
continue
fi
new_size=$(stat -c%s "$out")
if (( new_size >= orig_size )); then
rm -f "$out"
echo "$(ts) [$count] SKIP larger orig=$orig_size new=$new_size bitrate=$bitrate crf=$crf file=$f" >> "$LOG"
echo "$(ts) [$count] SKIP larger orig=$orig_size new=$new_size bitrate=$bitrate crf=$crf file=$f"
echo "$f" >> "$PROGRESS"
continue
fi
if [[ $? -eq 0 ]]; then
touch -r "$f" "$out"
if [[ "$container" == "mp4" ]]; then
mv "$out" "$f"
else
final="${base}.mkv"
mv "$out" "$final"
mv "$f" "${f}_delete"
fi
echo "$f" >> "$PROGRESS"
echo "$(ts) [$count] SUCCESS $f"
else
echo "$(ts) [$count] ERROR encoding failed for $f"
rm -f "$out"
fi
reduction=$(( (orig_size - new_size) * 100 / orig_size ))
echo "$(ts) [$count] DONE file=$f reduction=${reduction}%"
echo "$(ts) [$count] OK orig=$orig_size new=$new_size bitrate=$bitrate crf=$crf reduction=${reduction}% file=$f" >> "$LOG"
echo "$f" >> "$PROGRESS"
done
echo "done"

View File

@@ -0,0 +1,162 @@
#!/bin/bash
IGNORED_FOLDERS=("backdrops" "samples" "extras" "featurettes")
VIDEO_EXTENSIONS=(mp4 mkv mov avi wmv m4v ts m2ts webm)
EXISTING_FILES="existing_target.txt"
classify_resolution() {
local WIDTH="$1"
local HEIGHT="$2"
local MAX=$((WIDTH > HEIGHT ? WIDTH : HEIGHT))
if ((MAX >= 3800)); then
echo " [2160p]"
elif ((MAX >= 1900)); then
echo " [1080p]"
elif ((MAX >= 1200)); then
echo " [720p]"
elif ((MAX >= 700)); then
echo " [480p]"
elif ((MAX >= 500)); then
echo " [360p]"
else
echo " [240p]"
fi
}
strip_resolution_tag() {
echo "$1" | sed -E 's/ ?\[[0-9]{3,4}p\]//g'
}
move_item() {
local SRC="$1"
local DST="$2"
if [[ "$SRC" != "$DST" ]]; then
if [[ -e "$DST" ]]; then
echo "⚠️ Target already exists, skipping:"
echo " existing: $DST"
echo " incoming: $SRC"
echo "$SRC -> $DST" >>$EXISTING_FILES
continue
fi
if $DRY_RUN; then
echo "[DRY RUN] Would rename:"
echo " $SRC"
echo " $DST"
else
echo "Renaming:"
echo " $SRC"
echo " $DST"
mv "$SRC" "$DST"
fi
fi
}
DRY_RUN=false
if [[ "$1" == "--dry-run" || "$1" == "-n" ]]; then
DRY_RUN=true
echo "Running in DRY-RUN mode. No files will be renamed."
fi
if ! $DRY_RUN; then
read -p "This will automatically classify and rename the resolution for all nested files in the current dir. Continue? [Y/n] " -n 1 -r
echo
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
echo "Batch renaming cancelled by user."
exit 1
fi
fi
echo
FIND_IGNORE_PARAMS=()
for FOLDER in "${IGNORED_FOLDERS[@]}"; do
FIND_IGNORE_PARAMS+=(-type d -name "$FOLDER" -o)
done
unset 'FIND_IGNORE_PARAMS[${#FIND_IGNORE_PARAMS[@]}-1]'
EXT_ARGS=()
for EXT in "${VIDEO_EXTENSIONS[@]}"; do
EXT_ARGS+=(-iname "*.${EXT}" -o)
done
unset 'EXT_ARGS[${#EXT_ARGS[@]}-1]'
find . \( "${FIND_IGNORE_PARAMS[@]}" \) -prune -o \
-type f \
-size +1M \
! -iname "*_delete" \
\( "${EXT_ARGS[@]}" \) \
-print0 | while IFS= read -r -d '' VIDEO_FILE; do
echo "-----------------------------"
echo "Processing file: $VIDEO_FILE"
RESOLUTION=$(ffprobe -v error \
-select_streams v:0 \
-show_entries stream=width,height \
-of csv=p=0:s=x \
"$VIDEO_FILE" | head -n1)
WIDTH=$(echo $RESOLUTION | cut -d'x' -f1)
HEIGHT=$(echo $RESOLUTION | cut -d'x' -f2)
# echo "Resolution: $RESOLUTION (${WIDTH}x${HEIGHT})"
if ((WIDTH < 100 || HEIGHT < 100)); then
echo "Invalid resolution detected (${WIDTH}x${HEIGHT}), skipping"
continue
fi
CLASSIFICATION=$(classify_resolution "$WIDTH" "$HEIGHT")
# echo "Resolution classification: $CLASSIFICATION"
BASENAME=$(basename -- "$VIDEO_FILE")
DIRNAME=$(dirname -- "$VIDEO_FILE")
BASENAME_NO_EXT="${BASENAME%.*}"
BASE_CLEAN=$(strip_resolution_tag "$BASENAME_NO_EXT")
EXTENSION="${BASENAME##*.}"
# detect cd suffix like -cd1, -cd2 etc (because Jellyfin absolutely requires those to be the last thing before the extension)
CD_SUFFIX=""
if [[ "$BASE_CLEAN" =~ (.*)(-(cd|disc|disk|part)[0-9]+)$ ]]; then
BASE_CLEAN="${BASH_REMATCH[1]}"
CD_SUFFIX="${BASH_REMATCH[2]}"
fi
NEW_BASE="${BASE_CLEAN}${CLASSIFICATION}${CD_SUFFIX}"
NEW_FILENAME="${BASE_CLEAN}${CLASSIFICATION}${CD_SUFFIX}.${EXTENSION}"
TARGET="$DIRNAME/$NEW_FILENAME"
OLD_BASE="$BASENAME_NO_EXT"
OLD_TRICKPLAY="$DIRNAME/${OLD_BASE}.trickplay"
NEW_TRICKPLAY="$DIRNAME/${NEW_BASE}.trickplay"
move_item "$VIDEO_FILE" "$TARGET"
if [[ -d "$OLD_TRICKPLAY" ]]; then
echo
echo "[Trickplay] Matching trickplay folder detected"
move_item "$OLD_TRICKPLAY" "$NEW_TRICKPLAY"
else
VIDEO_COUNT=$(find "$DIRNAME" -maxdepth 1 -type f \( "${EXT_ARGS[@]}" \) | wc -l)
TRICKPLAY_COUNT=$(find "$DIRNAME" -maxdepth 1 -type d -name "*.trickplay" | wc -l)
if [[ "$VIDEO_COUNT" -eq 1 && "$TRICKPLAY_COUNT" -eq 1 ]]; then
FOUND_TRICKPLAY=$(find "$DIRNAME" -maxdepth 1 -type d -name "*.trickplay")
echo
echo "[Trickplay] Detected lone trickplay folder:"
echo " $FOUND_TRICKPLAY"
echo "[Trickplay] Assuming it belongs to this video"
move_item "$FOUND_TRICKPLAY" "$NEW_TRICKPLAY"
fi
fi
done

View File

@@ -0,0 +1,65 @@
#!/usr/bin/env bash
set -e
ROOT="${1:-.}"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
LOG="$SCRIPT_DIR/deleted_poster_log.txt"
touch "$LOG"
find "$ROOT" -type f -name ".deleted" | while read -r DEL; do
DIR="$(dirname "$DEL")"
find "$DIR" -maxdepth 1 -type f \( \
-iname "folder.jpg" -o \
-iname "folder.png" -o \
-iname "*-thumb*.jpg" -o \
-iname "*-thumb*.png" -o \
-iname "backdrop*.jpg" -o \
-iname "backdrop*.png" \
\) | while read -r IMG; do
ABS=$(realpath "$IMG")
grep -Fqx "$ABS" "$LOG" && echo "Skipping $ABS" && continue
echo "Processing: $ABS"
cp "$IMG" "$IMG.bak"
WIDTH=$(identify -format "%w" "$IMG")
BADGEW=$((WIDTH * 4 / 10))
BADGEH=$((WIDTH * 12 / 100))
RADIUS=$((BADGEH / 2))
FONTSIZE=$((BADGEH / 2))
OFFSET=$((WIDTH / 40))
convert "$IMG" \
-modulate 60,5 -contrast -contrast \
\( -size ${BADGEW}x${BADGEH} xc:none \
-fill "rgba(0,0,0,0.35)" \
-draw "roundrectangle 0,0 ${BADGEW},${BADGEH} ${RADIUS},${RADIUS}" \
\) \
-gravity northeast -geometry +$((OFFSET+4))+$((OFFSET+4)) -composite \
\( -size ${BADGEW}x${BADGEH} xc:none \
-fill "rgba(220,53,69,0.95)" \
-draw "roundrectangle 0,0 ${BADGEW},${BADGEH} ${RADIUS},${RADIUS}" \
-gravity center \
-fill white \
-font DejaVu-Sans-Bold \
-pointsize ${FONTSIZE} \
-annotate +0+0 "DELETED" \
\) \
-gravity northeast -geometry +${OFFSET}+${OFFSET} -composite \
-quality 95 \
"$IMG"
echo "$ABS" >> "$LOG"
echo " -> marked + logged"
done
done

View File

@@ -0,0 +1,103 @@
#!/bin/bash
usage() {
echo "Usage: $0 [-bg] [-no-source-mv] start_timestamp end_timestamp"
echo "e.g., $0 00:42 01:37:18"
echo " $0 -bg 00:42 01:37:18 to run in background"
}
background=false
move_source=true
while [[ $# -gt 0 ]]; do
case "$1" in
-bg)
background=true
shift
;;
-no-source-mv)
move_source=false
shift
;;
-*)
echo "Unknown option: $1"
usage
exit 1
;;
*)
break
;;
esac
done
if [ "$#" -ne 2 ]; then
usage
exit 1
fi
START_CUT="$1"
END_CUT="$2"
# Supported video extensions
VIDEO_EXTS=("mp4" "mkv" "mov" "avi" "webm" "m4v")
shopt -s nullglob
VIDEO_FILE=""
for ext in "${VIDEO_EXTS[@]}"; do
files=(*."$ext")
if [ ${#files[@]} -gt 0 ]; then
VIDEO_FILE="${files[0]}"
break
fi
done
if [ -z "$VIDEO_FILE" ]; then
echo "No supported video files found in the current directory."
exit 1
fi
echo "Video File: ${VIDEO_FILE}"
base="${VIDEO_FILE%.*}"
ext="${VIDEO_FILE##*.}"
PROCESSED_DIR="processed"
OUTPUT_DIR="target/${base}"
mkdir -p "${OUTPUT_DIR}"
mkdir -p "${PROCESSED_DIR}"
max=0
for f in "${OUTPUT_DIR}/${base}_"*.${ext}; do
num=${f##*_}
num=${num%.${ext}}
(( num > max )) && max=$num
done
index=$(printf "%03d" $((max + 1)))
OUTPUT_FILE="${OUTPUT_DIR}/${base}_${index}.${ext}"
SOURCE_PATH="${VIDEO_FILE}"
if $move_source; then
mv "${VIDEO_FILE}" "${PROCESSED_DIR}/"
SOURCE_PATH="${PROCESSED_DIR}/${VIDEO_FILE}"
fi
LOGS_DIR="logs"
mkdir -p "${LOGS_DIR}"
LOG_FILE="${LOGS_DIR}/${base}.log"
export VIDEO_TAG="CLIP"
if $background; then
echo "Processing ${VIDEO_FILE} in the background..."
nohup bash -c "VIDEO_TAG='${VIDEO_TAG}' ffmpeg -i '${SOURCE_PATH}' -ss '${START_CUT}' -to '${END_CUT}' -max_muxing_queue_size 102400 '${OUTPUT_FILE}'" >> "${LOG_FILE}" 2>&1 &
echo "Clip complete! Output is in ${OUTPUT_FILE}"
echo "Log file: ${LOG_FILE}"
else
VIDEO_TAG="${VIDEO_TAG}" ffmpeg -i "${SOURCE_PATH}" -ss "${START_CUT}" -to "${END_CUT}" -max_muxing_queue_size 102400 "${OUTPUT_FILE}" 2>&1 | tee "${LOG_FILE}"
echo "Clip complete! Output is in ${OUTPUT_FILE}"
echo "Log file: ${LOG_FILE}"
fi

View File

@@ -0,0 +1,76 @@
#!/bin/bash
# Usage function to display help
usage() {
echo "Usage: $0 [-no-source-mv] timestamp"
echo "e.g., $0 01:37:18 23:59:59"
}
# Check for the optional background flag
background=false
move_source=true
if [[ "$1" == "-no-source-mv" ]]; then
move_source=false
shift
fi
# Verify timestamp was provided
if [ "$#" -ne 2 ]; then
usage
exit 1
fi
# Find the first .mp4 file
shopt -s nullglob
mp4_files=(*.mp4)
VIDEO_FILE="${mp4_files[0]}"
if [ -z "$VIDEO_FILE" ]; then
echo "No .mp4 files found in the current directory."
exit 1
fi
echo "Video File: ${VIDEO_FILE}"
# Setting up directories
START_CUT="$1"
END_CUT="$2"
PROCESSED_DIR="processed"
OUTPUT_DIR="target"
base="${VIDEO_FILE%.*}"
run=$(date +%Y%m%d_%H%M%S)
RUN_DIR="${OUTPUT_DIR}/${base}/${base} - ${run}"
OUTPUT_FILE="${RUN_DIR}/${base} - ${run} - %03d.png"
# Create directories
mkdir -p "${RUN_DIR}"
mkdir -p "${PROCESSED_DIR}"
# Move the source video to the "processed" directory
SOURCE_PATH="${VIDEO_FILE}"
if $move_source; then
mv "${VIDEO_FILE}" "${PROCESSED_DIR}/"
SOURCE_PATH="${PROCESSED_DIR}/${VIDEO_FILE}"
fi
LOGS_DIR="logs"
mkdir -p "${LOGS_DIR}"
LOG_FILE="${LOGS_DIR}/$(basename "${VIDEO_FILE}" .mp4).log"
export VIDEO_TAG="SCREENSHOT"
# Run ffmpeg command with output redirection to log file
if $background; then
echo "Processing ${VIDEO_FILE} in the background..."
nohup bash -c "VIDEO_TAG='${VIDEO_TAG}' ./ffmpeg -ss '${START_CUT}' -to '${END_CUT}' -i '${SOURCE_PATH}' -vf \"select='eq(pict_type,PICT_TYPE_I)'\" -vsync vfr '${OUTPUT_FILE}'" >> "${LOG_FILE}" 2>&1 &
echo "Extracting screenshots complete! Output is in ${OUTPUT_FILE}"
echo "Log file: ${LOG_FILE}"
else
VIDEO_TAG="${VIDEO_TAG}" ./ffmpeg -ss "${START_CUT}" -to "${END_CUT}" -i "${SOURCE_PATH}" -vf "select='eq(pict_type,PICT_TYPE_I)'" -vsync vfr "${OUTPUT_FILE}" 2>&1 | tee "${LOG_FILE}"
echo "Extracting screenshots complete! Output is in ${OUTPUT_FILE}"
echo "Log file: ${LOG_FILE}"
fi

View File

@@ -0,0 +1,42 @@
#!/usr/bin/env bash
set -e
IMG=$(find . -type f -iname "folder.jpg" | fzf --preview 'convert {} -resize 200x - | display jpg:-' --prompt="Select poster to mark deleted: ")
[ -z "$IMG" ] && exit 0
BACKUP="${IMG}.bak"
cp "$IMG" "$BACKUP"
WIDTH=$(identify -format "%w" "$IMG")
BADGEW=$((WIDTH / 3))
BADGEH=$((WIDTH / 10))
RADIUS=$((BADGEH / 2))
FONTSIZE=$((BADGEH / 2))
OFFSET=$((WIDTH / 40))
convert "$IMG" \
\( -size ${BADGEW}x${BADGEH} xc:none \
-fill "rgba(0,0,0,0.35)" \
-draw "roundrectangle 0,0 ${BADGEW},${BADGEH} ${RADIUS},${RADIUS}" \
\) \
-gravity northeast -geometry +$((OFFSET+3))+$((OFFSET+3)) -composite \
\( -size ${BADGEW}x${BADGEH} xc:none \
-fill "rgba(220,53,69,0.95)" \
-draw "roundrectangle 0,0 ${BADGEW},${BADGEH} ${RADIUS},${RADIUS}" \
-gravity center \
-fill white \
-font DejaVu-Sans-Bold \
-pointsize ${FONTSIZE} \
-annotate +0+0 "DELETED" \
\) \
-gravity northeast -geometry +${OFFSET}+${OFFSET} -composite \
-quality 95 \
"$IMG"
echo "Marked deleted: $IMG"
echo "Backup stored at: $BACKUP"

View File

@@ -0,0 +1,254 @@
#!/bin/bash
CLIP_SCRIPT="./clip.sh"
FRAME_SCRIPT="./frames.sh"
QUEUE_FILE="/tmp/clip_queue.txt"
> "$QUEUE_FILE"
RED="\033[31m"
GREEN="\033[32m"
YELLOW="\033[33m"
BLUE="\033[34m"
CYAN="\033[36m"
NC="\033[0m"
video=""
declare -a queue
pick_video() {
#video=$(ls *.mp4 2>/dev/null | fzf --prompt="Select video > ")
video=$(find . -maxdepth 1 -type f \( -iname "*.mp4" -o -iname "*.mkv" \) | fzf --prompt="Select video > ")
if [[ -n "$video" ]]; then
echo "Selected: $video"
else
echo "No selection."
fi
}
preview_timestamp() {
if [[ -z "$video" ]]; then
echo "No video selected"
return
fi
ts="$1"
mpv --quiet --hr-seek=yes --start="$ts" "$video"
}
scrub_video() {
if [[ -z "$video" ]]; then
echo "No video selected"
return
fi
export SCRUB_QUEUE="$QUEUE_FILE"
mpv --keep-open=yes \
--pause \
"$video"
echo ""
echo "Importing marks..."
while read -r line; do
queue+=("$line")
echo "queued $line"
done < "$QUEUE_FILE"
}
show_queue() {
if [ ${#queue[@]} -eq 0 ]; then
echo -e "${YELLOW}(queue empty)${NC}"
return
fi
i=1
for job in "${queue[@]}"; do
type=$(echo "$job" | awk '{print $1}')
start=$(echo "$job" | awk '{print $2}')
end=$(echo "$job" | awk '{print $3}')
if [[ "$type" == "c" ]]; then
label="CLIP"
color=$BLUE
else
label="FRAMES"
color=$CYAN
fi
echo -e " $i. ${color}$label${NC} $start → $end"
((i++))
done
}
save_config() {
if [[ -z "$video" ]]; then
echo "No video selected"
return
fi
name=$(basename "$video")
name="${name%.*}"
dir="./target/$name"
mkdir -p "$dir"
conf="$dir/video-clipper.conf"
{
echo "video=$video"
echo ""
echo "[jobs]"
for job in "${queue[@]}"; do
echo "$job"
done
} > "$conf"
echo -e "${GREEN}Saved config:${NC} $conf"
}
load_config() {
conf="$1"
if [[ ! -f "$conf" ]]; then
echo "Config not found: $conf"
return
fi
queue=()
video=""
mode=""
> "$QUEUE_FILE"
while IFS= read -r line; do
[[ -z "$line" || "$line" =~ ^[[:space:]]*# ]] && continue
if [[ "$line" == "[jobs]" ]]; then
mode="jobs"
continue
fi
if [[ "$line" == video=* ]]; then
video="${line#video=}"
continue
fi
if [[ "$mode" == "jobs" ]]; then
queue+=("$line")
echo "$line" >> "$QUEUE_FILE"
fi
done < "$conf"
echo -e "${GREEN}Loaded config:${NC} $conf"
echo "video: $video"
echo "jobs: ${#queue[@]}"
}
run_queue() {
if [ -z "$video" ]; then
echo -e "${RED}No video selected.${NC}"
return
fi
save_config
for job in "${queue[@]}"; do
type=$(echo "$job" | awk '{print $1}')
start=$(echo "$job" | awk '{print $2}')
end=$(echo "$job" | awk '{print $3}')
echo -e "${GREEN}Running ${type} ${start} -> ${end}${NC}"
if [[ "$type" == "c" ]]; then
$CLIP_SCRIPT -no-source-mv "$start" "$end"
else
$FRAME_SCRIPT -no-source-mv "$start" "$end"
fi
done
queue=()
> "$QUEUE_FILE"
echo -e "${GREEN}Queue finished.${NC}"
}
echo -e "${CYAN}FFmpeg Clip Console${NC}"
echo "commands: video, c, f, list, undo, go, quit"
while true; do
read -e -p "> " cmd a b
case "$cmd" in
video)
pick_video
;;
p)
preview_timestamp "$a"
;;
c)
queue+=("c $a $b")
echo -e "${BLUE}queued clip${NC} $a -> $b"
;;
f)
queue+=("f $a $b")
echo -e "${CYAN}queued frames${NC} $a -> $b"
;;
list)
show_queue
;;
del)
idx=$a
unset 'queue[$((idx-1))]'
queue=("${queue[@]}")
;;
scrub)
scrub_video
;;
undo)
unset 'queue[-1]'
echo "removed last job"
;;
go)
run_queue
;;
quit|exit)
break
;;
load)
conf=$(find ./target -type f -name "video-clipper.conf" \
| fzf --prompt="Select config > " \
--preview 'grep "^video=" {}')
if [[ -n "$conf" ]]; then
load_config "$conf"
else
echo "No selection."
fi
;;
*)
echo -e "${YELLOW}commands: video | scrub | p start | c start end | f start end | list | undo | go | quit${NC}"
;;
esac
done

View File

@@ -0,0 +1,13 @@
docker run --rm \
--volume=./video-renamer:/mnt \
jkwill87/mnamer \
--language de \
--no-guess \
--no-overwrite \
--movie-format "{name} ({year}){extension}" \
--episode-format "{series} S{season:02}E{episode:02}{extension}" \
--movie-directory "/mnt/movies/{name} ({year})" \
--episode-directory "/mnt/shows/{series}" \
-b \
--test \
/mnt

View File

@@ -0,0 +1,169 @@
#!/usr/bin/env bash
set -euo pipefail
video=$(find . -type f \( \
-iname "*.mp4" -o \
-iname "*.mkv" -o \
-iname "*.webm" -o \
-iname "*.mov" -o \
-iname "*.avi" \
\) | fzf --prompt="Select video: ")
[ -z "${video:-}" ] && exit 0
config="${video%.*}.jobs"
echo
echo "Choose detection method:"
echo "1) freeze (almost identical frames)"
echo "2) motion (low motion using frame differences)"
echo "3) both"
read -rp "Selection: " mode
case "$mode" in
1) method="freeze" ;;
2) method="motion" ;;
3) method="both" ;;
*) echo "Invalid choice"; exit 1 ;;
esac
freeze_noise=""
freeze_dur=""
motion_amount=""
motion_thresh=""
if [[ "$method" == "freeze" || "$method" == "both" ]]; then
read -rp "freeze noise threshold n (default 0.005): " freeze_noise
freeze_noise="${freeze_noise:-0.005}"
read -rp "freeze minimum duration seconds d (default 2): " freeze_dur
freeze_dur="${freeze_dur:-2}"
fi
if [[ "$method" == "motion" || "$method" == "both" ]]; then
read -rp "motion blackframe percent amount (default 98): " motion_amount
motion_amount="${motion_amount:-98}"
read -rp "motion threshold (default 20): " motion_thresh
motion_thresh="${motion_thresh:-20}"
fi
read -rp "merge gap tolerance seconds (default 3): " merge_gap
merge_gap="${merge_gap:-3}"
read -rp "minimum segment length seconds (default 3): " min_len
min_len="${min_len:-3}"
echo
echo "Video: $video"
echo "Method: $method"
if [[ -f "$config" ]]; then
read -rp "Config exists ($config). Append run? [y/N]: " yn
[[ "$yn" =~ ^[Yy]$ ]] || exit 0
fi
tmp=$(mktemp)
run_freeze () {
ffmpeg -hide_banner -i "$video" \
-vf "freezedetect=n=${freeze_noise}:d=${freeze_dur}" \
-f null - 2>&1 | \
awk '
/freeze_start/ {s=$NF}
/freeze_end/ {printf "%s %s\n", s, $NF}
'
}
run_motion () {
ffmpeg -hide_banner -i "$video" \
-vf "tblend=all_mode=difference,blackframe=amount=${motion_amount}:threshold=${motion_thresh}" \
-f null - 2>&1 | \
awk '
/black_start/ {s=$NF}
/black_end/ {printf "%s %s\n", s, $NF}
'
}
{
if [[ "$method" == "freeze" ]]; then
run_freeze
elif [[ "$method" == "motion" ]]; then
run_motion
else
run_freeze
run_motion
fi
} | sort -n -k1 | awk -v gap="$merge_gap" -v minlen="$min_len" '
{
start=$1
end=$2
if (NR==1) {
cur_s=start
cur_e=end
next
}
# overlapping or small gap
if (start <= cur_e + gap) {
if (end > cur_e)
cur_e=end
}
else {
if (cur_e-cur_s >= minlen)
printf "%f %f\n", cur_s, cur_e
cur_s=start
cur_e=end
}
}
END {
if (NR>0 && cur_e-cur_s >= minlen)
printf "%f %f\n", cur_s, cur_e
}
' > "$tmp"
if [[ ! -s "$tmp" ]]; then
rm -f "$tmp"
echo "No quiet scenes detected."
exit 0
fi
if [[ ! -f "$config" ]]; then
{
echo "video=$video"
echo
echo "[jobs]"
} > "$config"
fi
{
echo
echo "# run method=$method $(date)"
if [[ "$method" == "freeze" || "$method" == "both" ]]; then
echo "# freeze n=$freeze_noise d=$freeze_dur"
fi
if [[ "$method" == "motion" || "$method" == "both" ]]; then
echo "# motion amount=$motion_amount threshold=$motion_thresh"
fi
awk '{printf "d %s %s\n",$1,$2}'
} < "$tmp" >> "$config"
rm -f "$tmp"
entries=$(grep -c '^d ' "$config" || true)
if [[ "$entries" -eq 0 ]]; then
echo "No job entries created. Removing config."
rm -f "$config"
else
echo
echo "Jobs written to $config"
tail -n 10 "$config"
fi

View File

@@ -0,0 +1,4 @@
./video-splicer.sh good-video.mkv bad-video-but-good-audio.mkv out.mkv
./video-splicer.sh --auto --done-dir finished/ --out-dir merged/ one.mkv two.mkv final.mkv
./video-splicer-wizard.sh --done-dir "./processed"

View File

@@ -0,0 +1,261 @@
#!/usr/bin/env bash
set -Eeuo pipefail
require() {
command -v "$1" >/dev/null || {
echo "Missing dependency: $1"
exit 1
}
}
strip_resolution_tag() {
echo "$1" | sed -E 's/ ?\[[0-9]{3,4}p\]//g'
}
require ffprobe
require jq
SCAN_DIR="."
DONE_DIR=""
DRY_RUN=0
MOVE_NON_GER=1
MOVE_ALL=0
ENGINE="./video-splicer.sh"
LOG_DIR="${LOG_DIR:-./logs}"
while [[ $# -gt 0 ]]; do
case "$1" in
--scan)
SCAN_DIR="$2"
shift
;;
--done-dir)
DONE_DIR="$2"
shift
;;
--engine)
ENGINE="$2"
shift
;;
--dry-run)
DRY_RUN=1
;;
--no-move-non-ger)
MOVE_NON_GER=0
;;
--move-all)
MOVE_ALL=1
;;
*)
echo "Unknown flag $1"
exit 1
;;
esac
shift
done
mkdir -p "$LOG_DIR"
RUN_ID=$(date +"%Y%m%d_%H%M%S")_$RANDOM
LOG_FILE="$LOG_DIR/automerge_$RUN_ID.log"
log() {
echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] $*" | tee -a "$LOG_FILE"
}
log_json() {
jq -nc "$@" >> "$LOG_FILE"
}
probe_json() {
ffprobe -v error -print_format json -show_streams "$1"
}
has_german_audio() {
local json="$1"
count=$(echo "$json" | jq '[.streams[]
| select(.codec_type=="audio")
| select(.tags.language=="ger" or .tags.language=="deu")] | length')
[[ "$count" -gt 0 ]] && echo 1 || echo 0
}
has_english_audio() {
local json="$1"
count=$(echo "$json" | jq '[.streams[]
| select(.codec_type=="audio")
| select(.tags.language=="eng")] | length')
[[ "$count" -gt 0 ]] && echo 1 || echo 0
}
video_score() {
local file="$1"
RESOLUTION=$(ffprobe -v error \
-select_streams v:0 \
-show_entries stream=width,height \
-of csv=p=0:s=x \
"$file" | head -n1)
width=$(echo $RESOLUTION | cut -d'x' -f1)
height=$(echo $RESOLUTION | cut -d'x' -f2)
score=$((width * height))
echo "$score"
}
process_movie_dir() {
dir="$1"
log "Scanning $dir"
mapfile -t files < <(find "$dir" -maxdepth 1 -type f \( -iname "*.mkv" -o -iname "*.mp4" \))
if [[ ${#files[@]} -lt 2 ]]; then
log "Skipping $dir (need >=2 files)"
return
fi
GER_FILES=()
NON_GER_FILES=()
declare -A PROBE_CACHE
for f in "${files[@]}"; do
log "Checking file $f"
json=$(probe_json "$f")
PROBE_CACHE["$f"]="$json"
ger=$(has_german_audio "$json")
if [[ "$ger" -eq 1 ]]; then
GER_FILES+=("$f")
else
NON_GER_FILES+=("$f")
fi
done
if [[ ${#GER_FILES[@]} -eq 0 ]]; then
log "No German tracks detected. Skip."
return
fi
if [[ ${#NON_GER_FILES[@]} -eq 0 ]]; then
log "All files already contain German audio. Likely resolution variants. Skip."
return
fi
best_file=""
best_score=0
for f in "${NON_GER_FILES[@]}"; do
score=$(video_score "$f")
if ((score > best_score)); then
best_score="$score"
best_file="$f"
fi
done
if [[ -z "$best_file" ]]; then
log "No suitable primary source found"
return
fi
inputs=("$best_file")
for f in "${GER_FILES[@]}"; do
inputs+=("$f")
done
base=$(basename "$best_file")
name="${base%.*}"
BASE_CLEAN=$(strip_resolution_tag "$name")
EXTENSION="${base##*.}"
OUT_FILE="$dir/${BASE_CLEAN}.${EXTENSION}"
counter=1
final_out="$OUT_FILE"
while [[ -e "$final_out" ]]; do
final_out="$dir/${BASE_CLEAN}.${EXTENSION}.spliced${counter}"
((counter++))
done
OUT_FILE="$final_out"
log "Merge candidate detected"
log "Primary video: $best_file"
log "GER sources: ${GER_FILES[*]}"
log "Output: $OUT_FILE"
log_json \
--arg dir "$dir" \
--arg primary "$best_file" \
--argjson ger "$(printf '%s\n' "${GER_FILES[@]}" | jq -R . | jq -s .)" \
'{
event:"merge_candidate",
directory:$dir,
primary_source:$primary,
german_sources:$ger
}'
if [[ "$DRY_RUN" -eq 1 ]]; then
log "DRY RUN: skipping merge"
return
fi
cmd=("$ENGINE" --auto)
for f in "${inputs[@]}"; do
cmd+=("$f")
done
cmd+=("$OUT_FILE")
log "Executing merge engine"
"${cmd[@]}"
if [[ "$MOVE_NON_GER" -eq 1 && -n "$DONE_DIR" ]]; then
mkdir -p "$DONE_DIR"
mv "$best_file" "$DONE_DIR/"
log "Moved non-german source $best_file"
fi
if [[ "$MOVE_ALL" -eq 1 && -n "$DONE_DIR" ]]; then
for f in "${GER_FILES[@]}"; do
mv "$f" "$DONE_DIR/"
done
fi
log "Merge finished for $dir"
}
export -f process_movie_dir
export -f probe_json
export -f has_german_audio
export -f has_english_audio
export -f video_score
export ENGINE DRY_RUN LOG_FILE DONE_DIR MOVE_NON_GER MOVE_ALL
log "Starting automerge scan of $SCAN_DIR"
#mapfile -t dirs < <(find "$SCAN_DIR" -type d)
#for d in "${dirs[@]}"; do
# process_movie_dir "$d"
#done
process_movie_dir "$SCAN_DIR"
log "Scan complete"

View File

@@ -0,0 +1,348 @@
#!/usr/bin/env bash
set -Eeuo pipefail
require() {
command -v "$1" >/dev/null || {
echo "Missing dependency: $1"
exit 1
}
}
require ffmpeg
require ffprobe
require jq
ARGS=()
AUTO=0
DONE_DIR=""
OUT_DIR=""
while [[ $# -gt 0 ]]; do
case "$1" in
--auto) AUTO=1 ;;
--done-dir)
DONE_DIR="$2"
shift
;;
--out-dir)
OUT_DIR="$2"
shift
;;
*) ARGS+=("$1") ;;
esac
shift
done
if [[ ${#ARGS[@]} -lt 2 ]]; then
echo "Usage: merge.sh input1 [input2 ...] output"
exit 1
fi
OUT="${ARGS[-1]}"
unset 'ARGS[-1]'
INPUT_FILES=("${ARGS[@]}")
LOG_DIR="${LOG_DIR:-./logs}"
mkdir -p "$LOG_DIR"
START_TIME=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
RUN_ID=$(date +"%Y%m%d_%H%M%S")_$RANDOM
LOG_FILE="$LOG_DIR/merge_$(basename "$OUT")_${RUN_ID}.log"
log_json() { jq -nc "$@" >>"$LOG_FILE"; }
log() { echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] $*" | tee -a "$LOG_FILE"; }
probe() { ffprobe -loglevel error -print_format json -show_streams "$1"; }
declare -a INPUT_JSONS
for f in "${INPUT_FILES[@]}"; do
INPUT_JSONS+=("$(probe "$f")")
done
log "Starting merge run $RUN_ID"
log_json \
--arg time "$START_TIME" \
--argjson sources "$(printf '%s\n' "${INPUT_FILES[@]}" | jq -R . | jq -s .)" \
'{event:"sources_detected",timestamp:$time,sources:$sources}'
declare -A STREAM_FILE
declare -A STREAM_INDEX
declare -A STREAM_TYPE
declare -A STREAM_CODEC
declare -A STREAM_LANG
declare -A STREAM_CHANNELS
declare -A STREAM_TITLE
declare -A STREAM_SCORE
declare -A STREAM_WIDTH
declare -A STREAM_HEIGHT
ALL_STREAMS=()
check_sources() {
base="${INPUT_FILES[0]}"
for cur in "${INPUT_FILES[@]:1}"; do
echo
echo "==== SOURCE COMPAT CHECK ===="
d1=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$base")
d2=$(ffprobe -v error -show_entries format=duration -of csv=p=0 "$cur")
diff=$(awk -v a="$d1" -v b="$d2" 'BEGIN{print (a>b)?a-b:b-a}')
printf "Duration base: %.3f\n" "$d1"
printf "Duration curr: %.3f\n" "$d2"
printf "Δ difference : %.3f\n" "$diff"
fps1=$(ffprobe -v error -select_streams v:0 -show_entries stream=r_frame_rate -of csv=p=0 "$base")
fps2=$(ffprobe -v error -select_streams v:0 -show_entries stream=r_frame_rate -of csv=p=0 "$cur")
echo "FPS base : $fps1"
echo "FPS curr : $fps2"
risk=0
if [[ "$fps1" != "$fps2" ]]; then
echo "⚠ FPS mismatch"
risk=1
fi
awk_check=$(awk -v d="$diff" 'BEGIN{print (d>2)?1:0}')
if [[ "$awk_check" == 1 ]]; then
echo "⚠ Duration >2s"
risk=2
fi
if [[ $risk -eq 2 ]]; then
echo "❌ Sources incompatible"
exit 1
elif [[ $risk -eq 1 ]]; then
read -rp "Potential risk detected. Continue? [y/N]: " ans
[[ "$ans" =~ ^[Yy]$ ]] || exit 1
else
echo "✅ Compatible"
fi
done
}
detect_commentary() {
shopt -s nocasematch
[[ "$1" =~ commentary ]] && echo 1 || echo 0
}
score_video() {
codec=$1
width=$2
height=$3
bitrate=$4
score=0
case "$codec" in
av1) score=100 ;;
hevc) score=90 ;;
h264) score=80 ;;
*) score=50 ;;
esac
pixels=$((width * height))
((score += pixels / 500000))
[[ "$bitrate" != null ]] && ((score += bitrate / 1000000))
echo "$score"
}
score_audio() {
codec=$1
lang=$2
ch=$3
commentary=$4
score=0
case "$lang" in
ger | deu) score=1000 ;;
eng) score=200 ;;
*) score=100 ;;
esac
case "$codec" in
truehd) ((score += 100)) ;;
dts*) ((score += 90)) ;;
ac3) ((score += 70)) ;;
aac) ((score += 60)) ;;
*) ((score += 40)) ;;
esac
((score += ch * 5))
[[ "$commentary" == 1 ]] && ((score -= 150))
echo "$score"
}
audio_sig() {
echo "${STREAM_CODEC[$1]}-${STREAM_LANG[$1]}-${STREAM_CHANNELS[$1]}-${STREAM_SCORE[$1]}"
}
add_streams() {
filetag="$1"
json="$2"
mapfile -t rows < <(echo "$json" | jq -c '.streams[]')
for row in "${rows[@]}"; do
idx=$(jq -r '.index' <<<"$row")
type=$(jq -r '.codec_type' <<<"$row")
codec=$(jq -r '.codec_name' <<<"$row")
lang=$(jq -r '.tags.language // "unknown"' <<<"$row")
title=$(jq -r '.tags.title // ""' <<<"$row")
channels=$(jq -r '.channels // 0' <<<"$row")
width=$(jq -r '.width // 0' <<<"$row")
height=$(jq -r '.height // 0' <<<"$row")
bitrate=$(jq -r '.bit_rate // 0' <<<"$row")
id="${filetag}:${idx}"
STREAM_FILE[$id]=$filetag
STREAM_INDEX[$id]=$idx
STREAM_TYPE[$id]=$type
STREAM_CODEC[$id]=$codec
STREAM_LANG[$id]=$lang
STREAM_CHANNELS[$id]=$channels
STREAM_TITLE[$id]=$title
STREAM_WIDTH[$id]=$width
STREAM_HEIGHT[$id]=$height
score=0
if [[ "$type" == video ]]; then
score=$(score_video "$codec" "$width" "$height" "$bitrate")
fi
if [[ "$type" == audio ]]; then
comm=$(detect_commentary "$title")
score=$(score_audio "$codec" "$lang" "$channels" "$comm")
fi
STREAM_SCORE[$id]=$score
ALL_STREAMS+=("$id")
done
}
check_sources
declare -A TAG_TO_INPUT
for i in "${!INPUT_FILES[@]}"; do
tag="f$i"
TAG_TO_INPUT[$tag]=$i
add_streams "$tag" "${INPUT_JSONS[$i]}"
done
echo
echo "==== STREAM INVENTORY ===="
for id in "${ALL_STREAMS[@]}"; do
if [[ ${STREAM_TYPE[$id]} == video ]]; then
echo "$id video ${STREAM_WIDTH[$id]}x${STREAM_HEIGHT[$id]} ${STREAM_CODEC[$id]} score=${STREAM_SCORE[$id]}"
else
echo "$id ${STREAM_TYPE[$id]} ${STREAM_LANG[$id]} ${STREAM_CODEC[$id]} score=${STREAM_SCORE[$id]}"
fi
done
mapfile -t VIDEO < <(for s in "${ALL_STREAMS[@]}"; do [[ ${STREAM_TYPE[$s]} == video ]] && echo "$s ${STREAM_SCORE[$s]}"; done | sort -k2 -nr)
mapfile -t AUDIO < <(for s in "${ALL_STREAMS[@]}"; do [[ ${STREAM_TYPE[$s]} == audio ]] && echo "$s ${STREAM_SCORE[$s]}"; done | sort -k2 -nr)
mapfile -t SUBS < <(for s in "${ALL_STREAMS[@]}"; do [[ ${STREAM_TYPE[$s]} == subtitle ]] && echo "$s"; done)
ORDER=()
best_video=$(awk '{print $1}' <<<"${VIDEO[0]}")
ORDER+=("$best_video")
declare -A AUDIO_SEEN
for a in "${AUDIO[@]}"; do
id=$(awk '{print $1}' <<<"$a")
sig=$(audio_sig "$id")
if [[ -z "${AUDIO_SEEN[$sig]+x}" ]]; then
ORDER+=("$id")
AUDIO_SEEN[$sig]=1
fi
done
for s in "${SUBS[@]}"; do
ORDER+=($(awk '{print $1}' <<<"$s"))
done
if [[ "$AUTO" -eq 1 ]]; then
ans=y
else
read -rp "Accept layout? [Y/n/edit]: " ans
fi
MAP=()
for s in "${ORDER[@]}"; do
tag="${STREAM_FILE[$s]}"
input_index="${TAG_TO_INPUT[$tag]}"
MAP+=(-map "${input_index}:${STREAM_INDEX[$s]}")
done
TMP="${OUT}.tmp.mkv"
INPUT_ARGS=()
for f in "${INPUT_FILES[@]}"; do
INPUT_ARGS+=(-i "$f")
done
BUILD_LOG_B64=$(base64 -w0 "$LOG_FILE")
FF_CMD=(ffmpeg "${INPUT_ARGS[@]}"
"${MAP[@]}"
-map_chapters 0
-c copy
-metadata build_input_files="${INPUT_FILES[*]}"
-metadata building_log="$BUILD_LOG_B64"
-metadata build_time="$(date -u +"%Y-%m-%dT%H:%M:%SZ")"
-metadata build_stream_map="${MAP[*]}"
-stats -stats_period 1
-reset_timestamps 1
-fflags +genpts
-avoid_negative_ts make_zero
-max_interleave_delta 0
"$TMP")
log_json --arg cmd "${FF_CMD[*]}" '{event:"ffmpeg_command",command:$cmd}'
"${FF_CMD[@]}" 2>&1 | tee -a "$LOG_FILE"
FINAL_OUT="$OUT"
if [[ -n "$OUT_DIR" ]]; then
mkdir -p "$OUT_DIR"
FINAL_OUT="$OUT_DIR/$(basename "$OUT")"
fi
mv "$TMP" "$FINAL_OUT"
echo "Created $FINAL_OUT"
if [[ "$AUTO" -eq 1 && -n "$DONE_DIR" ]]; then
mkdir -p "$DONE_DIR/$(basename "$OUT")"
for f in "${INPUT_FILES[@]}"; do
mv "$f" "$DONE_DIR/$(basename "$OUT")/"
done
fi

View File

@@ -0,0 +1,26 @@
#!/bin/bash
VIDEO_FOLDER="./0-auto-split-input"
ROWS=3
OUTPUT_DIR="./0-multi-input"
mkdir -p "$OUTPUT_DIR"
cd "$VIDEO_FOLDER"
index=1
files_per_row=$((($(ls | wc -l) + ROWS - 1) / ROWS))
for file in *.mp4 *.mov *.avi *.m4v; do
if [ ! -f "$file" ]; then
continue
fi
folder_index=$(( (index - 1) / files_per_row ))
mkdir -p "$OUTPUT_DIR/horizontal-$folder_index"
mv "$file" "$OUTPUT_DIR/horizontal-$folder_index/"
((index++))
done

View File

@@ -0,0 +1,22 @@
#!/bin/bash
TARGET_DIR="./0-input"
if [ ! -d "$TARGET_DIR" ]; then
echo "---->>>> Error: Directory '$TARGET_DIR' does not exist."
exit 1
fi
cd "$TARGET_DIR"
for gif in *.gif; do
if [ -f "$gif" ]; then
mp4="${gif%.gif}.mp4"
if ffmpeg -hide_banner -loglevel error -i "$gif" -movflags faststart -pix_fmt yuv420p -vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" "$mp4"; then
echo "---->>>> Converted $gif to $mp4 successfully."
rm "$gif"
else
echo "---->>>> Failed to convert $gif."
fi
fi
done

View File

@@ -0,0 +1,31 @@
#!/bin/bash
TARGET_DIR="./0-input"
DURATION=1 # seconds per image
if [ ! -d "$TARGET_DIR" ]; then
echo "---->>>> Error: Directory '$TARGET_DIR' does not exist."
exit 1
fi
cd "$TARGET_DIR"
for img in *.png *.jpg *.jpeg *.webp; do
if [ -f "$img" ]; then
mp4="${img%.*}.mp4"
if ffmpeg -hide_banner -loglevel error \
-loop 1 -i "$img" \
-t $DURATION \
-movflags faststart \
-pix_fmt yuv420p \
-vf "scale=trunc(iw/2)*2:trunc(ih/2)*2" \
"$mp4"; then
echo "---->>>> Converted $img to $mp4 successfully."
rm "$img"
else
echo "---->>>> Failed to convert $img."
fi
fi
done

View File

@@ -0,0 +1,27 @@
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <height>"
exit 1
fi
COMMON_HEIGHT=$1
INPUT_DIR="./0-input"
OUTPUT_DIR="./1-scaled"
mkdir -p "$OUTPUT_DIR"
for video_file in "$INPUT_DIR"/*.{mp4,mov,avi,m4v}; do
if [ -f "$video_file" ]; then
base_name=$(basename "$video_file")
output_file="$OUTPUT_DIR/$base_name"
ffmpeg -y -i "$video_file" -vf "scale='ceil($COMMON_HEIGHT*a/2)*2:$COMMON_HEIGHT'" -c:a copy "$output_file"
rm "$video_file"
echo "---->>>> Scaled $video_file to have a height of $COMMON_HEIGHT pixels and even width."
fi
done
echo "---->>>> All videos have been scaled to a common height of $COMMON_HEIGHT pixels with even widths."

View File

@@ -0,0 +1,27 @@
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <common_width>"
exit 1
fi
COMMON_WIDTH=$1
INPUT_DIR="./0-input"
OUTPUT_DIR="./1-scaled"
mkdir -p "$OUTPUT_DIR"
for video_file in "$INPUT_DIR"/*.{mp4,mov,avi,m4v}; do
if [ -f "$video_file" ]; then
base_name=$(basename "$video_file")
output_file="$OUTPUT_DIR/$base_name"
ffmpeg -y -i "$video_file" -vf "scale=$COMMON_WIDTH:'ceil(ow/a/2)*2'" -c:a copy "$output_file"
rm "$video_file"
echo "---->>>> Scaled $video_file to have a width of $COMMON_WIDTH pixels and even height."
fi
done
echo "---->>>> All videos have been scaled to a common width of $COMMON_WIDTH pixels with even heights."

View File

@@ -0,0 +1,31 @@
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <duration>"
exit 1
fi
DURATION=$1
INPUT_DIR="./1-scaled"
OUTPUT_DIR="./2-looped"
mkdir -p "$OUTPUT_DIR"
for video_file in "$INPUT_DIR"/*; do
if [[ $video_file == *.mp4 ]] || [[ $video_file == *.mov ]] || [[ $video_file == *.avi ]] || [[ $video_file == *.m4v ]]; then
filename=$(basename -- "$video_file")
extension="${filename##*.}"
filename="${filename%.*}"
output_file="${OUTPUT_DIR}/${filename}.${extension}"
ffmpeg -y -stream_loop -1 -i "$video_file" -c copy -t "$DURATION" -f mp4 -y "$output_file"
rm "$video_file"
echo "---->>>> Generated looped video: $output_file"
else
echo "---->>>> Skipping non-video file: $video_file"
fi
done
echo "---->>>> All videos processed."

View File

@@ -0,0 +1,57 @@
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <output_name>"
exit 1
fi
OUTPUT_FILE=$1
INPUT_DIR="./2-looped"
OUTPUT_DIR="./3-output"
mkdir -p $OUTPUT_DIR
mapfile -t video_files < <(
find "$INPUT_DIR" -maxdepth 1 -type f \( \
-iname "*.mp4" -o -iname "*.mov" -o -iname "*.avi" -o -iname "*.m4v" -o -iname "*.mkv" -o -iname "*.webm" \
\) -printf "%f\n" |
sort -t. -k1,1V |
sed "s|^|$INPUT_DIR/|"
)
if [ "${#video_files[@]}" -lt 2 ]; then
echo "Need at least two video files to concatenate."
exit 1
fi
echo "Found ${#video_files[@]} video files to concatenate."
ffmpeg_cmd="ffmpeg -y"
filter_complex=""
input_count=0
for video_file in "${video_files[@]}"; do
if [[ -f $video_file ]]; then
ffmpeg_cmd+=" -i \"$video_file\""
filter_complex+="[${input_count}:v:0] "
input_count=$((input_count+1))
fi
done
filter_complex+="hstack=inputs=$input_count [v]"
ffmpeg_cmd+=" -filter_complex \"$filter_complex\" -map \"[v]\" \"$OUTPUT_DIR/$OUTPUT_FILE\""
eval $ffmpeg_cmd
if [ $? -eq 0 ]; then
echo "---->>>> Generated concatenated video: $OUTPUT_DIR/$OUTPUT_FILE"
for video_file in "${video_files[@]}"; do
if [ -f "$video_file" ]; then
rm "$video_file"
echo "---->>>> Removed video file: $video_file"
fi
done
else
echo "---->>>> FFmpeg command failed. Video files have not been removed."
fi

View File

@@ -0,0 +1,54 @@
#!/bin/bash
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <output_name>"
exit 1
fi
OUTPUT_FILE=$1
INPUT_DIR="./2-looped"
OUTPUT_DIR="./3-output"
mkdir -p "$OUTPUT_DIR"
video_files=( "$INPUT_DIR"/*.{mp4,mov,avi,m4v} )
if [ "${#video_files[@]}" -lt 2 ]; then
echo "Need at least two video files to concatenate vertically."
exit 1
fi
echo "Found ${#video_files[@]} video files to concatenate vertically."
ffmpeg_cmd="ffmpeg -y"
filter_complex=""
input_count=0
for video_file in "${video_files[@]}"; do
if [[ -f $video_file ]]; then
ffmpeg_cmd+=" -i \"$video_file\""
filter_complex+="[${input_count}:v:0] "
input_count=$((input_count+1))
fi
done
filter_complex+="vstack=inputs=$input_count [v]"
ffmpeg_cmd+=" -filter_complex \"$filter_complex\" -map \"[v]\" \"$OUTPUT_DIR/$OUTPUT_FILE\""
eval $ffmpeg_cmd
if [ $? -eq 0 ]; then
echo "---->>>> Generated concatenated video: $OUTPUT_DIR/$OUTPUT_FILE"
for video_file in "${video_files[@]}"; do
if [ -f "$video_file" ]; then
rm "$video_file"
echo "---->>>> Removed video file: $video_file"
fi
done
else
echo "---->>>> FFmpeg command failed. Video files have not been removed."
fi

View File

@@ -0,0 +1,31 @@
#!/bin/bash
INPUT_DIR="./0-multi-input/vertical-0"
OUTPUT_DIR="./3-output"
largest_width=0
largest_height=0
mkdir -p "$INPUT_DIR"
for video_file in "$OUTPUT_DIR"/*.{mp4,mov,avi,m4v}; do
if [ -f "$video_file" ]; then
filename=$(basename "$video_file")
dimensions=$(ffprobe -v error -select_streams v:0 -show_entries stream=width,height -of csv=p=0 "$video_file")
width=$(echo "$dimensions" | cut -d ',' -f 1)
height=$(echo "$dimensions" | cut -d ',' -f 2)
if [ "$width" -gt "$largest_width" ]; then
largest_width=$width
fi
if [ "$height" -gt "$largest_height" ]; then
largest_height=$height
fi
mv "$video_file" "$INPUT_DIR/$filename"
fi
done
echo "---->>>> Largest Width Found: $largest_width px"
echo "---->>>> Largest Height Found: $largest_height px"
echo "---->>>> All video files have been moved from $OUTPUT_DIR to $INPUT_DIR."

View File

@@ -0,0 +1,32 @@
#!/bin/bash
VIDEO="$1"
DESC="$2"
if [ -z "$VIDEO" ] || [ -z "$DESC" ]; then
echo "Usage: $0 <video_file> <description>"
exit 1
fi
if [ ! -f "$VIDEO" ]; then
echo "Error: file '$VIDEO' not found."
exit 1
fi
TMP="${VIDEO%.*}_meta.${VIDEO##*.}"
ffmpeg -hide_banner -loglevel error \
-i "$VIDEO" \
-map 0 \
-c copy \
-metadata description="$DESC" \
-metadata comment="$DESC" \
"$TMP"
if [ $? -eq 0 ]; then
mv "$TMP" "$VIDEO"
echo "---->>>> Description added successfully."
else
echo "---->>>> Failed to write metadata."
rm -f "$TMP"
fi

View File

@@ -0,0 +1,8 @@
#How to do a multi row auto convert
Row files into 0-multi-input separated into folders, optionally prefixed with index_ for particular order
define horizontal settings in run-full-wizard
run run-full-wizard
run 4-move-to-input
configure vertical in run-full-wizard
run run-full-wizard

View File

@@ -0,0 +1,108 @@
#!/bin/bash
base_dir="./0-multi-input"
TARGET_INPUT="./0-input"
OUTPUT_DIR="./3-output"
DURATION_SECONDS=5
#Do horizontal
PROCESS_HORIZONTAL=true
PROCESS_VERTICAL=false
OUTPUT_NAME_HORIZONTAL="tom-lizard-waving.mp4"
HEIGHT=1920
#Then do vertical
#PROCESS_HORIZONTAL=false
#PROCESS_VERTICAL=true
OUTPUT_NAME_VERTICAL="tom-lizard-waving.mp4"
WIDTH=7000
# Optional description (leave empty to skip)
DESCRIPTION=""
process_horizontal() {
local dir=$1
index=$2
echo "---->>>> Processing horizontal directory: $dir"
mv "$dir"/* "$TARGET_INPUT"/
./0-convert-gif.sh
./0-convert-images.sh
./1-scale-to-height.sh $HEIGHT
./2-loop.sh $DURATION_SECONDS
./3-merge-horizontal.sh "${index}_${OUTPUT_NAME_HORIZONTAL}"
}
process_vertical() {
local dir=$1
index=$2
echo "---->>>> Processing vertical directory: $dir"
mv "$dir"/* "$TARGET_INPUT"/
./0-convert-gif.sh
./0-convert-images.sh
./1-scale-to-width.sh $WIDTH
./2-loop.sh $DURATION_SECONDS
./3-merge-vertical.sh "${index}_${OUTPUT_NAME_VERTICAL}"
}
post_horizontal() {
echo "---->>>> Running scripts after processing all horizontal directories..."
./4-move-to-input.sh
}
post_vertical() {
echo "---->>>> Running scripts after processing all vertical directories..."
}
if [ "$PROCESS_HORIZONTAL" = true ]; then
horizontal_index=0
echo "---->>>> Processing all horizontal directories..."
for dir in "$base_dir"/horizontal*/; do
if [ -d "$dir" ] && [ -n "$(find "$dir" -maxdepth 1 -type f \( -iname "*.mp4" -o -iname "*.mov" -o -iname "*.avi" -o -iname "*.m4v" \) -print -quit)" ]; then
process_horizontal "$dir" "$horizontal_index"
fi
((horizontal_index++))
done
fi
# Call scripts after processing all horizontal directories
#post_horizontal
if [ "$PROCESS_VERTICAL" = true ]; then
vertical_index=0
echo "---->>>> Processing all vertical directories..."
for dir in "$base_dir"/vertical*/; do
if [ -d "$dir" ] && [ -n "$(find "$dir" -maxdepth 1 -type f \( -iname "*.mp4" -o -iname "*.mov" -o -iname "*.avi" -o -iname "*.m4v" \) -print -quit)" ]; then
process_vertical "$dir" "$vertical_index"
fi
((vertical_index++))
done
fi
# Call scripts after processing all vertical directories
#post_vertical
if [ -n "$DESCRIPTION" ]; then
for vid in "$OUTPUT_DIR"/*.{mp4,mkv,mov,webm}; do
./5-metadata.sh "$vid" "$DESCRIPTION"
done
fi
echo "---->>>> All processing complete."

17
misc/open-urls-from-file.sh Executable file
View File

@@ -0,0 +1,17 @@
#!/bin/bash
# Path to the text file containing URLs
url_file="open_urls.txt"
# Check if the file with URLs exists
if [[ ! -f "$url_file" ]]; then
echo "File with URLs not found: $url_file"
exit 1
fi
# Iterate over lines in the file and open each URL
while IFS= read -r url; do
ungoogled-chromium --new-tab "$url"
done < "$url_file"
echo "All URLs have been opened in new tabs."

31
misc/yandex-extract-img-url.sh Executable file
View File

@@ -0,0 +1,31 @@
#!/bin/sh
# Validate input
if [ "$#" -ne 2 ]; then
echo "Usage: $0 <input_file_with_urls> <output_file_for_extracted_img_urls>"
exit 1
fi
input_file="$1"
output_file="$2"
error_file="error_urls.txt"
# Loop through each URL, extract, decode, and save the 'img_url', with indexing
index=0
while IFS= read -r line; do
# Increment our index counter
index=$((index+1))
# Extract the 'img_url' query parameter
extracted_url=$(echo "$line" | awk -F 'img_url=' '{print $2}' | cut -d'&' -f1 | python3 -c "import sys; from urllib.parse import unquote; print(unquote(sys.stdin.read()));")
# Save and print the results
if [ -n "$extracted_url" ]; then
echo "$index: $extracted_url"
echo "$extracted_url" >> "$output_file"
else
echo "$index: No 'img_url' found"
echo "$line" >> "$error_file"
fi
done < "$input_file"

Some files were not shown because too many files have changed in this diff Show More