from base64 import b64encode from html import escape from pathlib import Path import gradio as gr from generator import GenerationError, generate_svg from motion import edit_motion from validator import MAX_SVG_BYTES, SVGError HERE = Path(__file__).resolve().parent SAMPLE = (HERE / "sample.svg").read_text(encoding="utf-8") SAMPLE_PROMPT = "보랏빛 행성 주위를 작은 달이 돌고, 별이 반짝이는 장면을 만들어 줘." PREVIEW_DOCUMENT = """ {svg}""" def render_preview(svg: str) -> str: frame = escape(PREVIEW_DOCUMENT.replace("{svg}", svg), quote=True) data = b64encode(svg.encode("utf-8")).decode("ascii") return ( f'' '
' '' '' '' f'SVG 다운로드 ' '
' ) def generate(prompt: str, upload: bytes | None, speed: float, repeat: str, color: str): try: source = generate_svg(prompt, upload) svg = edit_motion(source, speed, repeat, color) except (GenerationError, SVGError) as exc: raise gr.Error(str(exc)) from exc return source, render_preview(svg), svg def apply_settings(source: str, speed: float, repeat: str, color: str): try: svg = edit_motion(source, speed, repeat, color) except SVGError as exc: raise gr.Error(str(exc)) from exc return render_preview(svg), svg def load_sample(): return SAMPLE_PROMPT, None, 1, "original", "", SAMPLE, render_preview(SAMPLE), SAMPLE with gr.Blocks(title="Motion SVG", analytics_enabled=False, delete_cache=(1800, 1800)) as demo: source = gr.State(SAMPLE) gr.HTML("""

Motion SVG

한 문장으로 그리는 벡터 애니메이션

""") with gr.Row(elem_id="motion-workspace"): with gr.Column(scale=4, min_width=285, elem_classes="motion-panel"): gr.HTML("

움직임 만들기

") prompt = gr.Textbox( label="움직임 설명", placeholder="예: 작은 유령이 둥실 떠다니고 주변의 별이 천천히 반짝여.", lines=4, max_lines=5, max_length=600, ) with gr.Accordion("기존 SVG에 움직임 추가", open=False): upload = gr.File(label="SVG 파일", file_types=[".svg"], type="binary", height=110) with gr.Row(elem_classes="input-actions"): generate_btn = gr.Button("애니메이션 생성", variant="primary", scale=2) sample_btn = gr.Button("샘플 보기", scale=1) gr.HTML('

움직임 편집

') speed = gr.Slider(0.5, 3, value=1, step=0.1, label="속도 (배)") with gr.Row(elem_classes="editor-options"): repeat = gr.Dropdown( choices=[("원본", "original"), ("무한", "indefinite"), ("1회", "1"), ("2회", "2"), ("3회", "3"), ("5회", "5")], value="original", label="반복", min_width=90, ) color = gr.Textbox( label="대표 색상", placeholder="#7C58DB", max_lines=1, max_length=7, min_width=120, ) apply_btn = gr.Button("편집 적용") with gr.Column(scale=6, min_width=300, elem_classes="motion-panel preview-panel"): gr.HTML("

미리보기

") preview = gr.HTML( render_preview(SAMPLE), elem_id="motion-preview", js_on_load=""" element.addEventListener('click', async (event) => { const button = event.target.closest('button'); if (!button) return; if (button.hasAttribute('data-copy')) { const link = element.querySelector('a[download]'); const encoded = link.href.split(',')[1]; const bytes = Uint8Array.from(atob(encoded), char => char.charCodeAt(0)); const text = new TextDecoder().decode(bytes); let copied = false; try { await navigator.clipboard.writeText(text); copied = true; } catch { const input = document.createElement('textarea'); input.value = text; input.style.cssText = 'position:fixed;opacity:0'; element.append(input); try { input.select(); copied = document.execCommand('copy'); } catch { copied = false; } finally { input.remove(); button.focus(); } } button.textContent = copied ? '복사 완료' : '복사 실패'; setTimeout(() => { button.textContent = '코드 복사'; }, 1800); return; } const svg = element.querySelector('iframe')?.contentDocument?.querySelector('svg'); if (!svg) return; if (button.hasAttribute('data-restart')) { svg.setCurrentTime(0); return; } if (svg.animationsPaused()) { svg.unpauseAnimations(); button.textContent = '일시정지'; button.setAttribute('aria-pressed', 'false'); } else { svg.pauseAnimations(); button.textContent = '재생'; button.setAttribute('aria-pressed', 'true'); } }); """, ) with gr.Accordion("SVG 코드", open=False): code = gr.Code(SAMPLE, language="html", lines=8, interactive=False, show_label=False) render_inputs = [speed, repeat, color] action_options = {"api_visibility": "private", "concurrency_id": "motion-workspace"} generate_btn.click( generate, [prompt, upload, *render_inputs], [source, preview, code], **action_options, ) sample_btn.click( load_sample, outputs=[prompt, upload, *render_inputs, source, preview, code], **action_options, ) apply_btn.click( apply_settings, [source, *render_inputs], [preview, code], **action_options, ) def launch(*, share: bool = False): theme = gr.themes.Base( primary_hue="violet", neutral_hue="slate", font=["Pretendard", "Apple SD Gothic Neo", "Malgun Gothic", "system-ui", "sans-serif"], ).set( block_border_color="#eae3f5", block_background_fill="#ffffff", body_background_fill="#f7f4fb", button_primary_background_fill="#5936ab", button_primary_text_color="#ffffff", button_primary_background_fill_hover="#47298d", button_secondary_background_fill="#f6f2fb", button_secondary_text_color="#392465", ) return demo.queue(max_size=12).launch( css_paths=HERE / "style.css", theme=theme, share=share, max_file_size=MAX_SVG_BYTES, footer_links=[], ) if __name__ == "__main__": launch()