""" return gr.HTML(value=html_content) # 전역 변수로 템플릿 데이터 캐시 TEMPLATE_CACHE = None def load_session_history(template_type="best"): global TEMPLATE_CACHE try: json_data = load_json_data() # 데이터를 세 섹션으로 나누기 templates = { "best": json_data[:12], "trending": json_data[12:24], "new": json_data[24:44] } titles = { "best": "🏆 베스트 게임 템플릿", "trending": "🔥 트렌딩 게임 템플릿", "new": "✨ NEW 게임 템플릿" } html_content = """
""" # 각 섹션의 템플릿 생성 for section, items in templates.items(): html_content += f"""
""" for item in items: html_content += f"""
{html.escape(item.get('name', ''))}
{html.escape(item.get('name', ''))}
{html.escape(item.get('prompt', ''))}
""" html_content += "
" html_content += """ """ return gr.HTML(value=html_content) except Exception as e: print(f"Error in load_session_history: {str(e)}") return gr.HTML("Error loading templates") # 배포 관련 함수 추가 def generate_space_name(): """6자리 랜덤 영문 이름 생성""" letters = string.ascii_lowercase return ''.join(random.choice(letters) for i in range(6)) def deploy_to_vercel(code: str): try: token = "A8IFZmgW2cqA4yUNlLPnci0N" if not token: return "Vercel 토큰이 설정되지 않았습니다." # 6자리 영문 프로젝트 이름 생성 project_name = ''.join(random.choice(string.ascii_lowercase) for i in range(6)) deploy_url = "https://api.vercel.com/v13/deployments" headers = { "Authorization": f"Bearer {token}", "Content-Type": "application/json" } package_json = { "name": project_name, "version": "1.0.0", "private": True, "dependencies": { "vite": "^5.0.0" }, "scripts": { "dev": "vite", "build": "echo 'No build needed' && mkdir -p dist && cp index.html dist/", "preview": "vite preview" } } files = [ { "file": "index.html", "data": code }, { "file": "package.json", "data": json.dumps(package_json, indent=2) } ] project_settings = { "buildCommand": "npm run build", "outputDirectory": "dist", "installCommand": "npm install", "framework": None } deploy_data = { "name": project_name, "files": files, "target": "production", "projectSettings": project_settings } deploy_response = requests.post(deploy_url, headers=headers, json=deploy_data) if deploy_response.status_code != 200: return f"배포 실패: {deploy_response.text}" deployment_url = f"{project_name}.vercel.app" time.sleep(5) return f"""배포 완료! https://{deployment_url}""" except Exception as e: return f"배포 중 오류 발생: {str(e)}" def boost_prompt(prompt: str) -> str: if not prompt: return "" boost_system_prompt = """ 당신은 웹 게임 개발 프롬프트 전문가입니다. 주어진 프롬프트를 분석하여 더 상세하고 전문적인 요구사항으로 확장하되, 원래 의도와 목적은 그대로 유지하면서 다음 관점들을 고려하여 증강하십시오: 1. 게임 플레이 재미와 난이도 밸런스 2. 인터랙티브 그래픽 및 애니메이션 3. 사용자 경험 최적화 (UI/UX) 4. 성능 최적화 5. 접근성과 호환성 기존 SystemPrompt의 모든 규칙을 준수하면서 증강된 프롬프트를 생성하십시오. """ try: # Claude API 시도 try: response = claude_client.messages.create( model="claude-3-7-sonnet-20250219", max_tokens=2000, messages=[{ "role": "user", "content": f"다음 게임 프롬프트를 분석하고 증강하시오: {prompt}" }] ) if hasattr(response, 'content') and len(response.content) > 0: return response.content[0].text raise Exception("Claude API 응답 형식 오류") except Exception as claude_error: print(f"Claude API 에러, OpenAI로 전환: {str(claude_error)}") completion = openai_client.chat.completions.create( model="gpt-4", messages=[ {"role": "system", "content": boost_system_prompt}, {"role": "user", "content": f"다음 게임 프롬프트를 분석하고 증강하시오: {prompt}"} ], max_tokens=2000, temperature=0.7 ) if completion.choices and len(completion.choices) > 0: return completion.choices[0].message.content raise Exception("OpenAI API 응답 형식 오류") except Exception as e: print(f"프롬프트 증강 중 오류 발생: {str(e)}") return prompt def handle_boost(prompt: str): try: boosted_prompt = boost_prompt(prompt) return boosted_prompt, gr.update(active_key="empty") except Exception as e: print(f"Boost 처리 중 오류: {str(e)}") return prompt, gr.update(active_key="empty") demo_instance = Demo() with gr.Blocks(css_paths="app.css", theme=theme) as demo: history = gr.State([]) setting = gr.State({ "system": SystemPrompt, }) with ms.Application() as app: with antd.ConfigProvider(): with antd.Drawer(open=False, title="code", placement="left", width="750px") as code_drawer: code_output = legacy.Markdown() with antd.Drawer(open=False, title="history", placement="left", width="900px") as history_drawer: history_output = legacy.Chatbot(show_label=False, flushing=False, height=960, elem_classes="history_chatbot") with antd.Drawer( open=False, title="Templates", placement="right", width="900px", elem_classes="session-drawer" ) as session_drawer: with antd.Flex(vertical=True, gap="middle"): gr.Markdown("### Available Game Templates") session_history = gr.HTML( elem_classes="session-history" ) close_btn = antd.Button( "Close", type="default", elem_classes="close-btn" ) with antd.Row(gutter=[32, 12]) as layout: with antd.Col(span=24, md=8): with antd.Flex(vertical=True, gap="middle", wrap=True): header = gr.HTML(f"""

