﻿import os, json, io, time, traceback, threading, re
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Any, Dict, List, Optional
from urllib.error import HTTPError
from urllib.parse import urlparse
from urllib.request import Request, urlopen, url2pathname

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from PIL import Image, ImageOps
from pydantic import BaseModel

os.environ.setdefault("HF_HUB_DISABLE_SYMLINKS_WARNING", "1")

ROOT = os.path.dirname(os.path.abspath(__file__))
MODEL_DIR = os.path.join(ROOT, "model")
DBRATING_DIR = os.getenv("NSFW_DBRATING_DIR", "").strip() or os.path.join(MODEL_DIR, "dbrating", "mobilenetv3_large_100_v0_ls0.2")
TAGGER_DIR = os.getenv("NSFW_TAGGER_DIR", "").strip() or os.path.join(MODEL_DIR, "tagger")

DEVICE = os.getenv("NSFW_DEVICE", "").strip().lower()
HIGH_THRESHOLD = float(os.getenv("NSFW_HIGH_THRESHOLD", "0.62"))
REVIEW_THRESHOLD = float(os.getenv("NSFW_REVIEW_THRESHOLD", "0.35"))
MAX_IMAGE_BYTES = int(os.getenv("NSFW_MAX_IMAGE_BYTES", str(25 * 1024 * 1024)))
MAX_IMAGE_SIDE = int(os.getenv("NSFW_MAX_IMAGE_SIDE", "1024"))
FETCH_TIMEOUT = float(os.getenv("NSFW_FETCH_TIMEOUT", "30"))
FETCH_CONCURRENCY = max(1, int(os.getenv("NSFW_FETCH_CONCURRENCY", "4")))
FETCH_RETRIES = max(0, int(os.getenv("NSFW_FETCH_RETRIES", "2")))
RETRY_BASE_DELAY = float(os.getenv("NSFW_RETRY_BASE_DELAY", "0.5"))
MAX_RETRY_DELAY = float(os.getenv("NSFW_MAX_RETRY_DELAY", "8"))
BATCH_SIZE = max(1, int(os.getenv("NSFW_BATCH_SIZE", "4")))
MAX_REQUEST_ITEMS = max(1, int(os.getenv("NSFW_MAX_REQUEST_ITEMS", "128")))
BATCH_GAP_SEC = max(0.0, float(os.getenv("NSFW_BATCH_GAP_SEC", "0")))

# Tagger thresholds (PixAI recommended defaults)
TAG_THRESHOLDS = {
    "general": float(os.getenv("TAG_GENERAL_THRESHOLD", "0.35")),
    "character": float(os.getenv("TAG_CHARACTER_THRESHOLD", "0.85")),
    "copyright": float(os.getenv("TAG_COPYRIGHT_THRESHOLD", "0.45")),
    "artist": float(os.getenv("TAG_ARTIST_THRESHOLD", "0.45")),
    "meta": float(os.getenv("TAG_META_THRESHOLD", "0.45")),
    "rating": float(os.getenv("TAG_RATING_THRESHOLD", "0.45")),
}
TAG_MAX = int(os.getenv("TAG_MAX", "60"))

app = FastAPI(title="Pixify NSFW + Tagger helper")
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["GET", "POST", "OPTIONS"],
    allow_headers=["*"],
)

_lock = threading.Lock()
_inf_lock = threading.Lock()
_dbr_sess = None
_dbr_labels = ["general", "sensitive", "questionable", "explicit"]
_dbr_input = "input"
_tagger = None
_torch = None
_device = ""

class CheckBody(BaseModel):
    url: str
    includeTags: Optional[bool] = False

class BatchItem(BaseModel):
    id: str = ""
    url: str

class BatchBody(BaseModel):
    items: List[BatchItem]
    batchSize: Optional[int] = None
    includeTags: Optional[bool] = False


