4kanime / app /server.py
noreply's picture
Claude Opus 5.5
CPU sınırını cgroup'tan oku, çalışma dosyalarını yerel diske al
dd21950
Raw History Blame Contribute Delete
14.6 kB
"""4K Anime (doku) — HTTP API + static UI. One CPU worker processes jobs in order."""
import hashlib
import hmac
import json
import os
import queue
import re
import shutil
import threading
import time
import traceback
import uuid
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles
import pipeline
from models import MODELS, PRESETS
ROOT = os.path.dirname(os.path.abspath(__file__))
STATIC = os.path.join(os.path.dirname(ROOT), "static")
def _pick_data_dir():
# local disk on purpose: /data on Spaces may be a bucket mount (no append, slow seeks)
for d in (os.environ.get("DATA_DIR"), "/tmp/4kanime"):
if not d:
continue
try:
os.makedirs(d, exist_ok=True)
test = os.path.join(d, ".w")
open(test, "w").close()
os.remove(test)
return d
except OSError:
continue
raise RuntimeError("no writable data dir")
DATA = _pick_data_dir()
UPLOADS = os.path.join(DATA, "uploads")
OUTPUTS = os.path.join(DATA, "outputs")
PREVIEWS = os.path.join(DATA, "previews")
for d in (UPLOADS, OUTPUTS, PREVIEWS):
os.makedirs(d, exist_ok=True)
STATE_FILE = os.path.join(DATA, "state.json")
KEEP_HOURS = float(os.environ.get("KEEP_HOURS", "48"))
PASSWORD = os.environ.get("APP_PASSWORD", "")
MAX_UPLOAD = int(float(os.environ.get("MAX_UPLOAD_GB", "20")) * 1024**3)
lock = threading.RLock()
files: dict = {} # id -> {id,name,path,size,received,info,created}
jobs: dict = {} # id -> job dict
job_queue: "queue.Queue[str]" = queue.Queue()
cancel_flags: dict = {}
# ---------------------------------------------------------------- state
def save_state():
with lock:
tmp = STATE_FILE + ".tmp"
with open(tmp, "w") as f:
json.dump({"files": files, "jobs": jobs}, f)
os.replace(tmp, STATE_FILE)
def load_state():
if not os.path.exists(STATE_FILE):
return
try:
st = json.load(open(STATE_FILE))
except Exception:
return
for fid, f in st.get("files", {}).items():
if os.path.exists(f["path"]) and f.get("info"):
files[fid] = f
for jid, j in st.get("jobs", {}).items():
if j["status"] in ("sırada", "hazırlanıyor", "işleniyor"):
j["status"] = "yarıda kaldı"
j["error"] = "Sunucu yeniden başladı; işi tekrar başlatabilirsin."
jobs[jid] = j
def cleanup():
cutoff = time.time() - KEEP_HOURS * 3600
with lock:
for fid in [k for k, f in files.items() if f["created"] < cutoff]:
_remove_file(fid)
for jid in [k for k, j in jobs.items()
if j["created"] < cutoff and j["status"] not in ("sırada", "işleniyor", "hazırlanıyor")]:
_remove_job(jid)
for name in os.listdir(PREVIEWS):
p = os.path.join(PREVIEWS, name)
if os.path.getmtime(p) < time.time() - 3600 * 6:
os.remove(p)
# stray partial uploads
for name in os.listdir(UPLOADS):
fid = name.split(".")[0]
if fid not in files and os.path.getmtime(os.path.join(UPLOADS, name)) < cutoff:
os.remove(os.path.join(UPLOADS, name))
save_state()
def _remove_file(fid):
f = files.pop(fid, None)
if f and os.path.exists(f["path"]):
os.remove(f["path"])
def _remove_job(jid):
j = jobs.pop(jid, None)
if j:
for p in (j["output"], j["output"] + ".log"):
if os.path.exists(p):
os.remove(p)
# ---------------------------------------------------------------- worker
def worker():
while True:
jid = job_queue.get()
with lock:
job = jobs.get(jid)
if not job or job["status"] != "sırada":
continue
job["status"] = "hazırlanıyor"
job["started"] = time.time()
ev = cancel_flags.setdefault(jid, threading.Event())
def update(**kw):
with lock:
job.update(kw)
try:
pipeline.run_job(job, update, ev)
update(finished=time.time())
except pipeline.Cancelled:
update(status="iptal", finished=time.time())
if os.path.exists(job["output"]):
os.remove(job["output"])
except Exception as e: # noqa: BLE001
traceback.print_exc()
update(status="hata", error=str(e)[-2000:], finished=time.time())
save_state()
# ---------------------------------------------------------------- app
app = FastAPI(title="4kanime")
def _token():
return hmac.new(PASSWORD.encode(), b"4kanime", hashlib.sha256).hexdigest()
@app.middleware("http")
async def auth(request: Request, call_next):
path = request.url.path
if PASSWORD and path.startswith("/api/") and path not in ("/api/config", "/api/login"):
if not hmac.compare_digest(request.cookies.get("k4", ""), _token()):
return JSONResponse({"detail": "Şifre gerekli"}, status_code=401)
return await call_next(request)
@app.post("/api/login")
async def login(request: Request):
body = await request.json()
if not PASSWORD or hmac.compare_digest(str(body.get("password", "")), PASSWORD):
r = JSONResponse({"ok": True})
if PASSWORD:
r.set_cookie("k4", _token(), httponly=True, samesite="lax", secure=True,
max_age=3600 * 24 * 30)
return r
raise HTTPException(401, "Şifre yanlış")
@app.get("/api/config")
def config(request: Request):
authed = (not PASSWORD) or hmac.compare_digest(request.cookies.get("k4", ""), _token())
return {
"models": MODELS,
"presets": PRESETS,
"cpu": pipeline.CPU_COUNT,
"auth_required": bool(PASSWORD),
"authed": authed,
"keep_hours": KEEP_HOURS,
}
def _public_file(f):
return {k: v for k, v in f.items() if k != "path"}
def _safe_name(name: str) -> str:
name = os.path.basename(name or "video")
name = re.sub(r"[^\w.\- ()\[\]]+", "_", name, flags=re.UNICODE).strip() or "video"
return name[:150]
# --- chunked upload (works with multi-GB files through the Space proxy)
@app.post("/api/upload/init")
async def upload_init(request: Request):
body = await request.json()
size = int(body.get("size", 0))
if size <= 0 or size > MAX_UPLOAD:
raise HTTPException(400, f"Dosya boyutu geçersiz (en fazla {MAX_UPLOAD // 1024**3} GB)")
name = _safe_name(body.get("name"))
ext = os.path.splitext(name)[1].lower() or ".mkv"
if ext not in (".mkv", ".mp4", ".m4v", ".mov", ".webm", ".avi", ".ts", ".m2ts", ".flv", ".wmv"):
raise HTTPException(400, "Desteklenmeyen dosya türü")
fid = uuid.uuid4().hex[:12]
path = os.path.join(UPLOADS, fid + ext)
open(path, "wb").close()
with lock:
files[fid] = {"id": fid, "name": name, "path": path, "size": size,
"received": 0, "info": None, "created": time.time()}
return {"id": fid}
@app.put("/api/upload/{fid}")
async def upload_chunk(fid: str, request: Request, offset: int = 0):
f = files.get(fid)
if not f or f["info"]:
raise HTTPException(404, "Yükleme bulunamadı")
if offset != f["received"]:
return JSONResponse({"received": f["received"]}, status_code=409)
n = 0
with open(f["path"], "ab") as out:
async for chunk in request.stream():
n += len(chunk)
if f["received"] + n > f["size"]:
raise HTTPException(400, "Fazla veri")
out.write(chunk)
f["received"] += n
return {"received": f["received"]}
@app.post("/api/upload/{fid}/finish")
def upload_finish(fid: str):
f = files.get(fid)
if not f:
raise HTTPException(404, "Yükleme bulunamadı")
if f["received"] != f["size"]:
raise HTTPException(400, "Yükleme tamamlanmadı")
try:
f["info"] = pipeline.probe(f["path"])
except Exception as e: # noqa: BLE001
_remove_file(fid)
raise HTTPException(400, f"Video okunamadı: {e}")
save_state()
return _public_file(f)
@app.get("/api/files")
def list_files():
with lock:
return [_public_file(f) for f in
sorted((f for f in files.values() if f["info"]), key=lambda f: -f["created"])]
@app.delete("/api/files/{fid}")
def delete_file(fid: str):
with lock:
if any(j["file_id"] == fid and j["status"] in ("sırada", "işleniyor", "hazırlanıyor")
for j in jobs.values()):
raise HTTPException(400, "Bu dosyayla çalışan bir iş var")
_remove_file(fid)
save_state()
return {"ok": True}
@app.get("/api/files/{fid}/raw")
def raw_file(fid: str):
f = files.get(fid)
if not f or not f["info"]:
raise HTTPException(404)
return FileResponse(f["path"], filename=f["name"])
# --- settings validation
def _settings(body: dict) -> dict:
models = [m for m in body.get("models", []) if m in MODELS]
cas = min(max(float(body.get("cas", 0)), 0.0), 1.0)
target_h = body.get("target_h")
target_h = int(target_h) if target_h in (720, 1080, 1440, "720", "1080", "1440") else None
return {"models": models, "cas": round(cas, 2), "target_h": target_h}
# --- preview
preview_lock = threading.Lock()
@app.post("/api/preview")
async def make_preview(request: Request):
body = await request.json()
f = files.get(body.get("file_id"))
if not f or not f["info"]:
raise HTTPException(404, "Dosya yok")
s = _settings(body)
t = min(max(float(body.get("t", 0)), 0), max(f["info"]["duration"] - 0.1, 0))
def run():
with preview_lock:
return pipeline.preview(f["path"], t, s["models"], s["cas"], s["target_h"])
import asyncio
try:
before, after, spent = await asyncio.to_thread(run)
except Exception as e: # noqa: BLE001
raise HTTPException(400, f"Önizleme yapılamadı: {e}")
pid = uuid.uuid4().hex[:10]
open(os.path.join(PREVIEWS, pid + "_a.png"), "wb").write(before)
open(os.path.join(PREVIEWS, pid + "_b.png"), "wb").write(after)
return {"before": f"/api/preview/{pid}_a.png", "after": f"/api/preview/{pid}_b.png",
"seconds": round(spent, 2), "t": t}
@app.get("/api/preview/{name}")
def get_preview(name: str):
if not re.fullmatch(r"[0-9a-f]{10}_[ab]\.png", name):
raise HTTPException(404)
p = os.path.join(PREVIEWS, name)
if not os.path.exists(p):
raise HTTPException(404)
return FileResponse(p, media_type="image/png")
# --- jobs
def _public_job(j):
return {k: v for k, v in j.items() if k not in ("input", "output")}
@app.post("/api/jobs")
async def create_job(request: Request):
body = await request.json()
f = files.get(body.get("file_id"))
if not f or not f["info"]:
raise HTTPException(404, "Dosya yok")
s = _settings(body)
if not s["models"] and s["cas"] == 0:
raise HTTPException(400, "En az bir model ya da keskinlik seç")
codec = "x264" if body.get("codec") == "x264" else "x265"
preset = body.get("preset") if body.get("preset") in (
"ultrafast", "veryfast", "faster", "fast", "medium", "slow") else "medium"
crf = min(max(int(body.get("crf", 16)), 8), 30)
container = "mp4" if body.get("container") == "mp4" else "mkv"
jid = uuid.uuid4().hex[:12]
base = os.path.splitext(f["name"])[0]
out_name = f"{base} [4kanime].{container}"
job = {
"id": jid, "file_id": f["id"], "file_name": f["name"], "out_name": out_name,
"input": f["path"], "output": os.path.join(OUTPUTS, f"{jid}.{container}"),
**s, "codec": codec, "preset": preset, "crf": crf, "container": container,
"dedup": bool(body.get("dedup", True)),
"dedup_sens": min(max(float(body.get("dedup_sens", 1.0)), 0.25), 3.0),
"status": "sırada", "created": time.time(), "done": 0,
"total": f["info"]["frames"], "dups": 0, "fps": 0, "eta": None, "error": None,
}
with lock:
jobs[jid] = job
cancel_flags[jid] = threading.Event()
job_queue.put(jid)
save_state()
return _public_job(job)
@app.get("/api/jobs")
def list_jobs():
with lock:
return [_public_job(j) for j in sorted(jobs.values(), key=lambda j: -j["created"])]
@app.post("/api/jobs/{jid}/cancel")
def cancel_job(jid: str):
with lock:
j = jobs.get(jid)
if not j:
raise HTTPException(404)
if j["status"] == "sırada":
j["status"] = "iptal"
cancel_flags.setdefault(jid, threading.Event()).set()
save_state()
return {"ok": True}
@app.post("/api/jobs/{jid}/retry")
def retry_job(jid: str):
with lock:
j = jobs.get(jid)
if not j or j["status"] not in ("hata", "iptal", "yarıda kaldı"):
raise HTTPException(400, "Bu iş tekrar başlatılamaz")
if j["file_id"] not in files:
raise HTTPException(400, "Kaynak dosya silinmiş")
j.update(status="sırada", done=0, dups=0, fps=0, eta=None, error=None,
created=time.time())
cancel_flags[jid] = threading.Event()
job_queue.put(jid)
save_state()
return _public_job(j)
@app.delete("/api/jobs/{jid}")
def delete_job(jid: str):
with lock:
j = jobs.get(jid)
if not j:
raise HTTPException(404)
if j["status"] in ("sırada", "işleniyor", "hazırlanıyor"):
raise HTTPException(400, "Önce işi iptal et")
_remove_job(jid)
save_state()
return {"ok": True}
@app.get("/api/jobs/{jid}/download")
def download(jid: str):
j = jobs.get(jid)
if not j or j["status"] != "bitti" or not os.path.exists(j["output"]):
raise HTTPException(404, "Çıktı hazır değil")
return FileResponse(j["output"], filename=j["out_name"])
@app.get("/api/system")
def system():
du = shutil.disk_usage(DATA)
return {"disk_free_gb": round(du.free / 1024**3, 1), "data_dir": DATA,
"queue": job_queue.qsize(), "cpu": pipeline.CPU_COUNT}
app.mount("/", StaticFiles(directory=STATIC, html=True), name="static")
@app.on_event("startup")
def _startup():
load_state()
cleanup()
threading.Thread(target=worker, daemon=True).start()
def periodic():
while True:
time.sleep(3600)
try:
cleanup()
except Exception: # noqa: BLE001
traceback.print_exc()
threading.Thread(target=periodic, daemon=True).start()