# -*- coding: utf-8 -*-
"""
사진 한 장 → 붓질로 다시 그린 그림 + 그리는 과정 영상

  python photo_to_painting.py 내사진.jpg

만들어지는 것(사진과 같은 폴더):
  내사진_그림.png        완성된 그림
  내사진_과정.mp4        그리는 과정 영상(세로 1080x1920 — 위 그림, 아래 원본 사진)

옵션:
  --wide        가로 영상(1920x1080 — 왼쪽 그림, 오른쪽 원본 사진)
  --seconds 24  그리는 과정 길이(초). 기본 24
  --fast        빨리 만들기(그림이 조금 거칠어짐)
  --no-photo    영상에 원본 사진을 넣지 않고 그림만

필요한 것:  pip install opencv-python numpy
ffmpeg 이 깔려 있으면 인스타·유튜브에 바로 올라가는 H.264 영상으로 저장한다(없어도 영상은 나온다).

방식: 연필로 윤곽 → 큰 붓으로 전체 색 → 사진과 차이가 큰 곳만 점점 작은 붓으로 덧칠.
붓질의 색은 사진에서 찍고, 방향은 사진의 결(밝기 경계)을 따라간다. 가장자리부터 칠하고 가운데(주인공)는 나중에.
"""
import sys, os, random, shutil, subprocess, argparse
import numpy as np, cv2

ap = argparse.ArgumentParser()
ap.add_argument('photo'); ap.add_argument('--wide', action='store_true'); ap.add_argument('--fast', action='store_true')
ap.add_argument('--no-photo', action='store_true'); ap.add_argument('--seconds', type=float, default=24)
A = ap.parse_args()
random.seed(7); np.random.seed(7)
FPS = 30
BG, PAPER = (23, 20, 16), (230, 239, 243)

# ── 사진 읽기(한글 경로도 되게) · 휴대폰 사진의 눕힘 정보 반영 ──
src0 = cv2.imdecode(np.fromfile(A.photo, np.uint8), cv2.IMREAD_COLOR)
if src0 is None: sys.exit('사진을 열 수 없습니다: ' + A.photo)
try:
    from PIL import Image, ImageOps                      # 있으면 회전 정보(EXIF)를 바로잡는다
    src0 = cv2.cvtColor(np.asarray(ImageOps.exif_transpose(Image.open(A.photo)).convert('RGB')), cv2.COLOR_RGB2BGR)
except Exception:
    pass

