Upload files to "/"

This commit is contained in:
2026-11-25 20:20:43 -06:00
parent ce7b8f704e
commit c91b953bab
5 changed files with 2752 additions and 0 deletions
+283
View File
@@ -0,0 +1,283 @@
import os
import re
import unicodedata
from pathlib import Path
from dotenv import load_dotenv
from guessit import guessit
from pymediainfo import MediaInfo
BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / "config.env")
MIN_MEDIA_DURATION = float(os.getenv("MIN_MEDIA_DURATION", "30"))
VIDEO_EXTENSIONS = {
".mkv", ".mp4", ".m4v", ".avi", ".mov", ".webm",
".mpg", ".mpeg", ".ts", ".m2ts", ".wmv",
}
NOISE_TOKENS = {
"480p", "576p", "720p", "1080p", "1080i", "1440p", "2160p", "4k", "8k",
"bluray", "blu-ray", "bdrip", "brrip", "web", "webdl", "web-dl", "webrip", "web-rip",
"hdtv", "dvdrip", "remux", "x264", "x265", "h264", "h265", "hevc", "avc", "av1",
"aac", "aac2", "ac3", "eac3", "ddp", "ddp5", "ddp51", "truehd", "atmos", "dts", "dtshd",
"proper", "repack", "internal", "hdr", "hdr10", "hdr10plus", "dolbyvision", "dv",
}
KNOWN_PREFIXES = ("wanshow", "wan show")
ACRONYMS = {
"ai": "AI", "amd": "AMD", "arc": "Arc", "cpu": "CPU", "cpus": "CPUs",
"ddr4": "DDR4", "ddr5": "DDR5", "gpu": "GPU", "gpus": "GPUs", "hdr": "HDR",
"intel": "Intel", "linux": "Linux", "mac": "Mac", "nvidia": "NVIDIA", "oled": "OLED",
"pc": "PC", "pcs": "PCs", "ram": "RAM", "ssd": "SSD", "usb": "USB", "vr": "VR",
"wan": "WAN", "wifi": "WiFi",
}
SMALL_WORDS = {
"a", "an", "and", "as", "at", "but", "by", "for", "from", "in", "into", "of", "on",
"or", "the", "to", "vs", "with",
}
def normalize_number(value):
if value is None:
return None
if isinstance(value, (list, tuple)):
if not value:
return None
value = value[0]
try:
return int(value)
except (TypeError, ValueError):
return None
def looks_like_random_id(token):
token = str(token).strip()
if len(token) < 8 or len(token) > 20 or " " in token:
return False
letters = [c for c in token if c.isalpha()]
has_upper = any(c.isupper() for c in letters)
has_lower = any(c.islower() for c in letters)
has_digit = any(c.isdigit() for c in token)
has_separator = "-" in token or "_" in token
return has_digit and ((has_upper and has_lower) or has_separator)
def smart_title_case(text):
words = text.split()
output = []
for index, word in enumerate(words):
stripped = word.strip()
if not stripped:
continue
lower = stripped.lower()
if lower in ACRONYMS:
output.append(ACRONYMS[lower])
continue
if index > 0 and lower in SMALL_WORDS:
output.append(lower)
continue
if any(c.isupper() for c in stripped[1:]) and any(c.islower() for c in stripped):
output.append(stripped)
continue
if any(c.isdigit() for c in stripped):
output.append(stripped if stripped.isupper() else stripped[:1].upper() + stripped[1:])
continue
output.append(stripped[:1].upper() + stripped[1:].lower())
return " ".join(output)
def remove_known_prefixes(text):
cleaned = text.strip()
lowered = cleaned.lower()
for prefix in KNOWN_PREFIXES:
if lowered == prefix:
return ""
for sep in (" ", "-", "_"):
if lowered.startswith(prefix + sep):
return cleaned[len(prefix) + 1:].strip()
return cleaned
def remove_trailing_random_id(text):
parts = text.split()
if parts and looks_like_random_id(parts[-1]):
parts.pop()
return " ".join(parts)
def remove_noise_tokens(text):
output = []
for token in text.split():
normalized = token.lower().strip("[](){}.,")
if normalized in NOISE_TOKENS:
continue
output.append(token)
return " ".join(output)
def clean_title(value):
if value is None:
return None
text = unicodedata.normalize("NFKC", str(value)).strip()
if not text:
return None
suffix = Path(text).suffix.lower()
if suffix in VIDEO_EXTENSIONS:
text = Path(text).stem
text = re.sub(r"[._]+", " ", text)
text = re.sub(r"\s*-\s*", " ", text)
text = remove_known_prefixes(text)
text = remove_trailing_random_id(text)
text = remove_noise_tokens(text)
text = re.sub(r"\[[^\]]+\]", " ", text)
text = re.sub(r"\{[^}]+\}", " ", text)
text = re.sub(r"\s+", " ", text).strip(" -_.")
return smart_title_case(text) if text else None
MOVIE_FOLDER_PATTERN = re.compile(r"^(?P<title>.+?)\s*\((?P<year>\d{4})\)\s*$")
def clean_parent_movie_folder(path):
parent_name = Path(path).parent.name.strip()
match = MOVIE_FOLDER_PATTERN.match(parent_name)
if not match:
return None, None
return clean_title(match.group("title")), normalize_number(match.group("year"))
def list_media_files(root):
root = Path(root).resolve()
files = []
if not root.is_dir():
return files
for path in root.rglob("*"):
try:
if path.is_file() and path.suffix.lower() in VIDEO_EXTENSIONS:
files.append(path)
except OSError:
continue
files.sort(key=lambda p: str(p).lower())
return files
def extract_resolution(media_info):
for track in media_info.tracks:
if track.track_type != "Video":
continue
width = getattr(track, "width", None)
height = getattr(track, "height", None)
if width and height:
try:
return f"{int(width)}x{int(height)}"
except (TypeError, ValueError):
pass
return None
def extract_duration_seconds(media_info):
for wanted in ("General", "Video"):
for track in media_info.tracks:
if track.track_type != wanted:
continue
duration = getattr(track, "duration", None)
if duration is None:
continue
try:
duration_ms = float(duration)
if duration_ms >= 0:
return duration_ms / 1000.0
except (TypeError, ValueError):
pass
return None
def is_short_media(duration_seconds, minimum_duration=None):
if minimum_duration is None:
minimum_duration = MIN_MEDIA_DURATION
if duration_seconds is None:
return False
try:
return float(duration_seconds) < float(minimum_duration)
except (TypeError, ValueError):
return False
def inspect_media_file(path):
path = Path(path).resolve()
guessed = guessit(path.name)
media_info = MediaInfo.parse(str(path))
resolution = extract_resolution(media_info)
duration_seconds = extract_duration_seconds(media_info)
short_media = is_short_media(duration_seconds)
guessed_type = guessed.get("type")
season = normalize_number(guessed.get("season"))
episode = normalize_number(guessed.get("episode"))
guessed_year = normalize_number(guessed.get("year"))
guessed_title = clean_title(guessed.get("title"))
episode_title = clean_title(guessed.get("episode_title"))
filename_title = clean_title(path.stem)
parent_title, parent_year = clean_parent_movie_folder(path)
media_type = "episode" if guessed_type == "episode" or season is not None or episode is not None else "movie"
series_title = guessed_title if media_type == "episode" else None
if media_type == "movie":
title = parent_title or guessed_title or filename_title or path.stem
year = parent_year or guessed_year
else:
title = series_title or guessed_title or filename_title or path.stem
year = guessed_year
return {
"original_path": str(path),
"type": media_type,
"title": title,
"series_title": series_title,
"episode_title": episode_title,
"season": season,
"episode": episode,
"year": year,
"resolution": resolution,
"duration_seconds": duration_seconds,
"is_short_media": short_media,
}
def get_full_mediainfo(path):
path = Path(path).resolve()
if not path.is_file():
raise FileNotFoundError(path)
media_info = MediaInfo.parse(str(path))
guessed = guessit(path.name)
normalized = inspect_media_file(path)
try:
media_info_data = media_info.to_data()
except Exception:
media_info_data = {"tracks": [track.to_data() for track in media_info.tracks]}
return {
"file": path.name,
"guessit": dict(guessed),
"normalized": normalized,
"mediainfo": media_info_data,
}
def scan_media(root):
results = []
for path in list_media_files(root):
try:
item = inspect_media_file(path)
if item.get("is_short_media"):
duration = item.get("duration_seconds") or 0
print(f"[MEDIAINFO] Skipping short media ({duration:.1f}s): {path}")
continue
results.append(item)
except Exception as exc:
print(f"[MEDIAINFO] {path}: {exc}")
return results