dodoyy commited on
Commit
408a2cc
ยท
verified ยท
1 Parent(s): 1602b78

Retry invalid model-generated SVG

Browse files
Files changed (1) hide show
  1. generator.py +44 -18
generator.py CHANGED
@@ -13,20 +13,31 @@ ENDPOINT = "https://router.huggingface.co/v1/chat/completions"
13
  MAX_PROMPT_LENGTH = 600
14
  LOGGER = logging.getLogger(__name__)
15
 
16
- DRAW_PROMPT = """Create a polished original animated SVG from the user's request in any language.
17
- Return exactly one complete <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 400 300"> document.
18
- Use a transparent background, generous framing, and visible movement from the first second.
19
- Use SVG shape elements (g, path, rect, circle, ellipse, line, polygon, polyline, text, tspan)
20
- and optionally defs with linearGradient, radialGradient, stop or clipPath.
21
- Use presentation attributes and six-digit hex colors. Use only animate, animateTransform
22
- or animateMotion for animation. Put animation elements inside their target shapes or groups.
23
- Give every animation a dur in seconds, optional numeric begin with its unit, and use
24
- repeatCount="indefinite" for loops. For animateTransform use attributeName="transform",
25
- a supported type and semicolon-separated values. For animate use only numeric drawing
26
- properties, opacity, paths, or simple colors. Avoid links, style attributes, CSS, scripts,
27
- images, use elements, href, external references, and event-based timing.
28
- Keep the illustration compact so the document can fit within 2,000 tokens.
29
- Return only XML, without explanation, and close all tags."""
 
 
 
 
 
 
 
 
 
 
 
30
 
31
  MOTION_PROMPT = f"""Select the closest whole-image SVG animation for the user's request in any language.
32
  Return one JSON object with keys effect and duration. Allowed effects: {', '.join(MOTIONS)}.
@@ -88,6 +99,13 @@ else:
88
  _complete = _complete_with_provider
89
 
90
 
 
 
 
 
 
 
 
91
  def generate_svg(prompt: str, upload: bytes | None = None) -> str:
92
  prompt = prompt.strip()
93
  if not 0 < len(prompt) <= MAX_PROMPT_LENGTH:
@@ -113,7 +131,15 @@ def generate_svg(prompt: str, upload: bytes | None = None) -> str:
113
  return svg_text(parse_svg(add_motion(root, effect, duration), require_animation=True))
114
 
115
  response = _complete(DRAW_PROMPT, prompt, max_tokens=4500)
116
- match = re.search(r"<svg(?=[\s>]).*?</svg\s*>", response, re.DOTALL)
117
- if match is None:
118
- raise GenerationError("๋ชจ๋ธ์ด ์™„์ „ํ•œ SVG๋ฅผ ์ƒ์„ฑํ•˜์ง€ ๋ชปํ–ˆ์Šต๋‹ˆ๋‹ค. ์„ค๋ช…์„ ๋” ์งง๊ฒŒ ๋ฐ”๊ฟ” ๋‹ค์‹œ ์‹œ๋„ํ•ด ์ฃผ์„ธ์š”.")
119
- return svg_text(parse_svg(match.group(), require_animation=True))
 
 
 
 
 
 
 
 
 
13
  MAX_PROMPT_LENGTH = 600
14
  LOGGER = logging.getLogger(__name__)
15
 
16
+ DRAW_PROMPT = """Create an original animated SVG for the user's request in any language.
17
+ Return one complete SVG document with a viewBox, transparent canvas, and visible movement.
18
+ Draw with g, path, rect, circle, ellipse, line, polygon, polyline, text, or tspan.
19
+ You may use defs for linearGradient, radialGradient, stop, or clipPath.
20
+ For repeated objects, write the shapes again. Never emit <use>, <symbol>, href, or xlink:href.
21
+ Use presentation attributes and six-digit hex colors. Do not emit style, CSS, scripts, links, or images.
22
+ For motion, put animate, animateTransform, or animateMotion inside the target shape or group.
23
+ Give each animation a dur in seconds. For continuous loops, use repeatCount="indefinite".
24
+ Use numeric begin times with units if needed. For animateTransform, set attributeName="transform",
25
+ a transform type, and semicolon-separated values. For animate, use numeric drawing
26
+ attributes, opacity, paths, or simple colors.
27
+
28
+ This is an example of supported markup for a moving circle:
29
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 120">
30
+ <circle cx="100" cy="60" r="18" fill="#8054D8">
31
+ <animate attributeName="cx" values="65;135;65" dur="2s" repeatCount="indefinite"/>
32
+ </circle>
33
+ </svg>
34
+ Choose shapes and motion for the request. Keep the XML under 2,000 tokens, close all tags,
35
+ and return only the SVG document."""
36
+
37
+ SIMPLER_DRAW_INSTRUCTIONS = """
38
+ The previous output failed SVG validation. Use up to five inline shapes and a single
39
+ animate or animateTransform. Leave out definitions and references. Keep the requested
40
+ subject and movement, and close the SVG document."""
41
 
42
  MOTION_PROMPT = f"""Select the closest whole-image SVG animation for the user's request in any language.
43
  Return one JSON object with keys effect and duration. Allowed effects: {', '.join(MOTIONS)}.
 
99
  _complete = _complete_with_provider
100
 
101
 
102
+ def _read_generated_svg(response: str) -> str:
103
+ match = re.search(r"<svg(?=[\s>]).*?</svg\s*>", response, re.DOTALL)
104
+ if match is None:
105
+ raise SVGError("๋ชจ๋ธ ์‘๋‹ต์— ์™„์ „ํ•œ SVG ๋ฌธ์„œ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค.")
106
+ return svg_text(parse_svg(match.group(), require_animation=True))
107
+
108
+
109
  def generate_svg(prompt: str, upload: bytes | None = None) -> str:
110
  prompt = prompt.strip()
111
  if not 0 < len(prompt) <= MAX_PROMPT_LENGTH:
 
131
  return svg_text(parse_svg(add_motion(root, effect, duration), require_animation=True))
132
 
133
  response = _complete(DRAW_PROMPT, prompt, max_tokens=4500)
134
+ try:
135
+ return _read_generated_svg(response)
136
+ except SVGError:
137
+ LOGGER.info("Retrying with simpler instructions after SVG validation failed.")
138
+
139
+ response = _complete(DRAW_PROMPT + SIMPLER_DRAW_INSTRUCTIONS, prompt, max_tokens=1600)
140
+ try:
141
+ return _read_generated_svg(response)
142
+ except SVGError as exc:
143
+ raise GenerationError(
144
+ "๋ชจ๋ธ์ด ์˜ฌ๋ฐ”๋ฅธ SVG๋ฅผ ๋งŒ๋“ค์ง€ ๋ชปํ–ˆ์–ด์š”. ๋„ํ˜•์ด๋‚˜ ์›€์ง์ž„์„ ๊ฐ„๋‹จํžˆ ์„ค๋ช…ํ•ด ๋‹ค์‹œ ์‹œ๋„ํ•ด ์ฃผ์„ธ์š”."
145
+ ) from exc