# ── 화면 배치: 그림 칸과 사진 칸 ──
FW, FH = (1920, 1080) if A.wide else (1080, 1920)
if A.no_photo: boxes = [(0, 0, FW, FH)]
elif A.wide: boxes = [(0, 0, FW // 2, FH), (FW // 2, 0, FW // 2, FH)]
else: boxes = [(0, 0, FW, FH // 2), (0, FH // 2, FW, FH // 2)]
bx, by, bw, bh = boxes[0]
h0, w0 = src0.shape[:2]
k = min((bw - 24) / w0, (bh - 24) / h0)
DW, DH = int(w0 * k) // 2 * 2, int(h0 * k) // 2 * 2       # 화면에 보이는 그림 크기
SS = 1 if A.fast else 2                                   # 그릴 때는 2배로 그려서 줄인다(가는 선이 안 뭉개지게)
PW, PH = DW * SS, DH * SS
src = cv2.resize(src0, (PW, PH), interpolation=cv2.INTER_AREA)
small = cv2.resize(src0, (DW, DH), interpolation=cv2.INTER_AREA)
U = max(PW, PH) / 2712.0                                  # 붓 크기를 그림 크기에 맞추는 배율

# ── 붓질 계획 ──
def plan_layer(canvas, R, thresh, force=False, box=None, maxlen=8):
    """지금 그림(canvas)과 사진을 견주어, 이 붓 크기(R)로 그을 획 목록을 만든다."""
    ref = cv2.GaussianBlur(src, (0, 0), max(0.6, R * 0.5)).astype(np.float32)
    lum = cv2.cvtColor(ref.astype(np.uint8), cv2.COLOR_BGR2GRAY).astype(np.float32)
    gx = cv2.Sobel(lum, cv2.CV_32F, 1, 0, ksize=3); gy = cv2.Sobel(lum, cv2.CV_32F, 0, 1, ksize=3)
    cf = canvas.astype(np.float32); diff = np.sqrt(((cf - ref) ** 2).sum(2))
    g = max(2, int(R)); ny, nx = PH // g, PW // g
    blocks = diff[:ny * g, :nx * g].reshape(ny, g, nx, g).transpose(0, 2, 1, 3).reshape(ny, nx, g * g)
    err = blocks.mean(2); arg = blocks.argmax(2); out = []
    ys, xs = np.nonzero(np.ones_like(err, bool) if force else err > thresh)
    for cy, cx in zip(ys.tolist(), xs.tolist()):
        a = int(arg[cy, cx]); y0 = cy * g + a // g; x0 = cx * g + a % g
        if box and not (box[0] <= x0 < box[2] and box[1] <= y0 < box[3]): continue
        col = ref[y0, x0]; pts = [(x0, y0)]; x, y = float(x0), float(y0); lx = ly = 0.0
        for i in range(1, maxlen + 1):
            xi, yi = int(x), int(y)
            if not (0 <= xi < PW and 0 <= yi < PH): break
            if i > 2 and np.abs(ref[yi, xi] - cf[yi, xi]).sum() < np.abs(ref[yi, xi] - col).sum(): break
            dx, dy = -float(gy[yi, xi]), float(gx[yi, xi]); m = (dx * dx + dy * dy) ** 0.5   # 결을 따라가는 방향
            if m < 1e-3:
                if i == 1: break
                dx, dy = lx, ly
            else:
                dx /= m; dy /= m
                if lx * dx + ly * dy < 0: dx, dy = -dx, -dy
            lx, ly = dx, dy; x += R * dx; y += R * dy; pts.append((x, y))
        jit = np.random.uniform(-4, 4) if R >= 7 else 0
        c = tuple(int(min(255, max(0, v + jit))) for v in col)
        out.append((np.round(np.array(pts, np.float32) * 8).astype(np.int32), c, max(1, int(round(R * 2)))))
    return out

def draw(c, s):
    pts, col, th = s
    if len(pts) == 1: cv2.circle(c, tuple(int(v) for v in pts[0]), max(1, th // 2) * 8, col, -1, cv2.LINE_AA, 3)
    else: cv2.polylines(c, [pts], False, col, th, cv2.LINE_AA, 3)

def order(st):
    """가장자리 먼저, 가운데(주인공) 나중. 구역을 옮겨 다니듯 조금 섞는다."""
    cx, cy = PW / 2, PH * 0.45
    return sorted(st, key=lambda s: -(((s[0][0][0] / 8 - cx) / PW) ** 2 + ((s[0][0][1] / 8 - cy) / PH) ** 2) + random.random() * 0.08)

#          붓 반지름 · 덧칠 기준(사진과의 차이) · 과정에서 차지하는 비율
LAYERS = [(60, 0, .10), (28, 26, .12), (14, 20, .14), (7, 15, .18), (3.5, 11, .20), (1.8, 8, .18), (1.0, 5, .08)]
print('붓질 계획을 세우는 중… (사진 크기에 따라 1~5분)', flush=True)
plan = np.full((PH, PW, 3), PAPER, np.uint8); layers = []
center = (int(PW * .2), int(PH * .1), int(PW * .8), int(PH * .85))
for i, (R, th, share) in enumerate(LAYERS):
    R = max(0.8, R * U); last = i == len(LAYERS) - 1
    st = order(plan_layer(plan, R, th, force=(i == 0), box=center if last else None, maxlen=10 if R < 16 * U else 6))
    for s in st: draw(plan, s)
    layers.append((st, share)); print(f'  붓 {i + 1}/{len(LAYERS)}: {len(st):,}획', flush=True)
total = sum(len(l[0]) for l in layers)
stem = os.path.splitext(A.photo)[0]
cv2.imencode('.png', plan)[1].tofile(stem + '_그림.png')
print(f'완성 그림 저장: {stem}_그림.png  (붓질 {total:,}번)', flush=True)

# ── 연필 윤곽선 ──
gray = cv2.GaussianBlur(cv2.cvtColor(small, cv2.COLOR_BGR2GRAY), (0, 0), 2.0)
cons, _ = cv2.findContours(cv2.Canny(gray, 14, 40), cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
cons = sorted([c[:len(c) // 2 + 1] * SS for c in cons if len(c) > 70], key=lambda c: -len(c))

# ── 영상 쓰기: ffmpeg 이 있으면 H.264, 없으면 OpenCV 기본 ──
out_mp4 = stem + '_과정.mp4'
ff = shutil.which('ffmpeg'); proc = None; vw = None
if ff:
    proc = subprocess.Popen([ff, '-y', '-loglevel', 'error', '-f', 'rawvideo', '-pix_fmt', 'bgr24', '-s', f'{FW}x{FH}', '-r', str(FPS), '-i', '-',
                             '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-crf', '18', '-movflags', '+faststart', out_mp4], stdin=subprocess.PIPE)
else:
    tmp = os.path.join(os.path.dirname(os.path.abspath(out_mp4)), '_painting_tmp.mp4')   # OpenCV 는 한글 파일 이름으로 못 쓴다
    vw = cv2.VideoWriter(tmp, cv2.VideoWriter_fourcc(*'mp4v'), FPS, (FW, FH))

base = np.full((FH, FW, 3), BG, np.uint8)
def place(frame, img, box):
    x, y, w, h = box; ih, iw = img.shape[:2]
    ox, oy = x + (w - iw) // 2, y + (h - ih) // 2
    frame[oy:oy + ih, ox:ox + iw] = img
if not A.no_photo: place(base, small, boxes[1])

def emit(canvas, done):
    fr = base.copy()
    place(fr, cv2.resize(canvas, (DW, DH), interpolation=cv2.INTER_AREA) if SS > 1 else canvas, boxes[0])
    txt = f'{done:,}'                                       # 붓질 수(숫자만 — 글꼴 걱정 없이)
    (tw, th), _ = cv2.getTextSize(txt, cv2.FONT_HERSHEY_DUPLEX, 1.3, 2)
    x, y = bx + bw - tw - 44, by + bh - 34
    cv2.rectangle(fr, (x - 18, y - th - 16), (x + tw + 18, y + 14), (41, 198, 255), -1)
    cv2.putText(fr, txt, (x, y), cv2.FONT_HERSHEY_DUPLEX, 1.3, (10, 19, 23), 2, cv2.LINE_AA)
    if proc: proc.stdin.write(fr.tobytes())
    else: vw.write(fr)

print('그리는 과정을 영상으로 찍는 중…', flush=True)
canvas = np.full((PH, PW, 3), PAPER, np.uint8)
sk = int(A.seconds * 0.12 * FPS); npts = sum(len(c) for c in cons) or 1; per = npts / max(1, sk); budget = 0.0
for c in cons:                                              # 1) 연필
    i = 0
    while i < len(c) - 1:
        if budget < 1: emit(canvas, 0); budget += per
        n = int(min(budget, len(c) - 1 - i)); cv2.polylines(canvas, [c[i:i + n + 1]], False, (88, 84, 82), SS, cv2.LINE_AA); i += n; budget -= n
done = 0; paint_frames = int(A.seconds * 0.88 * FPS)
for st, share in layers:                                    # 2) 붓질
    nf = max(1, int(paint_frames * share))
    for f in range(nf):
        a, b = len(st) * f // nf, len(st) * (f + 1) // nf
        for s in st[a:b]: draw(canvas, s)
        done += b - a; emit(canvas, done)
for _ in range(int(2.5 * FPS)): emit(canvas, total)         # 3) 완성본을 잠깐 보여 준다
if proc: proc.stdin.close(); proc.wait()
else:
    vw.release(); shutil.move(tmp, out_mp4)
    print('※ ffmpeg 이 없어 기본 방식으로 저장했습니다. 인스타에 안 올라가면 ffmpeg 을 깔고 다시 실행하세요.')
print('과정 영상 저장:', out_mp4)
