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 , , 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"]).*?", 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