Motion-SVG-Vector / generator.py
dodoyy's picture
Restore the pre-Arrow SVG generator
ff8fb9c verified
Raw History Blame Contribute Delete
7.34 kB
import json
import logging
import os
import re
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
from motion import MOTIONS, add_motion
from validator import MAX_SVG_BYTES, SVGError, parse_svg, svg_text
DEFAULT_MODEL = "Qwen/Qwen3-Coder-30B-A3B-Instruct"
ENDPOINT = "https://router.huggingface.co/v1/chat/completions"
MAX_PROMPT_LENGTH = 600
LOGGER = logging.getLogger(__name__)
DRAW_PROMPT = """Create an original animated SVG for the user's request in any language.
Return one complete SVG document with a viewBox, transparent canvas, and visible movement.
Draw with g, path, rect, circle, ellipse, line, polygon, polyline, text, or tspan.
You may use defs for linearGradient, radialGradient, stop, or clipPath.
For repeated objects, write the shapes again. Never emit <use>, <symbol>, href, or xlink:href.
Use presentation attributes and six-digit hex colors. Do not emit style, CSS, scripts, links, or images.
For motion, put animate, animateTransform, or animateMotion inside the target shape or group.
Give each animation a dur in seconds. For continuous loops, use repeatCount="indefinite".
Use numeric begin times with units if needed. For animateTransform, set attributeName="transform",
a transform type, and semicolon-separated values. For animate, use numeric drawing
attributes, opacity, paths, or simple colors.
Choose geometry for the requested subject. A five-point star can be drawn as a polygon
with ten alternating outer and inner vertices. Draw a circle only when the subject calls for one.
For rotation, put the animation inside the group or shape that should move. Include
the object's center in each rotate value, for example values="0 100 60;360 100 60".
Adapt the timing and positions to the request. Keep the XML under 2,000 tokens, close
all tags, and return only the SVG document."""
SIMPLER_DRAW_INSTRUCTIONS = """
The previous output failed SVG validation. Use up to five inline shapes and a single
animate or animateTransform. Leave out definitions and references. Keep the requested
subject and movement, and close the SVG document."""
MOTION_PROMPT = f"""Select the closest whole-image SVG animation for the user's request in any language.
Return one JSON object with keys effect and duration. Allowed effects: {', '.join(MOTIONS)}.
Duration is the number of seconds for one cycle, from 0.4 to 12. If unspecified,
choose a natural duration. For example {{"effect":"float","duration":2.5}}.
Return only JSON."""
class GenerationError(RuntimeError):
"""A generation request could not be completed."""
def _complete_with_provider(system: str, prompt: str, *, max_tokens: int) -> str:
token = os.getenv("HF_TOKEN", "").strip()
if not token:
raise GenerationError("AI 생성을 μ‚¬μš©ν•˜λ €λ©΄ HF_TOKEN을 μ„€μ •ν•΄ μ£Όμ„Έμš”. μƒ˜ν”Œμ€ λ°”λ‘œ νŽΈμ§‘ν•  수 μžˆμŠ΅λ‹ˆλ‹€.")
request = Request(
ENDPOINT,
data=json.dumps({
"model": os.getenv("HF_MODEL", "").strip() or DEFAULT_MODEL,
"messages": [
{"role": "system", "content": system},
{"role": "user", "content": prompt},
],
"max_tokens": max_tokens,
"temperature": 0.35,
}).encode("utf-8"),
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
)
try:
with urlopen(request, timeout=55) as response:
payload = json.loads(response.read(500_000))
content = payload["choices"][0]["message"]["content"]
if not isinstance(content, str) or not content.strip():
raise ValueError("Empty response")
return content
except HTTPError as exc:
LOGGER.warning("Hugging Face Inference returned HTTP %d", exc.code)
messages = {
401: "HF_TOKEN 인증에 μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€. 토큰을 확인해 μ£Όμ„Έμš”.",
402: "Hugging Face μΆ”λ‘  ν¬λ ˆλ”§μ„ 확인해 μ£Όμ„Έμš”.",
403: "HF_TOKEN에 Inference Providers 호좜 κΆŒν•œμ΄ μžˆλŠ”μ§€ 확인해 μ£Όμ„Έμš”.",
404: "ν˜„μž¬ μΆ”λ‘  λͺ¨λΈμ„ μ‚¬μš©ν•  수 μ—†μŠ΅λ‹ˆλ‹€. HF_MODEL 섀정을 확인해 μ£Όμ„Έμš”.",
429: "μš”μ²­ ν•œλ„μ— λ„λ‹¬ν–ˆμŠ΅λ‹ˆλ‹€. μž μ‹œ λ’€ λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.",
}
raise GenerationError(messages.get(exc.code, "Hugging Face λͺ¨λΈ μš”μ²­μ— μ‹€νŒ¨ν–ˆμŠ΅λ‹ˆλ‹€. μž μ‹œ λ’€ λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.")) from exc
except (URLError, TimeoutError, OSError) as exc:
raise GenerationError("Hugging Face에 μ—°κ²°ν•˜μ§€ λͺ»ν–ˆμŠ΅λ‹ˆλ‹€. μž μ‹œ λ’€ λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”.") from exc
except (ValueError, KeyError, IndexError, TypeError) as exc:
raise GenerationError("λͺ¨λΈ 응닡이 λΉ„μ–΄ μžˆκ±°λ‚˜ ν˜•μ‹μ΄ μ˜¬λ°”λ₯΄μ§€ μ•ŠμŠ΅λ‹ˆλ‹€.") from exc
# The Space runtime sets its hardware flavor before the app imports this module.
if os.getenv("HF_SPACE_FLAVOR", "").lower().startswith("zero") or os.getenv(
"SPACES_ZERO_GPU", ""
).lower() in {"1", "true"}:
from zero_gpu import complete as _complete
else:
_complete = _complete_with_provider
def _read_generated_svg(response: str) -> str:
match = re.search(r"<svg(?=[\s>]).*?</svg\s*>", response, re.DOTALL)
if match is None:
raise SVGError("λͺ¨λΈ 응닡에 μ™„μ „ν•œ SVG λ¬Έμ„œκ°€ μ—†μŠ΅λ‹ˆλ‹€.")
return svg_text(parse_svg(match.group(), require_animation=True))
def generate_svg(prompt: str, upload: bytes | None = None) -> str:
prompt = prompt.strip()
if not 0 < len(prompt) <= MAX_PROMPT_LENGTH:
raise GenerationError(f"μ›€μ§μž„ μ„€λͺ…을 1~{MAX_PROMPT_LENGTH}자둜 μž…λ ₯ν•΄ μ£Όμ„Έμš”.")
if upload is not None:
if len(upload) > MAX_SVG_BYTES:
raise SVGError("SVGλŠ” 100 KB μ΄ν•˜μ—¬μ•Ό ν•©λ‹ˆλ‹€.")
try:
root = parse_svg(upload.decode("utf-8-sig"))
except UnicodeDecodeError as exc:
raise SVGError("UTF-8둜 μ €μž₯된 SVGλ₯Ό 올렀 μ£Όμ„Έμš”.") from exc
response = _complete(MOTION_PROMPT, prompt, max_tokens=180)
try:
match = re.search(r"\{[^{}]*\}", response)
if match is None:
raise ValueError("No JSON object")
data = json.loads(match.group())
effect, duration = data["effect"], data["duration"]
if effect not in MOTIONS or type(duration) not in (int, float) or not 0.4 <= duration <= 12:
raise ValueError("Invalid animation")
except (ValueError, KeyError, TypeError) as exc:
raise GenerationError("λͺ¨λΈμ΄ μ›€μ§μž„μ„ μ„ νƒν•˜μ§€ λͺ»ν–ˆμŠ΅λ‹ˆλ‹€. λ™μž‘μ„ 더 κ°„λ‹¨νžˆ μ„€λͺ…ν•΄ μ£Όμ„Έμš”.") from exc
return svg_text(parse_svg(add_motion(root, effect, duration), require_animation=True))
response = _complete(DRAW_PROMPT, prompt, max_tokens=4500)
try:
return _read_generated_svg(response)
except SVGError:
LOGGER.info("Retrying with simpler instructions after SVG validation failed.")
response = _complete(DRAW_PROMPT + SIMPLER_DRAW_INSTRUCTIONS, prompt, max_tokens=1600)
try:
return _read_generated_svg(response)
except SVGError as exc:
raise GenerationError(
"λͺ¨λΈμ΄ μ˜¬λ°”λ₯Έ SVGλ₯Ό λ§Œλ“€μ§€ λͺ»ν–ˆμ–΄μš”. λ„ν˜•μ΄λ‚˜ μ›€μ§μž„μ„ κ°„λ‹¨νžˆ μ„€λͺ…ν•΄ λ‹€μ‹œ μ‹œλ„ν•΄ μ£Όμ„Έμš”."
) from exc