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43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
"""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()