def resolve_device_name():
    req = DEVICE
    if req in ("cuda", "gpu"):
        req = "cuda"
    elif req in ("dml", "directml"):
        req = "dml"
    elif req in ("cpu",):
        req = "cpu"
    else:
        req = "auto"
    try:
        import torch
        cuda_ok = bool(torch.cuda.is_available())
    except Exception:
        cuda_ok = False
    try:
        import onnxruntime as ort
        providers = set(ort.get_available_providers() or [])
    except Exception:
        providers = set()
    dml_ok = "DmlExecutionProvider" in providers
    if req == "cpu":
        return "cpu"
    if req == "cuda":
        return "cuda" if cuda_ok else ("dml" if dml_ok else "cpu")
    if req == "dml":
        return "dml" if dml_ok else ("cuda" if cuda_ok else "cpu")
    if cuda_ok:
        return "cuda"
    if dml_ok:
        return "dml"
    return "cpu"


def get_ort_providers(device: str):
    try:
        import onnxruntime as ort
        available = set(ort.get_available_providers() or [])
    except Exception:
        available = {"CPUExecutionProvider"}
    requested = os.getenv("NSFW_ONNX_PROVIDERS", "").strip()
    if requested:
        providers = [p.strip() for p in requested.split(",") if p.strip()]
        return providers or ["CPUExecutionProvider"]
    if device == "cuda":
        if "CUDAExecutionProvider" in available:
            return ["CUDAExecutionProvider", "CPUExecutionProvider"]
        if "DmlExecutionProvider" in available:
            return ["DmlExecutionProvider", "CPUExecutionProvider"]
    if device == "dml" and "DmlExecutionProvider" in available:
        return ["DmlExecutionProvider", "CPUExecutionProvider"]
    # auto: prefer CUDA, then DirectML, then CPU
    if "CUDAExecutionProvider" in available:
        return ["CUDAExecutionProvider", "CPUExecutionProvider"]
    if "DmlExecutionProvider" in available:
        return ["DmlExecutionProvider", "CPUExecutionProvider"]
    return ["CPUExecutionProvider"]


def load_dbrating():
    global _dbr_sess, _dbr_labels, _dbr_input
    if _dbr_sess is not None:
        return
    import onnxruntime as ort
    meta_path = os.path.join(DBRATING_DIR, "meta.json")
    model_path = os.path.join(DBRATING_DIR, "model.onnx")
    if not os.path.exists(model_path):
        raise FileNotFoundError(f"dbrating model not found: {model_path}")
    if os.path.exists(meta_path):
        try:
            meta = json.load(open(meta_path, "r", encoding="utf-8"))
            labels = meta.get("labels")
            if isinstance(labels, list) and labels:
                _dbr_labels = [str(x).lower() for x in labels]
        except Exception:
            pass
    device = resolve_device_name()
    providers = get_ort_providers(device)
    try:
        _dbr_sess = ort.InferenceSession(model_path, providers=providers)
    except Exception:
        # Fallback to CPU if CUDA provider fails/missing
        _dbr_sess = ort.InferenceSession(model_path, providers=["CPUExecutionProvider"])
    _dbr_input = _dbr_sess.get_inputs()[0].name


def load_tagger():
    global _tagger, _torch, _device
    if _tagger is not None:
        return
    import torch
    from transformers import pipeline
    _device = resolve_device_name()
    _torch = torch
    model_id = TAGGER_DIR if os.path.isdir(TAGGER_DIR) else "pixai-labs/pixai-tagger-v1.0"
    torch_cuda = bool(torch.cuda.is_available())
    dev = 0 if _device == "cuda" and torch_cuda else -1
    if _device == "cuda" and not torch_cuda:
        _device = "cpu"
    if _device == "cuda":
        try:
            torch.backends.cuda.matmul.allow_tf32 = True
            torch.backends.cudnn.benchmark = True
            if hasattr(torch, "set_float32_matmul_precision"):
                torch.set_float32_matmul_precision("high")
        except Exception:
            pass
    # PixAI v1.0 registers custom pipeline "tagger" via config.custom_pipelines
    last_err = None
    for attempt in (
        lambda: pipeline(task="tagger", model=model_id, trust_remote_code=True, device=dev),
        lambda: pipeline(model=model_id, trust_remote_code=True, device=dev),
        lambda: pipeline("image-classification", model=model_id, trust_remote_code=True, device=dev),
    ):
        try:
            _tagger = attempt()
            return
        except Exception as e:
            last_err = e
    raise last_err or RuntimeError("Failed to load tagger")


def ensure_models(include_tags=True):
    with _lock:
        load_dbrating()
        if include_tags:
            load_tagger()


