File size: 25,374 Bytes
3878434 fa0d7e5 3878434 02ccd7f 1876526 16cc2de e27811d 3878434 7bfffd0 b32380d 6753681 9319937 7f1e73f 9319937 7f1e73f a7a6c64 7bfffd0 a7a6c64 79f7fd8 a7a6c64 18647c1 a7a6c64 79f7fd8 a7a6c64 79f7fd8 a7a6c64 19fd7dc 79f7fd8 19fd7dc a7a6c64 7bfffd0 57b5f83 7bfffd0 3878434 e51a8ef 7f1e73f e51a8ef 0ad9e3f 6e63c85 0ad9e3f 1fbe5a8 5b26d99 6d46d5d 5b26d99 0ad9e3f 5b26d99 0ad9e3f 5b26d99 8132686 1fbe5a8 ebc7917 1fbe5a8 ebc7917 1fbe5a8 ebc7917 0ad9e3f 7f1e73f 0ad9e3f 5b26d99 1fbe5a8 ebc7917 1fbe5a8 ebc7917 7f1e73f ebc7917 1fbe5a8 7f1e73f 1fbe5a8 ebc7917 1fbe5a8 ebc7917 1fbe5a8 7f1e73f 1fbe5a8 8132686 1fbe5a8 7f1e73f 095a9f5 204dfa4 7f1e73f 6d46d5d 7f1e73f 6d46d5d 7f1e73f 204dfa4 7f1e73f 6d46d5d 7f1e73f 6d46d5d 7f1e73f 6d46d5d 7f1e73f 6d46d5d 7f1e73f 6d46d5d 7f1e73f e51a8ef 8132686 db57af7 8132686 db57af7 8132686 6e63c85 db57af7 8132686 6e63c85 db57af7 6e63c85 db57af7 e51a8ef 8132686 e51a8ef 8132686 e51a8ef 6d46d5d 8132686 6d46d5d 8132686 6d46d5d 9319937 6e63c85 e51a8ef 6e63c85 3878434 6e63c85 8132686 6e63c85 fa9d328 6e63c85 1c4cd1c 6e63c85 1c4cd1c 18f7bef 7f1e73f 1c4cd1c 7f1e73f 1c4cd1c 6e63c85 1c4cd1c 6e63c85 1c4cd1c 6e63c85 1c4cd1c 8132686 c016c07 6e63c85 1a1e451 1c4cd1c 8132686 6e63c85 8132686 6e63c85 e5edb92 1c4cd1c 6e63c85 8132686 6e63c85 1c4cd1c 6e63c85 8132686 6e63c85 1c4cd1c 18f7bef 1c4cd1c 6e63c85 1c4cd1c 7c2ac54 3878434 64ad997 6e63c85 64ad997 ac8a9a6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 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 105 106 107 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 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 |
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 ์ ์
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
# API ํด๋ผ์ด์ธํธ ์ด๊ธฐํ
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)
# Built-in modules that don't need to be in requirements.txt
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 Name Mapping Dictionary
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 = []
# 0. ์ฝ๋ ๊ฐ์
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>")
# 1. ์ฌ์ฉ๋ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ๋ถ์
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>")
# 2. ํจ์ ๋ถ์
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>")
# 3. UI ์ปดํฌ๋ํธ ๋ถ์
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>")
# 4. ํ๋กฌํํธ ๋์ ๋ถ์
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:
# 1) ๊ธฐ๋ณธ ๊ฒ์ฆ
if not token:
return "HuggingFace ํ ํฐ์ด ์
๋ ฅ๋์ง ์์์ต๋๋ค."
# 2) Space ์์ฑ ์ค๋น
api = HfApi(token=token)
space_name = generate_space_name()
username = api.whoami()['name']
repo_id = f"{username}/{space_name}"
# 3) Space ์์ฑ (private๋ก ์ค์ )
try:
create_repo(
repo_id,
repo_type="space",
space_sdk="gradio",
token=token,
private=True
)
except Exception as e:
raise e
# 4) ์ฝ๋ ์ ๋ฆฌ
code = code.replace("```python", "").replace("```", "").strip()
# 5) ์ ์ฒด ์ ํ๋ฆฌ์ผ์ด์
์ฝ๋ ์์ฑ
if "demo.launch()" not in code:
full_app_code = code + "\n\nif __name__ == '__main__':\n demo.launch()"
else:
full_app_code = code
# 6) ํ์ผ ์์ฑ ๋ฐ ์
๋ก๋
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"
)
# 7) requirements.txt ์์ฑ ๋ฐ ์
๋ก๋
analysis_result = analyze_code(code)
requirements = ""
# HTML์์ requirements.txt ์น์
์ฐพ๊ธฐ
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()
# requirements.txt ์์ฑ
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"
)
# 8) ๊ฒฐ๊ณผ ๋ฐํ
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 ์คํ์ผ
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 ์ธ์คํด์ค ์์ฑ
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="์ฝ๋ ๋ถ์")
# Group์ผ๋ก ๋ณ๊ฒฝ
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
|