Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -8,7 +8,6 @@ import json
|
|
8 |
import asyncio
|
9 |
import requests
|
10 |
import anthropic
|
11 |
-
import openai
|
12 |
import io
|
13 |
import logging
|
14 |
|
@@ -21,174 +20,361 @@ import modelscope_studio.components.base as ms
|
|
21 |
import modelscope_studio.components.legacy as legacy
|
22 |
import modelscope_studio.components.antd as antd
|
23 |
|
24 |
-
# === [1]
|
25 |
log_stream = io.StringIO()
|
26 |
handler = logging.StreamHandler(log_stream)
|
27 |
logger = logging.getLogger()
|
28 |
-
logger.setLevel(logging.DEBUG) #
|
29 |
logger.addHandler(handler)
|
30 |
|
31 |
def get_logs():
|
32 |
-
"""StringIO
|
33 |
return log_stream.getvalue()
|
34 |
|
35 |
import re
|
36 |
|
37 |
-
deploying_flag = False
|
38 |
|
39 |
|
40 |
def get_deployment_update(code_md: str):
|
|
|
41 |
clean = remove_code_block(code_md)
|
42 |
result = deploy_to_vercel(clean)
|
43 |
|
44 |
m = re.search(r"https?://[\w\.-]+\.vercel\.app", result)
|
45 |
-
if m:
|
46 |
url = m.group(0)
|
47 |
md = (
|
48 |
-
"✅
|
49 |
-
f"➡️ [
|
50 |
)
|
51 |
-
else:
|
52 |
md = (
|
53 |
-
"❌
|
54 |
f"```\n{result}\n```"
|
55 |
)
|
56 |
|
57 |
-
# Markdown 컴포넌트이므로 gr.update 로 값/표시 전환
|
58 |
return gr.update(value=md, visible=True)
|
59 |
|
60 |
|
61 |
# ------------------------
|
62 |
-
# 1) DEMO_LIST
|
63 |
# ------------------------
|
64 |
|
65 |
-
|
66 |
DEMO_LIST = [
|
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 |
SystemPrompt = """
|
105 |
-
# GameCraft
|
106 |
-
|
107 |
-
## 1.
|
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 |
-
-
|
145 |
-
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
-
|
150 |
-
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
-
|
159 |
-
|
160 |
-
|
161 |
-
|
162 |
-
|
163 |
-
|
164 |
-
|
165 |
-
-
|
166 |
-
-
|
167 |
-
-
|
168 |
-
|
169 |
-
|
170 |
-
|
171 |
-
-
|
172 |
-
-
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
-
|
177 |
-
-
|
178 |
-
-
|
179 |
-
-
|
180 |
-
-
|
181 |
-
|
182 |
-
## 11.
|
183 |
-
-
|
184 |
-
-
|
185 |
-
-
|
186 |
-
- 코드 크기가 커질 경우 기능을 간소화하거나 생략할 것
|
187 |
"""
|
188 |
|
189 |
-
|
190 |
# ------------------------
|
191 |
-
# 2)
|
192 |
# ------------------------
|
193 |
|
194 |
class Role:
|
@@ -202,9 +388,7 @@ Messages = List[Dict[str, str]]
|
|
202 |
IMAGE_CACHE = {}
|
203 |
|
204 |
def get_image_base64(image_path):
|
205 |
-
"""
|
206 |
-
이미지 파일을 base64로 읽어서 캐싱
|
207 |
-
"""
|
208 |
if image_path in IMAGE_CACHE:
|
209 |
return IMAGE_CACHE[image_path]
|
210 |
try:
|
@@ -231,29 +415,29 @@ def messages_to_history(messages: Messages) -> History:
|
|
231 |
|
232 |
|
233 |
# ------------------------
|
234 |
-
# 3) API
|
235 |
# ------------------------
|
236 |
|
237 |
YOUR_ANTHROPIC_TOKEN = os.getenv('ANTHROPIC_API_KEY', '').strip()
|
238 |
-
YOUR_OPENAI_TOKEN = os.getenv('OPENAI_API_KEY', '').strip()
|
239 |
-
|
240 |
claude_client = anthropic.Anthropic(api_key=YOUR_ANTHROPIC_TOKEN)
|
241 |
-
openai_client = openai.OpenAI(api_key=YOUR_OPENAI_TOKEN)
|
242 |
|
243 |
async def try_claude_api(system_message, claude_messages, timeout=15):
|
244 |
"""
|
245 |
-
Claude API
|
246 |
"""
|
247 |
try:
|
248 |
-
system_message_with_limit =
|
249 |
-
|
|
|
|
|
250 |
start_time = time.time()
|
|
|
251 |
with claude_client.messages.stream(
|
252 |
model="claude-3-7-sonnet-20250219",
|
253 |
max_tokens=19800,
|
254 |
system=system_message_with_limit,
|
255 |
messages=claude_messages,
|
256 |
-
temperature=0.3
|
257 |
) as stream:
|
258 |
collected_content = ""
|
259 |
for chunk in stream:
|
@@ -268,46 +452,23 @@ async def try_claude_api(system_message, claude_messages, timeout=15):
|
|
268 |
except Exception as e:
|
269 |
raise e
|
270 |
|
271 |
-
async def try_openai_api(openai_messages):
|
272 |
-
"""
|
273 |
-
OpenAI API 호출 (스트리밍) - 코드 길이 제한 강화
|
274 |
-
"""
|
275 |
-
try:
|
276 |
-
if openai_messages and openai_messages[0]["role"] == "system":
|
277 |
-
openai_messages[0]["content"] += "\n\n추가 중요 지침: 생성하는 코드는 절대로 200줄을 넘지 마세요. 코드 간결성이 최우선입니다. 주석은 최소화하고, 핵심 기능만 구현하세요."
|
278 |
-
|
279 |
-
stream = openai_client.chat.completions.create(
|
280 |
-
model="o3",
|
281 |
-
messages=openai_messages,
|
282 |
-
stream=True,
|
283 |
-
max_tokens=19800,
|
284 |
-
temperature=0.2
|
285 |
-
)
|
286 |
-
collected_content = ""
|
287 |
-
for chunk in stream:
|
288 |
-
if chunk.choices[0].delta.content is not None:
|
289 |
-
collected_content += chunk.choices[0].delta.content
|
290 |
-
yield collected_content
|
291 |
-
except Exception as e:
|
292 |
-
raise e
|
293 |
-
|
294 |
|
295 |
# ------------------------
|
296 |
-
# 4)
|
297 |
# ------------------------
|
298 |
|
299 |
def load_json_data():
|
300 |
data_list = []
|
301 |
for item in DEMO_LIST:
|
302 |
data_list.append({
|
303 |
-
"name": f"[
|
304 |
"prompt": item['description']
|
305 |
})
|
306 |
return data_list
|
307 |
|
308 |
def create_template_html(title, items):
|
309 |
"""
|
310 |
-
|
311 |
"""
|
312 |
html_content = r"""
|
313 |
<style>
|
@@ -362,6 +523,7 @@ def create_template_html(title, items):
|
|
362 |
"""
|
363 |
html_content += card_html
|
364 |
html_content += r"""
|
|
|
365 |
<script>
|
366 |
function copyToInput(card) {
|
367 |
const prompt = card.dataset.prompt;
|
@@ -369,21 +531,19 @@ function copyToInput(card) {
|
|
369 |
if (textarea) {
|
370 |
textarea.value = prompt;
|
371 |
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
372 |
-
// 템플릿 Drawer 닫기
|
373 |
document.querySelector('.session-drawer .close-btn').click();
|
374 |
}
|
375 |
}
|
376 |
</script>
|
377 |
-
</div>
|
378 |
"""
|
379 |
return gr.HTML(value=html_content)
|
380 |
|
381 |
def load_all_templates():
|
382 |
-
return create_template_html("
|
383 |
|
384 |
|
385 |
# ------------------------
|
386 |
-
# 5)
|
387 |
# ------------------------
|
388 |
|
389 |
def remove_code_block(text):
|
@@ -402,6 +562,7 @@ def remove_code_block(text):
|
|
402 |
return text.strip()
|
403 |
|
404 |
def optimize_code(code: str) -> str:
|
|
|
405 |
if not code or len(code.strip()) == 0:
|
406 |
return code
|
407 |
|
@@ -409,6 +570,7 @@ def optimize_code(code: str) -> str:
|
|
409 |
if len(lines) <= 200:
|
410 |
return code
|
411 |
|
|
|
412 |
comment_patterns = [
|
413 |
r'/\*[\s\S]*?\*/',
|
414 |
r'//.*?$',
|
@@ -418,6 +580,7 @@ def optimize_code(code: str) -> str:
|
|
418 |
for pattern in comment_patterns:
|
419 |
cleaned_code = re.sub(pattern, '', cleaned_code, flags=re.MULTILINE)
|
420 |
|
|
|
421 |
cleaned_lines = []
|
422 |
empty_line_count = 0
|
423 |
for line in cleaned_code.split('\n'):
|
@@ -430,7 +593,9 @@ def optimize_code(code: str) -> str:
|
|
430 |
cleaned_lines.append(line)
|
431 |
|
432 |
cleaned_code = '\n'.join(cleaned_lines)
|
|
|
433 |
cleaned_code = re.sub(r'console\.log\(.*?\);', '', cleaned_code, flags=re.MULTILINE)
|
|
|
434 |
cleaned_code = re.sub(r' {2,}', ' ', cleaned_code)
|
435 |
return cleaned_code
|
436 |
|
@@ -460,52 +625,37 @@ def send_to_sandbox(code):
|
|
460 |
return f'<iframe src="{data_uri}" width="100%" height="920px" style="border:none;"></iframe>'
|
461 |
|
462 |
def boost_prompt(prompt: str) -> str:
|
|
|
|
|
|
|
|
|
463 |
if not prompt:
|
464 |
return ""
|
465 |
-
boost_system_prompt =
|
466 |
-
|
467 |
-
|
468 |
-
|
469 |
-
1
|
470 |
-
2
|
471 |
-
3
|
472 |
-
4
|
473 |
-
5
|
474 |
-
|
475 |
-
|
476 |
-
- 불필요한 세부 사항이나 부가 기능은 제외
|
477 |
-
- 생성될 코드가 600줄을 넘지 않도록 기능을 제한
|
478 |
-
- 명확하고 간결한 언어로 요구사항 작성
|
479 |
-
- 최소한의 필수 게임 요소만 포함
|
480 |
-
"""
|
481 |
try:
|
482 |
-
|
483 |
-
|
484 |
-
|
485 |
-
|
486 |
-
|
487 |
-
|
488 |
-
|
489 |
-
|
490 |
-
|
491 |
-
|
492 |
-
|
493 |
-
|
494 |
-
|
495 |
-
raise Exception("Claude API 응답 형식 오류")
|
496 |
-
except Exception:
|
497 |
-
completion = openai_client.chat.completions.create(
|
498 |
-
model="gpt-4",
|
499 |
-
messages=[
|
500 |
-
{"role": "system", "content": boost_system_prompt},
|
501 |
-
{"role": "user", "content": f"다음 게임 프롬프트를 분석하고 증강하되, 간결함을 유지하세요: {prompt}"}
|
502 |
-
],
|
503 |
-
max_tokens=10000,
|
504 |
-
temperature=0.3
|
505 |
-
)
|
506 |
-
if completion.choices and len(completion.choices) > 0:
|
507 |
-
return completion.choices[0].message.content
|
508 |
-
raise Exception("OpenAI API 응답 형식 오류")
|
509 |
except Exception:
|
510 |
return prompt
|
511 |
|
@@ -520,6 +670,7 @@ def history_render(history: History):
|
|
520 |
return gr.update(open=True), history
|
521 |
|
522 |
def execute_code(query: str):
|
|
|
523 |
if not query or query.strip() == '':
|
524 |
return None, gr.update(active_key="empty")
|
525 |
try:
|
@@ -528,19 +679,18 @@ def execute_code(query: str):
|
|
528 |
clean_code = clean_code[7:].strip()
|
529 |
if clean_code.endswith('```'):
|
530 |
clean_code = clean_code[:-3].strip()
|
531 |
-
|
|
|
532 |
if not ('<body' in clean_code and '</body>' in clean_code):
|
533 |
-
clean_code =
|
534 |
-
<html
|
535 |
-
<
|
536 |
-
<meta
|
537 |
-
<
|
538 |
-
|
539 |
-
|
540 |
-
|
541 |
-
|
542 |
-
</body>
|
543 |
-
</html>"""
|
544 |
return send_to_sandbox(clean_code), gr.update(active_key="render")
|
545 |
except Exception as e:
|
546 |
print(f"Execute code error: {str(e)}")
|
@@ -548,87 +698,94 @@ def execute_code(query: str):
|
|
548 |
|
549 |
|
550 |
# ------------------------
|
551 |
-
# 6)
|
552 |
# ------------------------
|
553 |
-
|
554 |
def deploy_and_show(code_md: str):
|
|
|
|
|
|
|
555 |
global deploying_flag
|
556 |
|
557 |
-
#
|
558 |
if deploying_flag:
|
559 |
-
return (
|
560 |
-
|
561 |
-
|
|
|
|
|
562 |
deploying_flag = True
|
563 |
|
564 |
-
# ② 코드 정리 & 배포 --------------------------------
|
565 |
clean = remove_code_block(code_md)
|
566 |
result = deploy_to_vercel(clean)
|
567 |
|
568 |
-
|
569 |
-
|
570 |
-
|
571 |
-
|
572 |
-
|
573 |
-
|
574 |
-
|
575 |
-
iframe = (f"<iframe src='{url}' width='100%' height='920px' "
|
576 |
-
"style='border:none;'></iframe>")
|
577 |
-
|
578 |
deploying_flag = False
|
579 |
-
return (
|
580 |
-
|
581 |
-
|
|
|
|
|
582 |
|
583 |
-
|
584 |
-
md_err = f"❌ **배포 실패**\n\n```\n{result}\n```"
|
585 |
deploying_flag = False
|
586 |
-
return (
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
|
591 |
|
592 |
class Demo:
|
593 |
def __init__(self):
|
594 |
pass
|
595 |
-
|
596 |
-
async def generation_code(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
597 |
if not query or query.strip() == '':
|
598 |
query = random.choice(DEMO_LIST)['description']
|
599 |
|
600 |
if _history is None:
|
601 |
_history = []
|
602 |
|
603 |
-
|
604 |
-
|
605 |
-
|
606 |
-
1.
|
607 |
-
2.
|
608 |
-
3.
|
609 |
-
4.
|
610 |
-
5.
|
611 |
-
|
612 |
-
|
613 |
|
614 |
messages = history_to_messages(_history, _setting['system'])
|
615 |
system_message = messages[0]['content']
|
616 |
-
|
|
|
617 |
claude_messages = [
|
618 |
-
{
|
619 |
-
|
|
|
|
|
|
|
620 |
if msg["content"].strip() != ''
|
621 |
]
|
622 |
-
|
623 |
-
openai_messages = [{"role": "system", "content": system_message}]
|
624 |
-
for msg in messages[1:]:
|
625 |
-
openai_messages.append({
|
626 |
-
"role": msg["role"],
|
627 |
-
"content": msg["content"]
|
628 |
-
})
|
629 |
-
openai_messages.append({"role": "user", "content": query})
|
630 |
-
|
631 |
try:
|
|
|
632 |
yield [
|
633 |
"Generating code...",
|
634 |
_history,
|
@@ -637,58 +794,48 @@ class Demo:
|
|
637 |
gr.update(open=True)
|
638 |
]
|
639 |
await asyncio.sleep(0)
|
|
|
640 |
collected_content = None
|
641 |
-
|
642 |
-
|
643 |
-
|
644 |
-
|
645 |
-
|
646 |
-
|
647 |
-
|
648 |
-
|
649 |
-
|
650 |
-
|
651 |
-
collected_content = content
|
652 |
-
except Exception:
|
653 |
-
async for content in try_openai_api(openai_messages):
|
654 |
-
yield [
|
655 |
-
content,
|
656 |
-
_history,
|
657 |
-
None,
|
658 |
-
gr.update(active_key="loading"),
|
659 |
-
gr.update(open=True)
|
660 |
-
]
|
661 |
-
await asyncio.sleep(0)
|
662 |
-
collected_content = content
|
663 |
|
664 |
if collected_content:
|
665 |
clean_code = remove_code_block(collected_content)
|
666 |
code_lines = clean_code.count('\n') + 1
|
667 |
if code_lines > 700:
|
668 |
-
warning_msg =
|
669 |
-
⚠️
|
670 |
-
|
671 |
-
1
|
672 |
-
2
|
673 |
-
|
674 |
-
|
675 |
-
|
676 |
-
|
677 |
-
collected_content = warning_msg
|
678 |
yield [
|
679 |
-
|
680 |
_history,
|
681 |
None,
|
682 |
gr.update(active_key="empty"),
|
683 |
gr.update(open=True)
|
684 |
]
|
685 |
else:
|
686 |
-
|
687 |
-
|
688 |
-
|
689 |
-
|
690 |
-
|
691 |
-
|
|
|
|
|
692 |
yield [
|
693 |
collected_content,
|
694 |
_history,
|
@@ -697,31 +844,32 @@ class Demo:
|
|
697 |
gr.update(open=True)
|
698 |
]
|
699 |
else:
|
700 |
-
raise ValueError("No content
|
701 |
except Exception as e:
|
702 |
-
raise ValueError(f
|
703 |
-
|
704 |
def clear_history(self):
|
705 |
return []
|
706 |
|
707 |
-
|
708 |
####################################################
|
709 |
-
# 1) deploy_to_vercel
|
710 |
####################################################
|
711 |
def deploy_to_vercel(code: str):
|
712 |
-
|
|
|
713 |
try:
|
714 |
if not code or len(code.strip()) < 10:
|
715 |
-
print("[DEBUG]
|
716 |
return "No code to deploy."
|
717 |
|
|
|
718 |
token = "A8IFZmgW2cqA4yUNlLPnci0N"
|
719 |
if not token:
|
720 |
-
print("[DEBUG] Vercel
|
721 |
return "Vercel token is not set."
|
722 |
|
723 |
project_name = ''.join(random.choice(string.ascii_lowercase) for _ in range(6))
|
724 |
-
print(f"[DEBUG]
|
725 |
|
726 |
deploy_url = "https://api.vercel.com/v13/deployments"
|
727 |
headers = {
|
@@ -759,16 +907,16 @@ def deploy_to_vercel(code: str):
|
|
759 |
"projectSettings": project_settings
|
760 |
}
|
761 |
|
762 |
-
print("[DEBUG]
|
763 |
deploy_response = requests.post(deploy_url, headers=headers, json=deploy_data)
|
764 |
-
print("[DEBUG]
|
765 |
|
766 |
if deploy_response.status_code != 200:
|
767 |
-
print("[DEBUG]
|
768 |
return f"Deployment failed: {deploy_response.text}"
|
769 |
|
770 |
deployment_url = f"https://{project_name}.vercel.app"
|
771 |
-
print(f"[DEBUG]
|
772 |
time.sleep(5)
|
773 |
|
774 |
return (
|
@@ -777,55 +925,42 @@ def deploy_to_vercel(code: str):
|
|
777 |
f"[**{deployment_url}**]({deployment_url})"
|
778 |
)
|
779 |
|
780 |
-
|
781 |
-
|
782 |
except Exception as e:
|
783 |
-
print("[ERROR] deploy_to_vercel()
|
784 |
return f"Error during deployment: {str(e)}"
|
785 |
|
786 |
|
787 |
-
|
788 |
# ------------------------
|
789 |
-
# (
|
790 |
# ------------------------
|
791 |
def handle_deploy_legacy(code):
|
792 |
-
logger.debug(f"[handle_deploy_legacy] code
|
793 |
if not code or len(code.strip()) < 10:
|
794 |
-
logger.info("[handle_deploy_legacy]
|
795 |
-
return "<div style='color:red;'
|
796 |
|
797 |
-
# 1) 코드 블록 제거
|
798 |
clean_code = remove_code_block(code)
|
799 |
-
|
800 |
-
# 2) Vercel에 배포
|
801 |
result = deploy_to_vercel(clean_code)
|
802 |
-
logger.debug(f"[handle_deploy_legacy] deploy_to_vercel
|
803 |
-
|
804 |
-
# 3) 배포 URL 추출
|
805 |
-
import re
|
806 |
|
807 |
match = re.search(r'https?://[\w.-]+\.vercel\.app', result)
|
808 |
if match:
|
809 |
deployment_url = match.group(0)
|
810 |
-
# 4) iframe으로 직접 렌더링
|
811 |
iframe_html = (
|
812 |
f'<iframe src="{deployment_url}" '
|
813 |
'width="100%" height="600px" style="border:none;" '
|
814 |
'sandbox="allow-scripts allow-same-origin allow-popups"></iframe>'
|
815 |
)
|
816 |
-
logger.debug("[handle_deploy_legacy] iframe_html
|
817 |
return iframe_html
|
818 |
|
819 |
-
|
820 |
-
logger.warning("[handle_deploy_legacy] 배포 URL을 찾을 수 없음")
|
821 |
safe_result = html.escape(result)
|
822 |
-
return f"<div style='color:red;'
|
823 |
-
|
824 |
-
|
825 |
|
826 |
|
827 |
# ------------------------
|
828 |
-
# 8) Gradio / Modelscope UI
|
829 |
# ------------------------
|
830 |
demo_instance = Demo()
|
831 |
theme = gr.themes.Soft(
|
@@ -838,102 +973,85 @@ theme = gr.themes.Soft(
|
|
838 |
)
|
839 |
|
840 |
with gr.Blocks(css_paths=["app.css"], theme=theme) as demo:
|
841 |
-
|
842 |
<style>
|
843 |
.app-header{ text-align:center; margin-bottom:24px; }
|
844 |
-
.badge-row{
|
845 |
-
display:inline-flex; /* 가로 정렬 */
|
846 |
-
gap:8px; /* 배지 사이 여백 */
|
847 |
-
margin:8px 0;
|
848 |
-
}
|
849 |
</style>
|
850 |
-
|
851 |
<div class="app-header">
|
852 |
<h1>🎮 Vibe Game Craft</h1>
|
853 |
-
|
854 |
<div class="badge-row">
|
855 |
-
<!-- ① Vibe-Game 공간 배지 -->
|
856 |
<a href="https://huggingface.co/spaces/openfree/Vibe-Game" target="_blank">
|
857 |
<img src="https://img.shields.io/static/v1?label=huggingface&message=Vibe%20Game%20Craft&color=%23800080&labelColor=%23ffa500&logo=huggingface&logoColor=%23ffff00&style=for-the-badge" alt="HF Vibe badge">
|
858 |
</a>
|
859 |
-
|
860 |
-
<!-- ② Game Gallery 배지 -->
|
861 |
<a href="https://huggingface.co/spaces/openfree/Game-Gallery" target="_blank">
|
862 |
<img src="https://img.shields.io/static/v1?label=huggingface&message=Game%20Gallery&color=%23800080&labelColor=%23ffa500&logo=huggingface&logoColor=%23ffff00&style=for-the-badge" alt="HF Gallery badge">
|
863 |
</a>
|
864 |
-
|
865 |
-
<!-- ③ Discord 배지 -->
|
866 |
<a href="https://discord.gg/openfreeai" target="_blank">
|
867 |
<img src="https://img.shields.io/static/v1?label=Discord&message=Openfree%20AI&color=%230000ff&labelColor=%23800080&logo=discord&logoColor=white&style=for-the-badge" alt="Discord badge">
|
868 |
</a>
|
869 |
</div>
|
870 |
-
|
871 |
-
<p>프롬프트 입력만으로 최신 LLM들과 Agent가 협업하여 웹 기반 HTML5, JavaScript, CSS 게임을 생성합니다. 실시간 미리보기와 배포 기능도 지원됩니다.</p>
|
872 |
</div>
|
873 |
""")
|
874 |
-
|
875 |
-
|
876 |
|
877 |
history = gr.State([])
|
878 |
setting = gr.State({"system": SystemPrompt})
|
879 |
-
deploy_status = gr.State({"is_deployed": False,"status": "","url": "","message": ""})
|
880 |
|
881 |
with ms.Application() as app:
|
882 |
with antd.ConfigProvider():
|
883 |
-
|
884 |
-
with antd.Drawer(open=False, title="코드 보기", placement="left", width="750px") as code_drawer:
|
885 |
code_output = legacy.Markdown()
|
886 |
|
887 |
-
with antd.Drawer(open=False, title="
|
888 |
history_output = legacy.Chatbot(show_label=False, flushing=False, height=960, elem_classes="history_chatbot")
|
889 |
|
890 |
with antd.Drawer(
|
891 |
open=False,
|
892 |
-
title="
|
893 |
placement="right",
|
894 |
width="900px",
|
895 |
elem_classes="session-drawer"
|
896 |
) as session_drawer:
|
897 |
with antd.Flex(vertical=True, gap="middle"):
|
898 |
-
gr.Markdown("###
|
899 |
session_history = gr.HTML(elem_classes="session-history")
|
900 |
-
close_btn = antd.Button("
|
901 |
-
|
902 |
-
with antd.Row(gutter=[32, 12], align="top", elem_classes="equal-height-container") as layout:
|
903 |
|
904 |
-
|
|
|
905 |
with antd.Col(span=24, md=16, elem_classes="equal-height-col"):
|
906 |
with ms.Div(elem_classes="right_panel panel"):
|
907 |
-
gr.HTML(
|
908 |
<div class="render_header">
|
909 |
<span class="header_btn"></span><span class="header_btn"></span><span class="header_btn"></span>
|
910 |
</div>
|
911 |
""")
|
912 |
with antd.Tabs(active_key="empty", render_tab_bar="() => null") as state_tab:
|
913 |
with antd.Tabs.Item(key="empty"):
|
914 |
-
|
915 |
with antd.Tabs.Item(key="loading"):
|
916 |
-
|
917 |
with antd.Tabs.Item(key="render"):
|
918 |
sandbox = gr.HTML(elem_classes="html_content")
|
919 |
|
920 |
-
#
|
921 |
with antd.Col(span=24, md=8, elem_classes="equal-height-col"):
|
922 |
with antd.Flex(vertical=True, gap="small", elem_classes="right-top-buttons"):
|
923 |
with antd.Flex(gap="small", elem_classes="setting-buttons", justify="space-between"):
|
924 |
-
codeBtn = antd.Button("
|
925 |
-
historyBtn = antd.Button("
|
926 |
-
template_btn = antd.Button("🎮
|
927 |
-
|
928 |
with antd.Flex(gap="small", justify="space-between", elem_classes="action-buttons"):
|
929 |
-
|
930 |
-
|
931 |
-
|
932 |
-
deploy_btn = antd.Button("
|
933 |
-
clear_btn = antd.Button("
|
934 |
|
935 |
with antd.Flex(vertical=True, gap="middle", wrap=True, elem_classes="input-panel"):
|
936 |
-
# ── 배포 결과 메시지가 가장 위에 오도록 ──
|
937 |
deploy_result_container = gr.Markdown(value="", visible=False)
|
938 |
input_text = antd.InputTextarea(
|
939 |
size="large",
|
@@ -941,19 +1059,15 @@ with gr.Blocks(css_paths=["app.css"], theme=theme) as demo:
|
|
941 |
placeholder=random.choice(DEMO_LIST)['description'],
|
942 |
max_length=100000
|
943 |
)
|
944 |
-
gr.HTML('<div class="help-text">💡
|
945 |
-
|
946 |
|
947 |
-
|
948 |
-
# Code Drawer 열기/닫기
|
949 |
codeBtn.click(lambda: gr.update(open=True), inputs=[], outputs=[code_drawer])
|
950 |
code_drawer.close(lambda: gr.update(open=False), inputs=[], outputs=[code_drawer])
|
951 |
|
952 |
-
# History Drawer 열기/닫기
|
953 |
historyBtn.click(history_render, inputs=[history], outputs=[history_drawer, history_output])
|
954 |
history_drawer.close(lambda: gr.update(open=False), inputs=[], outputs=[history_drawer])
|
955 |
|
956 |
-
# Template Drawer
|
957 |
template_btn.click(
|
958 |
fn=lambda: (gr.update(open=True), load_all_templates()),
|
959 |
outputs=[session_drawer, session_history],
|
@@ -962,42 +1076,29 @@ with gr.Blocks(css_paths=["app.css"], theme=theme) as demo:
|
|
962 |
session_drawer.close(lambda: (gr.update(open=False), gr.HTML("")), outputs=[session_drawer, session_history])
|
963 |
close_btn.click(lambda: (gr.update(open=False), gr.HTML("")), outputs=[session_drawer, session_history])
|
964 |
|
965 |
-
#
|
966 |
-
|
967 |
demo_instance.generation_code,
|
968 |
inputs=[input_text, setting, history],
|
969 |
outputs=[code_output, history, sandbox, state_tab, code_drawer]
|
970 |
)
|
971 |
|
972 |
-
# 클리어 버튼
|
973 |
clear_btn.click(demo_instance.clear_history, inputs=[], outputs=[history])
|
974 |
|
975 |
-
|
976 |
-
|
977 |
-
fn=handle_boost,
|
978 |
-
inputs=[input_text],
|
979 |
-
outputs=[input_text, state_tab]
|
980 |
-
)
|
981 |
-
|
982 |
-
# 코드 실행 버튼
|
983 |
-
execute_btn.click(
|
984 |
-
fn=execute_code,
|
985 |
-
inputs=[input_text],
|
986 |
-
outputs=[sandbox, state_tab]
|
987 |
-
)
|
988 |
|
989 |
deploy_btn.click(
|
990 |
-
fn=deploy_and_show,
|
991 |
inputs=[code_output],
|
992 |
outputs=[
|
993 |
-
deploy_result_container,
|
994 |
-
sandbox,
|
995 |
-
state_tab
|
996 |
]
|
997 |
-
)
|
998 |
-
|
999 |
-
# 9)
|
1000 |
-
# ------------------------
|
1001 |
if __name__ == "__main__":
|
1002 |
try:
|
1003 |
demo_instance = Demo()
|
|
|
8 |
import asyncio
|
9 |
import requests
|
10 |
import anthropic
|
|
|
11 |
import io
|
12 |
import logging
|
13 |
|
|
|
20 |
import modelscope_studio.components.legacy as legacy
|
21 |
import modelscope_studio.components.antd as antd
|
22 |
|
23 |
+
# === [1] Logger Setup ===
|
24 |
log_stream = io.StringIO()
|
25 |
handler = logging.StreamHandler(log_stream)
|
26 |
logger = logging.getLogger()
|
27 |
+
logger.setLevel(logging.DEBUG) # Set desired level
|
28 |
logger.addHandler(handler)
|
29 |
|
30 |
def get_logs():
|
31 |
+
"""Return the logs in the StringIO buffer as a string."""
|
32 |
return log_stream.getvalue()
|
33 |
|
34 |
import re
|
35 |
|
36 |
+
deploying_flag = False # Global flag for deployment
|
37 |
|
38 |
|
39 |
def get_deployment_update(code_md: str):
|
40 |
+
"""Return a Gradio Markdown update with the Vercel deployment status."""
|
41 |
clean = remove_code_block(code_md)
|
42 |
result = deploy_to_vercel(clean)
|
43 |
|
44 |
m = re.search(r"https?://[\w\.-]+\.vercel\.app", result)
|
45 |
+
if m:
|
46 |
url = m.group(0)
|
47 |
md = (
|
48 |
+
"✅ **Deployment Complete!**\n\n"
|
49 |
+
f"➡️ [Open Deployed App]({url})"
|
50 |
)
|
51 |
+
else:
|
52 |
md = (
|
53 |
+
"❌ **Deployment Failed**\n\n"
|
54 |
f"```\n{result}\n```"
|
55 |
)
|
56 |
|
|
|
57 |
return gr.update(value=md, visible=True)
|
58 |
|
59 |
|
60 |
# ------------------------
|
61 |
+
# 1) DEMO_LIST and SystemPrompt
|
62 |
# ------------------------
|
63 |
|
|
|
64 |
DEMO_LIST = [
|
65 |
+
{
|
66 |
+
"description": (
|
67 |
+
"Please build a classic Tetris game with blocks falling from the top. "
|
68 |
+
"Use arrow keys to move and rotate blocks. A completed horizontal line clears "
|
69 |
+
"and increases the score. Speed up over time, include a game over condition, and display score."
|
70 |
+
)
|
71 |
+
},
|
72 |
+
{
|
73 |
+
"description": (
|
74 |
+
"Please build a two-player chess game where players take turns. Implement basic chess rules "
|
75 |
+
"(King, Queen, Rook, Bishop, Knight, Pawn moves) with check/checkmate detection. "
|
76 |
+
"Enable drag-and-drop for moving pieces and record each move."
|
77 |
+
)
|
78 |
+
},
|
79 |
+
{
|
80 |
+
"description": (
|
81 |
+
"Please build a memory matching card game. Flip a card to reveal an image; "
|
82 |
+
"if two match, the player scores. Include flip animation, track attempts, and implement difficulty levels (easy/medium/hard)."
|
83 |
+
)
|
84 |
+
},
|
85 |
+
{
|
86 |
+
"description": (
|
87 |
+
"Please build a space shooter game. Control a spaceship with arrow keys and fire with the spacebar. "
|
88 |
+
"Waves of enemies attack, collisions are detected, and power-ups (shield, multi-fire, speed boost) appear. Difficulty increases gradually."
|
89 |
+
)
|
90 |
+
},
|
91 |
+
{
|
92 |
+
"description": (
|
93 |
+
"Please build a sliding puzzle (3x3 or 4x4). Shuffle tiles, then slide them into place using the empty space. "
|
94 |
+
"Include a shuffle function, move counter, completion message, and optional size selection for difficulty."
|
95 |
+
)
|
96 |
+
},
|
97 |
+
{
|
98 |
+
"description": (
|
99 |
+
"Please build a classic Snake game. Control the snake with arrow keys to eat randomly placed food. "
|
100 |
+
"Eating food grows the snake. Colliding with itself or a wall ends the game. Score equals the number of food pieces eaten. "
|
101 |
+
"Increase speed over time."
|
102 |
+
)
|
103 |
+
},
|
104 |
+
{
|
105 |
+
"description": (
|
106 |
+
"Please build a Breakout game. Move a paddle at the bottom to bounce a ball and break bricks at the top. "
|
107 |
+
"Clearing all bricks finishes a level, losing the ball reduces a life. The ball speeds up over time, "
|
108 |
+
"and special bricks can grant power-ups."
|
109 |
+
)
|
110 |
+
},
|
111 |
+
{
|
112 |
+
"description": (
|
113 |
+
"Please build a tower defense game. Place various towers (basic, splash, slow) to stop enemies traveling along a path. "
|
114 |
+
"Each wave is stronger, and destroying enemies grants resources to build or upgrade towers."
|
115 |
+
)
|
116 |
+
},
|
117 |
+
{
|
118 |
+
"description": (
|
119 |
+
"Please build an endless runner. The player jumps over obstacles (rocks, pits, etc.) with spacebar or mouse click. "
|
120 |
+
"Distance is the score. Include collectible coins, power-ups, and increase speed over time."
|
121 |
+
)
|
122 |
+
},
|
123 |
+
{
|
124 |
+
"description": (
|
125 |
+
"Please build a 2D platformer. Move with arrow keys, jump with spacebar, and collect items. "
|
126 |
+
"Avoid enemies/traps and reach the goal. Implement multiple levels with a simple health system and checkpoints."
|
127 |
+
)
|
128 |
+
},
|
129 |
+
{
|
130 |
+
"description": (
|
131 |
+
"Please build a maze game that generates a new maze each time. "
|
132 |
+
"Use arrow keys to move from the start to the exit. Generate mazes using an algorithm (like DFS or Prim's). "
|
133 |
+
"Add a timer and optionally show a shortest path hint."
|
134 |
+
)
|
135 |
+
},
|
136 |
+
{
|
137 |
+
"description": (
|
138 |
+
"Please build a simple turn-based RPG. The player moves on a tile-based map, encountering monsters triggers turn-based combat. "
|
139 |
+
"Include basic attacks, special skills, items, and experience/level-up. Add a shop to buy equipment after winning battles."
|
140 |
+
)
|
141 |
+
},
|
142 |
+
{
|
143 |
+
"description": (
|
144 |
+
"Please build a match-3 puzzle game. Swap adjacent items to match 3 or more. "
|
145 |
+
"Matched items disappear, scoring points. Larger matches create special items; chain combos yield extra points. "
|
146 |
+
"Include a target score or limited moves/time mode."
|
147 |
+
)
|
148 |
+
},
|
149 |
+
{
|
150 |
+
"description": (
|
151 |
+
"Please build a Flappy Bird-style game. The bird jumps with spacebar or mouse click, avoiding top/bottom pipes. "
|
152 |
+
"Each pipe pair passed scores 1 point, and hitting a pipe or the top/bottom ends the game. Store high scores locally."
|
153 |
+
)
|
154 |
+
},
|
155 |
+
{
|
156 |
+
"description": (
|
157 |
+
"Please build a spot-the-difference game using pairs of similar images with 5-10 differences. "
|
158 |
+
"Click differences to mark them. There's a time limit, with penalty for wrong clicks. "
|
159 |
+
"Include a hint system and easy/hard difficulty modes."
|
160 |
+
)
|
161 |
+
},
|
162 |
+
{
|
163 |
+
"description": (
|
164 |
+
"Please build a typing game where words fall from the top. Type them correctly before they reach the bottom. "
|
165 |
+
"Words vary in length and speed based on difficulty. Special words provide bonuses or extra time. "
|
166 |
+
"Difficulty increases gradually with the score."
|
167 |
+
)
|
168 |
+
},
|
169 |
+
{
|
170 |
+
"description": (
|
171 |
+
"Please build a mini golf game with a basic physics engine. Drag to set shot direction and power, then shoot to reach the hole. "
|
172 |
+
"Multiple courses with obstacles (sand, water, ramps). Keep track of strokes and total score. Optional wind and shot preview."
|
173 |
+
)
|
174 |
+
},
|
175 |
+
{
|
176 |
+
"description": (
|
177 |
+
"Please build a fishing simulator. Click to cast, and if a fish bites, a timing mini-game determines success. "
|
178 |
+
"Different fish have different rarity and scores. Earn gold for upgrades (rods, bait). "
|
179 |
+
"Time/weather can affect which fish appear."
|
180 |
+
)
|
181 |
+
},
|
182 |
+
{
|
183 |
+
"description": (
|
184 |
+
"Please build a single-player or AI-versus bingo game. A 5x5 grid with numbers 1-25 is randomized. "
|
185 |
+
"Players mark chosen numbers in turns. A line (horizontal, vertical, diagonal) is a 'bingo'. "
|
186 |
+
"Get 3 bingos first to win. Include a timer and record wins/losses."
|
187 |
+
)
|
188 |
+
},
|
189 |
+
{
|
190 |
+
"description": (
|
191 |
+
"Please build a rhythm game with notes rising from the bottom. Press keys (D,F,J,K) at the right time. "
|
192 |
+
"Judge timing as Perfect, Good, or Miss. Show combos and final results (accuracy, combos, score). Include difficulty (note speed)."
|
193 |
+
)
|
194 |
+
},
|
195 |
+
{
|
196 |
+
"description": (
|
197 |
+
"Please build a top-down 2D racing game. The player drives a car with arrow keys on a track. "
|
198 |
+
"Leaving the track slows the car. Add AI opponents, a 3-lap race mode, and a time attack mode. "
|
199 |
+
"Offer multiple cars with different speeds/handling."
|
200 |
+
)
|
201 |
+
},
|
202 |
+
{
|
203 |
+
"description": (
|
204 |
+
"Please build a trivia quiz game with various categories. 4 multiple-choice answers, 30s limit per question. "
|
205 |
+
"Correct answers score points, wrong answers cost lives. Provide difficulty levels and hint items. "
|
206 |
+
"Show a summary of results at the end."
|
207 |
+
)
|
208 |
+
},
|
209 |
+
{
|
210 |
+
"description": (
|
211 |
+
"Please build a shooting gallery with moving targets. Click to shoot. Targets move at various speeds/patterns. "
|
212 |
+
"Limited time and ammo. Special targets grant bonuses. Consecutive hits form combos. Increase target speed for difficulty."
|
213 |
+
)
|
214 |
+
},
|
215 |
+
{
|
216 |
+
"description": (
|
217 |
+
"Please build a board game with a virtual dice (1-6) to move a piece around. Different board spaces trigger events: "
|
218 |
+
"move forward/back, skip turns, mini-games, etc. Players collect items to use. Up to 4 players or AI. "
|
219 |
+
"First to reach the goal or highest points wins."
|
220 |
+
)
|
221 |
+
},
|
222 |
+
{
|
223 |
+
"description": (
|
224 |
+
"Please build a top-down zombie survival game. Move with WASD, aim and shoot with the mouse. "
|
225 |
+
"Zombies come in waves, increasing in number and speed. Implement ammo, health packs, bombs, and special zombie types. "
|
226 |
+
"Survive as long as possible."
|
227 |
+
)
|
228 |
+
},
|
229 |
+
{
|
230 |
+
"description": (
|
231 |
+
"Please build a soccer penalty shootout game. The player sets direction and power to shoot, or chooses a direction for the goalkeeper. "
|
232 |
+
"5 rounds each, plus sudden death if tied. The AI goalkeeper can learn player tendencies. Support single-player and 2-player local mode."
|
233 |
+
)
|
234 |
+
},
|
235 |
+
{
|
236 |
+
"description": (
|
237 |
+
"Please build a classic Minesweeper game. NxN grid, M mines. Left-click reveals a cell, right-click flags a mine. "
|
238 |
+
"Numbers show how many mines are adjacent. Reveal all safe cells to win; hitting a mine loses. "
|
239 |
+
"Offer beginner/intermediate/expert sizes and ensure the first click is safe."
|
240 |
+
)
|
241 |
+
},
|
242 |
+
{
|
243 |
+
"description": (
|
244 |
+
"Please build a Connect Four game on a 7x6 grid. Players drop colored discs to form a line of 4 horizontally, vertically, or diagonally. "
|
245 |
+
"Alternate turns. First to connect 4 wins, or it's a draw if the board fills. Include AI and local 2-player modes."
|
246 |
+
)
|
247 |
+
},
|
248 |
+
{
|
249 |
+
"description": (
|
250 |
+
"Please build a Scrabble-style word game. Each player has 7 letter tiles. Place them on the board to form words. "
|
251 |
+
"All new words must connect to existing ones. Each tile has a point value. Include bonus spaces (double letter, triple word). "
|
252 |
+
"Validate words against a dictionary, support 1-4 players or AI."
|
253 |
+
)
|
254 |
+
},
|
255 |
+
{
|
256 |
+
"description": (
|
257 |
+
"Please build a 2D tank battle game. Move with WASD, aim and fire with the mouse. "
|
258 |
+
"Destructible terrain (brick, wood) and indestructible blocks (steel, water). Various weapons (shell, spread, laser) and power-ups. "
|
259 |
+
"Add multiple stages with AI enemies and increasing difficulty."
|
260 |
+
)
|
261 |
+
},
|
262 |
+
{
|
263 |
+
"description": (
|
264 |
+
"Please build a gem-matching puzzle game. Swap adjacent gems to match 3. Matched gems vanish and new gems fall. "
|
265 |
+
"4+ matches create special gems with bigger explosions. Chain combos increase score. "
|
266 |
+
"Use limited moves or time, plus special objectives like clearing obstacles."
|
267 |
+
)
|
268 |
+
},
|
269 |
+
{
|
270 |
+
"description": (
|
271 |
+
"Please build a single-tower defense game. The tower is in the center and auto-attacks incoming enemies. "
|
272 |
+
"Between waves, use earned resources to upgrade damage, speed, or range. "
|
273 |
+
"Waves get harder with different enemy types (fast, armored, splitting). Survive as long as possible."
|
274 |
+
)
|
275 |
+
},
|
276 |
+
{
|
277 |
+
"description": (
|
278 |
+
"Please build a side-scrolling runner with zombies and obstacles. Press space to jump and S to slide. "
|
279 |
+
"Collect coins and power-ups (invincibility, magnet, slow). Occasionally fight a mini-boss zombie. "
|
280 |
+
"Earn points for distance, spend coins on upgrades like double-jump or extra health."
|
281 |
+
)
|
282 |
+
},
|
283 |
+
{
|
284 |
+
"description": (
|
285 |
+
"Please build a top-down action RPG. Move with WASD, basic attack with the mouse, and use skills (keys 1-4). "
|
286 |
+
"Defeat monsters to gain XP and items, level up to improve stats. Equip weapons/armor, use a skill tree, and fight bosses. "
|
287 |
+
"Add simple quests and multiple zones."
|
288 |
+
)
|
289 |
+
},
|
290 |
]
|
291 |
|
|
|
292 |
SystemPrompt = """
|
293 |
+
# GameCraft System Prompt
|
294 |
+
|
295 |
+
## 1. Basic Info & Role
|
296 |
+
Your name is 'GameCraft'. You are a web game developer specialized in gameplay mechanics, interactive design, and performance optimization.
|
297 |
+
You build concise, efficient HTML/JS/CSS web-based games.
|
298 |
+
|
299 |
+
## 2. Core Tech Stack
|
300 |
+
- **Frontend**: HTML5, CSS3, JavaScript (ES6+)
|
301 |
+
- **Rendering**: Directly in browser
|
302 |
+
- **Code Style**: Vanilla JS first, minimal external libraries
|
303 |
+
|
304 |
+
## 3. Game Type Guidelines
|
305 |
+
### 3.1 Arcade/Action
|
306 |
+
- Simple collision detection
|
307 |
+
- Keyboard/touch optimization
|
308 |
+
- Basic scoring
|
309 |
+
|
310 |
+
### 3.2 Puzzle
|
311 |
+
- Clear rules & win conditions
|
312 |
+
- Basic difficulty levels
|
313 |
+
- Focus on core mechanics
|
314 |
+
|
315 |
+
### 3.3 Card/Board
|
316 |
+
- Simplified turn-based system
|
317 |
+
- Automate main rules
|
318 |
+
- Focus on core logic
|
319 |
+
|
320 |
+
### 3.4 Simulation
|
321 |
+
- Efficient state management
|
322 |
+
- Implement essential interactions
|
323 |
+
- Only critical elements
|
324 |
+
|
325 |
+
## 4. Emoji Usage 🎮
|
326 |
+
- Use emojis for key UI elements (HP ❤️, coin 💰, timer ⏱️)
|
327 |
+
- Minimal, essential usage
|
328 |
+
|
329 |
+
## 5. Technical Implementation
|
330 |
+
### 5.1 Code Structure
|
331 |
+
- **Conciseness**: Keep code as short as possible, minimal comments
|
332 |
+
- **Modularity**: Split by function, avoid unnecessary abstraction
|
333 |
+
- **Optimization**: Focus on game loop & rendering
|
334 |
+
- **Size Limit**: Entire code under 200 lines
|
335 |
+
|
336 |
+
### 5.2 Performance
|
337 |
+
- Minimize DOM manipulation
|
338 |
+
- Remove unused variables
|
339 |
+
- Watch memory usage
|
340 |
+
|
341 |
+
### 5.3 Responsive
|
342 |
+
- Basic responsive layout
|
343 |
+
- Simple UI focusing on core features
|
344 |
+
|
345 |
+
## 6. External Libraries
|
346 |
+
- Use minimal libraries, only if necessary
|
347 |
+
- If used, load via CDN
|
348 |
+
|
349 |
+
## 7. Accessibility & Inclusion
|
350 |
+
- Only essential accessibility features
|
351 |
+
|
352 |
+
## 8. Constraints & Notes
|
353 |
+
- No external API calls
|
354 |
+
- Keep code minimal (<200 lines)
|
355 |
+
- Minimal comments (only what's necessary)
|
356 |
+
- Avoid unnecessary features
|
357 |
+
|
358 |
+
## 9. Output Format
|
359 |
+
- Provide code in an HTML code block only
|
360 |
+
- No extra explanations, just a single-file ready code
|
361 |
+
- Must be fully self-contained
|
362 |
+
|
363 |
+
## 10. Code Quality
|
364 |
+
- Efficiency & brevity are top priorities
|
365 |
+
- Focus on core gameplay mechanics
|
366 |
+
- Prefer basic functionality over complexity
|
367 |
+
- No redundant comments
|
368 |
+
- Single file, <200 lines total
|
369 |
+
|
370 |
+
## 11. Important: Code Generation Limit
|
371 |
+
- Must NOT exceed 200 lines
|
372 |
+
- Omit non-essential details
|
373 |
+
- If code grows too long, simplify or remove features
|
|
|
374 |
"""
|
375 |
|
|
|
376 |
# ------------------------
|
377 |
+
# 2) Constants, Functions, Classes
|
378 |
# ------------------------
|
379 |
|
380 |
class Role:
|
|
|
388 |
IMAGE_CACHE = {}
|
389 |
|
390 |
def get_image_base64(image_path):
|
391 |
+
"""Read an image file into base64 and cache it."""
|
|
|
|
|
392 |
if image_path in IMAGE_CACHE:
|
393 |
return IMAGE_CACHE[image_path]
|
394 |
try:
|
|
|
415 |
|
416 |
|
417 |
# ------------------------
|
418 |
+
# 3) API Setup
|
419 |
# ------------------------
|
420 |
|
421 |
YOUR_ANTHROPIC_TOKEN = os.getenv('ANTHROPIC_API_KEY', '').strip()
|
|
|
|
|
422 |
claude_client = anthropic.Anthropic(api_key=YOUR_ANTHROPIC_TOKEN)
|
|
|
423 |
|
424 |
async def try_claude_api(system_message, claude_messages, timeout=15):
|
425 |
"""
|
426 |
+
Claude 3.7 Sonnet API call (streaming).
|
427 |
"""
|
428 |
try:
|
429 |
+
system_message_with_limit = (
|
430 |
+
system_message
|
431 |
+
+ "\n\nAdditional note: The generated code must NOT exceed 200 lines. Keep it concise, minimal comments, essential only."
|
432 |
+
)
|
433 |
start_time = time.time()
|
434 |
+
|
435 |
with claude_client.messages.stream(
|
436 |
model="claude-3-7-sonnet-20250219",
|
437 |
max_tokens=19800,
|
438 |
system=system_message_with_limit,
|
439 |
messages=claude_messages,
|
440 |
+
temperature=0.3
|
441 |
) as stream:
|
442 |
collected_content = ""
|
443 |
for chunk in stream:
|
|
|
452 |
except Exception as e:
|
453 |
raise e
|
454 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
455 |
|
456 |
# ------------------------
|
457 |
+
# 4) Templates
|
458 |
# ------------------------
|
459 |
|
460 |
def load_json_data():
|
461 |
data_list = []
|
462 |
for item in DEMO_LIST:
|
463 |
data_list.append({
|
464 |
+
"name": f"[Game] {item['description'][:25]}...",
|
465 |
"prompt": item['description']
|
466 |
})
|
467 |
return data_list
|
468 |
|
469 |
def create_template_html(title, items):
|
470 |
"""
|
471 |
+
Create simple HTML for game templates (no images).
|
472 |
"""
|
473 |
html_content = r"""
|
474 |
<style>
|
|
|
523 |
"""
|
524 |
html_content += card_html
|
525 |
html_content += r"""
|
526 |
+
</div>
|
527 |
<script>
|
528 |
function copyToInput(card) {
|
529 |
const prompt = card.dataset.prompt;
|
|
|
531 |
if (textarea) {
|
532 |
textarea.value = prompt;
|
533 |
textarea.dispatchEvent(new Event('input', { bubbles: true }));
|
|
|
534 |
document.querySelector('.session-drawer .close-btn').click();
|
535 |
}
|
536 |
}
|
537 |
</script>
|
|
|
538 |
"""
|
539 |
return gr.HTML(value=html_content)
|
540 |
|
541 |
def load_all_templates():
|
542 |
+
return create_template_html("Available Game Templates", load_json_data())
|
543 |
|
544 |
|
545 |
# ------------------------
|
546 |
+
# 5) Deploy/Boost/Utils
|
547 |
# ------------------------
|
548 |
|
549 |
def remove_code_block(text):
|
|
|
562 |
return text.strip()
|
563 |
|
564 |
def optimize_code(code: str) -> str:
|
565 |
+
"""Remove comments/whitespace if code exceeds 200 lines."""
|
566 |
if not code or len(code.strip()) == 0:
|
567 |
return code
|
568 |
|
|
|
570 |
if len(lines) <= 200:
|
571 |
return code
|
572 |
|
573 |
+
# Remove comments
|
574 |
comment_patterns = [
|
575 |
r'/\*[\s\S]*?\*/',
|
576 |
r'//.*?$',
|
|
|
580 |
for pattern in comment_patterns:
|
581 |
cleaned_code = re.sub(pattern, '', cleaned_code, flags=re.MULTILINE)
|
582 |
|
583 |
+
# Remove extra blank lines
|
584 |
cleaned_lines = []
|
585 |
empty_line_count = 0
|
586 |
for line in cleaned_code.split('\n'):
|
|
|
593 |
cleaned_lines.append(line)
|
594 |
|
595 |
cleaned_code = '\n'.join(cleaned_lines)
|
596 |
+
# Remove console logs
|
597 |
cleaned_code = re.sub(r'console\.log\(.*?\);', '', cleaned_code, flags=re.MULTILINE)
|
598 |
+
# Remove double spaces
|
599 |
cleaned_code = re.sub(r' {2,}', ' ', cleaned_code)
|
600 |
return cleaned_code
|
601 |
|
|
|
625 |
return f'<iframe src="{data_uri}" width="100%" height="920px" style="border:none;"></iframe>'
|
626 |
|
627 |
def boost_prompt(prompt: str) -> str:
|
628 |
+
"""
|
629 |
+
Ask Claude to refine the prompt for clarity and conciseness,
|
630 |
+
ensuring minimal extraneous requirements.
|
631 |
+
"""
|
632 |
if not prompt:
|
633 |
return ""
|
634 |
+
boost_system_prompt = (
|
635 |
+
"You are an expert prompt engineer for web game development. "
|
636 |
+
"Please analyze the given prompt and refine it for clarity and brevity, "
|
637 |
+
"while preserving the original intent. Focus on: \n"
|
638 |
+
"1) Clarifying core gameplay mechanics\n"
|
639 |
+
"2) Essential interactions only\n"
|
640 |
+
"3) Simple UI elements\n"
|
641 |
+
"4) Minimizing features to ensure code under 600 lines\n"
|
642 |
+
"5) Basic rules and win/lose conditions\n\n"
|
643 |
+
"Important: Exclude unneeded details, keep it under 600 lines of code overall, and be concise."
|
644 |
+
)
|
|
|
|
|
|
|
|
|
|
|
645 |
try:
|
646 |
+
# Single direct request to Claude
|
647 |
+
response = claude_client.messages.create(
|
648 |
+
model="claude-3-7-sonnet-20250219",
|
649 |
+
max_tokens=10000,
|
650 |
+
temperature=0.3,
|
651 |
+
messages=[
|
652 |
+
{"role": "user", "content": f"Refine this game prompt while keeping it concise: {prompt}"}
|
653 |
+
],
|
654 |
+
system=boost_system_prompt
|
655 |
+
)
|
656 |
+
if hasattr(response, 'content') and len(response.content) > 0:
|
657 |
+
return response.content[0].text
|
658 |
+
return prompt
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
659 |
except Exception:
|
660 |
return prompt
|
661 |
|
|
|
670 |
return gr.update(open=True), history
|
671 |
|
672 |
def execute_code(query: str):
|
673 |
+
"""Try to interpret the content as code and display it."""
|
674 |
if not query or query.strip() == '':
|
675 |
return None, gr.update(active_key="empty")
|
676 |
try:
|
|
|
679 |
clean_code = clean_code[7:].strip()
|
680 |
if clean_code.endswith('```'):
|
681 |
clean_code = clean_code[:-3].strip()
|
682 |
+
|
683 |
+
if not (clean_code.strip().startswith('<!DOCTYPE') or clean_code.strip().startswith('<html')):
|
684 |
if not ('<body' in clean_code and '</body>' in clean_code):
|
685 |
+
clean_code = (
|
686 |
+
"<!DOCTYPE html>\n<html>\n<head>\n"
|
687 |
+
' <meta charset="UTF-8">\n'
|
688 |
+
' <meta name="viewport" content="width=device-width, initial-scale=1.0">\n'
|
689 |
+
' <title>Game Preview</title>\n'
|
690 |
+
"</head>\n<body>\n"
|
691 |
+
+ clean_code
|
692 |
+
+ "\n</body>\n</html>"
|
693 |
+
)
|
|
|
|
|
694 |
return send_to_sandbox(clean_code), gr.update(active_key="render")
|
695 |
except Exception as e:
|
696 |
print(f"Execute code error: {str(e)}")
|
|
|
698 |
|
699 |
|
700 |
# ------------------------
|
701 |
+
# 6) Demo Class
|
702 |
# ------------------------
|
703 |
+
|
704 |
def deploy_and_show(code_md: str):
|
705 |
+
"""
|
706 |
+
Deploy button logic.
|
707 |
+
"""
|
708 |
global deploying_flag
|
709 |
|
710 |
+
# Prevent repeated clicks
|
711 |
if deploying_flag:
|
712 |
+
return (
|
713 |
+
gr.update(value="⏳ Already deploying...", visible=True),
|
714 |
+
None,
|
715 |
+
gr.update(active_key="empty")
|
716 |
+
)
|
717 |
deploying_flag = True
|
718 |
|
|
|
719 |
clean = remove_code_block(code_md)
|
720 |
result = deploy_to_vercel(clean)
|
721 |
|
722 |
+
m = re.search(r"https?://[\w\.-]+\.vercel\.app", result)
|
723 |
+
if m:
|
724 |
+
url = m.group(0)
|
725 |
+
md_out = f"✅ **Deployment Complete!**\n\n➡️ [Open]({url})"
|
726 |
+
iframe = (
|
727 |
+
f"<iframe src='{url}' width='100%' height='920px' style='border:none;'></iframe>"
|
728 |
+
)
|
|
|
|
|
|
|
729 |
deploying_flag = False
|
730 |
+
return (
|
731 |
+
gr.update(value=md_out, visible=True),
|
732 |
+
iframe,
|
733 |
+
gr.update(active_key="render")
|
734 |
+
)
|
735 |
|
736 |
+
md_err = f"❌ **Deployment Failed**\n\n```\n{result}\n```"
|
|
|
737 |
deploying_flag = False
|
738 |
+
return (
|
739 |
+
gr.update(value=md_err, visible=True),
|
740 |
+
None,
|
741 |
+
gr.update(active_key="empty")
|
742 |
+
)
|
743 |
|
744 |
class Demo:
|
745 |
def __init__(self):
|
746 |
pass
|
747 |
+
|
748 |
+
async def generation_code(
|
749 |
+
self,
|
750 |
+
query: Optional[str],
|
751 |
+
_setting: Dict[str, str],
|
752 |
+
_history: Optional[History]
|
753 |
+
):
|
754 |
+
"""
|
755 |
+
Create the game code from user prompt using only Claude.
|
756 |
+
"""
|
757 |
if not query or query.strip() == '':
|
758 |
query = random.choice(DEMO_LIST)['description']
|
759 |
|
760 |
if _history is None:
|
761 |
_history = []
|
762 |
|
763 |
+
# Additional constraints for the request
|
764 |
+
query = (
|
765 |
+
"Please create the following game. Important requirements: \n"
|
766 |
+
"1. Keep code as concise as possible.\n"
|
767 |
+
"2. Omit unnecessary comments.\n"
|
768 |
+
"3. The code must NOT exceed 600 lines.\n"
|
769 |
+
"4. All code in one HTML file.\n"
|
770 |
+
"5. Implement core features only.\n\n"
|
771 |
+
f"Game request: {query}"
|
772 |
+
)
|
773 |
|
774 |
messages = history_to_messages(_history, _setting['system'])
|
775 |
system_message = messages[0]['content']
|
776 |
+
|
777 |
+
# For Claude
|
778 |
claude_messages = [
|
779 |
+
{
|
780 |
+
"role": (msg["role"] if msg["role"] != "system" else "user"),
|
781 |
+
"content": msg["content"]
|
782 |
+
}
|
783 |
+
for msg in messages[1:] + [{"role": Role.USER, "content": query}]
|
784 |
if msg["content"].strip() != ''
|
785 |
]
|
786 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
787 |
try:
|
788 |
+
# Start streaming response
|
789 |
yield [
|
790 |
"Generating code...",
|
791 |
_history,
|
|
|
794 |
gr.update(open=True)
|
795 |
]
|
796 |
await asyncio.sleep(0)
|
797 |
+
|
798 |
collected_content = None
|
799 |
+
async for content in try_claude_api(system_message, claude_messages):
|
800 |
+
yield [
|
801 |
+
content,
|
802 |
+
_history,
|
803 |
+
None,
|
804 |
+
gr.update(active_key="loading"),
|
805 |
+
gr.update(open=True)
|
806 |
+
]
|
807 |
+
await asyncio.sleep(0)
|
808 |
+
collected_content = content
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
809 |
|
810 |
if collected_content:
|
811 |
clean_code = remove_code_block(collected_content)
|
812 |
code_lines = clean_code.count('\n') + 1
|
813 |
if code_lines > 700:
|
814 |
+
warning_msg = (
|
815 |
+
f"⚠️ **Warning: Generated code is too long ({code_lines} lines).**\n"
|
816 |
+
"This may cause issues. Try simplifying the request:\n"
|
817 |
+
"1) Request a simpler game\n"
|
818 |
+
"2) Omit advanced features\n"
|
819 |
+
"```html\n"
|
820 |
+
+ clean_code[:2000]
|
821 |
+
+ "\n... (truncated) ..."
|
822 |
+
)
|
|
|
823 |
yield [
|
824 |
+
warning_msg,
|
825 |
_history,
|
826 |
None,
|
827 |
gr.update(active_key="empty"),
|
828 |
gr.update(open=True)
|
829 |
]
|
830 |
else:
|
831 |
+
# Add final message to chat history
|
832 |
+
final_msg = {
|
833 |
+
"role": Role.ASSISTANT,
|
834 |
+
"content": collected_content
|
835 |
+
}
|
836 |
+
updated_messages = messages + [final_msg]
|
837 |
+
_history = messages_to_history(updated_messages)
|
838 |
+
|
839 |
yield [
|
840 |
collected_content,
|
841 |
_history,
|
|
|
844 |
gr.update(open=True)
|
845 |
]
|
846 |
else:
|
847 |
+
raise ValueError("No content generated from Claude.")
|
848 |
except Exception as e:
|
849 |
+
raise ValueError(f"Error calling Claude: {str(e)}")
|
850 |
+
|
851 |
def clear_history(self):
|
852 |
return []
|
853 |
|
|
|
854 |
####################################################
|
855 |
+
# 1) deploy_to_vercel
|
856 |
####################################################
|
857 |
def deploy_to_vercel(code: str):
|
858 |
+
"""Deploy code to Vercel and return the response."""
|
859 |
+
print(f"[DEBUG] deploy_to_vercel() start. code length: {len(code) if code else 0}")
|
860 |
try:
|
861 |
if not code or len(code.strip()) < 10:
|
862 |
+
print("[DEBUG] No code to deploy (too short).")
|
863 |
return "No code to deploy."
|
864 |
|
865 |
+
# Hard-coded token for demonstration
|
866 |
token = "A8IFZmgW2cqA4yUNlLPnci0N"
|
867 |
if not token:
|
868 |
+
print("[DEBUG] Vercel token is not set.")
|
869 |
return "Vercel token is not set."
|
870 |
|
871 |
project_name = ''.join(random.choice(string.ascii_lowercase) for _ in range(6))
|
872 |
+
print(f"[DEBUG] Generated project_name: {project_name}")
|
873 |
|
874 |
deploy_url = "https://api.vercel.com/v13/deployments"
|
875 |
headers = {
|
|
|
907 |
"projectSettings": project_settings
|
908 |
}
|
909 |
|
910 |
+
print("[DEBUG] Sending request to Vercel...")
|
911 |
deploy_response = requests.post(deploy_url, headers=headers, json=deploy_data)
|
912 |
+
print("[DEBUG] Response status_code:", deploy_response.status_code)
|
913 |
|
914 |
if deploy_response.status_code != 200:
|
915 |
+
print("[DEBUG] Deployment failed:", deploy_response.text)
|
916 |
return f"Deployment failed: {deploy_response.text}"
|
917 |
|
918 |
deployment_url = f"https://{project_name}.vercel.app"
|
919 |
+
print(f"[DEBUG] Deployment success -> URL: {deployment_url}")
|
920 |
time.sleep(5)
|
921 |
|
922 |
return (
|
|
|
925 |
f"[**{deployment_url}**]({deployment_url})"
|
926 |
)
|
927 |
|
|
|
|
|
928 |
except Exception as e:
|
929 |
+
print("[ERROR] deploy_to_vercel() exception:", e)
|
930 |
return f"Error during deployment: {str(e)}"
|
931 |
|
932 |
|
|
|
933 |
# ------------------------
|
934 |
+
# (Legacy Deploy Handler)
|
935 |
# ------------------------
|
936 |
def handle_deploy_legacy(code):
|
937 |
+
logger.debug(f"[handle_deploy_legacy] code length: {len(code) if code else 0}")
|
938 |
if not code or len(code.strip()) < 10:
|
939 |
+
logger.info("[handle_deploy_legacy] Not enough code.")
|
940 |
+
return "<div style='color:red;'>No code to deploy.</div>"
|
941 |
|
|
|
942 |
clean_code = remove_code_block(code)
|
|
|
|
|
943 |
result = deploy_to_vercel(clean_code)
|
944 |
+
logger.debug(f"[handle_deploy_legacy] deploy_to_vercel result: {result}")
|
|
|
|
|
|
|
945 |
|
946 |
match = re.search(r'https?://[\w.-]+\.vercel\.app', result)
|
947 |
if match:
|
948 |
deployment_url = match.group(0)
|
|
|
949 |
iframe_html = (
|
950 |
f'<iframe src="{deployment_url}" '
|
951 |
'width="100%" height="600px" style="border:none;" '
|
952 |
'sandbox="allow-scripts allow-same-origin allow-popups"></iframe>'
|
953 |
)
|
954 |
+
logger.debug("[handle_deploy_legacy] returning iframe_html")
|
955 |
return iframe_html
|
956 |
|
957 |
+
logger.warning("[handle_deploy_legacy] No deployment URL found.")
|
|
|
958 |
safe_result = html.escape(result)
|
959 |
+
return f"<div style='color:red;'>Deployment URL not found.<br>Result: {safe_result}</div>"
|
|
|
|
|
960 |
|
961 |
|
962 |
# ------------------------
|
963 |
+
# 8) Gradio / Modelscope UI
|
964 |
# ------------------------
|
965 |
demo_instance = Demo()
|
966 |
theme = gr.themes.Soft(
|
|
|
973 |
)
|
974 |
|
975 |
with gr.Blocks(css_paths=["app.css"], theme=theme) as demo:
|
976 |
+
gr.HTML("""
|
977 |
<style>
|
978 |
.app-header{ text-align:center; margin-bottom:24px; }
|
979 |
+
.badge-row{ display:inline-flex; gap:8px; margin:8px 0; }
|
|
|
|
|
|
|
|
|
980 |
</style>
|
|
|
981 |
<div class="app-header">
|
982 |
<h1>🎮 Vibe Game Craft</h1>
|
|
|
983 |
<div class="badge-row">
|
|
|
984 |
<a href="https://huggingface.co/spaces/openfree/Vibe-Game" target="_blank">
|
985 |
<img src="https://img.shields.io/static/v1?label=huggingface&message=Vibe%20Game%20Craft&color=%23800080&labelColor=%23ffa500&logo=huggingface&logoColor=%23ffff00&style=for-the-badge" alt="HF Vibe badge">
|
986 |
</a>
|
|
|
|
|
987 |
<a href="https://huggingface.co/spaces/openfree/Game-Gallery" target="_blank">
|
988 |
<img src="https://img.shields.io/static/v1?label=huggingface&message=Game%20Gallery&color=%23800080&labelColor=%23ffa500&logo=huggingface&logoColor=%23ffff00&style=for-the-badge" alt="HF Gallery badge">
|
989 |
</a>
|
|
|
|
|
990 |
<a href="https://discord.gg/openfreeai" target="_blank">
|
991 |
<img src="https://img.shields.io/static/v1?label=Discord&message=Openfree%20AI&color=%230000ff&labelColor=%23800080&logo=discord&logoColor=white&style=for-the-badge" alt="Discord badge">
|
992 |
</a>
|
993 |
</div>
|
994 |
+
<p>Enter a game description, and this tool will generate an HTML5/JS/CSS game via Claude. Preview or deploy it easily.</p>
|
|
|
995 |
</div>
|
996 |
""")
|
|
|
|
|
997 |
|
998 |
history = gr.State([])
|
999 |
setting = gr.State({"system": SystemPrompt})
|
1000 |
+
deploy_status = gr.State({"is_deployed": False, "status": "", "url": "", "message": ""})
|
1001 |
|
1002 |
with ms.Application() as app:
|
1003 |
with antd.ConfigProvider():
|
1004 |
+
with antd.Drawer(open=False, title="View Code", placement="left", width="750px") as code_drawer:
|
|
|
1005 |
code_output = legacy.Markdown()
|
1006 |
|
1007 |
+
with antd.Drawer(open=False, title="History", placement="left", width="900px") as history_drawer:
|
1008 |
history_output = legacy.Chatbot(show_label=False, flushing=False, height=960, elem_classes="history_chatbot")
|
1009 |
|
1010 |
with antd.Drawer(
|
1011 |
open=False,
|
1012 |
+
title="Game Templates",
|
1013 |
placement="right",
|
1014 |
width="900px",
|
1015 |
elem_classes="session-drawer"
|
1016 |
) as session_drawer:
|
1017 |
with antd.Flex(vertical=True, gap="middle"):
|
1018 |
+
gr.Markdown("### Available Game Templates")
|
1019 |
session_history = gr.HTML(elem_classes="session-history")
|
1020 |
+
close_btn = antd.Button("Close", type="default", elem_classes="close-btn")
|
|
|
|
|
1021 |
|
1022 |
+
with antd.Row(gutter=[32, 12], align="top", elem_classes="equal-height-container"):
|
1023 |
+
# Left Column
|
1024 |
with antd.Col(span=24, md=16, elem_classes="equal-height-col"):
|
1025 |
with ms.Div(elem_classes="right_panel panel"):
|
1026 |
+
gr.HTML("""
|
1027 |
<div class="render_header">
|
1028 |
<span class="header_btn"></span><span class="header_btn"></span><span class="header_btn"></span>
|
1029 |
</div>
|
1030 |
""")
|
1031 |
with antd.Tabs(active_key="empty", render_tab_bar="() => null") as state_tab:
|
1032 |
with antd.Tabs.Item(key="empty"):
|
1033 |
+
antd.Empty(description="Enter a description to generate a game", elem_classes="right_content")
|
1034 |
with antd.Tabs.Item(key="loading"):
|
1035 |
+
antd.Spin(True, tip="Generating game code...", size="large", elem_classes="right_content")
|
1036 |
with antd.Tabs.Item(key="render"):
|
1037 |
sandbox = gr.HTML(elem_classes="html_content")
|
1038 |
|
1039 |
+
# Right Column
|
1040 |
with antd.Col(span=24, md=8, elem_classes="equal-height-col"):
|
1041 |
with antd.Flex(vertical=True, gap="small", elem_classes="right-top-buttons"):
|
1042 |
with antd.Flex(gap="small", elem_classes="setting-buttons", justify="space-between"):
|
1043 |
+
codeBtn = antd.Button("View Code", type="default", elem_classes="code-btn")
|
1044 |
+
historyBtn = antd.Button("History", type="default", elem_classes="history-btn")
|
1045 |
+
template_btn = antd.Button("🎮 Templates", type="default", elem_classes="template-btn")
|
1046 |
+
|
1047 |
with antd.Flex(gap="small", justify="space-between", elem_classes="action-buttons"):
|
1048 |
+
send_btn = antd.Button("Send", type="primary", size="large", elem_classes="send-btn")
|
1049 |
+
enhance_btn = antd.Button("Enhance", type="default", size="large", elem_classes="boost-btn")
|
1050 |
+
code_exec_btn = antd.Button("Code", type="default", size="large", elem_classes="execute-btn")
|
1051 |
+
deploy_btn = antd.Button("Deploy", type="default", size="large", elem_classes="deploy-btn")
|
1052 |
+
clear_btn = antd.Button("Clear", type="default", size="large", elem_classes="clear-btn")
|
1053 |
|
1054 |
with antd.Flex(vertical=True, gap="middle", wrap=True, elem_classes="input-panel"):
|
|
|
1055 |
deploy_result_container = gr.Markdown(value="", visible=False)
|
1056 |
input_text = antd.InputTextarea(
|
1057 |
size="large",
|
|
|
1059 |
placeholder=random.choice(DEMO_LIST)['description'],
|
1060 |
max_length=100000
|
1061 |
)
|
1062 |
+
gr.HTML('<div class="help-text">💡 Describe your game here, e.g. "Please build a simple Tetris game."</div>')
|
|
|
1063 |
|
1064 |
+
# Drawer Toggles
|
|
|
1065 |
codeBtn.click(lambda: gr.update(open=True), inputs=[], outputs=[code_drawer])
|
1066 |
code_drawer.close(lambda: gr.update(open=False), inputs=[], outputs=[code_drawer])
|
1067 |
|
|
|
1068 |
historyBtn.click(history_render, inputs=[history], outputs=[history_drawer, history_output])
|
1069 |
history_drawer.close(lambda: gr.update(open=False), inputs=[], outputs=[history_drawer])
|
1070 |
|
|
|
1071 |
template_btn.click(
|
1072 |
fn=lambda: (gr.update(open=True), load_all_templates()),
|
1073 |
outputs=[session_drawer, session_history],
|
|
|
1076 |
session_drawer.close(lambda: (gr.update(open=False), gr.HTML("")), outputs=[session_drawer, session_history])
|
1077 |
close_btn.click(lambda: (gr.update(open=False), gr.HTML("")), outputs=[session_drawer, session_history])
|
1078 |
|
1079 |
+
# Buttons
|
1080 |
+
send_btn.click(
|
1081 |
demo_instance.generation_code,
|
1082 |
inputs=[input_text, setting, history],
|
1083 |
outputs=[code_output, history, sandbox, state_tab, code_drawer]
|
1084 |
)
|
1085 |
|
|
|
1086 |
clear_btn.click(demo_instance.clear_history, inputs=[], outputs=[history])
|
1087 |
|
1088 |
+
enhance_btn.click(handle_boost, inputs=[input_text], outputs=[input_text, state_tab])
|
1089 |
+
code_exec_btn.click(execute_code, inputs=[input_text], outputs=[sandbox, state_tab])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1090 |
|
1091 |
deploy_btn.click(
|
1092 |
+
fn=deploy_and_show,
|
1093 |
inputs=[code_output],
|
1094 |
outputs=[
|
1095 |
+
deploy_result_container,
|
1096 |
+
sandbox,
|
1097 |
+
state_tab
|
1098 |
]
|
1099 |
+
)
|
1100 |
+
|
1101 |
+
# 9) Launch
|
|
|
1102 |
if __name__ == "__main__":
|
1103 |
try:
|
1104 |
demo_instance = Demo()
|