render까지 8초 shortform pipeline 형성
This commit is contained in:
1 parent
05747f6b8f
commit
659fd53b97
30 files changed
+1203
-30
No files matched your search
+51
-1
@@ -1,5 +1,6 @@
|
||||
"""메모리 위에서만 도는 오디오 처리. 파일도 서브프로세스도 없다."""
|
||||
"""파일도 서브프로세스도 없이 메모리에서 처리하는 오디오 유틸."""
|
||||
import io
|
||||
from fractions import Fraction
|
||||
|
||||
import av
|
||||
import numpy as np
|
||||
@@ -40,6 +41,55 @@ def encode_mp3(pcm: np.ndarray, sample_rate: int = SAMPLE_RATE) -> bytes:
|
||||
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:
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""structured output 공용 래퍼.
|
||||
|
||||
OpenAI 호환 /chat/completions를 쓰는 프로바이더면 base_url만 바꿔 그대로 쓴다.
|
||||
이미지는 이미 인코딩된 URL(data URI 또는 http)로 받는다 — 인코딩은 호출측 책임.
|
||||
이미지 인코딩은 호출측 책임이라 여기서는 URL(data URI 또는 http)만 받는다.
|
||||
"""
|
||||
from collections.abc import Sequence
|
||||
from typing import TypeVar
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""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
|
||||
|
||||
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)
|
||||
+41
-1
@@ -1,10 +1,50 @@
|
||||
import base64
|
||||
import io
|
||||
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
Image.MAX_IMAGE_PIXELS = None
|
||||
|
||||
LOGO_BAR_SEARCH_FROM = 0.88 # 하단 12%에서만 밝은 띠를 찾는다
|
||||
LOGO_BAR_BRIGHTNESS = 200
|
||||
LOGO_BAR_MIN_ROWS = 20
|
||||
|
||||
|
||||
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 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()
|
||||
|
||||
+26
-6
@@ -1,13 +1,13 @@
|
||||
"""포스터에서 QR 흰 카드를 찾는다.
|
||||
|
||||
"우상단에서 가장 큰 흰 블롭"을 QR로 삼던 검출기는 하늘 그러데이션·흰 글자띠·색 체크무늬를
|
||||
줄줄이 걸었다. 배치 27장으로 캘리브레이션해 파인더 패턴(1:1:3:1:1)까지 확인한다.
|
||||
"우상단에서 가장 큰 흰 블롭"으로 잡던 검출기가 하늘 그러데이션·흰 글자띠·색 체크무늬까지
|
||||
걸어서, 배치 27장으로 캘리브레이션한 뒤 파인더 패턴(1:1:3:1:1)까지 확인한다.
|
||||
"""
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from scipy import ndimage
|
||||
|
||||
# QR은 우상단에만 있지 않다 — 우하단에 단 포스터를 통째로 놓친 적이 있다. 네 귀퉁이를 다 본다.
|
||||
# 우하단에 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
|
||||
@@ -98,12 +98,32 @@ def qr_box(poster: Image.Image, strict: bool = True,
|
||||
) -> tuple[int, int, int, int] | None:
|
||||
"""QR 흰 카드의 bbox. 없으면 None.
|
||||
|
||||
strict=True(원본 포스터용): is_qr을 통과한 블롭만. QR의 유무는 원본이 정한다.
|
||||
strict=False(모델 출력 검증용): 창 안의 가장 큰 흰 블롭. 모델이 뭉갠 QR은 파인더가
|
||||
살아남지 못하므로, 묻는 것은 "QR인가"가 아니라 "예상한 자리에 흰 카드가 있는가"다.
|
||||
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
|
||||
@@ -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()
|
||||
Reference in new issue
Block a user