def retry_delay(headers: Any, attempt: int) -> float:
    value = ""
    try:
        value = str(headers.get("Retry-After") or "") if headers else ""
    except Exception:
        value = ""
    if value:
        try:
            return min(max(float(value), 0.0), MAX_RETRY_DELAY)
        except ValueError:
            pass
    return min(RETRY_BASE_DELAY * (2 ** attempt), MAX_RETRY_DELAY)


def fetch_image(url: str) -> Image.Image:
    raw = str(url or "").strip()
    if not raw:
        raise ValueError("Missing image URL/path.")
    local_path = None
    if raw.startswith("file://"):
        local_path = url2pathname(urlparse(raw).path)
    elif re.match(r"^[A-Za-z]:[\\/]", raw) or raw.startswith("\\\\"):
        local_path = raw
    elif raw.startswith("/api/media/") or raw.startswith("api/media/"):
        media_root = os.getenv("PIXIFY_MEDIA_DIR", "").strip()
        if media_root:
            local_path = os.path.join(media_root, raw.split("/")[-1])
    if local_path:
        p = os.path.abspath(local_path)
        if not os.path.exists(p):
            raise ValueError(f"Local image not found: {p}")
        with open(p, "rb") as f:
            data = f.read(MAX_IMAGE_BYTES + 1)
        if len(data) > MAX_IMAGE_BYTES:
            raise ValueError("Image is too large to classify locally.")
        image = Image.open(io.BytesIO(data))
        image = ImageOps.exif_transpose(image).convert("RGB")
        image.thumbnail((MAX_IMAGE_SIDE, MAX_IMAGE_SIDE), Image.Resampling.LANCZOS)
        return image

    parsed = urlparse(raw)
    if parsed.scheme not in ("http", "https") or not parsed.netloc:
        raise ValueError("Only http(s) image URLs, file paths, or local media paths can be checked.")
    request = Request(raw, headers={"User-Agent": "Pixify-Audit/3.0", "Accept": "image/*,*/*;q=0.8"})
    last_error = None
    for attempt in range(FETCH_RETRIES + 1):
        try:
            with urlopen(request, timeout=FETCH_TIMEOUT) as response:
                data = response.read(MAX_IMAGE_BYTES + 1)
            if len(data) > MAX_IMAGE_BYTES:
                raise ValueError("Image is too large to classify locally.")
            image = Image.open(io.BytesIO(data))
            image = ImageOps.exif_transpose(image).convert("RGB")
            image.thumbnail((MAX_IMAGE_SIDE, MAX_IMAGE_SIDE), Image.Resampling.LANCZOS)
            return image
        except HTTPError as exc:
            last_error = exc
            if exc.code in (408, 425, 429, 500, 502, 503, 504) and attempt < FETCH_RETRIES:
                time.sleep(retry_delay(exc.headers, attempt))
                continue
            raise
        except Exception as exc:
            last_error = exc
            if attempt < FETCH_RETRIES:
                time.sleep(retry_delay(None, attempt))
                continue
            raise
    raise last_error or RuntimeError("Image fetch failed.")


