"""
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('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