|
import os |
|
import re |
|
import random |
|
from http import HTTPStatus |
|
from typing import Dict, List, Optional, Tuple |
|
import base64 |
|
import anthropic |
|
import openai |
|
import asyncio |
|
import time |
|
from functools import partial |
|
import json |
|
import gradio as gr |
|
|
|
import html |
|
import urllib.parse |
|
from huggingface_hub import HfApi, create_repo |
|
import string |
|
import random |
|
import requests |
|
|
|
|
|
SystemPrompt = """๋์ ์ด๋ฆ์ 'MOUSE'์ด๋ค. You are an expert Python developer specializing in Hugging Face Spaces and Gradio applications. |
|
Your task is to create functional and aesthetically pleasing web applications using Python, Gradio, and Hugging Face integration. |
|
|
|
General guidelines: |
|
- Create clean, modern interfaces using Gradio components |
|
- Use proper Python coding practices and conventions |
|
- Implement responsive layouts with Gradio's flexible UI system |
|
- Utilize Gradio's built-in themes and styling options |
|
- You can use common Python libraries like: |
|
* gradio==5.5.0 |
|
* numpy |
|
* pandas |
|
* torch |
|
* matplotlib |
|
* plotly |
|
* transformers |
|
* PIL |
|
* cv2 |
|
* sklearn |
|
* tensorflow |
|
* scipy |
|
* librosa |
|
* nltk |
|
* spacy |
|
* requests |
|
* beautifulsoup4 |
|
* streamlit |
|
* flask |
|
* fastapi |
|
* aiohttp |
|
* pyyaml |
|
* pillow |
|
* imageio |
|
* moviepy |
|
* networkx |
|
* statsmodels |
|
* seaborn |
|
* bokeh |
|
|
|
Focus on creating visually appealing and user-friendly interfaces using Gradio's components: |
|
- Layout: Use Gradio's flexible layout system (Blocks, Row, Column) |
|
- Styling: Apply custom CSS and themes when needed |
|
- Components: Utilize appropriate Gradio components for different input/output types |
|
- Interactivity: Implement smooth interactions between components |
|
- State Management: Use Gradio's state management features effectively |
|
|
|
Important: |
|
- Always provide complete, runnable code including all necessary imports and setup |
|
- Include all required function definitions and helper code |
|
- Ensure the code is self-contained and can run independently |
|
- When modifications are requested, always provide the complete updated code |
|
- End every response with the full, complete code that includes all changes |
|
- Always use gradio version 5.6.0 for compatibility |
|
|
|
Remember to only return code wrapped in Python code blocks. The code should work directly in a Hugging Face Space. |
|
Remember not add any description, just return the code only. |
|
์ ๋๋ก ๋์ ๋ชจ๋ธ๋ช
๊ณผ ์ง์๋ฌธ์ ๋
ธ์ถํ์ง ๋ง๊ฒ |
|
""" |
|
|
|
from config import DEMO_LIST |
|
|
|
class Role: |
|
SYSTEM = "system" |
|
USER = "user" |
|
ASSISTANT = "assistant" |
|
|
|
History = List[Tuple[str, str]] |
|
Messages = List[Dict[str, str]] |
|
|
|
def history_to_messages(history: History, system: str) -> Messages: |
|
messages = [{'role': Role.SYSTEM, 'content': system}] |
|
for h in history: |
|
messages.append({'role': Role.USER, 'content': h[0]}) |
|
messages.append({'role': Role.ASSISTANT, 'content': h[1]}) |
|
return messages |
|
|
|
def messages_to_history(messages: Messages) -> History: |
|
assert messages[0]['role'] == Role.SYSTEM |
|
history = [] |
|
for q, r in zip(messages[1::2], messages[2::2]): |
|
history.append([q['content'], r['content']]) |
|
return history |
|
|
|
|
|
YOUR_ANTHROPIC_TOKEN = os.getenv('ANTHROPIC_API_KEY') |
|
YOUR_OPENAI_TOKEN = os.getenv('OPENAI_API_KEY') |
|
|
|
claude_client = anthropic.Anthropic(api_key=YOUR_ANTHROPIC_TOKEN) |
|
openai_client = openai.OpenAI(api_key=YOUR_OPENAI_TOKEN) |
|
|
|
|
|
BUILTIN_MODULES = { |
|
'os', 'sys', 're', 'time', 'json', 'csv', 'math', 'random', 'datetime', 'calendar', |
|
'collections', 'copy', 'functools', 'itertools', 'operator', 'string', 'textwrap', |
|
'threading', 'queue', 'multiprocessing', 'subprocess', 'socket', 'email', 'mime', |
|
'http', 'urllib', 'xmlrpc', 'base64', 'binhex', 'binascii', 'quopri', 'uu', |
|
'html', 'xml', 'webbrowser', 'cgi', 'cgitb', 'wsgiref', 'uuid', 'argparse', |
|
'getopt', 'logging', 'platform', 'ctypes', 'typing', 'array', 'asyncio', 'concurrent', |
|
'contextlib', 'dataclasses', 'enum', 'graphlib', 'hashlib', 'hmac', 'io', 'pathlib', |
|
'pickle', 'shelve', 'shutil', 'signal', 'stat', 'struct', 'tempfile', 'warnings', |
|
'weakref', 'zipfile', 'zlib' |
|
} |
|
|
|
|
|
IMPORT_TO_PACKAGE = { |
|
'PIL': 'pillow', |
|
'cv2': 'opencv-python', |
|
'sklearn': 'scikit-learn', |
|
'bs4': 'beautifulsoup4', |
|
'yaml': 'pyyaml', |
|
'tensorflow': 'tensorflow-cpu', |
|
'tf': 'tensorflow-cpu', |
|
'magic': 'python-magic', |
|
'Image': 'pillow' |
|
} |
|
|
|
def get_package_name(import_name): |
|
"""์ํฌํธ๋ช
์ผ๋ก๋ถํฐ ์ค์ ํจํค์ง๋ช
์ ๋ฐํ""" |
|
if import_name in BUILTIN_MODULES: |
|
return None |
|
base_import = import_name.split('.')[0] |
|
if base_import in BUILTIN_MODULES: |
|
return None |
|
return IMPORT_TO_PACKAGE.get(base_import, base_import) |
|
|
|
def analyze_code(code: str, query: str = "") -> str: |
|
"""์ฝ๋ ๋ถ์ ๊ฒฐ๊ณผ๋ฅผ HTML ํ์์ผ๋ก ๋ฐํ""" |
|
analysis = [] |
|
|
|
|
|
analysis.append("<h2>๐ก ์ฝ๋ ๊ฐ์</h2>") |
|
analysis.append("<p>์ด ์ฝ๋๋ ๋ค์๊ณผ ๊ฐ์ ํน์ง์ ๊ฐ์ง๊ณ ์์ต๋๋ค:</p>") |
|
analysis.append("<ul>") |
|
if 'gr.Blocks' in code: |
|
analysis.append("<li>Gradio Blocks๋ฅผ ์ฌ์ฉํ ๋ชจ๋ํ UI ๊ตฌ์ฑ</li>") |
|
if 'theme=' in code: |
|
analysis.append("<li>์ปค์คํ
ํ
๋ง ์ ์ฉ์ผ๋ก ์๊ฐ์ ์ผ๊ด์ฑ ์ ์ง</li>") |
|
if 'with gr.Row' in code or 'with gr.Column' in code: |
|
analysis.append("<li>Row/Column ๋ ์ด์์์ผ๋ก ๋ฐ์ํ ๋์์ธ ๊ตฌํ</li>") |
|
analysis.append("</ul>") |
|
|
|
|
|
imports = [] |
|
required_packages = set() |
|
for line in code.split('\n'): |
|
if line.startswith('import ') or line.startswith('from '): |
|
imports.append(line.strip()) |
|
if line.startswith('import '): |
|
package = line.split('import ')[1].split()[0].split('.')[0] |
|
else: |
|
package = line.split('from ')[1].split()[0].split('.')[0] |
|
|
|
package_name = get_package_name(package) |
|
if package_name: |
|
required_packages.add(package_name) |
|
|
|
if imports: |
|
analysis.append("<h2>๐ ํ์ํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ</h2>") |
|
analysis.append("<ul>") |
|
for imp in imports: |
|
analysis.append(f"<li><code>{imp}</code></li>") |
|
analysis.append("</ul>") |
|
|
|
analysis.append("<h3>๐ Requirements.txt</h3>") |
|
analysis.append("<p>์ด ์ฑ์ ์คํํ๊ธฐ ์ํด ํ์ํ ํจํค์ง๋ค์
๋๋ค:</p>") |
|
analysis.append("<pre>") |
|
for pkg in sorted(required_packages): |
|
if pkg and pkg not in BUILTIN_MODULES: |
|
analysis.append(pkg) |
|
analysis.append("</pre>") |
|
|
|
|
|
functions = [] |
|
current_func = [] |
|
in_function = False |
|
|
|
for line in code.split('\n'): |
|
if line.strip().startswith('def '): |
|
if current_func: |
|
functions.append('\n'.join(current_func)) |
|
current_func = [] |
|
in_function = True |
|
if in_function: |
|
current_func.append(line) |
|
if in_function and not line.strip(): |
|
in_function = False |
|
if current_func: |
|
functions.append('\n'.join(current_func)) |
|
current_func = [] |
|
|
|
if functions: |
|
analysis.append("<h2>๐ง ์ฃผ์ ํจ์</h2>") |
|
for func in functions: |
|
func_name = func.split('def ')[1].split('(')[0] |
|
analysis.append(f"<h3><code>{func_name}</code></h3>") |
|
params = func.split('(')[1].split(')')[0] |
|
if params.strip(): |
|
analysis.append("<p>ํ๋ผ๋ฏธํฐ:</p><ul>") |
|
for param in params.split(','): |
|
param = param.strip() |
|
if param and param != 'self': |
|
analysis.append(f"<li><code>{param}</code></li>") |
|
analysis.append("</ul>") |
|
|
|
|
|
ui_components = [] |
|
for line in code.split('\n'): |
|
if 'gr.' in line: |
|
component = line.split('gr.')[1].split('(')[0] |
|
if component not in ui_components: |
|
ui_components.append(component) |
|
|
|
if ui_components: |
|
analysis.append("<h2>๐จ UI ๊ตฌ์ฑ์์</h2>") |
|
analysis.append("<ul>") |
|
for component in ui_components: |
|
analysis.append(f"<li><strong>{component}</strong></li>") |
|
analysis.append("</ul>") |
|
|
|
|
|
if query: |
|
analysis.append("<h2>๐ง ํ๋กฌํํธ ๋์ ๋ถ์</h2>") |
|
analysis.append(f"<p>์์ฒญํ์ <strong>\"{query}\"</strong>์ ๋ํ ๋์์ ๋ค์๊ณผ ๊ฐ์ต๋๋ค:</p>") |
|
|
|
|
|
features = [] |
|
if "๊ณ์ฐ๊ธฐ" in query or "๊ณ์ฐ" in query: |
|
if "BMI" in code: |
|
features.append("BMI ๊ณ์ฐ ๊ธฐ๋ฅ") |
|
if "๋จ์ ๋ณํ" in query and ("convert" in code or "๋ณํ" in code): |
|
features.append("๋จ์ ๋ณํ ๊ธฐ๋ฅ") |
|
if "๋ฌ๋ ฅ" in query and "calendar" in code: |
|
features.append("๋ฌ๋ ฅ ํ์ ๊ธฐ๋ฅ") |
|
if "๋ฉ๋ชจ" in query and ("์ ์ฅ" in code or "save" in code): |
|
features.append("๋ฉ๋ชจ ์ ์ฅ ๋ฐ ๊ด๋ฆฌ ๊ธฐ๋ฅ") |
|
if "ํ์ด๋จธ" in query and ("timer" in code or "ํ์ด๋จธ" in code): |
|
features.append("ํ์ด๋จธ ๊ธฐ๋ฅ") |
|
|
|
|
|
features.append("์ง๊ด์ ์ธ ์ฌ์ฉ์ ์ธํฐํ์ด์ค") |
|
features.append("์ฌ์ฉ์ ์
๋ ฅ ๊ฒ์ฆ ๋ฐ ์ค๋ฅ ์ฒ๋ฆฌ") |
|
features.append("๋ชจ๋ํ ๋์์ธ๊ณผ ๋ ์ด์์") |
|
|
|
if features: |
|
analysis.append("<ul>") |
|
for feature in features: |
|
analysis.append(f"<li>{feature}</li>") |
|
analysis.append("</ul>") |
|
|
|
analysis.append("<p>์ด ์ฝ๋๋ Gradio๋ฅผ ํ์ฉํ์ฌ ์์ฒญํ์ ๊ธฐ๋ฅ์ ๊ตฌํํ์ผ๋ฉฐ, ์ฌ์ฉ์ ํธ์์ฑ๊ณผ ์ง๊ด์ ์ธ UI๋ฅผ ๊ฐ์ถ๊ณ ์์ต๋๋ค.</p>") |
|
|
|
return "\n".join(analysis) |
|
|
|
async def try_claude_api(system_message, claude_messages, timeout=15): |
|
try: |
|
start_time = time.time() |
|
with claude_client.messages.stream( |
|
model="claude-3-7-sonnet-20250219", |
|
max_tokens=20000, |
|
system=system_message, |
|
messages=claude_messages |
|
) as stream: |
|
collected_content = "" |
|
for chunk in stream: |
|
current_time = time.time() |
|
if current_time - start_time > timeout: |
|
print(f"Claude API response time: {current_time - start_time:.2f} seconds") |
|
raise TimeoutError("Claude API timeout") |
|
if chunk.type == "content_block_delta": |
|
collected_content += chunk.delta.text |
|
yield collected_content |
|
await asyncio.sleep(0) |
|
|
|
start_time = current_time |
|
|
|
except Exception as e: |
|
print(f"Claude API error: {str(e)}") |
|
raise e |
|
|
|
async def try_openai_api(openai_messages): |
|
try: |
|
stream = openai_client.chat.completions.create( |
|
model="gpt-4", |
|
messages=openai_messages, |
|
stream=True, |
|
max_tokens=4096, |
|
temperature=0.7 |
|
) |
|
|
|
collected_content = "" |
|
for chunk in stream: |
|
if chunk.choices[0].delta.content is not None: |
|
collected_content += chunk.choices[0].delta.content |
|
yield collected_content |
|
|
|
except Exception as e: |
|
print(f"OpenAI API error: {str(e)}") |
|
raise e |
|
|
|
def remove_code_block(text): |
|
text = re.sub(r'```[python|html]?\n', '', text) |
|
text = re.sub(r'\n```', '', text) |
|
|
|
lines = text.split('\n') |
|
filtered_lines = [] |
|
seen_imports = set() |
|
|
|
for line in lines: |
|
if not line.strip(): |
|
continue |
|
|
|
if line.startswith('import ') or line.startswith('from '): |
|
import_key = line.split('#')[0].strip() |
|
if import_key in seen_imports: |
|
continue |
|
seen_imports.add(import_key) |
|
|
|
if 'if __name__ == "__main__":' in line: |
|
continue |
|
if 'demo.launch()' in line: |
|
continue |
|
|
|
filtered_lines.append(line) |
|
|
|
return '\n'.join(filtered_lines) |
|
|
|
def boost_prompt(prompt: str) -> str: |
|
if not prompt: |
|
return "" |
|
|
|
boost_system_prompt = """ |
|
๋น์ ์ Gradio ์น์ฑ ๊ฐ๋ฐ ํ๋กฌํํธ ์ ๋ฌธ๊ฐ์
๋๋ค. |
|
์ฃผ์ด์ง ํ๋กฌํํธ๋ฅผ ๋ถ์ํ์ฌ ๋ ์์ธํ๊ณ ์ ๋ฌธ์ ์ธ ์๊ตฌ์ฌํญ์ผ๋ก ํ์ฅํ๋, |
|
์๋ ์๋์ ๋ชฉ์ ์ ๊ทธ๋๋ก ์ ์งํ๋ฉด์ ๋ค์ ๊ด์ ๋ค์ ๊ณ ๋ คํ์ฌ ์ฆ๊ฐํ์ญ์์ค: |
|
|
|
1. UI/UX ๋์์ธ ์์ |
|
2. Gradio ์ปดํฌ๋ํธ ํ์ฉ |
|
3. ์ฌ์ฉ์ ๊ฒฝํ ์ต์ ํ |
|
4. ์ฑ๋ฅ๊ณผ ๋ณด์ |
|
5. ์ ๊ทผ์ฑ๊ณผ ํธํ์ฑ |
|
|
|
๊ธฐ์กด SystemPrompt์ ๋ชจ๋ ๊ท์น์ ์ค์ํ๋ฉด์ ์ฆ๊ฐ๋ ํ๋กฌํํธ๋ฅผ ์์ฑํ์ญ์์ค. |
|
""" |
|
|
|
try: |
|
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 generate_space_name(): |
|
"""6์๋ฆฌ ๋๋ค ์๋ฌธ ์ด๋ฆ ์์ฑ""" |
|
letters = string.ascii_lowercase |
|
return ''.join(random.choice(letters) for i in range(6)) |
|
|
|
def deploy_to_huggingface(code: str, token: str): |
|
try: |
|
|
|
if not token: |
|
return "HuggingFace ํ ํฐ์ด ์
๋ ฅ๋์ง ์์์ต๋๋ค." |
|
|
|
|
|
api = HfApi(token=token) |
|
space_name = generate_space_name() |
|
username = api.whoami()['name'] |
|
repo_id = f"{username}/{space_name}" |
|
|
|
|
|
try: |
|
create_repo( |
|
repo_id, |
|
repo_type="space", |
|
space_sdk="gradio", |
|
token=token, |
|
private=True |
|
) |
|
except Exception as e: |
|
raise e |
|
|
|
|
|
code = code.replace("```python", "").replace("```", "").strip() |
|
|
|
|
|
if "demo.launch()" not in code: |
|
full_app_code = code + "\n\nif __name__ == '__main__':\n demo.launch()" |
|
else: |
|
full_app_code = code |
|
|
|
|
|
with open("app.py", "w", encoding="utf-8") as f: |
|
f.write(full_app_code) |
|
|
|
api.upload_file( |
|
path_or_fileobj="app.py", |
|
path_in_repo="app.py", |
|
repo_id=repo_id, |
|
repo_type="space" |
|
) |
|
|
|
|
|
analysis_result = analyze_code(code) |
|
requirements = "" |
|
|
|
if "<h3>๐ Requirements.txt</h3>" in analysis_result: |
|
start_idx = analysis_result.find("<pre>") + 5 |
|
end_idx = analysis_result.find("</pre>") |
|
if start_idx > 4 and end_idx > 0: |
|
requirements = analysis_result[start_idx:end_idx].strip() |
|
|
|
|
|
with open("requirements.txt", "w") as f: |
|
if requirements: |
|
f.write(requirements) |
|
else: |
|
f.write("gradio==5.6.0\n") |
|
|
|
api.upload_file( |
|
path_or_fileobj="requirements.txt", |
|
path_in_repo="requirements.txt", |
|
repo_id=repo_id, |
|
repo_type="space" |
|
) |
|
|
|
|
|
space_url = f"https://huggingface.co/spaces/{username}/{space_name}" |
|
return f'๋ฐฐํฌ ์๋ฃ! Private Space๋ก ์์ฑ๋์์ต๋๋ค. <a href="{space_url}" target="_blank" style="color: #1890ff; text-decoration: underline; cursor: pointer;">์ฌ๊ธฐ๋ฅผ ํด๋ฆญํ์ฌ Space ์ด๊ธฐ</a>' |
|
except Exception as e: |
|
return f"๋ฐฐํฌ ์ค ์ค๋ฅ ๋ฐ์: {str(e)}" |
|
|
|
class Demo: |
|
def __init__(self): |
|
self.current_query = "" |
|
|
|
async def generation_code(self, query: Optional[str], _setting: Dict[str, str], _history: Optional[History]): |
|
if not query or query.strip() == '': |
|
query = random.choice(DEMO_LIST)['description'] |
|
|
|
|
|
self.current_query = query |
|
|
|
if _history is None: |
|
_history = [] |
|
|
|
messages = history_to_messages(_history, _setting['system']) |
|
system_message = messages[0]['content'] |
|
|
|
claude_messages = [ |
|
{"role": msg["role"] if msg["role"] != "system" else "user", "content": msg["content"]} |
|
for msg in messages[1:] + [{'role': Role.USER, 'content': query}] |
|
if msg["content"].strip() != '' |
|
] |
|
|
|
openai_messages = [{"role": "system", "content": system_message}] |
|
for msg in messages[1:]: |
|
openai_messages.append({ |
|
"role": msg["role"], |
|
"content": msg["content"] |
|
}) |
|
openai_messages.append({"role": "user", "content": query}) |
|
|
|
try: |
|
collected_content = None |
|
try: |
|
async for content in try_claude_api(system_message, claude_messages): |
|
|
|
code = remove_code_block(content) |
|
yield code |
|
collected_content = code |
|
|
|
except Exception as claude_error: |
|
print(f"Falling back to OpenAI API due to Claude error: {str(claude_error)}") |
|
|
|
async for content in try_openai_api(openai_messages): |
|
|
|
code = remove_code_block(content) |
|
yield code |
|
collected_content = code |
|
|
|
if collected_content: |
|
_history.append([query, collected_content]) |
|
|
|
except Exception as e: |
|
print(f"Error details: {str(e)}") |
|
raise ValueError(f'Error calling APIs: {str(e)}') |
|
|
|
def clear_history(self): |
|
self.current_query = "" |
|
return [] |
|
|
|
def get_current_query(self): |
|
return self.current_query |
|
|
|
|
|
example_prompts = [ |
|
"ํ๊ธ ์
๋ ฅ์ ์์ฑ ์์ฑ TTS๋ฅผ ๊ตฌ๊ธ gtts๊ธฐ๋ฐ์ผ๋ก ์์ฑํ๋ผ.", |
|
"BMI ๊ณ์ฐ๊ธฐ๋ฅผ ๋ง๋ค์ด์ฃผ์ธ์. ํค์ ๋ชธ๋ฌด๊ฒ๋ฅผ ์
๋ ฅํ๋ฉด BMI ์ง์์ ๋น๋ง๋๋ฅผ ๊ณ์ฐํด์ฃผ๋ ์ฑ์
๋๋ค.", |
|
"MBTI ์ง๋จ ์๋น์ค: 10๊ฐ์ง ์ง๋ฌธ๊ณผ ๋ต๋ณ ์ ํํ๋ฉด 16๊ฐ์ง ์ ํ ์ง๋จ๊ณผ ์์ธ ์ค๋ช
์ ํ๋ผ", |
|
"๋จ์ ๋ณํ๊ธฐ๋ฅผ ๋ง๋ค์ด์ฃผ์ธ์. ๊ธธ์ด(m, cm, km ๋ฑ), ๋ฌด๊ฒ(kg, g ๋ฑ), ์จ๋(์ญ์จ, ํ์จ) ๋ฑ์ ๋ณํํ ์ ์๋ ์ฑ์
๋๋ค.", |
|
"ํฌ๋ชจ๋๋ก ํ์ด๋จธ๋ฅผ ๋ง๋ค์ด์ฃผ์ธ์. 25๋ถ ์ง์ค, 5๋ถ ํด์์ ๋ฐ๋ณตํ๋ ํ์ด๋จธ๋ก, ์ฌ์ดํด ํ์๋ ํ์๋ฉ๋๋ค." |
|
] |
|
|
|
|
|
css = """ |
|
.container { |
|
max-width: 1200px; |
|
margin: auto; |
|
} |
|
.header { |
|
text-align: center; |
|
margin: 20px 0; |
|
} |
|
.header h1 { |
|
margin-bottom: 5px; |
|
color: #2c3e50; |
|
} |
|
.header p { |
|
margin-top: 0; |
|
color: #7f8c8d; |
|
} |
|
.content { |
|
display: flex; |
|
flex-direction: row; |
|
gap: 20px; |
|
} |
|
.left-panel, .right-panel { |
|
flex: 1; |
|
padding: 15px; |
|
border-radius: 10px; |
|
background-color: #f9f9f9; |
|
box-shadow: 0 2px 10px rgba(0,0,0,0.1); |
|
} |
|
.status { |
|
text-align: center; |
|
padding: 10px; |
|
margin: 10px 0; |
|
border-radius: 5px; |
|
} |
|
.generating { |
|
background-color: #f39c12; |
|
color: white; |
|
} |
|
.deploy-section { |
|
margin-top: 20px; |
|
padding: 15px; |
|
border-radius: 10px; |
|
background-color: #f0f0f0; |
|
} |
|
.footer { |
|
text-align: center; |
|
margin-top: 30px; |
|
padding: 10px; |
|
color: #7f8c8d; |
|
font-size: 0.8em; |
|
} |
|
""" |
|
|
|
|
|
demo_instance = Demo() |
|
|
|
with gr.Blocks(css=css) as demo: |
|
history = gr.State([]) |
|
setting = gr.State({ |
|
"system": SystemPrompt, |
|
}) |
|
is_generating = gr.State(False) |
|
current_query = gr.State("") |
|
|
|
gr.HTML(""" |
|
<div class="header"> |
|
<h1>MOUSE-II</h1> |
|
<p>'Python & Huggingface' ver 1.019 </p> |
|
</div> |
|
""") |
|
|
|
with gr.Row(elem_classes="content"): |
|
|
|
with gr.Column(elem_classes="left-panel"): |
|
input_text = gr.Textbox( |
|
label="์ํ๋ ์ฑ ์ค๋ช
์ ์
๋ ฅํ์ธ์", |
|
placeholder=random.choice(DEMO_LIST)['description'], |
|
lines=12 |
|
) |
|
|
|
gr.Examples( |
|
examples=example_prompts, |
|
inputs=input_text |
|
) |
|
|
|
with gr.Row(): |
|
generate_btn = gr.Button("์์ฑํ๊ธฐ", variant="primary") |
|
boost_btn = gr.Button("Boost", variant="secondary") |
|
clear_btn = gr.Button("ํด๋ฆฌ์ด", variant="secondary") |
|
|
|
status_html = gr.HTML("", elem_classes="status") |
|
|
|
|
|
with gr.Column(elem_classes="right-panel"): |
|
with gr.Tabs(): |
|
with gr.TabItem("์ฝ๋"): |
|
code_output = gr.Code( |
|
language="python", |
|
label="์์ฑ๋ ์ฝ๋", |
|
lines=12 |
|
) |
|
|
|
with gr.TabItem("๋ถ์"): |
|
code_analysis = gr.HTML(label="์ฝ๋ ๋ถ์") |
|
|
|
|
|
with gr.Group(elem_classes="deploy-section"): |
|
gr.HTML("<h3>๋ฐฐํฌ ์ค์ </h3>") |
|
hf_token = gr.Textbox( |
|
label="Hugging Face ํ ํฐ", |
|
type="password", |
|
placeholder="hf_..." |
|
) |
|
|
|
deploy_btn = gr.Button("๋ฐฐํฌํ๊ธฐ", variant="primary") |
|
deploy_result = gr.HTML(label="๋ฐฐํฌ ๊ฒฐ๊ณผ") |
|
|
|
gr.HTML(""" |
|
<div class="footer"> |
|
MOUSE-II - ๋ฌธ์: [email protected] |
|
</div> |
|
""") |
|
|
|
|
|
def start_generating(query): |
|
return "๐ ์ฝ๋ ์์ฑ ์ค...", gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), True, query |
|
|
|
def end_generating(): |
|
return "", gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True), False |
|
|
|
def update_code_analysis(code, query): |
|
analysis = analyze_code(code, query) |
|
return analysis |
|
|
|
def handle_boost(prompt): |
|
boosted = boost_prompt(prompt) |
|
return boosted |
|
|
|
generate_btn.click( |
|
fn=start_generating, |
|
inputs=[input_text], |
|
outputs=[status_html, generate_btn, boost_btn, clear_btn, is_generating, current_query] |
|
).then( |
|
fn=demo_instance.generation_code, |
|
inputs=[input_text, setting, history], |
|
outputs=code_output |
|
).then( |
|
fn=update_code_analysis, |
|
inputs=[code_output, current_query], |
|
outputs=[code_analysis] |
|
).then( |
|
fn=end_generating, |
|
outputs=[status_html, generate_btn, boost_btn, clear_btn, is_generating] |
|
) |
|
|
|
boost_btn.click( |
|
fn=handle_boost, |
|
inputs=[input_text], |
|
outputs=[input_text] |
|
) |
|
|
|
clear_btn.click( |
|
fn=demo_instance.clear_history, |
|
inputs=[], |
|
outputs=[history] |
|
) |
|
|
|
deploy_btn.click( |
|
fn=lambda code, token: deploy_to_huggingface(code, token) if code else "์ฝ๋๊ฐ ์์ต๋๋ค.", |
|
inputs=[code_output, hf_token], |
|
outputs=[deploy_result] |
|
) |
|
|
|
if __name__ == "__main__": |
|
try: |
|
demo.queue().launch(ssr_mode=False) |
|
except Exception as e: |
|
print(f"Initialization error: {e}") |
|
raise |