Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -1,1108 +1,35 @@
|
|
1 |
import os
|
2 |
-
import
|
3 |
-
import
|
4 |
-
import
|
5 |
-
import base64
|
6 |
-
import string
|
7 |
-
import json
|
8 |
-
import asyncio
|
9 |
-
import requests
|
10 |
-
import anthropic
|
11 |
-
import io
|
12 |
-
import logging
|
13 |
|
14 |
-
|
15 |
-
from typing import Dict, List, Optional, Tuple
|
16 |
-
from functools import partial
|
17 |
-
|
18 |
-
import gradio as gr
|
19 |
-
import modelscope_studio.components.base as ms
|
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:
|
381 |
-
SYSTEM = "system"
|
382 |
-
USER = "user"
|
383 |
-
ASSISTANT = "assistant"
|
384 |
-
|
385 |
-
History = List[Tuple[str, str]]
|
386 |
-
Messages = List[Dict[str, str]]
|
387 |
-
|
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:
|
395 |
-
with open(image_path, "rb") as image_file:
|
396 |
-
encoded_string = base64.b64encode(image_file.read()).decode()
|
397 |
-
IMAGE_CACHE[image_path] = encoded_string
|
398 |
-
return encoded_string
|
399 |
-
except:
|
400 |
-
return IMAGE_CACHE.get('default.png', '')
|
401 |
-
|
402 |
-
def history_to_messages(history: History, system: str) -> Messages:
|
403 |
-
messages = [{'role': Role.SYSTEM, 'content': system}]
|
404 |
-
for h in history:
|
405 |
-
messages.append({'role': Role.USER, 'content': h[0]})
|
406 |
-
messages.append({'role': Role.ASSISTANT, 'content': h[1]})
|
407 |
-
return messages
|
408 |
-
|
409 |
-
def messages_to_history(messages: Messages) -> History:
|
410 |
-
assert messages[0]['role'] == Role.SYSTEM
|
411 |
-
history = []
|
412 |
-
for q, r in zip(messages[1::2], messages[2::2]):
|
413 |
-
history.append([q['content'], r['content']])
|
414 |
-
return history
|
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:
|
444 |
-
current_time = time.time()
|
445 |
-
if current_time - start_time > timeout:
|
446 |
-
raise TimeoutError("Claude API timeout")
|
447 |
-
if chunk.type == "content_block_delta":
|
448 |
-
collected_content += chunk.delta.text
|
449 |
-
yield collected_content
|
450 |
-
await asyncio.sleep(0)
|
451 |
-
start_time = current_time
|
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>
|
475 |
-
.prompt-grid {
|
476 |
-
display: grid;
|
477 |
-
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
|
478 |
-
gap: 16px;
|
479 |
-
padding: 12px;
|
480 |
-
}
|
481 |
-
.prompt-card {
|
482 |
-
background: white;
|
483 |
-
border: 1px solid #eee;
|
484 |
-
border-radius: 12px;
|
485 |
-
padding: 12px;
|
486 |
-
cursor: pointer;
|
487 |
-
box-shadow: 0 4px 8px rgba(0,0,0,0.05);
|
488 |
-
transition: all 0.3s ease;
|
489 |
-
}
|
490 |
-
.prompt-card:hover {
|
491 |
-
transform: translateY(-4px);
|
492 |
-
box-shadow: 0 6px 12px rgba(0,0,0,0.1);
|
493 |
-
}
|
494 |
-
.card-name {
|
495 |
-
font-weight: bold;
|
496 |
-
margin-bottom: 8px;
|
497 |
-
font-size: 13px;
|
498 |
-
color: #444;
|
499 |
-
}
|
500 |
-
.card-prompt {
|
501 |
-
font-size: 11px;
|
502 |
-
line-height: 1.4;
|
503 |
-
color: #666;
|
504 |
-
display: -webkit-box;
|
505 |
-
-webkit-line-clamp: 7;
|
506 |
-
-webkit-box-orient: vertical;
|
507 |
-
overflow: hidden;
|
508 |
-
height: 84px;
|
509 |
-
background-color: #f8f9fa;
|
510 |
-
padding: 8px;
|
511 |
-
border-radius: 6px;
|
512 |
-
}
|
513 |
-
</style>
|
514 |
-
<div class="prompt-grid">
|
515 |
-
"""
|
516 |
-
import html as html_lib
|
517 |
-
for item in items:
|
518 |
-
card_html = f"""
|
519 |
-
<div class="prompt-card" onclick="copyToInput(this)" data-prompt="{html_lib.escape(item.get('prompt', ''))}">
|
520 |
-
<div class="card-name">{html_lib.escape(item.get('name', ''))}</div>
|
521 |
-
<div class="card-prompt">{html_lib.escape(item.get('prompt', ''))}</div>
|
522 |
-
</div>
|
523 |
-
"""
|
524 |
-
html_content += card_html
|
525 |
-
html_content += r"""
|
526 |
-
</div>
|
527 |
-
<script>
|
528 |
-
function copyToInput(card) {
|
529 |
-
const prompt = card.dataset.prompt;
|
530 |
-
const textarea = document.querySelector('.ant-input-textarea-large textarea');
|
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):
|
550 |
-
pattern = r'```html\s*([\s\S]+?)\s*```'
|
551 |
-
match = re.search(pattern, text, re.DOTALL)
|
552 |
-
if match:
|
553 |
-
return match.group(1).strip()
|
554 |
-
|
555 |
-
pattern = r'```(?:\w+)?\s*([\s\S]+?)\s*```'
|
556 |
-
match = re.search(pattern, text, re.DOTALL)
|
557 |
-
if match:
|
558 |
-
return match.group(1).strip()
|
559 |
-
|
560 |
-
text = re.sub(r'```html\s*', '', text)
|
561 |
-
text = re.sub(r'\s*```', '', 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 |
-
|
569 |
-
lines = code.split('\n')
|
570 |
-
if len(lines) <= 200:
|
571 |
-
return code
|
572 |
-
|
573 |
-
# Remove comments
|
574 |
-
comment_patterns = [
|
575 |
-
r'/\*[\s\S]*?\*/',
|
576 |
-
r'//.*?$',
|
577 |
-
r'<!--[\s\S]*?-->'
|
578 |
-
]
|
579 |
-
cleaned_code = code
|
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'):
|
587 |
-
if line.strip() == '':
|
588 |
-
empty_line_count += 1
|
589 |
-
if empty_line_count <= 1:
|
590 |
-
cleaned_lines.append('')
|
591 |
-
else:
|
592 |
-
empty_line_count = 0
|
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 |
-
|
602 |
-
def send_to_sandbox(code):
|
603 |
-
clean_code = remove_code_block(code)
|
604 |
-
clean_code = optimize_code(clean_code)
|
605 |
-
|
606 |
-
if clean_code.startswith('```html'):
|
607 |
-
clean_code = clean_code[7:].strip()
|
608 |
-
if clean_code.endswith('```'):
|
609 |
-
clean_code = clean_code[:-3].strip()
|
610 |
-
|
611 |
-
if not clean_code.strip().startswith('<!DOCTYPE') and not clean_code.strip().startswith('<html'):
|
612 |
-
clean_code = f"""<!DOCTYPE html>
|
613 |
-
<html>
|
614 |
-
<head>
|
615 |
-
<meta charset="UTF-8">
|
616 |
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
617 |
-
<title>Game Preview</title>
|
618 |
-
</head>
|
619 |
-
<body>
|
620 |
-
{clean_code}
|
621 |
-
</body>
|
622 |
-
</html>"""
|
623 |
-
encoded_html = base64.b64encode(clean_code.encode('utf-8')).decode('utf-8')
|
624 |
-
data_uri = f"data:text/html;charset=utf-8;base64,{encoded_html}"
|
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 |
-
|
662 |
-
def handle_boost(prompt: str):
|
663 |
-
try:
|
664 |
-
boosted_prompt = boost_prompt(prompt)
|
665 |
-
return boosted_prompt, gr.update(active_key="empty")
|
666 |
-
except Exception:
|
667 |
-
return prompt, gr.update(active_key="empty")
|
668 |
-
|
669 |
-
def history_render(history: History):
|
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:
|
677 |
-
|
678 |
-
|
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)}")
|
697 |
-
return None, gr.update(active_key="empty")
|
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
|
761 |
-
|
|
|
762 |
|
763 |
-
#
|
764 |
-
|
765 |
-
|
766 |
-
|
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 |
-
|
775 |
-
|
776 |
-
|
777 |
-
#
|
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 |
-
|
789 |
-
|
790 |
-
|
791 |
-
|
792 |
-
None,
|
793 |
-
gr.update(active_key="loading"),
|
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,
|
842 |
-
send_to_sandbox(clean_code),
|
843 |
-
gr.update(active_key="render"),
|
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 = {
|
876 |
-
"Authorization": f"Bearer {token}",
|
877 |
-
"Content-Type": "application/json"
|
878 |
-
}
|
879 |
-
|
880 |
-
package_json = {
|
881 |
-
"name": project_name,
|
882 |
-
"version": "1.0.0",
|
883 |
-
"private": True,
|
884 |
-
"dependencies": {"vite": "^5.0.0"},
|
885 |
-
"scripts": {
|
886 |
-
"dev": "vite",
|
887 |
-
"build": "echo 'No build needed' && mkdir -p dist && cp index.html dist/",
|
888 |
-
"preview": "vite preview"
|
889 |
-
}
|
890 |
-
}
|
891 |
-
|
892 |
-
files = [
|
893 |
-
{"file": "index.html", "data": code},
|
894 |
-
{"file": "package.json", "data": json.dumps(package_json, indent=2)}
|
895 |
-
]
|
896 |
-
project_settings = {
|
897 |
-
"buildCommand": "npm run build",
|
898 |
-
"outputDirectory": "dist",
|
899 |
-
"installCommand": "npm install",
|
900 |
-
"framework": None
|
901 |
-
}
|
902 |
-
|
903 |
-
deploy_data = {
|
904 |
-
"name": project_name,
|
905 |
-
"files": files,
|
906 |
-
"target": "production",
|
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 (
|
923 |
-
"✅ **Deployment complete!** \n"
|
924 |
-
"Your app is live at: \n"
|
925 |
-
f"[**{deployment_url}**]({deployment_url})"
|
926 |
-
)
|
927 |
-
|
928 |
except Exception as e:
|
929 |
-
|
930 |
-
|
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(
|
967 |
-
primary_hue="blue",
|
968 |
-
secondary_hue="purple",
|
969 |
-
neutral_hue="slate",
|
970 |
-
spacing_size=gr.themes.sizes.spacing_md,
|
971 |
-
radius_size=gr.themes.sizes.radius_md,
|
972 |
-
text_size=gr.themes.sizes.text_md,
|
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",
|
1058 |
-
allow_clear=True,
|
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],
|
1074 |
-
queue=False
|
1075 |
-
)
|
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 |
-
|
1104 |
-
demo_instance = Demo()
|
1105 |
-
demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)
|
1106 |
-
except Exception as e:
|
1107 |
-
print(f"Initialization error: {e}")
|
1108 |
-
raise
|
|
|
1 |
import os
|
2 |
+
import sys
|
3 |
+
import streamlit as st
|
4 |
+
from tempfile import NamedTemporaryFile
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
+
def main():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
try:
|
8 |
+
# Get the code from secrets
|
9 |
+
code = os.environ.get("MAIN_CODE")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
+
if not code:
|
12 |
+
st.error("⚠️ The application code wasn't found in secrets. Please add the MAIN_CODE secret.")
|
13 |
+
return
|
14 |
|
15 |
+
# Create a temporary Python file
|
16 |
+
with NamedTemporaryFile(suffix='.py', delete=False, mode='w') as tmp:
|
17 |
+
tmp.write(code)
|
18 |
+
tmp_path = tmp.name
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
|
20 |
+
# Execute the code
|
21 |
+
exec(compile(code, tmp_path, 'exec'), globals())
|
22 |
+
|
23 |
+
# Clean up the temporary file
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
try:
|
25 |
+
os.unlink(tmp_path)
|
26 |
+
except:
|
27 |
+
pass
|
28 |
+
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
34 |
if __name__ == "__main__":
|
35 |
+
main()
|
|
|
|
|
|
|
|
|
|