File size: 33,984 Bytes
9a3b674 bbf28e1 9a3b674 |
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 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 |
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
# λ³λ CSS νμΌ λΆλ¬μ€κΈ° ν¨μ
def load_css():
"""μΈλΆ CSS νμΌμ λΆλ¬μ€κ±°λ, νμΌμ΄ μμ κ²½μ° λ΄μ₯ μ€νμΌ λ°ν"""
try:
with open('styles.css', 'r', encoding='utf-8') as f:
return f.read()
except:
# νμΌμ΄ μμ κ²½μ° λ΄μ₯ μ€νμΌ λ°ν (λ€ν¬λͺ¨λ μ§μ)
return """
/* FontAwesome μμ΄μ½ ν¬ν¨ */
@import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css");
/* ============================================
λ€ν¬λͺ¨λ μλ λ³κ²½ ν
νλ¦Ώ CSS
============================================ */
/* 1. CSS λ³μ μ μ (λΌμ΄νΈλͺ¨λ - κΈ°λ³Έκ°) */
:root {
/* λ©μΈ μ»¬λ¬ */
--primary-color: #FB7F0D;
--secondary-color: #ff9a8b;
--accent-color: #FF6B6B;
/* λ°°κ²½ μ»¬λ¬ */
--background-color: #FFFFFF;
--card-bg: #ffffff;
--input-bg: #ffffff;
/* ν
μ€νΈ μ»¬λ¬ */
--text-color: #334155;
--text-secondary: #64748b;
/* 보λ λ° κ΅¬λΆμ */
--border-color: #dddddd;
--border-light: #e5e5e5;
/* ν
μ΄λΈ μ»¬λ¬ */
--table-even-bg: #f3f3f3;
--table-hover-bg: #f0f0f0;
/* κ·Έλ¦Όμ */
--shadow: 0 8px 30px rgba(251, 127, 13, 0.08);
--shadow-light: 0 2px 4px rgba(0, 0, 0, 0.1);
/* κΈ°ν */
--border-radius: 18px;
}
/* 2. λ€ν¬λͺ¨λ μμ λ³μ (μλ κ°μ§) */
@media (prefers-color-scheme: dark) {
:root {
/* λ°°κ²½ μ»¬λ¬ */
--background-color: #1a1a1a;
--card-bg: #2d2d2d;
--input-bg: #2d2d2d;
/* ν
μ€νΈ μ»¬λ¬ */
--text-color: #e5e5e5;
--text-secondary: #a1a1aa;
/* 보λ λ° κ΅¬λΆμ */
--border-color: #404040;
--border-light: #525252;
/* ν
μ΄λΈ μ»¬λ¬ */
--table-even-bg: #333333;
--table-hover-bg: #404040;
/* κ·Έλ¦Όμ */
--shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
--shadow-light: 0 2px 4px rgba(0, 0, 0, 0.2);
}
}
/* 3. μλ λ€ν¬λͺ¨λ ν΄λμ€ (Gradio ν κΈμ©) */
[data-theme="dark"],
.dark,
.gr-theme-dark {
/* λ°°κ²½ μ»¬λ¬ */
--background-color: #1a1a1a;
--card-bg: #2d2d2d;
--input-bg: #2d2d2d;
/* ν
μ€νΈ μ»¬λ¬ */
--text-color: #e5e5e5;
--text-secondary: #a1a1aa;
/* 보λ λ° κ΅¬λΆμ */
--border-color: #404040;
--border-light: #525252;
/* ν
μ΄λΈ μ»¬λ¬ */
--table-even-bg: #333333;
--table-hover-bg: #404040;
/* κ·Έλ¦Όμ */
--shadow: 0 8px 30px rgba(0, 0, 0, 0.3);
--shadow-light: 0 2px 4px rgba(0, 0, 0, 0.2);
}
/* 4. κΈ°λ³Έ μμ λ€ν¬λͺ¨λ μ μ© */
body {
font-family: 'Pretendard', 'Noto Sans KR', -apple-system, BlinkMacSystemFont, sans-serif;
background-color: var(--background-color) !important;
color: var(--text-color) !important;
line-height: 1.6;
transition: background-color 0.3s ease, color 0.3s ease;
}
footer {
visibility: hidden;
}
/* 5. Gradio 컨ν
μ΄λ κ°μ μ μ© */
.gradio-container,
.gradio-container *,
.gr-app,
.gr-app *,
.gr-interface {
background-color: var(--background-color) !important;
color: var(--text-color) !important;
}
.container {
max-width: 1200px;
margin: 0 auto;
}
.header {
background: linear-gradient(135deg, #FB7F0D, #FF9A5B);
padding: 2rem;
border-radius: 15px;
margin-bottom: 20px;
box-shadow: var(--shadow);
text-align: center;
color: white;
}
.header h1 {
margin: 0;
font-size: 2.5rem;
font-weight: 700;
}
.header p {
margin: 10px 0 0;
font-size: 1.2rem;
opacity: 0.9;
}
.card {
background-color: var(--card-bg) !important;
border-radius: var(--border-radius);
padding: 20px;
margin: 10px 0;
box-shadow: var(--shadow);
border: 1px solid var(--border-color);
color: var(--text-color) !important;
transition: all 0.3s ease;
}
.button-primary {
border-radius: 30px !important;
background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)) !important;
color: white !important;
font-size: 18px !important;
padding: 10px 20px !important;
border: none;
box-shadow: 0 4px 8px rgba(251, 127, 13, 0.25);
transition: transform 0.3s ease;
text-align: center;
font-weight: 600;
}
.button-primary:hover {
transform: translateY(-2px);
box-shadow: 0 6px 12px rgba(251, 127, 13, 0.3);
}
.section-title {
display: flex;
align-items: center;
font-size: 20px;
font-weight: 700;
color: var(--text-color) !important;
margin-bottom: 15px;
padding-bottom: 8px;
border-bottom: 2px solid var(--primary-color);
}
.section-title i {
margin-right: 10px;
color: var(--primary-color);
}
.guide-container {
background-color: var(--card-bg) !important;
border-radius: var(--border-radius);
padding: 1.5rem;
margin-bottom: 1.5rem;
border: 1px solid var(--border-color);
color: var(--text-color) !important;
}
.guide-title {
font-size: 1.3rem;
font-weight: 700;
color: var(--primary-color) !important;
margin-bottom: 1rem;
display: flex;
align-items: center;
}
.guide-title i {
margin-right: 0.8rem;
font-size: 1.3rem;
}
.guide-item {
display: flex;
margin-bottom: 0.8rem;
align-items: flex-start;
}
.guide-number {
background-color: var(--primary-color);
color: white;
width: 24px;
height: 24px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
margin-right: 10px;
flex-shrink: 0;
font-size: 14px;
}
.guide-text {
flex: 1;
line-height: 1.6;
color: var(--text-color) !important;
}
.feature-tag {
display: inline-block;
background-color: rgba(251, 127, 13, 0.1);
color: var(--primary-color);
padding: 3px 10px;
border-radius: 12px;
font-size: 14px;
font-weight: 600;
margin-right: 8px;
margin-bottom: 8px;
}
.input-label {
font-weight: 600;
margin-bottom: 8px;
color: var(--text-color) !important;
}
/* 6. μΉ΄λ λ° ν¨λ μ€νμΌ */
.gr-form,
.gr-box,
.gr-panel,
.custom-frame,
[class*="frame"],
[class*="panel"] {
background-color: var(--card-bg) !important;
border-color: var(--border-color) !important;
color: var(--text-color) !important;
box-shadow: var(--shadow) !important;
}
/* 7. μ
λ ₯ νλ μ€νμΌ */
input[type="text"],
input[type="number"],
input[type="email"],
input[type="password"],
textarea,
select,
.gr-input,
.gr-text-input,
.gr-textarea,
.gr-dropdown {
background-color: var(--input-bg) !important;
color: var(--text-color) !important;
border-color: var(--border-color) !important;
border-radius: var(--border-radius) !important;
border: 1px solid var(--border-color) !important;
padding: 12px !important;
transition: all 0.3s ease !important;
}
input[type="text"]:focus,
input[type="number"]:focus,
input[type="email"]:focus,
input[type="password"]:focus,
textarea:focus,
select:focus,
.gr-input:focus,
.gr-text-input:focus,
.gr-textarea:focus,
.gr-dropdown:focus {
border-color: var(--primary-color) !important;
outline: none !important;
box-shadow: 0 0 0 2px rgba(251, 127, 13, 0.2) !important;
}
/* 8. λΌλ²¨ λ° ν
μ€νΈ μμ */
label,
.gr-label,
.gr-checkbox label,
.gr-radio label,
p, span, div {
color: var(--text-color) !important;
}
/* 9. ν
μ΄λΈ μ€νμΌ */
table {
background-color: var(--card-bg) !important;
color: var(--text-color) !important;
border-color: var(--border-color) !important;
}
table th {
background-color: var(--primary-color) !important;
color: white !important;
border-color: var(--border-color) !important;
}
table td {
background-color: var(--card-bg) !important;
color: var(--text-color) !important;
border-color: var(--border-color) !important;
}
table tbody tr:nth-child(even) {
background-color: var(--table-even-bg) !important;
}
table tbody tr:hover {
background-color: var(--table-hover-bg) !important;
}
/* 10. 체ν¬λ°μ€ λ° λΌλμ€ λ²νΌ */
input[type="checkbox"],
input[type="radio"] {
accent-color: var(--primary-color) !important;
}
/* 11. μ€ν¬λ‘€λ° μ€νμΌ */
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: var(--card-bg);
border-radius: 10px;
}
::-webkit-scrollbar-thumb {
background: var(--primary-color);
border-radius: 10px;
}
::-webkit-scrollbar-thumb:hover {
background: var(--secondary-color);
}
/* 12. μμ½λμΈ λ° λλ‘λ€μ΄ */
details {
background-color: var(--card-bg) !important;
border-color: var(--border-color) !important;
color: var(--text-color) !important;
}
details summary {
background-color: var(--card-bg) !important;
color: var(--text-color) !important;
}
/* 13. μΆκ° Gradio μ»΄ν¬λνΈλ€ */
.gr-block,
.gr-group,
.gr-row,
.gr-column {
background-color: var(--background-color) !important;
color: var(--text-color) !important;
}
/* 14. λ²νΌμ κΈ°μ‘΄ μ€νμΌ μ μ§ (primary-color μ¬μ©) */
button:not([class*="custom"]):not([class*="primary"]):not([class*="secondary"]) {
background-color: var(--card-bg) !important;
color: var(--text-color) !important;
border-color: var(--border-color) !important;
}
/* 15. μ½λ λΈλ‘ λ° pre νκ·Έ */
code,
pre,
.code-block {
background-color: var(--table-even-bg) !important;
color: var(--text-color) !important;
border-color: var(--border-color) !important;
}
/* 16. μ ν μ λλ©μ΄μ
*/
* {
transition: background-color 0.3s ease,
color 0.3s ease,
border-color 0.3s ease !important;
}
/* κΈ°μ‘΄ GIF λ³νκΈ° μ μ© μ€νμΌ μ μ§ */
.left-column, .right-column {
border: 2px solid var(--primary-color);
border-radius: var(--border-radius);
padding: 20px;
background-color: var(--card-bg) !important;
color: var(--text-color) !important;
}
.left-column {
margin-right: 10px;
}
.right-column {
margin-left: 10px;
}
.section-border {
border: 1px solid var(--border-color);
border-radius: 6px;
padding: 10px;
margin-bottom: 15px;
background-color: var(--card-bg) !important;
color: var(--text-color) !important;
}
"""
########################################
# 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
########################################
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=load_css() # μΈλΆ CSS νμΌ λλ λ΄μ₯ μ€νμΌ λ‘λ
) as demo:
# FontAwesome μμ΄μ½ ν€λ μΆκ°
gr.HTML("""
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
""")
with gr.Row():
# μΌμͺ½ 컬λΌ: μμ μ
λ‘λ λ° μ 보
with gr.Column(elem_classes="left-column"):
# μμ μ
λ‘λ μΉμ
with gr.Row(elem_classes="card"):
gr.HTML('<div class="section-title"><i class="fas fa-cloud-upload-alt"></i> μμ μ
λ‘λ</div>')
video_input = gr.Video(label="")
# μμ κΈΈμ΄ λ° ν΄μλ μΉμ
with gr.Row(elem_classes="card"):
gr.HTML('<div class="section-title"><i class="fas fa-info-circle"></i> μμ μ 보</div>')
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="card"):
gr.HTML('<div class="section-title"><i class="fas fa-image"></i> κ²°κ³Ό GIF</div>')
output_gif = gr.Image(label="")
# νμΌ μ©λ λ° λ€μ΄λ‘λ μΉμ
with gr.Row(elem_classes="card"):
gr.HTML('<div class="section-title"><i class="fas fa-download"></i> λ€μ΄λ‘λ</div>')
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.Column(elem_classes="card"):
gr.HTML('<div class="section-title"><i class="fas fa-clock"></i> μκ° μ€μ </div>')
with gr.Row():
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="card"):
gr.HTML('<div class="section-title"><i class="fas fa-camera"></i> 미리보기</div>')
start_screenshot = gr.Image(label="μμ μ§μ μΊ‘μ³λ³Έ")
end_screenshot = gr.Image(label="λ μ§μ μΊ‘μ³λ³Έ")
# μ€μ μ¬λΌμ΄λ μΉμ
with gr.Column(elem_classes="card"):
gr.HTML('<div class="section-title"><i class="fas fa-sliders-h"></i> λ³ν μ€μ </div>')
# λ°°μ μ‘°μ μ¬λΌμ΄λ
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="card"):
generate_button = gr.Button("β¨ GIF μμ±νκΈ°", elem_classes="button-primary")
# μ΄λ²€νΈ μ½λ°± μ€μ
# μ
λ‘λ μ β μμ κΈΈμ΄, ν΄μλ μ
λ°μ΄νΈ
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() |