Spaces:
Running on Zero
Running on Zero
Download generator.py from dodoyy/Motion-SVG-Vector: direct link, hf CLI and curl.
- Browser
- Download file 7.34 kB
-
https://huggingface.co/spaces/dodoyy/Motion-SVG-Vector/resolve/main/generator.py
- Command line
-
hf download hf://spaces/dodoyy/Motion-SVG-Vector/generator.py
-
curl -L -o generator.py https://huggingface.co/spaces/dodoyy/Motion-SVG-Vector/resolve/main/generator.py
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 | |