dodoyy's picture
Restore the pre-Arrow Motion SVG interface
2c4e9e0 verified
Raw History Blame Contribute Delete
8.64 kB
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 = """<!doctype html>
<html lang="ko"><head><meta charset="utf-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">
<style>html,body{margin:0;width:100%;height:100%;overflow:hidden}
svg{display:block;width:100%;height:100%}</style></head>
<body>{svg}</body></html>"""
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'<iframe id="preview-frame" title="์›€์ง์ด๋Š” SVG ๋ฏธ๋ฆฌ๋ณด๊ธฐ" sandbox="allow-same-origin" srcdoc="{frame}"></iframe>'
'<div class="preview-actions">'
'<button type="button" data-play aria-pressed="false">์ผ์‹œ์ •์ง€</button>'
'<button type="button" data-restart>์ฒ˜์Œ๋ถ€ํ„ฐ</button>'
'<button type="button" data-copy aria-live="polite">์ฝ”๋“œ ๋ณต์‚ฌ</button>'
f'<a download="motion.svg" href="data:image/svg+xml;base64,{data}">SVG ๋‹ค์šด๋กœ๋“œ <span aria-hidden="true">โ†“</span></a>'
'</div>'
)
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("""
<header class="motion-title">
<div class="motion-mark" aria-hidden="true">โœฆ</div>
<div>
<h1>Motion <em>SVG</em></h1>
<p>ํ•œ ๋ฌธ์žฅ์œผ๋กœ ๊ทธ๋ฆฌ๋Š” ๋ฒกํ„ฐ ์• ๋‹ˆ๋ฉ”์ด์…˜</p>
</div>
</header>
""")
with gr.Row(elem_id="motion-workspace"):
with gr.Column(scale=4, min_width=285, elem_classes="motion-panel"):
gr.HTML("<h2>์›€์ง์ž„ ๋งŒ๋“ค๊ธฐ</h2>")
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('<h2 class="editor-heading">์›€์ง์ž„ ํŽธ์ง‘</h2>')
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("<h2>๋ฏธ๋ฆฌ๋ณด๊ธฐ</h2>")
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()