def classify_nsfw(image: Image.Image) -> Dict[str, Any]:
    import numpy as np
    load_dbrating()
    # Common dbrating ONNX preprocessing: resize 224/256 depending model; infer from input shape if possible
    sess = _dbr_sess
    inp = sess.get_inputs()[0]
    shape = inp.shape
    size = 224
    try:
        if len(shape) >= 4 and isinstance(shape[2], int) and shape[2] > 0:
            size = int(shape[2])
    except Exception:
        size = 224
    img = image.convert("RGB").resize((size, size), Image.Resampling.BICUBIC)
    arr = np.asarray(img).astype("float32") / 255.0
    # try NCHW
    if len(shape) == 4 and shape[1] == 3:
        arr = np.transpose(arr, (2, 0, 1))
    arr = np.expand_dims(arr, 0)
    with _inf_lock:
        out = sess.run(None, {inp.name: arr})[0]
    probs = out[0].tolist() if hasattr(out[0], "tolist") else list(out[0])
    # softmax if not already
    s = sum(max(0.0, float(x)) for x in probs)
    if s <= 0 or max(probs) > 1.5 or min(probs) < -0.001:
        import math
        exps = [math.exp(float(x) - max(float(v) for v in probs)) for x in probs]
        z = sum(exps) or 1.0
        probs = [e / z for e in exps]
    labels = _dbr_labels[:len(probs)]
    scores = {labels[i]: float(probs[i]) for i in range(len(labels))}
    rating = max(scores.items(), key=lambda kv: kv[1])[0] if scores else "general"
    # NSFW policy: explicit/questionable = nsfw, sensitive/general = sfw
    nsfw_score = max(scores.get("explicit", 0.0), scores.get("questionable", 0.0))
    label = "nsfw" if nsfw_score >= HIGH_THRESHOLD or rating in ("explicit", "questionable") and nsfw_score >= REVIEW_THRESHOLD else "sfw"
    uncertain = REVIEW_THRESHOLD <= nsfw_score < HIGH_THRESHOLD
    return {
        "label": label,
        "score": round(nsfw_score, 4),
        "rating": rating,
        "scores": {k: round(v, 4) for k, v in scores.items()},
        "uncertain": uncertain,
        "nsfwModel": "deepghs/anime_dbrating:mobilenetv3_large_100_v0_ls0.2",
        "model": "deepghs/anime_dbrating:mobilenetv3_large_100_v0_ls0.2",
    }


def classify_tags(image: Image.Image) -> Dict[str, Any]:
    load_tagger()
    with _inf_lock:
        # pixai custom pipeline returns dict with results/categories depending impl; handle common shapes
        out = _tagger(image)
    tags = []
    raw = out
    # normalize
    def add(tag, score, cat="general"):
        t = str(tag).strip().replace("_", " ")
        if not t: return
        tags.append({"tag": t, "score": float(score), "category": cat})

    if isinstance(out, dict):
        # maybe {"results": {"general": {...}, ...}} or {"labels":..., "scores"...}
        if "results" in out and isinstance(out["results"], dict):
            for cat, vals in out["results"].items():
                if isinstance(vals, dict):
                    for k,v in vals.items():
                        add(k,v,cat)
                elif isinstance(vals, list):
                    for it in vals:
                        if isinstance(it, dict): add(it.get("tag") or it.get("label"), it.get("score",0), cat)
        elif "general" in out or "character" in out:
            for cat, vals in out.items():
                if isinstance(vals, dict):
                    for k,v in vals.items(): add(k,v,cat)
    elif isinstance(out, list):
        # standard image-classification pipeline: [{label, score}]
        for it in out:
            if isinstance(it, dict):
                label = it.get("label","")
                score = float(it.get("score",0))
                cat = "general"
                for prefix in ["character:","copyright:","artist:","meta:","rating:"]:
                    if label.startswith(prefix):
                        cat = prefix[:-1]
                        label = label[len(prefix):]
                        break
                add(label, score, cat)
    # filter by thresholds and dedupe
    best = {}
    for t in tags:
        cat = t["category"]
        thr = TAG_THRESHOLDS.get(cat, 0.35)
        if t["score"] < thr: continue
        key = t["tag"].lower()
        if key not in best or t["score"] > best[key]["score"]:
            best[key] = t
    final = sorted(best.values(), key=lambda x: (-x["score"], x["category"], x["tag"]))[:TAG_MAX]
    return {
        "tags": [t["tag"] for t in final],
        "tagDetails": final,
        "taggerModel": "pixai-labs/pixai-tagger-v1.0",
    }


def fetch_images_concurrently(items: List[BatchItem]):
    images = [None] * len(items)
    errors = [None] * len(items)
    with ThreadPoolExecutor(max_workers=FETCH_CONCURRENCY) as pool:
        futures = {pool.submit(fetch_image, item.url): i for i, item in enumerate(items)}
        for fut in as_completed(futures):
            i = futures[fut]
            try:
                images[i] = fut.result()
            except Exception as exc:
                errors[i] = f"{type(exc).__name__}: {exc}"
    return images, errors


