File size: 9,398 Bytes
a3953cb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
object_removal.py — POST /object-removal/upload,
                    POST /object-removal/generate,
                    GET  /object-removal/result/{job_id}

Object-removal pipeline: identical to watermark removal except:
  - Storage:  storage/object-removal/{job_id}/steps/{n}/
  - job_type: "object"
  - Reuses app.state.inpaint_engine (same LaMa model)
"""

from __future__ import annotations

import io
import shutil
import traceback
import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Literal

import cv2
import numpy as np
from fastapi import APIRouter, BackgroundTasks, File, HTTPException, Request, UploadFile
from PIL import Image, ImageOps
from pydantic import BaseModel

from app.config import STORAGE_DIR
from app.utils import job_folder_name
from app.jobs_store import (
    add_step,
    create_job,
    get_job,
    truncate_steps_after,
    update_job,
    update_step,
)
from app.models.schemas import Job, StepRecord
from app.services.blend_service import blend, check_output_quality
from app.services.inpaint_engine import BaseInpaintEngine
from app.services.mask_service import build_masks, save_mask

router = APIRouter()

_SUBDIR = "object-removal"


def _to_url(abs_path: str | None) -> str | None:
    """Convert an absolute path under STORAGE_DIR to a /storage/… URL."""
    if abs_path is None:
        return None
    try:
        rel = Path(abs_path).relative_to(STORAGE_DIR)
        return "/storage/" + rel.as_posix()
    except ValueError:
        return None


# ---------------------------------------------------------------------------
# Upload
# ---------------------------------------------------------------------------

@router.post("/upload")
async def obj_upload(file: UploadFile = File(...)) -> dict:
    """Accept an image upload for object removal, return job_id + dimensions."""
    if not file.content_type.startswith("image/"):
        raise HTTPException(
            status_code=415,
            detail=f"Expected an image file, got content-type '{file.content_type}'.",
        )

    raw_bytes = await file.read()
    if not raw_bytes:
        raise HTTPException(status_code=400, detail="Uploaded file is empty.")

    try:
        pil_img = Image.open(io.BytesIO(raw_bytes))
        pil_img = ImageOps.exif_transpose(pil_img)
        pil_img = pil_img.convert("RGB")
    except Exception as exc:
        raise HTTPException(status_code=422, detail=f"Could not decode image: {exc}")

    img_bgr: np.ndarray = cv2.cvtColor(np.array(pil_img), cv2.COLOR_RGB2BGR)
    height, width = img_bgr.shape[:2]

    job_id     = str(uuid.uuid4())
    created_at = datetime.now(timezone.utc)
    folder     = job_folder_name(job_id, created_at)
    step0_dir  = STORAGE_DIR / _SUBDIR / folder / "steps" / "0"
    step0_dir.mkdir(parents=True, exist_ok=True)

    original_path = step0_dir / "original.jpg"
    ok = cv2.imwrite(str(original_path), img_bgr)
    if not ok:
        raise HTTPException(status_code=500, detail="Failed to write uploaded image to storage.")

    job = Job(id=job_id, current_step=0, job_type="object", created_at=created_at)
    create_job(job)

    step0 = StepRecord(
        step_number=0,
        original_image=str(original_path),
        result_image=str(original_path),
        status="completed",
    )
    add_step(job_id, step0)

    return {"job_id": job_id, "width": width, "height": height}


# ---------------------------------------------------------------------------
# Generate (background inpainting)
# ---------------------------------------------------------------------------

class ObjGenerateRequest(BaseModel):
    job_id:      str
    mask_source: Literal["manual", "ocr", "mixed"] = "manual"
    mask_json:   dict


def run_obj_inpaint_job(
    job_id:      str,
    folder_name: str,
    step_number: int,
    image:       np.ndarray,
    hard_mask:   np.ndarray,
    soft_mask:   np.ndarray,
    engine:      BaseInpaintEngine,
) -> None:
    """Run LaMa inpainting for an object-removal job step."""
    step_dir = STORAGE_DIR / _SUBDIR / folder_name / "steps" / str(step_number)
    try:
        lama_output: np.ndarray  = engine.inpaint(image, hard_mask)
        result_image: np.ndarray = blend(image, lama_output, soft_mask)

        passed, error_msg = check_output_quality(result_image, expected_shape=image.shape)
        if not passed:
            update_step(job_id, step_number, status="failed", error_message=error_msg)
            return

        result_path = step_dir / "result.jpg"
        ok = cv2.imwrite(str(result_path), result_image)
        if not ok:
            update_step(
                job_id, step_number,
                status="failed",
                error_message="cv2.imwrite failed writing result.jpg.",
            )
            return

        update_step(job_id, step_number, status="completed", result_image=str(result_path))

    except Exception:
        update_step(job_id, step_number, status="failed", error_message=traceback.format_exc())


@router.post("/generate")
async def obj_generate(
    body: ObjGenerateRequest,
    background_tasks: BackgroundTasks,
    request: Request,
) -> dict:
    """Create new step, enqueue background inpainting for object removal."""
    job_id = body.job_id
    job = get_job(job_id)
    if job is None:
        raise HTTPException(status_code=404, detail=f"Job '{job_id}' not found.")

    folder_name = job_folder_name(job.id, job.created_at)

    current_step_num = job.current_step
    current_step = next(
        (s for s in job.steps if s.step_number == current_step_num), None
    )
    if current_step is None or current_step.result_image is None:
        raise HTTPException(
            status_code=400,
            detail=f"Step {current_step_num} has no result image to build from.",
        )

    base_path = Path(current_step.result_image)
    if not base_path.exists():
        raise HTTPException(
            status_code=500,
            detail=f"Base image missing from storage: {base_path}",
        )

    image: np.ndarray = cv2.imread(str(base_path))
    if image is None:
        raise HTTPException(
            status_code=500,
            detail=f"cv2.imread could not decode: {base_path}",
        )

    try:
        hard_mask, soft_mask = build_masks(body.mask_json)
    except ValueError as exc:
        raise HTTPException(status_code=422, detail=str(exc))

    new_step_num = current_step_num + 1
    if any(s.step_number >= new_step_num for s in job.steps):
        removed = truncate_steps_after(job_id, keep_through=current_step_num)
        for s in removed:
            orphan = STORAGE_DIR / _SUBDIR / folder_name / "steps" / str(s["step_number"])
            if orphan.exists():
                shutil.rmtree(orphan)

    step_dir = STORAGE_DIR / _SUBDIR / folder_name / "steps" / str(new_step_num)
    step_dir.mkdir(parents=True, exist_ok=True)

    step_original = step_dir / "original.jpg"
    shutil.copy2(str(base_path), str(step_original))

    hard_mask_path = step_dir / "mask_hard.png"
    soft_mask_path = step_dir / "mask_soft.png"
    save_mask(hard_mask, str(hard_mask_path))
    save_mask(soft_mask, str(soft_mask_path))

    new_step = StepRecord(
        step_number=new_step_num,
        original_image=str(step_original),
        mask_image=str(hard_mask_path),
        mask_source=body.mask_source,
        status="processing",
    )
    add_step(job_id, new_step)
    update_job(job_id, current_step=new_step_num)

    engine: BaseInpaintEngine = request.app.state.inpaint_engine
    background_tasks.add_task(
        run_obj_inpaint_job,
        job_id      = job_id,
        folder_name = folder_name,
        step_number = new_step_num,
        image       = image,
        hard_mask   = hard_mask,
        soft_mask   = soft_mask,
        engine      = engine,
    )

    return {"job_id": job_id, "step_number": new_step_num, "status": "processing"}


# ---------------------------------------------------------------------------
# Result
# ---------------------------------------------------------------------------

@router.get("/result/{job_id}")
def obj_get_result(job_id: str) -> dict:
    """Return current object-removal job state including full step history."""
    job = get_job(job_id)
    if job is None:
        raise HTTPException(status_code=404, detail=f"Job '{job_id}' not found.")

    current = next((s for s in job.steps if s.step_number == job.current_step), None)
    step0   = next((s for s in job.steps if s.step_number == 0), None)

    steps_summary = [
        {
            "step_number":        s.step_number,
            "status":             s.status,
            "original_image_url": _to_url(s.original_image),
            "result_image_url":   _to_url(s.result_image),
            "error_message":      s.error_message,
        }
        for s in sorted(job.steps, key=lambda s: s.step_number)
    ]

    return {
        "job_id":             job.id,
        "current_step":       job.current_step,
        "status":             current.status        if current else "unknown",
        "error_message":      current.error_message if current else None,
        "original_image_url": _to_url(step0.original_image) if step0 else None,
        "result_image_url":   _to_url(current.result_image) if current else None,
        "steps":              steps_summary,
    }