File size: 19,852 Bytes
1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 1ed87be bbf28e1 |
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 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 |
import gradio as gr
import os
import tempfile
import base64
import math
import traceback
import numpy as np
from PIL import Image
from moviepy.editor import VideoFileClip, vfx
from shutil import copyfile
from datetime import datetime, timedelta
########################################
# 1) PIL ANTIALIAS μλ¬ λμ (Monkey-patch)
########################################
try:
from PIL import Resampling
if not hasattr(Image, "ANTIALIAS"):
Image.ANTIALIAS = Resampling.LANCZOS
except ImportError:
pass
########################################
# 2) λ΄λΆ λλ²κ·Έ λ‘κΉ
(UIμμ λ―ΈμΆλ ₯)
########################################
DEBUG_LOG_LIST = []
def log_debug(msg: str):
print("[DEBUG]", msg)
DEBUG_LOG_LIST.append(msg)
########################################
# 3) μκ° νμ λ³ν μ νΈλ¦¬ν° ν¨μ
########################################
END_EPSILON = 0.01
def round_down_to_one_decimal(value: float) -> float:
return math.floor(value * 10) / 10
def safe_end_time(duration: float) -> float:
tmp = duration - END_EPSILON
if tmp < 0:
tmp = 0
return round_down_to_one_decimal(tmp)
def coalesce_to_zero(val):
"""
Noneμ΄λ NaN, λ¬Έμμ΄ μ€λ₯ λ±μ΄ λ€μ΄μ€λ©΄ 0.0μΌλ‘ λ³ν
"""
if val is None:
return 0.0
try:
return float(val)
except:
return 0.0
def seconds_to_hms(seconds: float) -> str:
"""μ΄λ₯Ό HH:MM:SS νμμΌλ‘ λ³ν"""
try:
seconds = max(0, seconds)
td = timedelta(seconds=round(seconds))
return str(td)
except Exception as e:
log_debug(f"[seconds_to_hms] λ³ν μ€λ₯: {e}")
return "00:00:00"
def hms_to_seconds(time_str: str) -> float:
"""HH:MM:SS νμμ μ΄λ‘ λ³ν"""
try:
parts = time_str.strip().split(':')
parts = [int(p) for p in parts]
while len(parts) < 3:
parts.insert(0, 0) # λΆμ‘±ν λΆλΆμ 0μΌλ‘ μ±μ
hours, minutes, seconds = parts
return hours * 3600 + minutes * 60 + seconds
except Exception as e:
log_debug(f"[hms_to_seconds] λ³ν μ€λ₯: {e}")
return -1 # μ€λ₯ μ -1 λ°ν
########################################
# 4) μ
λ‘λλ μμ νμΌ μ μ₯
########################################
def save_uploaded_video(video_input):
if not video_input:
log_debug("[save_uploaded_video] video_input is None.")
return None
if isinstance(video_input, str):
log_debug(f"[save_uploaded_video] video_input is str: {video_input}")
if os.path.exists(video_input):
return video_input
else:
log_debug("[save_uploaded_video] Path does not exist.")
return None
if isinstance(video_input, dict):
log_debug(f"[save_uploaded_video] video_input is dict: {list(video_input.keys())}")
if 'data' in video_input:
file_data = video_input['data']
if isinstance(file_data, str) and file_data.startswith("data:"):
base64_str = file_data.split(';base64,')[-1]
try:
video_binary = base64.b64decode(base64_str)
tmp = tempfile.NamedTemporaryFile(delete=False, suffix=".mp4")
tmp.write(video_binary)
tmp.flush()
tmp.close()
log_debug(f"[save_uploaded_video] Created temp file: {tmp.name}")
return tmp.name
except Exception as e:
log_debug(f"[save_uploaded_video] base64 λμ½λ© μ€λ₯: {e}")
return None
else:
if isinstance(file_data, str) and os.path.exists(file_data):
log_debug("[save_uploaded_video] data νλκ° μ€μ κ²½λ‘")
return file_data
else:
log_debug("[save_uploaded_video] data νλκ° μμμΉ λͺ»ν νν.")
return None
else:
log_debug("[save_uploaded_video] dictμ΄μ§λ§ 'data' ν€κ° μμ.")
return None
log_debug("[save_uploaded_video] Unrecognized type.")
return None
########################################
# 5) μμ κΈΈμ΄, ν΄μλ, μ€ν¬λ¦°μ·
########################################
def get_video_duration(video_dict):
path = save_uploaded_video(video_dict)
if not path:
return "00:00:00"
try:
clip = VideoFileClip(path)
dur = clip.duration
clip.close()
log_debug(f"[get_video_duration] duration={dur}")
return seconds_to_hms(dur)
except Exception as e:
log_debug(f"[get_video_duration] μ€λ₯: {e}\n{traceback.format_exc()}")
return "00:00:00"
def get_resolution(video_dict):
path = save_uploaded_video(video_dict)
if not path:
return "0x0"
try:
clip = VideoFileClip(path)
w, h = clip.size
clip.close()
log_debug(f"[get_resolution] w={w}, h={h}")
return f"{w}x{h}"
except Exception as e:
log_debug(f"[get_resolution] μ€λ₯: {e}\n{traceback.format_exc()}")
return "0x0"
def get_screenshot_at_time(video_dict, time_in_seconds):
path = save_uploaded_video(video_dict)
if not path:
return None
try:
clip = VideoFileClip(path)
actual_duration = clip.duration
# λ§μ§λ§ νλ μ μ κ·Ό λ°©μ§
if time_in_seconds >= actual_duration - END_EPSILON:
time_in_seconds = safe_end_time(actual_duration)
t = max(0, min(time_in_seconds, clip.duration))
log_debug(f"[get_screenshot_at_time] t={t:.3f} / duration={clip.duration:.3f}")
frame = clip.get_frame(t)
clip.close()
return frame # numpy λ°°μ΄λ‘ λ°ν
except Exception as e:
log_debug(f"[get_screenshot_at_time] μ€λ₯: {e}\n{traceback.format_exc()}")
return None
########################################
# 6) μ
λ‘λ μ΄λ²€νΈ
########################################
def on_video_upload(video_dict):
log_debug("[on_video_upload] Called.")
dur_hms = get_video_duration(video_dict)
w, h = map(int, get_resolution(video_dict).split('x'))
resolution_str = f"{w}x{h}"
start_t = 0.0
end_t = safe_end_time(hms_to_seconds(dur_hms))
start_img = get_screenshot_at_time(video_dict, start_t)
end_img = None
if end_t > 0:
end_img = get_screenshot_at_time(video_dict, end_t)
# μμλλ‘: μμ κΈΈμ΄, ν΄μλ(λ¬Έμμ΄), μμ μκ°, λ μκ°, μμ μ€ν¬λ¦°μ·, λ μ€ν¬λ¦°μ·
return dur_hms, resolution_str, seconds_to_hms(start_t), seconds_to_hms(end_t), start_img, end_img
########################################
# 7) μ€ν¬λ¦°μ· κ°±μ
########################################
def update_screenshots(video_dict, start_time_str, end_time_str):
start_time = hms_to_seconds(start_time_str)
end_time = hms_to_seconds(end_time_str)
if start_time < 0 or end_time < 0:
return (None, None)
log_debug(f"[update_screenshots] start={start_time_str}, end={end_time_str}")
end_time = round_down_to_one_decimal(end_time)
img_start = get_screenshot_at_time(video_dict, start_time)
img_end = get_screenshot_at_time(video_dict, end_time)
return (img_start, img_end)
########################################
# 8) GIF μμ±
########################################
def generate_gif(video_dict, start_time_str, end_time_str, fps, resize_factor, speed_factor, duration, resolution_str):
# "WxH" νν ν΄μλ νμ±
parts = resolution_str.split("x")
if len(parts) == 2:
try:
orig_w = float(parts[0])
orig_h = float(parts[1])
except:
orig_w = 0
orig_h = 0
else:
orig_w = 0
orig_h = 0
start_time = hms_to_seconds(start_time_str)
end_time = hms_to_seconds(end_time_str)
if start_time < 0 or end_time < 0:
return "μλͺ»λ μκ° νμμ
λλ€. HH:MM:SS νμμΌλ‘ μ
λ ₯ν΄μ£ΌμΈμ."
fps = coalesce_to_zero(fps)
resize_factor = coalesce_to_zero(resize_factor)
speed_factor = coalesce_to_zero(speed_factor)
log_debug("[generate_gif] Called.")
log_debug(f" start_time={start_time}, end_time={end_time}, fps={fps}, resize_factor={resize_factor}, speed_factor={speed_factor}")
path = save_uploaded_video(video_dict)
if not path:
err_msg = "[generate_gif] μμμ΄ μ
λ‘λλμ§ μμμ΅λλ€."
log_debug(err_msg)
return err_msg
try:
clip = VideoFileClip(path)
end_time = round_down_to_one_decimal(end_time)
st = max(0, start_time)
et = max(0, end_time)
if et > clip.duration:
et = clip.duration
# λ§μ§λ§ νλ μ μ κ·Ό λ°©μ§
if et >= clip.duration - END_EPSILON:
et = safe_end_time(clip.duration)
log_debug(f" subclip range => st={st:.2f}, et={et:.2f}, totalDur={clip.duration:.2f}")
if st >= et:
clip.close()
err_msg = "μμ μκ°μ΄ λ μκ°λ³΄λ€ κ°κ±°λ ν½λλ€."
log_debug(f"[generate_gif] {err_msg}")
return err_msg
sub_clip = clip.subclip(st, et)
# λ°°μ μ‘°μ
if speed_factor != 1.0:
sub_clip = sub_clip.fx(vfx.speedx, speed_factor)
log_debug(f" speed_factor applied: {speed_factor}x")
# 리μ¬μ΄μ¦
if resize_factor < 1.0 and orig_w > 0 and orig_h > 0:
new_w = int(orig_w * resize_factor)
new_h = int(orig_h * resize_factor)
log_debug(f" resizing => {new_w}x{new_h}")
sub_clip = sub_clip.resize((new_w, new_h))
# κ³ μ ν νμΌ μ΄λ¦ μμ±
gif_fd, gif_path = tempfile.mkstemp(suffix=".gif")
os.close(gif_fd) # νμΌ λμ€ν¬λ¦½ν° λ«κΈ°
log_debug(f" writing GIF to {gif_path}")
sub_clip.write_gif(gif_path, fps=int(fps), program='ffmpeg') # ffmpeg μ¬μ©
clip.close()
sub_clip.close()
if os.path.exists(gif_path):
log_debug(f" GIF μμ± μλ£! size={os.path.getsize(gif_path)} bytes.")
return gif_path
else:
err_msg = "GIF μμ±μ μ€ν¨νμ΅λλ€."
log_debug(f"[generate_gif] {err_msg}")
return err_msg
except Exception as e:
err_msg = f"[generate_gif] μ€λ₯ λ°μ: {e}\n{traceback.format_exc()}"
log_debug(err_msg)
return err_msg
########################################
# 9) GIF λ€μ΄λ‘λ νμΌ μ΄λ¦ λ³κ²½ ν¨μ
########################################
def prepare_download_gif(gif_path, input_video_dict):
"""GIF νμΌμ λ€μ΄λ‘λ μ΄λ¦μ λ³κ²½νκ³ κ²½λ‘λ₯Ό λ°ν"""
if gif_path is None:
return None
# νκ΅ μκ° νμμ€ν¬ν μμ± ν¨μ
def get_korean_timestamp():
korea_time = datetime.utcnow() + timedelta(hours=9)
return korea_time.strftime('%Y%m%d_%H%M%S')
timestamp = get_korean_timestamp()
# μ
λ ₯λ GIF μ΄λ¦μμ κΈ°λ³Έ μ΄λ¦ μΆμΆ
if input_video_dict and isinstance(input_video_dict, dict) and 'data' in input_video_dict:
file_data = input_video_dict['data']
if isinstance(file_data, str) and file_data.startswith("data:"):
base_name = "GIF" # base64 λ°μ΄ν°μμλ μλ³Έ νμΌ μ΄λ¦μ μ μ μμΌλ―λ‘ κΈ°λ³Έ μ΄λ¦ μ¬μ©
elif isinstance(file_data, str) and os.path.exists(file_data):
base_name = os.path.splitext(os.path.basename(file_data))[0]
else:
base_name = "GIF"
else:
base_name = "GIF"
# μλ‘μ΄ νμΌ μ΄λ¦ μμ±
file_name = f"[λμ₯AI]λμ₯GIF_{base_name}_{timestamp}.gif"
# μμ λλ ν 리μ νμΌ μ μ₯
temp_file_path = os.path.join(tempfile.gettempdir(), file_name)
try:
# κΈ°μ‘΄ GIF νμΌμ μλ‘μ΄ μ΄λ¦μΌλ‘ 볡μ¬
copyfile(gif_path, temp_file_path)
except Exception as e:
log_debug(f"[prepare_download_gif] νμΌ λ³΅μ¬ μ€λ₯: {e}")
return gif_path # 볡μ¬μ μ€ν¨νλ©΄ μλ³Έ κ²½λ‘ λ°ν
return temp_file_path
########################################
# 10) μ½λ°± ν¨μ
########################################
def on_any_change(video_dict, start_time_str, end_time_str):
# μ€ν¬λ¦°μ·λ§ μ
λ°μ΄νΈ
start_img, end_img = update_screenshots(video_dict, start_time_str, end_time_str)
return (start_img, end_img)
def on_generate_click(video_dict, start_time_str, end_time_str, fps, resize_factor, speed_factor, duration, resolution_str):
"""GIF μμ± ν:
- μ±κ³΅μ: (μμ±λ GIF κ²½λ‘, νμΌ μ©λ λ¬Έμμ΄, νμΌ λ€μ΄λ‘λ κ²½λ‘)
- μ€ν¨μ: (None, μλ¬ λ©μμ§, None)
"""
# Convert duration from hms to seconds for internal use if needed
# durationλ νμ¬ μ¬μ©λμ§ μμΌλ―λ‘ λ¬΄μνκ±°λ νμ μ μ²λ¦¬ν μ μμ
result = generate_gif(video_dict, start_time_str, end_time_str, fps, resize_factor, speed_factor, duration, resolution_str)
if isinstance(result, str) and os.path.exists(result):
# GIF μμ± μ±κ³΅
size_bytes = os.path.getsize(result)
size_mb = size_bytes / (1024 * 1024)
file_size_str = f"{size_mb:.2f} MB"
# λ€μ΄λ‘λ νμΌ μ΄λ¦ λ³κ²½
download_path = prepare_download_gif(result, video_dict)
# Gradioκ° μλμΌλ‘ νμΌμ μ²λ¦¬νλλ‘ `download_path`λ₯Ό λ°ν
return (result, file_size_str, download_path)
else:
# GIF μμ± μ€ν¨, μλ¬ λ©μμ§ λ°ν
err_msg = result if isinstance(result, str) else "GIF μμ±μ μ€ν¨νμ΅λλ€."
return (None, err_msg, None)
########################################
# 11) Gradio UI
########################################
# μ€νμΌ μ μ©μ μν CSS λ° ν
λ§ μ€μ
css = """
footer {
visibility: hidden;
}
.left-column, .right-column {
border: 2px solid #ccc;
border-radius: 8px;
padding: 20px;
background-color: #f9f9f9;
}
.left-column {
margin-right: 10px;
}
.right-column {
margin-left: 10px;
}
.section-border {
border: 1px solid #ddd;
border-radius: 6px;
padding: 10px;
margin-bottom: 15px;
background-color: #ffffff;
}
"""
with gr.Blocks(
theme=gr.themes.Soft(
primary_hue=gr.themes.Color(
c50="#FFF7ED", # κ°μ₯ λ°μ μ£Όν©
c100="#FFEDD5",
c200="#FED7AA",
c300="#FDBA74",
c400="#FB923C",
c500="#F97316", # κΈ°λ³Έ μ£Όν©
c600="#EA580C",
c700="#C2410C",
c800="#9A3412",
c900="#7C2D12", # κ°μ₯ μ΄λμ΄ μ£Όν©
c950="#431407",
),
secondary_hue="zinc", # λͺ¨λν λλμ νμ κ³μ΄
neutral_hue="zinc",
font=("Pretendard", "sans-serif")
),
css=css
) as demo:
with gr.Row():
# μΌμͺ½ 컬λΌ: μμ μ
λ‘λ λ° μ 보
with gr.Column(elem_classes="left-column"):
# μμ μ
λ‘λ μΉμ
with gr.Row(elem_classes="section-border"):
video_input = gr.Video(label="μμ μ
λ‘λ")
# μμ κΈΈμ΄ λ° ν΄μλ μΉμ
with gr.Row(elem_classes="section-border"):
duration_box = gr.Textbox(label="μμ κΈΈμ΄", interactive=False, value="00:00:00")
resolution_box = gr.Textbox(label="ν΄μλ", interactive=False, value="0x0")
# μ€λ₯Έμͺ½ 컬λΌ: κ²°κ³Ό GIF λ° λ€μ΄λ‘λ
with gr.Column(elem_classes="right-column"):
# κ²°κ³Ό GIF μΉμ
with gr.Row(elem_classes="section-border"):
output_gif = gr.Image(label="κ²°κ³Ό GIF")
# νμΌ μ©λ λ° λ€μ΄λ‘λ μΉμ
with gr.Row(elem_classes="section-border"):
file_size_text = gr.Textbox(label="νμΌ μ©λ", interactive=False, value="0 MB")
download_gif_component = gr.File(label="GIF λ€μ΄λ‘λ") # μ΄λ¦ λ³κ²½νμ¬ μΆ©λ λ°©μ§
# μΆκ° μ€μ μΉμ
(μκ° μ€μ , μ€ν¬λ¦°μ·, μ¬λΌμ΄λ λ±)
with gr.Row():
with gr.Column():
# μκ° μ€μ μΉμ
with gr.Row(elem_classes="section-border"):
start_time_input = gr.Textbox(label="μμ μκ° (HH:MM:SS)", value="00:00:00")
end_time_input = gr.Textbox(label="λ μκ° (HH:MM:SS)", value="00:00:00")
# μ€ν¬λ¦°μ· μΉμ
with gr.Row(elem_classes="section-border"):
start_screenshot = gr.Image(label="μμ μ§μ μΊ‘μ³λ³Έ")
end_screenshot = gr.Image(label="λ μ§μ μΊ‘μ³λ³Έ")
# μ€μ μ¬λΌμ΄λ μΉμ
with gr.Row(elem_classes="section-border"):
# λ°°μ μ‘°μ μ¬λΌμ΄λ μΆκ°
speed_slider = gr.Slider(
label="λ°°μ",
minimum=0.5,
maximum=2.0,
step=0.1,
value=1.0,
info="0.5x: μ λ° μλ, 1.0x: μλ μλ, 2.0x: λ λ°° μλ"
)
# FPS μ¬λΌμ΄λ
fps_slider = gr.Slider(
label="FPS",
minimum=1,
maximum=30,
step=1,
value=10,
info="νλ μ μλ₯Ό μ‘°μ νμ¬ μ λλ©μ΄μ
μ λΆλλ¬μμ λ³κ²½ν©λλ€."
)
# ν΄μλ λ°°μ¨ μ¬λΌμ΄λ
resize_slider = gr.Slider(
label="ν΄μλ λ°°μ¨",
minimum=0.1,
maximum=1.0,
step=0.05,
value=1.0,
info="GIFμ ν΄μλλ₯Ό μ‘°μ ν©λλ€."
)
# GIF μμ± λ²νΌ μΉμ
with gr.Row(elem_classes="section-border"):
generate_button = gr.Button("GIF μμ±")
# μ΄λ²€νΈ μ½λ°± μ€μ
# μ
λ‘λ μ β μμ κΈΈμ΄, ν΄μλ μ
λ°μ΄νΈ
video_input.change(
fn=on_video_upload,
inputs=[video_input],
outputs=[
duration_box, # μμ κΈΈμ΄
resolution_box, # ν΄μλ("WxH")
start_time_input,
end_time_input,
start_screenshot,
end_screenshot
]
)
# μμ/λ μκ° λ³κ²½ μ β μ€ν¬λ¦°μ· μ
λ°μ΄νΈ
for c in [start_time_input, end_time_input]:
c.change(
fn=on_any_change,
inputs=[video_input, start_time_input, end_time_input],
outputs=[start_screenshot, end_screenshot]
)
# λ°°μ, FPS, ν΄μλ λ°°μ¨ λ³κ²½ μ β μ€ν¬λ¦°μ· μ
λ°μ΄νΈ
for c in [speed_slider, fps_slider, resize_slider]:
c.change(
fn=on_any_change,
inputs=[video_input, start_time_input, end_time_input],
outputs=[start_screenshot, end_screenshot]
)
# GIF μμ± λ²νΌ ν΄λ¦ μ β GIF μμ± λ° κ²°κ³Ό μ
λ°μ΄νΈ
generate_button.click(
fn=on_generate_click,
inputs=[
video_input,
start_time_input,
end_time_input,
fps_slider,
resize_slider,
speed_slider, # λ°°μ μ¬λΌμ΄λ μΆκ°
duration_box,
resolution_box
],
outputs=[
output_gif, # μμ±λ GIF 미리보기
file_size_text, # νμΌ μ©λ νμ
download_gif_component # λ€μ΄λ‘λ λ§ν¬
]
)
demo.launch() |