Spaces:
Paused
Paused
Upload 7 files
Browse filesFiles changed (7)
- DockerfileAdded+15
- LICENSEAdded+21
- README.md+26-12
- requirements.txtAdded+8
- server.pyAdded+121
- static/style.cssAdded+8
- templates/index.htmlAdded+61
123456789101112131415FROM python:3.11-slim
WORKDIR /appCOPY requirements.txt ./requirements.txtRUN pip install --no-cache-dir -r requirements.txt
COPY server.py ./server.pyCOPY templates ./templatesCOPY static ./staticCOPY README.md ./README.mdCOPY LICENSE ./LICENSE
EXPOSE 7860
CMD ["sh", "-c", "uvicorn server:app --host 0.0.0.0 --port ${PORT:-7860}"]123456789101112131415161718192021MIT License
Copyright (c) 2025 Waikul
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.123456789101112---title: RemoveWatermarkemoji: 🚀colorFrom: bluecolorTo: greensdk: dockerpinned: falselicense: mitshort_description: hell yeah---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567891011121314151617181920212223242526# Watermark Remover (Hugging Face Space)A simple FastAPI + OpenCV inpainting service to remove watermarks.Deployable for free on Hugging Face Spaces using Docker.## APIEndpoint: `POST /api/remove-watermark`### Fields (multipart/form-data)- `image`: file (required)- `mask`: file (optional)- `engine`: `opencv` (default) or `lama`- `method`: `telea` (default) or `ns`- `radius`: int (default 3, OpenCV only)- `auto_mask`: 1 or 0 (default 1)### Example```bashcurl -X POST https://<your-space>.hf.space/api/remove-watermark \-F image=@your_image.jpg \-F engine=opencv -F method=telea -F radius=3 -F auto_mask=1 \--output result.png```## LicenseMIT License
12345678fastapi==0.112.2uvicorn[standard]==0.30.6python-multipart==0.0.9Jinja2==3.1.4opencv-python==4.10.0.84numpy==1.26.4Pillow==10.4.0requests==2.32.3123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121import ioimport osfrom typing import Optional
import cv2import numpy as npfrom PIL import Imageimport requestsfrom fastapi import FastAPI, File, Form, UploadFile, HTTPException, Requestfrom fastapi.responses import StreamingResponse, HTMLResponse, JSONResponsefrom fastapi.staticfiles import StaticFilesfrom fastapi.templating import Jinja2Templates
app = FastAPI(title="Watermark Remover API")
# Serve static + templatesapp.mount("/static", StaticFiles(directory="static"), name="static")templates = Jinja2Templates(directory="templates")
LAMA_URL = os.getenv("LAMA_URL", "http://localhost:5000") # optional
def read_image_to_cv2(file: UploadFile) -> np.ndarray: data = file.file.read() img_arr = np.frombuffer(data, np.uint8) img = cv2.imdecode(img_arr, cv2.IMREAD_COLOR) if img is None: raise HTTPException(400, detail="Invalid image file") return img
def pil_bytes_from_cv2(img: np.ndarray, fmt: str = "PNG") -> io.BytesIO: img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) pil_img = Image.fromarray(img_rgb) buf = io.BytesIO() pil_img.save(buf, format=fmt) buf.seek(0) return buf
def auto_text_mask(img: np.ndarray) -> np.ndarray: """Simple heuristic mask for text/logo-like overlays.""" gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) gray = cv2.equalizeHist(gray) mser = cv2.MSER_create(_delta=5, _min_area=60, _max_area=10000) regions, _ = mser.detectRegions(gray) mask = np.zeros(gray.shape, dtype=np.uint8) for p in regions: hull = cv2.convexHull(p.reshape(-1, 1, 2)) cv2.drawContours(mask, [hull], -1, 255, thickness=-1) kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1) mask = cv2.dilate(mask, kernel, iterations=1) return mask
def inpaint_opencv(img: np.ndarray, mask: np.ndarray, method: str = "telea", radius: int = 3) -> np.ndarray: flag = cv2.INPAINT_TELEA if method.lower() == "telea" else cv2.INPAINT_NS if mask.ndim == 3: mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) _, mask_bin = cv2.threshold(mask, 1, 255, cv2.THRESH_BINARY) result = cv2.inpaint(img, mask_bin, radius, flag) return result
def call_lama_server(img: np.ndarray, mask: np.ndarray) -> np.ndarray: if mask.ndim == 3: mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY) _, mask_bin = cv2.threshold(mask, 1, 255, cv2.THRESH_BINARY)
def to_png_bytes(arr: np.ndarray) -> bytes: a = arr if a.ndim == 2: a = cv2.cvtColor(a, cv2.COLOR_GRAY2BGR) ok, buf = cv2.imencode('.png', a) if not ok: raise HTTPException(500, detail="Encoding error") return buf.tobytes()
files = { 'image': ('image.png', to_png_bytes(img), 'image/png'), 'mask': ('mask.png', to_png_bytes(mask_bin), 'image/png'), } data = {'method': 'lama'} try: resp = requests.post(f"{LAMA_URL}/inpaint", data=data, files=files, timeout=120) resp.raise_for_status() except Exception as e: raise HTTPException(502, detail=f"LaMa server error: {e}") nparr = np.frombuffer(resp.content, np.uint8) out = cv2.imdecode(nparr, cv2.IMREAD_COLOR) if out is None: raise HTTPException(502, detail="Invalid response from LaMa server") return out
@app.get("/", response_class=HTMLResponse)def index(request: Request): return templates.TemplateResponse("index.html", {"request": request})
@app.get("/health")def health(): return JSONResponse({"ok": True})
@app.post("/api/remove-watermark")def remove_watermark( image: UploadFile = File(...), mask: Optional[UploadFile] = File(None), engine: str = Form("opencv"), # "opencv" | "lama" method: str = Form("telea"), # opencv: telea | ns radius: int = Form(3), auto_mask: int = Form(1), # 1=true, 0=false): img = read_image_to_cv2(image)
if mask is not None: mask_img = read_image_to_cv2(mask) else: mask_img = auto_text_mask(img) if auto_mask else np.zeros(img.shape[:2], dtype=np.uint8)
if engine == "lama": out = call_lama_server(img, mask_img) else: out = inpaint_opencv(img, mask_img, method=method, radius=radius)
buf = pil_bytes_from_cv2(out, fmt="PNG") return StreamingResponse(buf, media_type="image/png")12345678body { font-family: system-ui, Arial, sans-serif; padding: 24px; }main { max-width: 840px; margin: auto; }h1 { margin-bottom: 16px; }form label { display: block; margin: 8px 0; }.row { display: grid; grid-template-columns: repeat(4, 1fr); gap: 8px; }button { padding: 8px 12px; }.hidden { display: none; }#output img { max-width: 100%; height: auto; margin-top: 12px; border: 1px solid #ddd; }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061<!doctype html><html><head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>Watermark Remover</title> <link rel="stylesheet" href="/static/style.css" /></head><body> <main> <h1>Watermark Remover</h1> <form id="form"> <label>Image <input type="file" name="image" accept="image/*" required></label> <label>Mask (optional) <input type="file" name="mask" accept="image/*"></label> <div class="row"> <label>Engine <select name="engine"> <option value="opencv" selected>OpenCV (fast, free)</option> <option value="lama">LaMa (needs separate server)</option> </select> </label> <label>Method <select name="method"> <option value="telea" selected>Telea</option> <option value="ns">Navier-Stokes</option> </select> </label> <label>Radius <input type="number" name="radius" value="3" min="1" max="50"></label> <label>Auto Mask <input type="checkbox" name="auto_mask" checked></label> </div> <button type="submit">Remove</button> </form>
<section id="output" class="hidden"> <h2>Result</h2> <img id="result-img" alt="result" /> <a id="download" download="result.png">Download</a> </section> </main>
<script>const form = document.getElementById('form');const out = document.getElementById('output');const img = document.getElementById('result-img');const dl = document.getElementById('download');
form.addEventListener('submit', async (e) => { e.preventDefault(); const data = new FormData(form); data.set('auto_mask', form.auto_mask.checked ? 1 : 0); const res = await fetch('/api/remove-watermark', { method: 'POST', body: data }); if (!res.ok) { alert('Failed: ' + res.status); return; } const blob = await res.blob(); const url = URL.createObjectURL(blob); img.src = url; dl.href = url; out.classList.remove('hidden');});</script></body></html>DockerfileAdded+15
LICENSEAdded+21
README.md+26-12
requirements.txtAdded+8
server.pyAdded+121
static/style.cssAdded+8
templates/index.htmlAdded+61