File size: 16,046 Bytes
06f2b0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
# app.py
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")          # 存放原始待复原图片的根目录:BASEDIR/{image_id}
HQ_BASE = Path("/hdd/Restoration/Inference/LQ")          # 存放高质量参考图:HQ_BASE/{image_id}
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 配置:按实际机器设置可用 GPU id 列表
GPU_IDS = [0, 1]   # 例如有两块 GPU:0 和 1

# 可选:如果模型脚本名与 env 不完全对应,可在这里指定精确映射,例如:
MODEL_SCRIPT_MAP = {"restormer": "restormer_api.py", "xrestormer": "x_restormer_api.py"}
MODEL_ENV_MAP = {"restormer": "restormer", "xrestormer": "basicsr"}  # env 名称映射
# 指定 score 脚本路径(假设在 PATH 或可通过相对路径调用)
SCORE_SCRIPT = "score.py"  # 使用方式:python score.py --input {img} --hq {hq_img}
# ---------------------------------------------------------

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")

# ---------------- GPU 资源池 ----------------
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()  # set of gpu ids currently used

    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:
            # wait until some GPU is free
            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:
                # blocking: wait until any GPU is free
                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:
                        # wait with timeout
                        self.condition.wait(timeout=timeout)
                        # after wait, try again and possibly exit if timed out
                        # (loop will repeat until timeout logic in caller)
                    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()

# single GPU manager for the service
gpu_manager = GPUManager(GPU_IDS)

# ---------------- 缓存管理 ----------------
# Cache key design:
# - For intermediate after running models [m1, m2, ..., mi] on image_id:
#   cache_dir = CACHE_DIR / image_id / "{hash_of_prefix_sequence}"
#   store output image as "output.png" (or keep original ext), and metadata.json for score (if computed)
# We'll store mapping info for readability: meta.json contains {"models": [...], "image_id": "..."}
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)
    # copy image into cache as output.png
    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")

# per-cache lock to avoid concurrent writes to same key
_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]
    # sanitize repo to be filename-friendly (replace ':' etc if necessary)
    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]
    # sanitize repo to be filename-friendly (replace ':' etc if necessary)
    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)
    # Prepare command using conda run -n {env} python {script} ...
    # Example: conda run -n restormer python restormer_api.py --input {input} --output {output} --model restormer.derain
    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
        # parse numeric score: try to find the first number in output
        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}")

    # validate inputs
    input_image = BASEDIR / image_id
    if not input_image.exists():
        return {"error": f"BASEDIR/{image_id} not found"}

    # prepare HQ image
    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")
    # Work through sequence step-by-step, using cache for prefixes
    current_input = input_image
    prefix = []
    last_cache_path = None

    for i, model in enumerate(models):
        prefix.append(model)
        # check cache for this prefix
        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

        # no cache: need to run this model
        with lock:  # ensure only one thread creates this cache entry
            # double-check inside lock after obtaining it
            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

            # acquire GPU
            gpu_id = gpu_manager.acquire(blocking=True)
            if gpu_id is None:
                # should not happen in blocking=True, but handle defensively
                return {"error": "no GPU available"}

            try:
                # prepare a temporary output path (can be in tmp dir)
                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}

                # after success, move tmp_output into cache location
                cache_path.mkdir(parents=True, exist_ok=True)
                shutil.copy2(tmp_output, cache_output_img)
                # record meta without score (score is only for full sequence)
                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:
                # release GPU
                gpu_manager.release(gpu_id)

    # At this point, current_input is the image after applying full sequence
    # Check if final score cached
    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

    # need to run scoring (requires HQ)
    if not hq_image.exists():
        log(f"[WARN] No HQ for scoring image_id={image_id}")
        # return without score but with output path
        return {
            "image_id": image_id,
            "models": models,
            "cached": False,
            "score": None,
            "output_image": str(current_input),
            "warning": "HQ reference not found; scoring skipped"
        }

    # run scoring (we do not need GPU for scoring usually; if scoring uses GPU modify accordingly)
    success, score_val, raw = run_score(current_input, hq_image)
    if not success:
        # scoring failed; still return output path
        return {
            "image_id": image_id,
            "models": models,
            "cached": False,
            "score": None,
            "output_image": str(current_input),
            "score_error": raw
        }

    final_score = score_val
    # write final score into cache meta
    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")
    }

# ---------------- Flask 路由 ----------------
executor = ThreadPoolExecutor(max_workers=8)  # adjust max_workers as needed

@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
    # Validate models type
    if not isinstance(models, list):
        return jsonify({"error": "models must be an array"}), 400

    # Submit to threadpool and wait for result to support concurrent handling
    future = executor.submit(process_restore_request, image_id, models)
    try:
        result = future.result()  # wait until done (the worker thread will block waiting for GPUs if needed)
    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__":
    # for quick testing; for production use gunicorn/uwsgi and set threads/processes accordingly
    app.run(host="0.0.0.0", port=5000, threaded=True)