Spaces:
Running on Zero
Running on Zero
File size: 8,644 Bytes
29e1b52 2c4e9e0 29e1b52 2c4e9e0 29e1b52 2c4e9e0 29e1b52 2c4e9e0 29e1b52 | 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 | 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()
|