def check_items(items: List[BatchItem], batch_size: int, include_tags: bool):
    results = []
    ensure_models(include_tags=include_tags)
    for start in range(0, len(items), batch_size):
        chunk = items[start:start+batch_size]
        images, errors = fetch_images_concurrently(chunk)
        for i, item in enumerate(chunk):
            if errors[i] or images[i] is None:
                results.append({"id": item.id, "success": False, "error": errors[i] or "fetch failed", "label":"sfw", "score":0, "uncertain":True, "tags":[]})
                continue
            try:
                nsfw = classify_nsfw(images[i])
                tags = classify_tags(images[i]) if include_tags else {"tags":[],"tagDetails":[],"taggerModel":""}
                results.append({"id": item.id, "success": True, **nsfw, **tags, "model": nsfw.get("nsfwModel",""), "taggerModel": tags.get("taggerModel","")})
            except Exception as exc:
                results.append({"id": item.id, "success": False, "error": f"{type(exc).__name__}: {exc}", "label":"sfw", "score":0, "uncertain":True, "tags":[]})
        if BATCH_GAP_SEC and start + batch_size < len(items):
            time.sleep(BATCH_GAP_SEC)
    return results


@app.get("/health")
def health():
    dbr_ok = os.path.exists(os.path.join(DBRATING_DIR, "model.onnx"))
    tagger_ok = os.path.isdir(TAGGER_DIR) and (os.path.exists(os.path.join(TAGGER_DIR, "config.json")) or os.path.exists(os.path.join(TAGGER_DIR, "model.safetensors")))
    device = _device or resolve_device_name()
    providers = []
    try:
        if _dbr_sess is not None:
            providers = list(_dbr_sess.get_providers() or [])
    except Exception:
        providers = []
    if not providers:
        providers = get_ort_providers(device)
    cuda = False
    torch_ver = ""
    try:
        import torch
        cuda = bool(torch.cuda.is_available())
        torch_ver = str(getattr(torch, "__version__", ""))
    except Exception:
        cuda = False
    return {
        "success": True, "ok": True,
        "model": "deepghs/anime_dbrating:mobilenetv3_large_100_v0_ls0.2 + pixai-labs/pixai-tagger-v1.0",
        "nsfwModel": "deepghs/anime_dbrating:mobilenetv3_large_100_v0_ls0.2",
        "taggerModel": "pixai-labs/pixai-tagger-v1.0",
        "modelLoaded": _dbr_sess is not None or _tagger is not None,
        "dbratingReady": dbr_ok,
        "taggerReady": tagger_ok,
        "device": device,
        "cudaAvailable": cuda,
        "torchVersion": torch_ver,
        "onnxProviders": providers,
        "batchSize": BATCH_SIZE,
    }


@app.post("/warm")
def warm():
    try:
        ensure_models(include_tags=True)
        return {"success": True, "ok": True, **health()}
    except Exception as exc:
        return JSONResponse(status_code=500, content={"success": False, "error": f"{type(exc).__name__}: {exc}", "trace": traceback.format_exc()[-1200:]})


@app.post("/check")
def check(body: CheckBody):
    try:
        ensure_models(include_tags=body.includeTags is True)
        img = fetch_image(body.url)
        nsfw = classify_nsfw(img)
        tags = classify_tags(img) if body.includeTags is True else {"tags":[],"tagDetails":[],"taggerModel":""}
        return {"success": True, **nsfw, **tags, "model": nsfw.get("nsfwModel",""), "taggerModel": tags.get("taggerModel","")}
    except Exception as exc:
        return JSONResponse(status_code=500, content={"success": False, "error": f"{type(exc).__name__}: {exc}", "trace": traceback.format_exc()[-1200:]})


@app.post("/check-batch")
def check_batch(body: BatchBody):
    try:
        items = body.items[:MAX_REQUEST_ITEMS]
        bs = min(max(1, int(body.batchSize or BATCH_SIZE)), BATCH_SIZE, MAX_REQUEST_ITEMS)
        results = check_items(items, bs, body.includeTags is True)
        return {"success": True, "results": results, "model": "deepghs/anime_dbrating+pixai-tagger-v1.0", "device": _device or resolve_device_name(), "batchSize": bs}
    except Exception as exc:
        return JSONResponse(status_code=500, content={"success": False, "error": f"{type(exc).__name__}: {exc}", "trace": traceback.format_exc()[-1200:]})


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host=os.getenv("NSFW_HOST", "127.0.0.1"), port=int(os.getenv("NSFW_PORT", "8787")))
