Spaces:
Running on Zero
Running on Zero
File size: 7,344 Bytes
29e1b52 408a2cc 4f612da 408a2cc 29e1b52 1602b78 29e1b52 1602b78 408a2cc ff8fb9c 29e1b52 408a2cc | 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 | 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
|