MOUSE-I: Web Game Creator & Deployer

게임 템플릿의 프롬프트를 복사하고 SEND를 클릭하면 코드가 생성됩니다. 생성된 코드로 '배포' 버튼을 누르면 글로벌 클라우드(VERCEL)에 자동 배포됩니다. 생성된 코드만 프롬프트에 붙여넣고 'Code실행'을 누르면 즉시 게임을 미리보기로 실행할 수 있습니다. 문의: arxivgpt@gmail.com

🎨 커뮤니티 바로가기 클릭

""") input = antd.InputTextarea( size="large", allow_clear=True, placeholder=random.choice(DEMO_LIST)['description'] ) with antd.Flex(gap="small", justify="space-between"): btn = antd.Button("Send", type="primary", size="large") boost_btn = antd.Button("Boost", type="default", size="large") execute_btn = antd.Button("Code실행", type="default", size="large") deploy_btn = antd.Button("배포", type="default", size="large") clear_btn = antd.Button("클리어", type="default", size="large") deploy_result = gr.HTML(label="배포 결과") with antd.Col(span=24, md=16): with ms.Div(elem_classes="right_panel"): with antd.Flex(gap="small", elem_classes="setting-buttons"): codeBtn = antd.Button("🧑‍💻 코드 보기", type="default") historyBtn = antd.Button("📜 히스토리", type="default") best_btn = antd.Button("🏆 베스트 템플릿", type="default") trending_btn = antd.Button("🔥 트렌딩 템플릿", type="default") new_btn = antd.Button("✨ NEW 템플릿", type="default") gr.HTML('
') with antd.Tabs(active_key="empty", render_tab_bar="() => null") as state_tab: with antd.Tabs.Item(key="empty"): empty = antd.Empty(description="empty input", elem_classes="right_content") with antd.Tabs.Item(key="loading"): loading = antd.Spin(True, tip="coding...", size="large", elem_classes="right_content") with antd.Tabs.Item(key="render"): sandbox = gr.HTML(elem_classes="html_content") def execute_code(query: str): if not query or query.strip() == '': return None, gr.update(active_key="empty") try: if '```html' in query and '```' in query: code = remove_code_block(query) else: code = query.strip() return send_to_sandbox(code), gr.update(active_key="render") except Exception as e: print(f"Error executing code: {str(e)}") return None, gr.update(active_key="empty") execute_btn.click( fn=execute_code, inputs=[input], outputs=[sandbox, state_tab] ) codeBtn.click( lambda: gr.update(open=True), inputs=[], outputs=[code_drawer] ) code_drawer.close( lambda: gr.update(open=False), inputs=[], outputs=[code_drawer] ) historyBtn.click( history_render, inputs=[history], outputs=[history_drawer, history_output] ) history_drawer.close( lambda: gr.update(open=False), inputs=[], outputs=[history_drawer] ) best_btn.click( fn=lambda: (gr.update(open=True), load_best_templates()), outputs=[session_drawer, session_history], queue=False ) trending_btn.click( fn=lambda: (gr.update(open=True), load_trending_templates()), outputs=[session_drawer, session_history], queue=False ) new_btn.click( fn=lambda: (gr.update(open=True), load_new_templates()), outputs=[session_drawer, session_history], queue=False ) session_drawer.close( lambda: (gr.update(open=False), gr.HTML("")), outputs=[session_drawer, session_history] ) close_btn.click( lambda: (gr.update(open=False), gr.HTML("")), outputs=[session_drawer, session_history] ) btn.click( demo_instance.generation_code, inputs=[input, setting, history], outputs=[code_output, history, sandbox, state_tab, code_drawer] ) clear_btn.click( demo_instance.clear_history, inputs=[], outputs=[history] ) boost_btn.click( fn=handle_boost, inputs=[input], outputs=[input, state_tab] ) deploy_btn.click( fn=lambda code: deploy_to_vercel(remove_code_block(code)) if code else "코드가 없습니다.", inputs=[code_output], outputs=[deploy_result] ) if __name__ == "__main__": try: demo_instance = Demo() demo.queue(default_concurrency_limit=20).launch(ssr_mode=False) except Exception as e: print(f"Initialization error: {e}") raise