| |
| import os |
| import json |
| import hashlib |
| import shutil |
| import threading |
| import subprocess |
| from pathlib import Path |
| from flask import Flask, request, jsonify |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| from typing import List, Tuple, Optional |
|
|
| |
| BASEDIR = Path("/hdd/Restoration/Inference/LQ") |
| HQ_BASE = Path("/hdd/Restoration/Inference/LQ") |
| CACHE_DIR = Path("/hdd/Restoration/Inference/Cache") |
| LOG_DIR = Path("/hdd/Restoration/Inference/log") |
| LOG_DIR.mkdir(parents=True, exist_ok=True) |
| CACHE_DIR.mkdir(parents=True, exist_ok=True) |
|
|
| |
| GPU_IDS = [0, 1] |
|
|
| |
| MODEL_SCRIPT_MAP = {"restormer": "restormer_api.py", "xrestormer": "x_restormer_api.py"} |
| MODEL_ENV_MAP = {"restormer": "restormer", "xrestormer": "basicsr"} |
| |
| SCORE_SCRIPT = "score.py" |
| |
|
|
| app = Flask(__name__) |
|
|
| |
| def log(msg: str): |
| print(msg) |
| with open(LOG_DIR / "server.log", "a", encoding="utf-8") as f: |
| f.write(msg + "\n") |
|
|
| |
| class GPUManager: |
| def __init__(self, gpu_ids: List[int]): |
| self.gpu_ids = gpu_ids |
| self.locks = {g: threading.Lock() for g in gpu_ids} |
| self.condition = threading.Condition() |
| self.in_use = set() |
|
|
| def acquire(self, blocking=True, timeout=None) -> Optional[int]: |
| """ |
| Acquire an available GPU id. Blocks until one is available (if blocking True). |
| Returns gpu_id or None if cannot acquire. |
| """ |
| with self.condition: |
| |
| if not blocking: |
| for g in self.gpu_ids: |
| if g not in self.in_use: |
| self.in_use.add(g) |
| return g |
| return None |
| else: |
| |
| while True: |
| for g in self.gpu_ids: |
| if g not in self.in_use: |
| self.in_use.add(g) |
| return g |
| if timeout is not None: |
| |
| self.condition.wait(timeout=timeout) |
| |
| |
| else: |
| self.condition.wait() |
|
|
| def release(self, gpu_id: int): |
| with self.condition: |
| if gpu_id in self.in_use: |
| self.in_use.remove(gpu_id) |
| self.condition.notify_all() |
|
|
| |
| gpu_manager = GPUManager(GPU_IDS) |
|
|
| |
| |
| |
| |
| |
| |
| def seq_hash(models: List[str]) -> str: |
| hasher = hashlib.sha256() |
| hasher.update("||".join(models).encode("utf-8")) |
| return hasher.hexdigest()[:16] |
|
|
| def get_cache_path(image_id: str, models_prefix: List[str]) -> Path: |
| h = seq_hash(models_prefix) |
| return CACHE_DIR / image_id / h |
|
|
| def cache_exists(image_id: str, models_prefix: List[str]) -> bool: |
| p = get_cache_path(image_id, models_prefix) |
| return (p / "output.png").exists() |
|
|
| def read_cached_score(image_id: str, models_prefix: List[str]) -> Optional[float]: |
| p = get_cache_path(image_id, models_prefix) / "meta.json" |
| if p.exists(): |
| try: |
| j = json.loads(p.read_text(encoding="utf-8")) |
| return j.get("score") |
| except Exception: |
| return None |
| return None |
|
|
| def write_cache(image_id: str, models_prefix: List[str], output_image_path: Path, score: Optional[float]=None, extra_meta: dict=None): |
| p = get_cache_path(image_id, models_prefix) |
| p.mkdir(parents=True, exist_ok=True) |
| |
| target = p / "output.png" |
| if output_image_path != target: |
| shutil.copy2(output_image_path, target) |
| meta = {"models": models_prefix, "image_id": image_id} |
| if score is not None: |
| meta["score"] = score |
| if extra_meta: |
| meta.update(extra_meta) |
| (p / "meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8") |
|
|
| |
| _cache_locks = {} |
| _cache_locks_lock = threading.Lock() |
| def get_cache_lock(image_id: str, prefix_hash: str) -> threading.Lock: |
| key = f"{image_id}_{prefix_hash}" |
| with _cache_locks_lock: |
| if key not in _cache_locks: |
| _cache_locks[key] = threading.Lock() |
| return _cache_locks[key] |
|
|
| |
| def model_env_from_model_name(model_name: str) -> str: |
| """ |
| Given 'restormer.derain' -> returns 'restormer' as env name. |
| If model name contains dash like 'x-restormer.dehaze', returns 'x-restormer'. |
| """ |
| if "." in model_name: |
| return model_name.split(".", 1)[0] |
| return model_name |
|
|
| def script_for_repo(repo: str) -> str: |
| """ |
| Return script filename for a given repo. Use MODEL_SCRIPT_MAP override if provided. |
| Default: {repo}_api.py |
| """ |
| if repo in MODEL_SCRIPT_MAP: |
| return MODEL_SCRIPT_MAP[repo] |
| |
| return f"{repo}_api.py" |
|
|
| def env_for_repo(repo: str) -> str: |
| """ |
| Return script filename for a given repo. Use MODEL_ENV_MAP override if provided. |
| Default: {repo}_api.py |
| """ |
| if repo in MODEL_ENV_MAP: |
| return MODEL_ENV_MAP[repo] |
| |
| return repo |
|
|
| def run_model_process(model_fullname: str, input_image: Path, output_image: Path, gpu_id: int, timeout: int=3600) -> Tuple[bool, str]: |
| """ |
| Run the model subprocess with CUDA_VISIBLE_DEVICES set to gpu_id. |
| Returns (success, stdout+stderr) |
| """ |
| repo_name = model_env_from_model_name(model_fullname) |
| script = script_for_repo(repo_name) |
| env_name = env_for_repo(repo_name) |
| |
| |
| cmd = ["conda", "run", "-n", env_name, "python", script, |
| "--input", str(input_image), |
| "--output", str(output_image), |
| "--model", model_fullname] |
|
|
| env = os.environ.copy() |
| env["CUDA_VISIBLE_DEVICES"] = str(gpu_id) |
|
|
| log(f"[MODEL] Running {cmd} with GPU={gpu_id}") |
| try: |
| proc = subprocess.run(cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, check=False) |
| output = proc.stdout.decode("utf-8", errors="replace") |
| success = proc.returncode == 0 |
| if success: |
| log(f"[MODEL] Success: {model_fullname} -> {output_image}") |
| else: |
| log(f"[MODEL] Failed ({proc.returncode}): {model_fullname}\n{output}") |
| return success, output |
| except subprocess.TimeoutExpired as e: |
| log(f"[MODEL] Timeout running {model_fullname}: {e}") |
| return False, f"timeout: {e}" |
| except Exception as e: |
| log(f"[MODEL] Exception running {model_fullname}: {e}") |
| return False, str(e) |
|
|
| def run_score(output_image: Path, hq_image: Path, timeout: int = 300) -> Tuple[bool, Optional[float], str]: |
| """ |
| Call score.py --input {output_image} --hq {hq_image} and parse stdout for numeric score. |
| Returns (success, score_or_None, raw_output) |
| """ |
| cmd = ["python", SCORE_SCRIPT, "--input", str(output_image), "--hq", str(hq_image)] |
| try: |
| proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=timeout, check=False) |
| out = proc.stdout.decode("utf-8", errors="replace") |
| if proc.returncode != 0: |
| log(f"[SCORE] score.py failed: {out}") |
| return False, None, out |
| |
| import re |
| m = re.search(r"([-+]?\d*\.\d+|\d+)", out) |
| if m: |
| score = float(m.group(0)) |
| return True, score, out |
| else: |
| return True, None, out |
| except subprocess.TimeoutExpired as e: |
| log(f"[SCORE] Timeout: {e}") |
| return False, None, f"timeout: {e}" |
| except Exception as e: |
| log(f"[SCORE] Exception: {e}") |
| return False, None, str(e) |
|
|
| |
| def process_restore_request(image_id: str, models: List[str]) -> dict: |
| """ |
| Run the sequence of models for given image_id, using cache and GPU management. |
| Returns a dict with result summary: { "image_id":..., "models":..., "final_cache":..., "score":..., "cached": bool, ... } |
| """ |
| log(f"[REQ] start image_id={image_id} models={models}") |
|
|
| |
| input_image = BASEDIR / image_id |
| if not input_image.exists(): |
| return {"error": f"BASEDIR/{image_id} not found"} |
|
|
| |
| hq_image = HQ_BASE / image_id |
| if not hq_image.exists(): |
| log(f"[WARN] HQ reference not found for {image_id} at {hq_image}; scoring will fail if required") |
| |
| current_input = input_image |
| prefix = [] |
| last_cache_path = None |
|
|
| for i, model in enumerate(models): |
| prefix.append(model) |
| |
| cache_path = get_cache_path(image_id, prefix) |
| cache_output_img = cache_path / "output.png" |
| prefix_hash = seq_hash(prefix) |
| lock = get_cache_lock(image_id, prefix_hash) |
|
|
| if cache_output_img.exists(): |
| log(f"[CACHE HIT] image={image_id} prefix={prefix} -> {cache_output_img}") |
| current_input = cache_output_img |
| last_cache_path = cache_path |
| continue |
|
|
| |
| with lock: |
| |
| if cache_output_img.exists(): |
| log(f"[CACHE HIT after lock] image={image_id} prefix={prefix} -> {cache_output_img}") |
| current_input = cache_output_img |
| last_cache_path = cache_path |
| continue |
|
|
| |
| gpu_id = gpu_manager.acquire(blocking=True) |
| if gpu_id is None: |
| |
| return {"error": "no GPU available"} |
|
|
| try: |
| |
| tmp_out_dir = CACHE_DIR / "tmp" / f"{image_id}_{prefix_hash}" |
| tmp_out_dir.mkdir(parents=True, exist_ok=True) |
| tmp_output = tmp_out_dir / "out.png" |
|
|
| success, out_log = run_model_process(model, current_input, tmp_output, gpu_id) |
| if not success: |
| return {"error": f"model {model} failed", "detail": out_log} |
|
|
| |
| cache_path.mkdir(parents=True, exist_ok=True) |
| shutil.copy2(tmp_output, cache_output_img) |
| |
| meta = {"models": prefix, "image_id": image_id} |
| (cache_path / "meta.json").write_text(json.dumps(meta, ensure_ascii=False, indent=2), encoding="utf-8") |
|
|
| log(f"[CACHE WRITE] wrote {cache_output_img}") |
| current_input = cache_output_img |
| last_cache_path = cache_path |
|
|
| finally: |
| |
| gpu_manager.release(gpu_id) |
|
|
| |
| |
| final_score = None |
| cached_score = read_cached_score(image_id, models) |
| if cached_score is not None: |
| log(f"[SCORE CACHE HIT] image={image_id} models={models} score={cached_score}") |
| final_score = cached_score |
| result = { |
| "image_id": image_id, |
| "models": models, |
| "cached": True, |
| "score": final_score, |
| "output_image": str(get_cache_path(image_id, models) / "output.png"), |
| } |
| return result |
|
|
| |
| if not hq_image.exists(): |
| log(f"[WARN] No HQ for scoring image_id={image_id}") |
| |
| return { |
| "image_id": image_id, |
| "models": models, |
| "cached": False, |
| "score": None, |
| "output_image": str(current_input), |
| "warning": "HQ reference not found; scoring skipped" |
| } |
|
|
| |
| success, score_val, raw = run_score(current_input, hq_image) |
| if not success: |
| |
| return { |
| "image_id": image_id, |
| "models": models, |
| "cached": False, |
| "score": None, |
| "output_image": str(current_input), |
| "score_error": raw |
| } |
|
|
| final_score = score_val |
| |
| write_cache(image_id, models, Path(current_input), score=final_score) |
| return { |
| "image_id": image_id, |
| "models": models, |
| "cached": False, |
| "score": final_score, |
| "output_image": str(get_cache_path(image_id, models) / "output.png") |
| } |
|
|
| |
| executor = ThreadPoolExecutor(max_workers=8) |
|
|
| @app.route("/restore", methods=["POST"]) |
| def restore(): |
| j = request.get_json(force=True) |
| image_id = j.get("image_id") |
| models = j.get("models") |
| if not image_id or not models: |
| return jsonify({"error": "missing image_id or models"}), 400 |
| |
| if not isinstance(models, list): |
| return jsonify({"error": "models must be an array"}), 400 |
|
|
| |
| future = executor.submit(process_restore_request, image_id, models) |
| try: |
| result = future.result() |
| except Exception as e: |
| log(f"[ERROR] exception processing request: {e}") |
| import traceback |
| traceback.print_exc() |
| return jsonify({"error": "internal error", "detail": str(e)}), 500 |
|
|
| status_code = 200 if "error" not in result else 500 |
| return jsonify(result), status_code |
|
|
| @app.route("/status", methods=["GET"]) |
| def status(): |
| return jsonify({ |
| "gpu_ids": GPU_IDS, |
| "in_use": list(gpu_manager.in_use), |
| "cache_root": str(CACHE_DIR) |
| }) |
|
|
| |
| if __name__ == "__main__": |
| |
| app.run(host="0.0.0.0", port=5000, threaded=True) |
|
|