feat: P2V 파이프라인 연동 및 좋아요·댓글·공유 지원

- 무빙 포스터(p2v_video)·롱컷(p2v_playreel) 파이프라인과 워커, 갤러리·내 콘텐츠 노출
- 좋아요·댓글: comment/video_reaction에 p2v_playreel_id 추가, 종류별 CHECK 확장
- P2V 소프트 삭제(is_deleted), queued/running 삭제 차단
- 공개 상세·공유 OG 페이지 추가
- 삭제된 부모 댓글이 목록에서 사라지던 has_live_reply 서브쿼리 버그 수정
- 마이그레이션: migration_2026-10-15_p2v_reactions.sql
This commit is contained in:
skkim committed 2026-10-15 10:42:30 +09:00
1 parent bb1ea12958
commit b16d4a8f1b
126 files changed
+6921 -62

No files matched your search

View File
Whitespace-only changes.
+103
View File
@@ -0,0 +1,103 @@
"""파일도 서브프로세스도 없이 메모리에서 처리하는 오디오 유틸."""
import io
from fractions import Fraction
import av
import numpy as np
SAMPLE_RATE = 44100 # 렌더 믹스 기준
MP3_BIT_RATE = 192000
INT16_FULL_SCALE = 32768
def decode_mp3(data: bytes, sample_rate: int = SAMPLE_RATE) -> np.ndarray:
"""mp3 → 모노 s16 PCM. 소스 샘플레이트가 달라도 리샘플해 맞춘다."""
container = av.open(io.BytesIO(data))
resampler = av.audio.resampler.AudioResampler(
format="s16", layout="mono", rate=sample_rate)
chunks = []
for frame in container.decode(audio=0):
for resampled in resampler.resample(frame):
chunks.append(resampled.to_ndarray().reshape(-1))
for resampled in resampler.resample(None): # 남은 것 밀어내기
chunks.append(resampled.to_ndarray().reshape(-1))
container.close()
return np.concatenate(chunks) if chunks else np.zeros(0, np.int16)
def encode_mp3(pcm: np.ndarray, sample_rate: int = SAMPLE_RATE) -> bytes:
buffer = io.BytesIO()
container = av.open(buffer, "w", format="mp3")
stream = container.add_stream("mp3", rate=sample_rate)
stream.layout = "mono"
stream.bit_rate = MP3_BIT_RATE
frame = av.AudioFrame.from_ndarray(pcm.reshape(1, -1), format="s16", layout="mono")
frame.rate = sample_rate
for packet in stream.encode(frame):
container.mux(packet)
for packet in stream.encode():
container.mux(packet)
container.close()
return buffer.getvalue()
def decode_audio(media: bytes, sample_rate: int = SAMPLE_RATE) -> np.ndarray | None:
"""비디오·오디오 컨테이너에서 오디오 트랙을 꺼낸다. 트랙이 없으면 None."""
container = av.open(io.BytesIO(media))
try:
if not container.streams.audio:
return None
resampler = av.audio.resampler.AudioResampler(
format="s16", layout="mono", rate=sample_rate)
chunks = []
for frame in container.decode(audio=0):
for resampled in resampler.resample(frame):
chunks.append(resampled.to_ndarray().reshape(-1))
for resampled in resampler.resample(None):
chunks.append(resampled.to_ndarray().reshape(-1))
finally:
container.close()
return np.concatenate(chunks) if chunks else None
def apply_limiter(pcm: np.ndarray, sample_rate: int = SAMPLE_RATE,
limit: float = 0.94, attack: int = 5, release: int = 60) -> np.ndarray:
"""ffmpeg alimiter를 그대로 태운다. 리미터가 컴프레서처럼 작동해 목소리가 또렷해진다."""
graph = av.filter.Graph()
source = graph.add_abuffer(format="s16", layout="mono", sample_rate=sample_rate,
time_base=Fraction(1, sample_rate))
limiter = graph.add("alimiter", f"limit={limit}:attack={attack}:release={release}")
# alimiter는 부동소수로 처리하므로 싱크 앞에서 s16으로 되돌린다
to_s16 = graph.add("aformat", "sample_fmts=s16:channel_layouts=mono")
sink = graph.add("abuffersink")
source.link_to(limiter)
limiter.link_to(to_s16)
to_s16.link_to(sink)
graph.configure()
frame = av.AudioFrame.from_ndarray(pcm.reshape(1, -1), format="s16", layout="mono")
frame.rate = sample_rate
frame.time_base = Fraction(1, sample_rate)
graph.push(frame)
graph.push(None)
chunks = []
while True:
try:
chunks.append(sink.pull().to_ndarray().reshape(-1))
except (av.error.EOFError, av.error.BlockingIOError):
break
return np.concatenate(chunks).astype(np.int16) if chunks else pcm
def trim_silence(pcm: np.ndarray, threshold_db: float = -45,
keep_lead: float = 0.05, keep_trail: float = 0.12,
sample_rate: int = SAMPLE_RATE) -> np.ndarray:
"""앞뒤 무음만 깎는다. 말소리 사이의 쉼은 보존한다."""
threshold = INT16_FULL_SCALE * 10 ** (threshold_db / 20)
loud = np.flatnonzero(np.abs(pcm) > threshold)
if len(loud) == 0:
return pcm[:0]
start = max(0, loud[0] - round(keep_lead * sample_rate))
end = min(len(pcm), loud[-1] + 1 + round(keep_trail * sample_rate))
return pcm[start:end]
+107
View File
@@ -0,0 +1,107 @@
"""Azure Blob Storage 업로드.
SAS 토큰을 붙인 URL로 PUT 한 번. 경로 규칙은 부르는 쪽이 정한다.
클라이언트를 모듈에서 공유해 커넥션 풀을 재사용한다.
"""
import mimetypes
from pathlib import Path
from urllib.parse import quote
import httpx
from config import azure_blob_settings
BLOB_TYPE_HEADER = {"x-ms-blob-type": "BlockBlob"}
DEFAULT_CONTENT_TYPE = "application/octet-stream"
UPLOAD_TIMEOUT = httpx.Timeout(180.0, connect=10.0)
POOL_LIMITS = httpx.Limits(max_keepalive_connections=10, max_connections=20)
_client: httpx.AsyncClient | None = None
def get_client() -> httpx.AsyncClient:
global _client
if _client is None or _client.is_closed:
_client = httpx.AsyncClient(timeout=UPLOAD_TIMEOUT, limits=POOL_LIMITS)
return _client
async def close_client() -> None:
global _client
if _client is not None and not _client.is_closed:
await _client.aclose()
_client = None
def guess_content_type(path: str) -> str:
return mimetypes.guess_type(path)[0] or DEFAULT_CONTENT_TYPE
def public_url(path: str) -> str:
return f"{azure_blob_settings.AZURE_BLOB_BASE_URL.rstrip('/')}/{path.lstrip('/')}"
def sas_token() -> str:
# SAS 토큰이 따옴표나 ? 로 감싸여 오는 경우가 있다
return azure_blob_settings.AZURE_BLOB_SAS_TOKEN.strip("?'\"")
def upload_url(path: str) -> str:
return f"{public_url(path)}?{sas_token()}"
def with_sas(url: str) -> str:
"""컨테이너가 비공개면 읽기에도 토큰이 필요함
우리가 올린 URL일 때만 붙임
"""
token = sas_token()
base = azure_blob_settings.AZURE_BLOB_BASE_URL.rstrip("/")
if token and base and url.startswith(base) and "?" not in url:
return f"{url}?{token}"
return url
def as_attachment(filename: str) -> str:
"""이 값이 붙은 blob은 브라우저가 열면 내려받기가 된다.
<a download>은 다른 출처에 안 먹어 완성본은 이 길로 간다.
한글 파일명은 RFC 5987 형식이라야 온전히 건너간다.
"""
return f"attachment; filename*=UTF-8''{quote(filename)}"
async def upload_bytes(data: bytes, path: str, content_type: str | None = None,
disposition: str | None = None) -> str:
"""path 예: playreel/nol_26007416/clip.mp4. 공개 URL을 돌려준다."""
if not azure_blob_settings.AZURE_BLOB_BASE_URL or not azure_blob_settings.AZURE_BLOB_SAS_TOKEN:
raise RuntimeError("AZURE_BLOB_BASE_URL / AZURE_BLOB_SAS_TOKEN 없음")
headers = {"Content-Type": content_type or guess_content_type(path), **BLOB_TYPE_HEADER}
if disposition:
# 헤더 이름이 Content-Disposition이면 이 요청 본문의 성격으로 읽힌다.
# blob 속성으로 저장되는 것은 x-ms- 쪽이다
headers["x-ms-blob-content-disposition"] = disposition
response = await get_client().put(upload_url(path), content=data, headers=headers)
if response.status_code not in (200, 201):
print(f"[blob] 업로드 실패 {response.status_code} {path}: {response.text[:300]}",
flush=True)
raise RuntimeError(f"blob 업로드 실패 {response.status_code}")
return public_url(path)
async def upload_file(file_path: Path, path: str, content_type: str | None = None) -> str:
return await upload_bytes(file_path.read_bytes(), path,
content_type or guess_content_type(file_path.name))
async def download_bytes(url: str) -> bytes:
"""upload_bytes가 돌려준 URL을 그대로 받아 내용을 가져온다.
예외 메시지에 주소를 넣지 않는다 — 실패는 잡에 기록되어 화면까지 간다.
어느 파일이었는지는 로그를 본다.
"""
response = await get_client().get(with_sas(url))
if response.status_code != 200:
print(f"[blob] 다운로드 실패 {response.status_code}: {url}", flush=True)
raise RuntimeError(f"blob 다운로드 실패 {response.status_code}")
return response.content
+62
View File
@@ -0,0 +1,62 @@
"""structured output 공용 래퍼.
OpenAI 호환 /chat/completions를 쓰는 프로바이더면 base_url만 바꿔 그대로 쓴다.
이미지 인코딩은 호출측 책임이라 여기서는 URL(data URI 또는 http)만 받는다.
"""
from collections.abc import Sequence
from typing import TypeVar
from openai import AsyncOpenAI
from pydantic import BaseModel
T = TypeVar("T", bound=BaseModel)
class StructuredLLM:
def __init__(self, model: str, api_key: str, base_url: str | None = None):
self.model = model
self._client = AsyncOpenAI(api_key=api_key, base_url=base_url)
async def ask(
self,
schema: type[T],
prompt: str,
*,
system: str | None = None,
temperature: float = 0.0,
) -> T:
return await self._parse(schema, prompt, system, temperature)
async def ask_with_images(
self,
schema: type[T],
prompt: str,
images: Sequence[tuple[str, str]],
*,
detail: str = "high",
system: str | None = None,
temperature: float = 0.0,
) -> T:
"""images는 (라벨, 이미지 URL) 쌍. 라벨이 이미지 바로 앞에 붙어 순서가 보존된다."""
content: list[dict] = [{"type": "text", "text": prompt}]
for label, url in images:
content.append({"type": "text", "text": label})
content.append({"type": "image_url", "image_url": {"url": url, "detail": detail}})
return await self._parse(schema, content, system, temperature)
async def _parse(self, schema: type[T], content, system: str | None, temperature: float) -> T:
messages = [{"role": "system", "content": system}] if system else []
messages.append({"role": "user", "content": content})
msg = (await self._client.chat.completions.parse(
model=self.model,
messages=messages,
response_format=schema,
temperature=temperature,
)).choices[0].message
if msg.refusal:
raise RuntimeError(f"{self.model} 거절: {msg.refusal}")
if msg.parsed is None:
raise RuntimeError(f"{self.model} 파싱 실패: {msg.content!r}")
return msg.parsed
+25
View File
@@ -0,0 +1,25 @@
"""동봉 폰트 로더. 없으면 그 자리에서 죽는다 — 기본 폰트로 떨어지면 타이포가 어긋난다."""
from functools import lru_cache
from pathlib import Path
from PIL import ImageFont
FONT_DIR = Path(__file__).resolve().parent.parent / "assets" / "fonts"
PRETENDARD = "Pretendard-{weight}.otf"
GYEONGGI = "GyeonggiTitleVOTF-Bold.otf"
@lru_cache(maxsize=32)
def font(weight: str, size: int) -> ImageFont.FreeTypeFont:
path = FONT_DIR / PRETENDARD.format(weight=weight)
if not path.exists():
raise RuntimeError(f"폰트 없음: {path}")
return ImageFont.truetype(str(path), size)
@lru_cache(maxsize=8)
def title_font(size: int) -> ImageFont.FreeTypeFont:
path = FONT_DIR / GYEONGGI
if not path.exists():
raise RuntimeError(f"폰트 없음: {path}")
return ImageFont.truetype(str(path), size)
+78
View File
@@ -0,0 +1,78 @@
"""Higgsfield CLI 래퍼.
인증이 `~/.config/higgsfield/credentials.json`의 CLI 토큰이라 서브프로세스를 피할 수 없고,
머신마다 사람이 한 번 로그인해야 한다:
`npm i -g @higgsfield/cli` → `higgsfield auth login` → `higgsfield workspace set <id>`
"""
import asyncio
import json
import re
CLI = "higgsfield"
CLI_TIMEOUT = 2100
# Higgsfield가 제공하는 모델 식별자. 어느 단계가 무엇을 쓸지는 그 단계가 정한다.
KLING_3_0 = "kling3_0"
VEO_3_1 = "veo3_1"
TOPAZ_IMAGE = "topaz_image"
TOPAZ_TEXT_REFINE = "Text Refine"
RESULT_URL_PATTERN = re.compile(r'"result_url"\s*:\s*"([^"]+)"')
CREDITS_PATTERN = re.compile(r'"credits(?:_exact)?"\s*:\s*([0-9.]+)')
PLAIN_CREDITS_PATTERN = re.compile(r"([0-9.]+)\s*credits")
async def run_cli(*args: str, timeout: int = CLI_TIMEOUT) -> str:
try:
process = await asyncio.create_subprocess_exec(
CLI, *args,
stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE)
except FileNotFoundError:
raise RuntimeError(
"higgsfield CLI가 없다 — `npm i -g @higgsfield/cli` 후 `higgsfield auth login`")
try:
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout)
except TimeoutError:
process.kill()
raise RuntimeError(f"higgsfield {args[0]} 타임아웃 {timeout}초")
if process.returncode != 0:
detail = (stderr or stdout).decode(errors="ignore")[-600:]
raise RuntimeError(f"higgsfield {args[0]} 실패:\n{detail}")
return stdout.decode(errors="ignore")
async def account_status() -> dict:
output = await run_cli("account", "status", "--json", timeout=60)
try:
return json.loads(output)
except json.JSONDecodeError:
raise RuntimeError(f"account status 응답을 파싱할 수 없다:\n{output[-400:]}")
async def assert_account(expected: str) -> dict:
"""다른 계정으로 로그인하면 토큰이 조용히 바뀌어 그 계정 크레딧이 빠지므로,
편당 22크레딧을 쓰기 직전에 로그인 계정을 확인하고 어긋나면 죽는다."""
status = await account_status()
email = (status.get("email") or "").strip().lower()
if email != expected.lower():
raise RuntimeError(
f"[가드] Higgsfield 계정 불일치 — 로그인: {email or '(없음)'} / 기대: {expected}\n"
f"크레딧이 다른 계정에서 빠진다. logout 후 {expected}로 다시 로그인할 것. "
f"의도한 전환이면 HIGGSFIELD_ACCOUNT={email} 로 명시할 것.")
return status
def parse_credits(output: str) -> float:
"""못 찾으면 죽는다. 0.0으로 때우면 CLI 출력 포맷이 바뀌어도 "0 크레딧 썼다"로 통과한다."""
match = CREDITS_PATTERN.search(output) or PLAIN_CREDITS_PATTERN.search(output)
if not match:
raise RuntimeError(f"CLI 출력에서 크레딧을 못 읽었다 — 포맷이 바뀌었는지 확인할 것:\n"
f"{output[-600:]}")
return float(match.group(1))
def parse_result_url(output: str) -> str:
match = RESULT_URL_PATTERN.search(output)
if not match:
raise RuntimeError(f"result_url 없음 — 생성 실패:\n{output[-1200:]}")
return match.group(1)
+106
View File
@@ -0,0 +1,106 @@
import base64
import io
import numpy as np
from PIL import Image, ImageDraw, ImageFont
Image.MAX_IMAGE_PIXELS = None
IMAGE_SIGNATURES = ((b"\xff\xd8\xff", "jpg"), (b"\x89PNG\r\n\x1a\n", "png"),
(b"GIF87a", "gif"), (b"GIF89a", "gif"))
LOGO_BAR_SEARCH_FROM = 0.88 # 하단 12%에서만 밝은 띠를 찾는다
LOGO_BAR_BRIGHTNESS = 200
LOGO_BAR_MIN_ROWS = 20
def sniff_extension(data: bytes) -> str:
"""확장자가 .gif여도 실제 바이트는 JPEG·PNG인 경우가 많아 매직 넘버로 판별한다."""
head = data[:12]
for signature, extension in IMAGE_SIGNATURES:
if head.startswith(signature):
return extension
if head[:4] == b"RIFF" and head[8:12] == b"WEBP":
return "webp"
return "bin"
def content_box(frame: Image.Image) -> tuple[int, int, int, int]:
"""레터박스(검정·흰 여백)를 걷어낸 실제 포스터 영역."""
brightness = np.asarray(frame.convert("RGB")).astype(np.float32).mean(2)
live = (brightness > 14) & (brightness < 244)
cols = np.nonzero(live.any(0))[0]
rows = np.nonzero(live.any(1))[0]
return int(cols.min()), int(rows.min()), int(cols.max()) + 1, int(rows.max()) + 1
def vlm_grid_overlay(poster: Image.Image) -> Image.Image:
"""VLM이 눈금을 읽어 좌표를 답하게 하는 격자.
숫자가 없으면 모델이 선을 세야 하는데 그걸 못한다. 축을 구분하려고 색도 둘로 나눈다 —
프롬프트가 '빨간 가로선 = 세로 위치, 하늘색 세로선 = 가로 위치'로 못박고 있다.
"""
overlay = poster.convert("RGB").copy()
width, height = overlay.size
draw = ImageDraw.Draw(overlay, "RGBA")
font = ImageFont.load_default(max(14, width // 55))
for row in range(1, 20):
y = int(height * row * 0.05)
draw.line([(0, y), (width, y)], fill=(255, 0, 80, 150), width=max(1, width // 700))
if row % 2 == 0:
draw.text((4, y + 2), f"{row * 5}", font=font, fill=(255, 255, 0, 255))
for col in range(1, 10):
x = int(width * col * 0.10)
draw.line([(x, 0), (x, height)], fill=(0, 220, 255, 130), width=max(1, width // 700))
draw.text((x + 3, 3), f"{col * 10}", font=font, fill=(0, 255, 255, 255))
return overlay
def review_grid_overlay(poster: Image.Image) -> Image.Image:
"""사람이 검수 화면에서 요소를 지목하는 격자.
읽는 게 아니라 가리키는 용도라 라벨이 필요 없고, 촘촘할수록 좋아서 가로도 5%로 둔다.
"""
overlay = poster.convert("RGB").copy()
width, height = overlay.size
draw = ImageDraw.Draw(overlay)
line_width = max(1, width // 900)
for step in range(1, 20):
x, y = width * step / 20, height * step / 20
draw.line([(x, 0), (x, height)], fill=(255, 0, 128), width=line_width)
draw.line([(0, y), (width, y)], fill=(255, 0, 128), width=line_width)
return overlay
def bar_box(poster: Image.Image) -> tuple[int, int, int, int] | None:
"""하단 주최·주관·후원 로고 띠(밝은 가로 밴드)의 bbox."""
pixels = np.asarray(poster.convert("RGB")).astype(np.float32)
height, width = pixels.shape[:2]
search_from = int(height * LOGO_BAR_SEARCH_FROM)
rows = np.nonzero(pixels[search_from:].mean(axis=(1, 2)) > LOGO_BAR_BRIGHTNESS)[0]
if len(rows) < LOGO_BAR_MIN_ROWS:
return None
return 0, search_from + rows.min() - 4, width, min(height, search_from + rows.max() + 5)
def logo_bar(poster: Image.Image) -> Image.Image | None:
box = bar_box(poster)
return poster.crop(box) if box else None
def round_mask(size: tuple[int, int], radius_ratio: float = 0.08) -> Image.Image:
"""사각 패치를 둥근 카드 위에 얹을 때 모서리가 튀는 것을 막는 알파 마스크."""
width, height = size
mask = Image.new("L", size, 0)
ImageDraw.Draw(mask).rounded_rectangle(
(0, 0, width - 1, height - 1),
radius=max(1, round(min(width, height) * radius_ratio)), fill=255)
return mask
def to_data_uri(image: Image.Image, max_size: tuple[int, int] = (1100, 1600)) -> str:
image = image.copy()
image.thumbnail(max_size, Image.LANCZOS)
buffer = io.BytesIO()
image.save(buffer, "JPEG", quality=92)
return "data:image/jpeg;base64," + base64.b64encode(buffer.getvalue()).decode()
+12
View File
@@ -0,0 +1,12 @@
import json
from pathlib import Path
RAW_PROMPT_DIR = Path(__file__).resolve().parent.parent / "raw_prompt"
def load_prompt(name: str) -> str:
return (RAW_PROMPT_DIR / f"{name}.txt").read_text(encoding="utf-8")
def load_prompt_json(name: str) -> dict:
return json.loads((RAW_PROMPT_DIR / f"{name}.json").read_text(encoding="utf-8"))
+129
View File
@@ -0,0 +1,129 @@
"""포스터에서 QR 흰 카드를 찾는다.
"우상단에서 가장 큰 흰 블롭"으로 잡던 검출기가 하늘 그러데이션·흰 글자띠·색 체크무늬까지
걸어서, 배치 27장으로 캘리브레이션한 뒤 파인더 패턴(1:1:3:1:1)까지 확인한다.
"""
import numpy as np
from PIL import Image
from scipy import ndimage
# 우하단에 QR을 단 포스터를 통째로 놓친 적이 있어 네 귀퉁이를 다 본다
CORNER_WINDOWS = ((0.70, 0.00, 1.00, 0.18), (0.70, 0.82, 1.00, 1.00),
(0.00, 0.00, 0.30, 0.18), (0.00, 0.82, 0.30, 1.00))
FINDER_HIT_THRESHOLD = 30
def otsu_threshold(gray: np.ndarray) -> int:
histogram, _ = np.histogram(gray, bins=256, range=(0, 256))
dark_counts = np.cumsum(histogram)
light_counts = gray.size - dark_counts
cumulative = np.cumsum(histogram * np.arange(256))
dark_mean = np.divide(cumulative, dark_counts, out=np.zeros(256), where=dark_counts > 0)
light_mean = np.divide(cumulative[-1] - cumulative, light_counts,
out=np.zeros(256), where=light_counts > 0)
return int(np.argmax(dark_counts * light_counts * (dark_mean - light_mean) ** 2))
def finder_pattern_hits(binary: np.ndarray) -> int:
"""QR 파인더 패턴(모서리 겹눈)의 1:1:3:1:1 런 비율을 만족하는 스캔라인 수."""
hits = 0
for line in binary:
change_points = np.flatnonzero(np.diff(line)) + 1
if len(change_points) < 4:
continue
bounds = np.concatenate(([0], change_points, [len(line)]))
runs, values = np.diff(bounds), line[bounds[:-1]]
for start in range(len(runs) - 4):
if values[start] != 1: # 어두운 런에서 시작해야 한다
continue
run = runs[start:start + 5]
unit = run.sum() / 7.0
if unit >= 1 and abs(run[0] - unit) <= .6 * unit and abs(run[1] - unit) <= .6 * unit \
and abs(run[2] - 3 * unit) <= 1.2 * unit \
and abs(run[3] - unit) <= .6 * unit and abs(run[4] - unit) <= .6 * unit:
hits += 1
break
return hits
def is_qr(poster: Image.Image, box: tuple[int, int, int, int]) -> bool:
"""밝은 블롭이 정말 QR인가. 정답과 오검출이 aspect·채도·잉크·파인더 어느 축으로도 겹치지 않는다."""
left, top, right, bottom = box
width, height = right - left, bottom - top
if not (0.75 <= width / max(height, 1) <= 1.35):
return False
if not (0.015 <= width / poster.width <= 0.15):
return False
card = poster.crop(box).convert("RGB")
if max(width, height) > 400: # 파인더 스캔은 400px면 충분하다
scale = 400 / max(width, height)
card = card.resize((max(1, round(width * scale)), max(1, round(height * scale))),
Image.LANCZOS)
pixels = np.asarray(card).astype(np.float32)
if float(np.mean(pixels.max(2) - pixels.min(2))) > 22: # QR은 무채색이다
return False
gray = pixels.mean(2)
binary = (gray < otsu_threshold(gray)).astype(np.uint8)
if not (0.15 <= float(binary.mean()) <= 0.60): # 글자는 더 성기고 반전 블록은 더 빽빽하다
return False
return (finder_pattern_hits(binary) >= FINDER_HIT_THRESHOLD
and finder_pattern_hits(binary.T) >= FINDER_HIT_THRESHOLD)
def find_white_blobs(poster: Image.Image, window: tuple[float, float, float, float],
top_n: int = 6) -> list[tuple[int, int, int, int]]:
"""정규 좌표 창 안의 밝은 블롭 bbox들. 큰 것부터."""
width, height = poster.size
offset_x, offset_y = int(width * window[0]), int(height * window[1])
region = np.asarray(poster.convert("RGB")).astype(np.float32)[
offset_y:int(height * window[3]), offset_x:int(width * window[2])]
if region.size == 0:
return []
white = ndimage.binary_closing(region.min(2) > 205, np.ones((9, 9), bool))
labels, count = ndimage.label(white)
if count == 0:
return []
sizes = ndimage.sum(white, labels, range(1, count + 1))
boxes = ndimage.find_objects(labels, max_label=count)
found = []
for index in np.argsort(sizes)[::-1][:top_n]: # 가장 큰 게 QR이 아닐 수도 있다
rows, cols = boxes[int(index)]
found.append((offset_x + cols.start, offset_y + rows.start,
offset_x + cols.stop, offset_y + rows.stop))
return found
def qr_box(poster: Image.Image, strict: bool = True,
window: tuple[float, float, float, float] | None = None
) -> tuple[int, int, int, int] | None:
"""QR 흰 카드의 bbox. 없으면 None.
strict=True(원본 포스터용)는 is_qr을 통과한 블롭만 돌려준다.
strict=False(모델 출력 검증용)는 창 안의 가장 큰 흰 블롭을 돌려주는데, 모델이 뭉갠 QR은
파인더가 살아남지 못해 "예상한 자리에 흰 카드가 있는가"만 물을 수 있기 때문이다.
"""
for corner in ((window,) if window else CORNER_WINDOWS):
for box in find_white_blobs(poster, corner):
if not strict or is_qr(poster, box):
return box
return None
def qr_card(poster: Image.Image, pad: int = 14) -> Image.Image | None:
"""QR 흰 카드를 오려낸다. 둥근 모서리라 사각 크롭엔 배경이 딸려와 채도로 걷어낸다.
pad는 카드 둘레에 덧대는 흰 여백(quiet zone). 포스터 안쪽 제자리에 덮을 때는
카드 자체에 여백이 있으므로 0을 준다.
"""
box = qr_box(poster)
if box is None:
return None
card = np.asarray(poster.crop(box).convert("RGB")).astype(np.float32)
card[(card.max(2) - card.min(2)) > 35] = 255.0 # 유채색 프린지 → 흰색
cropped = Image.fromarray(card.astype(np.uint8))
if pad == 0:
return cropped
padded = Image.new("RGB", (cropped.width + pad * 2, cropped.height + pad * 2),
(255, 255, 255))
padded.paste(cropped, (pad, pad))
return padded
+104
View File
@@ -0,0 +1,104 @@
"""프레임 PNG를 디스크에 풀지 않고 메모리에서 디코드·인코드하는 비디오 유틸."""
import io
from collections.abc import Iterable, Iterator, Sequence
from fractions import Fraction
from pathlib import Path
import av
import numpy as np
from PIL import Image
AAC_FRAME_SIZE = 1024
def open_clip(clip: bytes | Path):
return av.open(io.BytesIO(clip) if isinstance(clip, bytes) else str(clip))
def duration(clip: bytes | Path) -> float:
container = open_clip(clip)
try:
if container.duration is None:
raise RuntimeError("클립 길이를 읽을 수 없다")
return container.duration / av.time_base
finally:
container.close()
def frames_at(clip: bytes | Path, times: Sequence[float]) -> list[Image.Image]:
"""지정한 시각들의 프레임. seek은 키프레임 단위라 그 이후 첫 프레임을 취한다."""
container = open_clip(clip)
stream = container.streams.video[0]
frames = []
try:
for at in times:
container.seek(int(at / stream.time_base), stream=stream)
picked = None
for frame in container.decode(stream):
picked = frame
if frame.time is not None and frame.time >= at - 1e-3:
break
if picked is None:
raise RuntimeError(f"t={at}s 프레임을 못 뽑았다")
frames.append(picked.to_image())
finally:
container.close()
return frames
def decode_frames(clip: bytes | Path) -> Iterator[Image.Image]:
"""모든 프레임을 순서대로 흘려보낸다. 한 장씩만 메모리에 올라간다."""
container = open_clip(clip)
try:
for frame in container.decode(video=0):
yield frame.to_image()
finally:
container.close()
def encode_mp4(frames: Iterable[Image.Image], size: tuple[int, int],
audio: np.ndarray | None = None, *, fps: int = 24,
sample_rate: int = 44100, crf: int = 18,
audio_bit_rate: int = 192000) -> bytes:
"""H.264 영상 + AAC 스테레오 오디오를 mp4 바이트로 뽑는다. 모노 오디오는 양 채널에 복제한다."""
buffer = io.BytesIO()
container = av.open(buffer, "w", format="mp4")
video_stream = container.add_stream("libx264", rate=fps)
video_stream.width, video_stream.height = size
video_stream.pix_fmt = "yuv420p"
video_stream.options = {"crf": str(crf), "preset": "medium"}
audio_stream = None
if audio is not None:
audio_stream = container.add_stream("aac", rate=sample_rate)
audio_stream.layout = "stereo"
audio_stream.bit_rate = audio_bit_rate
for index, image in enumerate(frames):
frame = av.VideoFrame.from_image(image)
frame.pts = index
for packet in video_stream.encode(frame):
container.mux(packet)
for packet in video_stream.encode():
container.mux(packet)
if audio_stream is not None:
interleaved = np.repeat(audio, 2)
block_size = audio_stream.frame_size or AAC_FRAME_SIZE
for start in range(0, len(audio), block_size):
block = interleaved[start * 2:(start + block_size) * 2]
if len(block) < block_size * 2:
block = np.pad(block, (0, block_size * 2 - len(block)))
frame = av.AudioFrame.from_ndarray(block.reshape(1, -1),
format="s16", layout="stereo")
frame.rate = sample_rate
frame.pts = start
frame.time_base = Fraction(1, sample_rate)
for packet in audio_stream.encode(frame):
container.mux(packet)
for packet in audio_stream.encode():
container.mux(packet)
container.close()
return buffer.getvalue()