update loader
This commit is contained in:
@@ -4,7 +4,7 @@ import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse, unquote
|
||||
from urllib.parse import unquote, urlparse
|
||||
|
||||
|
||||
MODELS_DIR = Path("/models")
|
||||
@@ -13,7 +13,6 @@ DB_PATH = STATE_DIR / "queue.db"
|
||||
|
||||
POLL_INTERVAL = 2
|
||||
|
||||
|
||||
IGNORED_NAMES = {
|
||||
".gitkeep",
|
||||
}
|
||||
@@ -23,6 +22,14 @@ IGNORED_EXTENSIONS = {
|
||||
}
|
||||
|
||||
|
||||
def log(message: str):
|
||||
print(f"[worker] {message}", flush=True)
|
||||
|
||||
|
||||
def job_log(job_id: int, message: str):
|
||||
print(f"[job #{job_id}] {message}", flush=True)
|
||||
|
||||
|
||||
def db_connect():
|
||||
STATE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
@@ -54,6 +61,15 @@ def init_db():
|
||||
"""
|
||||
)
|
||||
|
||||
db.execute(
|
||||
"""
|
||||
UPDATE jobs
|
||||
SET status = 'pending',
|
||||
started_at = NULL
|
||||
WHERE status = 'running'
|
||||
"""
|
||||
)
|
||||
|
||||
db.commit()
|
||||
|
||||
|
||||
@@ -70,6 +86,9 @@ def is_model_file(path: Path) -> bool:
|
||||
if path.suffix.lower() in IGNORED_EXTENSIONS:
|
||||
return False
|
||||
|
||||
if path.name.endswith(".part"):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
@@ -106,16 +125,18 @@ def collect_models(model_type: str | None = None):
|
||||
files = []
|
||||
|
||||
for path in sorted(directory.rglob("*")):
|
||||
if is_model_file(path):
|
||||
try:
|
||||
files.append(
|
||||
(path, path.stat().st_size)
|
||||
)
|
||||
except OSError as exc:
|
||||
print(
|
||||
f"WARNING: Cannot read {path}: {exc}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
if not is_model_file(path):
|
||||
continue
|
||||
|
||||
try:
|
||||
files.append(
|
||||
(path, path.stat().st_size)
|
||||
)
|
||||
except OSError as exc:
|
||||
print(
|
||||
f"WARNING: Cannot read {path}: {exc}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
|
||||
if not files:
|
||||
continue
|
||||
@@ -158,13 +179,13 @@ def command_list(model_type: str | None = None) -> int:
|
||||
if not groups:
|
||||
print("No models found.")
|
||||
print()
|
||||
print("Total: 0 B (0 files)")
|
||||
print("Total: 0 B (0 models)")
|
||||
return 0
|
||||
|
||||
for group in groups:
|
||||
print(
|
||||
f"\n{group['name']}/ — "
|
||||
f"{len(group['files'])} files — "
|
||||
f"{len(group['files'])} models — "
|
||||
f"{human_size(group['size'])}"
|
||||
)
|
||||
|
||||
@@ -183,27 +204,12 @@ def command_list(model_type: str | None = None) -> int:
|
||||
print(
|
||||
f"Total: "
|
||||
f"{human_size(total_size)} "
|
||||
f"({total_files} files)"
|
||||
f"({total_files} models)"
|
||||
)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
def get_filename_from_url(url: str) -> str:
|
||||
parsed = urlparse(url)
|
||||
|
||||
filename = Path(
|
||||
unquote(parsed.path)
|
||||
).name
|
||||
|
||||
if not filename:
|
||||
raise ValueError(
|
||||
"Cannot determine filename from URL"
|
||||
)
|
||||
|
||||
return filename
|
||||
|
||||
|
||||
def get_model_types():
|
||||
if not MODELS_DIR.exists():
|
||||
return []
|
||||
@@ -230,13 +236,112 @@ def validate_model_type(model_type: str):
|
||||
return directory
|
||||
|
||||
|
||||
def enqueue_add(url: str, model_type: str) -> int:
|
||||
def get_filename_from_url(url: str) -> str:
|
||||
parsed = urlparse(url)
|
||||
|
||||
filename = Path(
|
||||
unquote(parsed.path)
|
||||
).name
|
||||
|
||||
if not filename:
|
||||
raise ValueError(
|
||||
"Cannot determine filename from URL"
|
||||
)
|
||||
|
||||
if filename in {".", ".."}:
|
||||
raise ValueError(
|
||||
"Invalid filename from URL"
|
||||
)
|
||||
|
||||
return filename
|
||||
|
||||
|
||||
def find_model(filename: str, model_type: str | None = None):
|
||||
matches = []
|
||||
|
||||
for group in collect_models(model_type):
|
||||
for path, _ in group["files"]:
|
||||
if path.name == filename:
|
||||
matches.append(
|
||||
(group["name"], path)
|
||||
)
|
||||
|
||||
return matches
|
||||
|
||||
|
||||
def find_partial(filename: str, model_type: str):
|
||||
directory = validate_model_type(model_type)
|
||||
|
||||
partial = directory / f".{filename}.part"
|
||||
|
||||
if partial.exists():
|
||||
return partial
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def find_existing_job(
|
||||
filename: str,
|
||||
model_type: str,
|
||||
action: str,
|
||||
):
|
||||
with db_connect() as db:
|
||||
return db.execute(
|
||||
"""
|
||||
SELECT *
|
||||
FROM jobs
|
||||
WHERE filename = ?
|
||||
AND model_type = ?
|
||||
AND action = ?
|
||||
AND status IN ('pending', 'running')
|
||||
ORDER BY id DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
(
|
||||
filename,
|
||||
model_type,
|
||||
action,
|
||||
),
|
||||
).fetchone()
|
||||
|
||||
|
||||
def enqueue_add(url: str, model_type: str) -> int:
|
||||
directory = validate_model_type(model_type)
|
||||
filename = get_filename_from_url(url)
|
||||
|
||||
destination = directory / filename
|
||||
|
||||
if destination.exists():
|
||||
print(
|
||||
f"ERROR: Model already exists: "
|
||||
f"{destination}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return 1
|
||||
|
||||
existing_job = find_existing_job(
|
||||
filename,
|
||||
model_type,
|
||||
"add",
|
||||
)
|
||||
|
||||
if existing_job:
|
||||
print(
|
||||
f"Job already queued: "
|
||||
f"#{existing_job['id']}"
|
||||
)
|
||||
|
||||
print(
|
||||
f"Status: {existing_job['status']}"
|
||||
)
|
||||
|
||||
return 0
|
||||
|
||||
partial = find_partial(
|
||||
filename,
|
||||
model_type,
|
||||
)
|
||||
|
||||
with db_connect() as db:
|
||||
cursor = db.execute(
|
||||
"""
|
||||
@@ -261,31 +366,22 @@ def enqueue_add(url: str, model_type: str) -> int:
|
||||
job_id = cursor.lastrowid
|
||||
|
||||
print(f"Queued job #{job_id}")
|
||||
print(f"Action: add")
|
||||
print("Action: add")
|
||||
print(f"Type: {model_type}")
|
||||
print(f"File: {filename}")
|
||||
print(f"URL: {url}")
|
||||
print(f"Target: {destination}")
|
||||
|
||||
if partial:
|
||||
print(
|
||||
f"Resume: {human_size(partial.stat().st_size)}"
|
||||
)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
def find_model(filename: str, model_type: str | None = None):
|
||||
groups = collect_models(model_type)
|
||||
|
||||
matches = []
|
||||
|
||||
for group in groups:
|
||||
for path, _ in group["files"]:
|
||||
if path.name == filename:
|
||||
matches.append(
|
||||
(group["name"], path)
|
||||
)
|
||||
|
||||
return matches
|
||||
|
||||
|
||||
def enqueue_rm(filename: str, model_type: str | None = None) -> int:
|
||||
def enqueue_rm(
|
||||
filename: str,
|
||||
model_type: str | None = None,
|
||||
) -> int:
|
||||
matches = find_model(
|
||||
filename,
|
||||
model_type,
|
||||
@@ -320,6 +416,22 @@ def enqueue_rm(filename: str, model_type: str | None = None) -> int:
|
||||
|
||||
found_type, path = matches[0]
|
||||
|
||||
existing_job = find_existing_job(
|
||||
filename,
|
||||
found_type,
|
||||
"rm",
|
||||
)
|
||||
|
||||
if existing_job:
|
||||
print(
|
||||
f"Job already queued: "
|
||||
f"#{existing_job['id']}"
|
||||
)
|
||||
print(
|
||||
f"Status: {existing_job['status']}"
|
||||
)
|
||||
return 0
|
||||
|
||||
with db_connect() as db:
|
||||
cursor = db.execute(
|
||||
"""
|
||||
@@ -342,10 +454,9 @@ def enqueue_rm(filename: str, model_type: str | None = None) -> int:
|
||||
job_id = cursor.lastrowid
|
||||
|
||||
print(f"Queued job #{job_id}")
|
||||
print(f"Action: rm")
|
||||
print("Action: rm")
|
||||
print(f"Type: {found_type}")
|
||||
print(f"File: {filename}")
|
||||
print(f"Target: {path}")
|
||||
|
||||
return 0
|
||||
|
||||
@@ -365,17 +476,29 @@ def run_download(job):
|
||||
f"Destination already exists: {destination}"
|
||||
)
|
||||
|
||||
print(
|
||||
f"[job #{job['id']}] Downloading "
|
||||
f"{filename}"
|
||||
existing_size = (
|
||||
partial.stat().st_size
|
||||
if partial.exists()
|
||||
else 0
|
||||
)
|
||||
|
||||
print(f"[job #{job['id']}] URL: {url}")
|
||||
if existing_size:
|
||||
job_log(
|
||||
job["id"],
|
||||
f"Resuming from {human_size(existing_size)}",
|
||||
)
|
||||
else:
|
||||
job_log(
|
||||
job["id"],
|
||||
"Starting download",
|
||||
)
|
||||
|
||||
command = [
|
||||
"curl",
|
||||
"--fail",
|
||||
"--location",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--retry", "5",
|
||||
"--retry-delay", "5",
|
||||
"--retry-all-errors",
|
||||
@@ -401,11 +524,14 @@ def run_download(job):
|
||||
"does not exist"
|
||||
)
|
||||
|
||||
final_size = partial.stat().st_size
|
||||
|
||||
partial.rename(destination)
|
||||
|
||||
print(
|
||||
f"[job #{job['id']}] Download complete: "
|
||||
f"{destination}"
|
||||
job_log(
|
||||
job["id"],
|
||||
f"Download complete: "
|
||||
f"{human_size(final_size)}",
|
||||
)
|
||||
|
||||
|
||||
@@ -417,9 +543,9 @@ def run_delete(job):
|
||||
destination = directory / filename
|
||||
|
||||
if not destination.exists():
|
||||
print(
|
||||
f"[job #{job['id']}] "
|
||||
f"File already gone: {destination}"
|
||||
job_log(
|
||||
job["id"],
|
||||
f"File already gone: {destination}",
|
||||
)
|
||||
return
|
||||
|
||||
@@ -430,9 +556,9 @@ def run_delete(job):
|
||||
|
||||
destination.unlink()
|
||||
|
||||
print(
|
||||
f"[job #{job['id']}] Deleted: "
|
||||
f"{destination}"
|
||||
job_log(
|
||||
job["id"],
|
||||
f"Deleted: {destination}",
|
||||
)
|
||||
|
||||
|
||||
@@ -504,6 +630,12 @@ def fail_job(job_id: int, error: str):
|
||||
|
||||
|
||||
def process_job(job):
|
||||
job_log(
|
||||
job["id"],
|
||||
f"{job['action'].upper()} "
|
||||
f"{job['model_type']}/{job['filename']}",
|
||||
)
|
||||
|
||||
try:
|
||||
if job["action"] == "add":
|
||||
run_download(job)
|
||||
@@ -519,9 +651,9 @@ def process_job(job):
|
||||
except Exception as exc:
|
||||
error = str(exc)
|
||||
|
||||
print(
|
||||
f"[job #{job['id']}] ERROR: {error}",
|
||||
file=sys.stderr,
|
||||
job_log(
|
||||
job["id"],
|
||||
f"FAILED: {error}",
|
||||
)
|
||||
|
||||
fail_job(
|
||||
@@ -533,11 +665,54 @@ def process_job(job):
|
||||
|
||||
finish_job(job["id"])
|
||||
|
||||
job_log(
|
||||
job["id"],
|
||||
"DONE",
|
||||
)
|
||||
|
||||
|
||||
def command_queue() -> int:
|
||||
with db_connect() as db:
|
||||
jobs = db.execute(
|
||||
"""
|
||||
SELECT *
|
||||
FROM jobs
|
||||
ORDER BY id DESC
|
||||
LIMIT 20
|
||||
"""
|
||||
).fetchall()
|
||||
|
||||
if not jobs:
|
||||
print("Queue is empty.")
|
||||
return 0
|
||||
|
||||
print(
|
||||
"ID STATUS ACTION TYPE"
|
||||
)
|
||||
print(
|
||||
"-----------------------------------------------"
|
||||
)
|
||||
|
||||
for job in jobs:
|
||||
print(
|
||||
f"{job['id']:<6} "
|
||||
f"{job['status']:<9} "
|
||||
f"{job['action']:<8} "
|
||||
f"{job['model_type']}/{job['filename']}"
|
||||
)
|
||||
|
||||
if job["status"] == "failed" and job["error"]:
|
||||
print(
|
||||
f" ERROR: {job['error']}"
|
||||
)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
def worker_loop():
|
||||
print("Model worker started.")
|
||||
print(f"Models: {MODELS_DIR}")
|
||||
print(f"Database: {DB_PATH}")
|
||||
log("Model worker started")
|
||||
log(f"Models: {MODELS_DIR}")
|
||||
log(f"Database: {DB_PATH}")
|
||||
|
||||
while True:
|
||||
job = claim_job()
|
||||
@@ -546,13 +721,6 @@ def worker_loop():
|
||||
time.sleep(POLL_INTERVAL)
|
||||
continue
|
||||
|
||||
print(
|
||||
f"[job #{job['id']}] "
|
||||
f"{job['action']} "
|
||||
f"{job['model_type']}/"
|
||||
f"{job['filename']}"
|
||||
)
|
||||
|
||||
process_job(job)
|
||||
|
||||
|
||||
@@ -562,11 +730,21 @@ def main():
|
||||
command = sys.argv[1] if len(sys.argv) > 1 else None
|
||||
|
||||
if command == "list":
|
||||
model_type = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
model_type = (
|
||||
sys.argv[2]
|
||||
if len(sys.argv) > 2
|
||||
else None
|
||||
)
|
||||
|
||||
raise SystemExit(
|
||||
command_list(model_type)
|
||||
)
|
||||
|
||||
if command == "queue":
|
||||
raise SystemExit(
|
||||
command_queue()
|
||||
)
|
||||
|
||||
if command == "add":
|
||||
if len(sys.argv) != 4:
|
||||
print(
|
||||
@@ -590,41 +768,22 @@ def main():
|
||||
)
|
||||
raise SystemExit(1)
|
||||
|
||||
filename = sys.argv[2]
|
||||
model_type = (
|
||||
sys.argv[3]
|
||||
if len(sys.argv) == 4
|
||||
else None
|
||||
)
|
||||
|
||||
raise SystemExit(
|
||||
enqueue_rm(
|
||||
filename,
|
||||
model_type,
|
||||
sys.argv[2],
|
||||
sys.argv[3]
|
||||
if len(sys.argv) == 4
|
||||
else None,
|
||||
)
|
||||
)
|
||||
|
||||
if command is not None:
|
||||
print(
|
||||
"Usage:",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print(
|
||||
" worker.py",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print(
|
||||
" worker.py list [type]",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print(
|
||||
" worker.py add <URL> <type>",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print(
|
||||
" worker.py rm <filename> [type]",
|
||||
file=sys.stderr,
|
||||
)
|
||||
print("Usage:", file=sys.stderr)
|
||||
print(" worker.py", file=sys.stderr)
|
||||
print(" worker.py list [type]", file=sys.stderr)
|
||||
print(" worker.py queue", file=sys.stderr)
|
||||
print(" worker.py add <URL> <type>", file=sys.stderr)
|
||||
print(" worker.py rm <filename> [type]", file=sys.stderr)
|
||||
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user