Spaces:
Running
Running
File size: 28,899 Bytes
941b583 606f0ee |
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 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 |
import os
import gradio as gr
import time
import logging
import random
import uuid
from datetime import datetime
from langdetect import detect, DetectorFactory
import google.generativeai as genai
from dotenv import load_dotenv
DetectorFactory.seed = 0
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
# νκ²½ λ³μ λ‘λ
load_dotenv()
# νκ²½λ³μμμ API ν€ μ€μ λ‘λ
def get_gemini_api_configs():
"""νκ²½λ³μμμ Gemini API ν€ μ€μ μ λ‘λ"""
api_configs_str = os.getenv('GEMINI_API_CONFIGS', '')
if not api_configs_str:
logger.error("GEMINI_API_CONFIGS νκ²½λ³μκ° μ€μ λμ§ μμμ΅λλ€.")
return []
try:
# νκ²½λ³μ κ°μ execλ‘ μ€ννμ¬ μ€μ λ‘λ
local_vars = {}
exec(api_configs_str, {}, local_vars)
return local_vars.get('API_KEYS_LIST', [])
except Exception as e:
logger.error(f"νκ²½λ³μ νμ± μ€λ₯: {e}")
return []
# API ν€ κ΄λ¦¬λ₯Ό μν μ μ λ³μ
api_key_manager = {
'keys': [],
'current_index': -1,
'failed_keys': set(), # μ€ν¨ν ν€λ€μ μΆμ
'is_initialized': False
}
# API ν€ λ‘λ ν¨μ (κ°μ λ λ²μ )
def load_api_keys():
"""νκ²½λ³μμμ API ν€λ₯Ό λ‘λν©λλ€."""
# νκ²½λ³μμμ API ν€ λͺ©λ‘ κ°μ Έμ€κΈ°
api_keys_from_env = get_gemini_api_configs()
# λΉ ν€λ νλ μ΄μ€νλ μ κ±°
api_keys = [
key.strip() for key in api_keys_from_env
if key and key.strip() and not key.startswith("YOUR_") and not key.startswith("your_")
]
# μ€λ³΅ μ κ±°
api_keys = list(dict.fromkeys(api_keys))
if not api_keys:
logger.error("API ν€κ° μ€μ λμ§ μμμ΅λλ€. GEMINI_API_CONFIGS νκ²½λ³μμ μ€μ API ν€λ₯Ό μΆκ°νμΈμ.")
raise ValueError("API ν€κ° μ€μ λμ§ μμμ΅λλ€. GEMINI_API_CONFIGS νκ²½λ³μμ μ€μ API ν€λ₯Ό μΆκ°ν΄μ£ΌμΈμ.")
logger.info(f"μ΄ {len(api_keys)}κ°μ API ν€κ° λ‘λλμμ΅λλ€.")
return api_keys
def initialize_api_keys():
"""API ν€ κ΄λ¦¬μλ₯Ό μ΄κΈ°νν©λλ€."""
global api_key_manager
if api_key_manager['is_initialized']:
return
try:
api_key_manager['keys'] = load_api_keys()
api_key_manager['is_initialized'] = True
logger.info("API ν€ κ΄λ¦¬μ μ΄κΈ°ν μλ£")
except Exception as e:
logger.error(f"API ν€ μ΄κΈ°ν μ€ν¨: {str(e)}")
raise e
def get_next_api_key():
"""λ€μ μ¬μ©ν API ν€λ₯Ό λ°νν©λλ€. μ€ν¨ν ν€λ 건λλλλ€."""
global api_key_manager
# μ΄κΈ°ν νμΈ
if not api_key_manager['is_initialized']:
initialize_api_keys()
available_keys = [
key for i, key in enumerate(api_key_manager['keys'])
if i not in api_key_manager['failed_keys']
]
if not available_keys:
# λͺ¨λ ν€κ° μ€ν¨νμΌλ©΄ μ€ν¨ λͺ©λ‘μ μ΄κΈ°ννκ³ λ€μ μλ
logger.warning("λͺ¨λ API ν€κ° μ€ν¨νμ΅λλ€. μ€ν¨ λͺ©λ‘μ μ΄κΈ°ννκ³ λ€μ μλν©λλ€.")
api_key_manager['failed_keys'].clear()
available_keys = api_key_manager['keys']
# 첫 λ²μ§Έ μ¬μ©μ λλ€μΌλ‘ μ ν
if api_key_manager['current_index'] == -1:
available_indices = [
i for i, key in enumerate(api_key_manager['keys'])
if i not in api_key_manager['failed_keys']
]
api_key_manager['current_index'] = random.choice(available_indices)
logger.info(f"첫 λ²μ§Έ API ν€ μ ν: λλ€ μΈλ±μ€ {api_key_manager['current_index'] + 1}")
else:
# μ΄ν μ¬μ©μ μμ°¨μ μΌλ‘ λ€μ ν€ μ ν (μ€ν¨ν ν€λ 건λλ)
original_index = api_key_manager['current_index']
for _ in range(len(api_key_manager['keys'])):
api_key_manager['current_index'] = (api_key_manager['current_index'] + 1) % len(api_key_manager['keys'])
if api_key_manager['current_index'] not in api_key_manager['failed_keys']:
break
if api_key_manager['current_index'] in api_key_manager['failed_keys']:
# λͺ¨λ ν€λ₯Ό μλνμ§λ§ μ¬μ©ν μ μλ ν€κ° μμ
logger.warning("μ¬μ© κ°λ₯ν API ν€κ° μμ΅λλ€. μ€ν¨ λͺ©λ‘μ μ΄κΈ°νν©λλ€.")
api_key_manager['failed_keys'].clear()
api_key_manager['current_index'] = 0
logger.info(f"λ€μ API ν€ μ ν: μΈλ±μ€ {api_key_manager['current_index'] + 1}")
return api_key_manager['keys'][api_key_manager['current_index']]
def mark_api_key_failed(api_key):
"""API ν€λ₯Ό μ€ν¨ λͺ©λ‘μ μΆκ°ν©λλ€."""
global api_key_manager
try:
key_index = api_key_manager['keys'].index(api_key)
api_key_manager['failed_keys'].add(key_index)
logger.warning(f"API ν€ μΈλ±μ€ {key_index + 1}λ₯Ό μ€ν¨ λͺ©λ‘μ μΆκ°νμ΅λλ€.")
except ValueError:
logger.error("μ€ν¨ν API ν€λ₯Ό λͺ©λ‘μμ μ°Ύμ μ μμ΅λλ€.")
def test_api_key(api_key):
"""API ν€κ° μ ν¨νμ§ ν
μ€νΈν©λλ€."""
try:
genai.configure(api_key=api_key)
model = genai.GenerativeModel(model_name="gemini-2.0-flash")
# κ°λ¨ν ν
μ€νΈ μμ²
response = model.generate_content("Test", generation_config={
"max_output_tokens": 10,
"temperature": 0.1,
})
if response and response.text:
return True
return False
except Exception as e:
logger.error(f"API ν€ ν
μ€νΈ μ€ν¨: {str(e)}")
return False
def get_working_api_key():
"""μλνλ API ν€λ₯Ό μ°Ύμ λ°νν©λλ€."""
max_attempts = len(api_key_manager['keys']) if api_key_manager['is_initialized'] else 5
for attempt in range(max_attempts):
try:
api_key = get_next_api_key()
if test_api_key(api_key):
logger.info(f"μλνλ API ν€λ₯Ό μ°Ύμμ΅λλ€. (μλ {attempt + 1}ν)")
return api_key
else:
mark_api_key_failed(api_key)
logger.warning(f"API ν€ ν
μ€νΈ μ€ν¨. λ€μ ν€λ‘ μλν©λλ€. (μλ {attempt + 1}ν)")
except Exception as e:
logger.error(f"API ν€ κ°μ Έμ€κΈ° μ€ν¨: {str(e)}")
raise Exception("μ¬μ© κ°λ₯ν API ν€λ₯Ό μ°Ύμ μ μμ΅λλ€.")
# νκ΅μ΄ μμ°μ€λ½κ² 쑰건 (ν-μ λ²μμ©)
KO_EN_CONDITIONS = """
μΆκ° 쑰건 (νκ΅μ΄ μμ°μ€λ½κ² νκΈ°):
- λ²μμ²΄κ° μλ μμ°μ€λ½κ³ λ§€λλ¬μ΄ νκ΅μ΄λ₯Ό μ΅μ°μ μ μΌλ‘ μμ±
- μλ 쑰건μ λ°λΌμ£ΌμΈμ:
1. λ¬Έλ²μ μ νμ±
- νΌλλ¬Έλ³΄λ€ λ₯λλ¬Έ μ°μ
- λλͺ
μ¬ μ΅μν
- λͺ
μ¬νλ³΄λ€ λμ¬/νμ©μ¬ μ°μ
- νμ¬μ§ννλ³΄λ€ λ¨μνμ¬λ μλ£ν μ°μ
- μ£Όμ΄-λͺ©μ μ΄-μμ μ΄ μμ μ μ§
- "~μμ΄μ" νν μ§μ
2. μ£Όμ λ¬Έλ§₯μ λ§λ μμ°μ€λ¬μ΄ νλ¦
3. μ£Όμ μ μν©μ μ΄μΈλ¦¬λ μ΄ν μ ν
4. λ¬Ένμ μ ν©μ± κ³ λ €
5. μ μμ λμμ€ λ°μ (κ³΅κ° μ΄λλ νν)
6. μ§μ/μμ κ· ν μ μ§
7. μ£Όμ ν€μλ λ°λ³΅ μΈκΈ κΈμ§
8. AIκ° μ΄ κΈμ²λΌ 보μ΄μ§ μλλ‘ μ£Όμ
"""
# μμ€ν
λ©μμ§ (ν-μ€ λ²μμ©)
KO_ZH_SYSTEM_MESSAGE = """λΉμ μ νκ΅μ΄-μ€κ΅μ΄ μλ°©ν₯ λ²μ μ΄μμ€ν΄νΈμ
λλ€.
μλ 쑰건μ μΆ©μ€ν λ°λ₯΄μΈμ.
[λͺ©μ λ° μν©]
- μ¬μ©μ λͺ©μ : 1688 μμ±, λλ§€, μ ν΅ κ΄λ ¨λ μν©μμ μΈμ΄ μ₯λ²½ μμ΄ μνν μν΅μ λλλ€.
- μ¬μ©μ μ
λ ₯μ΄ νκ΅μ΄μΌ κ²½μ° μμ°μ€λ½κ³ λ§₯λ½μ λ§κ² μ€κ΅μ΄λ‘ λ²μνλ€.
- μ¬μ©μ μ
λ ₯μ΄ μ€κ΅μ΄μΌ κ²½μ° μμ°μ€λ½κ³ λ§₯λ½μ λ§κ² νκ΅μ΄λ‘ λ²μνλ€.
[νκ΅μ΄ μμ°μ€λ½κ² 쑰건μ 리]
1. λ¬Έλ²μ μ νμ±
- νΌλλ¬Έ λμ λ₯λλ¬Έ
- λλͺ
μ¬ μ΅μν
- λͺ
μ¬νλ³΄λ€ λμ¬ λ° νμ©μ¬ μ°μ
- λ¨μνμ¬νμ΄λ μλ£ν μ°μ
- λ¬Έμ₯ ꡬ쑰λ μ£Όμ΄-λͺ©μ μ΄-λμ¬
- "~μμ΄μ" νν μ¬μ© μ§μ
2. μ£Όμ λ§₯λ½μ λ§λ μμ°μ€λ¬μ΄ νν
3. μ μ ν μ΄ν μ ν(μμ±, λλ§€, μ ν΅ μν© κ³ λ €)
4. λ¬Ένμ , μν©μ μ ν©μ±
5. μ μμ λμμ€ μ‘°ν
6. μ§μκ³Ό μμμ κ· ν
7. μ£Όμ ν€μλ λ°λ³΅ κΈμ§
8. μμ± AI ν° λμ§ μλλ‘ μ£Όμ
[μΆκ°μ¬ν]
- λ²μ μ μ΄μν λ²μ체λ₯Ό νΌνκ³ μμ°μ€λ¬μ΄ ννμ μ¬μ©νλ€.
- μΆλ ₯μ λ²μλ κ²°κ³Όλ¬Έλ§ μ μνλ€.
"""
# 1μ°¨ μΉ΄ν
κ³ λ¦¬ λ° 2μ°¨ μ§λ¬Έ λͺ©λ‘ μ μ
categories = {
"κΈ°λ³Έ μΈμ¬ λ° κ±°λ μμ": [
"μλ
νμΈμ, κ·μ¬μ μ νμ΄ λ§μμ λλλ€. μμΈν μ€λͺ
λΆνλ립λλ€.",
"μ νμ΄ νμ¬ μ¬κ³ κ° μλμ?",
"λλ§€ κ±°λλ₯Ό νκ³ μΆμ΅λλ€. κ°λ₯νκ°μ?",
"μλ‘μ΄ κ³ κ°μΈλ° κ±°λλ₯Ό μμν μ μμκΉμ?",
"νΉμ νκ΅ κ³ κ°λ€κ³Όλ κ±°λλ₯Ό νκ³ κ³μ κ°μ?",
"μ νμ λν μμΈν μ€λͺ
μλ λΈλ‘μμ΄κ° μλμ?",
"μ νμ΄ μΈκΈ° μνμΈκ°μ? νλ§€ λ°μ΄ν°λ₯Ό 곡μ ν μ μλμ?",
"νλ§€ μ§μμ΄λ μ νμ΄ μλμ?",
"μ΄ μ νμ νμ¬ μμ₯ νΈλ λλ μ΄λ€κ°μ?",
"νλ§€ κΈ°λ‘μ΄ μλ μ νμΈμ§ νμΈν μ μλμ?"
],
"μ ν μμΈ λ° νμ§ κ΄λ ¨ μ§λ¬Έ": [
"μ΄ μ νμ μ£Όμ κΈ°λ₯μ 무μμΈκ°μ?",
"νμ§ ν
μ€νΈλ₯Ό ν΅κ³Όν μ νμΈκ°μ?",
"μ νμ μμ¬λ£λ 무μμΈκ°μ?",
"μμ°μ§λ μ΄λμΈκ°μ?",
"μ νμ μ¬μ©νκΈ°μ μμ νκ°μ?",
"μΉνκ²½ μΈμ¦μ λ°μ μ νμΈκ°μ?",
"μ ν μ¬μ© κΈ°κ°(λ΄κ΅¬μ±)μ μ΄λ μ λμΈκ°μ?",
"λ³΄μ¦ κΈ°κ°μ μ΄λ»κ² λλμ?",
"μ¬μ© μ€ λ¬Έμ κ° λ°μνλ©΄ μ΄λ»κ² μ²λ¦¬ν΄μΌ νλμ?",
"μ¬μ© μ€λͺ
μκ° ν¬ν¨λμ΄ μλμ?"
],
"κ°κ²© λ° κ²°μ κ΄λ ¨ μ§λ¬Έ": [
"λλ§€ κ°κ²©μ μΌλ§μΈκ°μ?",
"λλ ꡬ맀 μ ν μΈμ΄ κ°λ₯νκ°μ?",
"첫 κ±°λ κ³ κ°μ μν νΉλ³ ννμ΄ μλμ?",
"κ²°μ 쑰건μ μλ €μ£ΌμΈμ.",
"λΆλΆ κ²°μ ν μκΈ κ²°μ κ° κ°λ₯νκ°μ?",
"λλ μ£Όλ¬Έ μ μ΄κΈ° 보μ¦κΈμ μꡬνμλμ?",
"λ°°μ‘λ£ ν¬ν¨ κ°κ²©μΈκ°μ?",
"μΆκ° λΉμ©μ΄ λ°μν μ μλμ?",
"ν μΈ μΏ ν°μ΄λ νλ‘λͺ¨μ
μ½λλ μλμ?",
"μ κΈ° ꡬ맀 κ³ κ°μ μν ν μΈ μ μ±
μ΄ μλμ?"
],
"λ°°μ‘ λ° λ¬Όλ₯ κ΄λ ¨ μ§λ¬Έ": [
"λ°°μ‘μ μ΄λ νλ°°μ¬λ₯Ό ν΅ν΄ μ§νλλμ?",
"μμ λ°°μ‘ κΈ°κ°μ μΌλ§λ λλμ?",
"νκ΅κΉμ§ λ°°μ‘μ΄ κ°λ₯νκ°μ?",
"κ΅μ λ°°μ‘λ£λ μ΄λ»κ² κ³μ°λλμ?",
"λλ μ£Όλ¬Έ μ λ°°μ‘λΉ ν μΈ ννμ΄ μλμ?",
"λ°°μ‘ μ€ νμμ΄ λ°μνλ©΄ μ΄λ»κ² μ²λ¦¬νλμ?",
"μ£Όλ¬Έ ν λͺ μΌ λ΄μ λ°°μ‘μ΄ μμλλμ?",
"λ°°μ‘ μΆμ λ²νΈλ₯Ό μ 곡νμλμ?",
"μ£Όλ¬Έ μνλ₯Ό μ΄λ»κ² νμΈν μ μλμ?",
"λ°°μ‘λ£λ₯Ό μ§μ λΆλ΄ν΄μΌ νλμ?"
]
}
def guess_lang(text: str) -> str:
text = text.strip()
if not text:
return ""
try:
lang = detect(text)
if lang in ['ko', 'en', 'zh-cn', 'zh-tw']:
if lang.startswith('zh'):
return 'zh'
return lang
else:
# langdetect κ²°κ³Όκ° ko, en, zhκ° μλ κ²½μ° ν΄λ¦¬μ€ν± μ μ©
if all('a' <= c.lower() <= 'z' for c in text if c.isalpha()):
return 'en'
# νκΈ μμ λ²μ νλ¨
elif any('\uac00' <= c <= '\ud7a3' for c in text):
return 'ko'
# μ€κ΅μ΄ λ²μ νλ¨
elif any('\u4e00' <= c <= '\u9fff' for c in text):
return 'zh'
else:
# λν΄νΈ μμ΄ μ²λ¦¬
return 'en'
except:
# langdetect μ€ν¨ μ ν΄λ¦¬μ€ν± μ μ©
if all('a' <= c.lower() <= 'z' for c in text if c.isalpha()):
return 'en'
elif any('\uac00' <= c <= '\ud7a3' for c in text):
return 'ko'
elif any('\u4e00' <= c <= '\u9fff' for c in text):
return 'zh'
else:
return 'en'
def validate_input(text: str, target_langs: list) -> bool:
lang = guess_lang(text)
logger.info(f"κ°μ§λ(μΆμ ) μΈμ΄: {lang}")
return lang in target_langs
def translate_ko_en(input_text: str):
logger.info("ν-μ λ²μ μμ")
if not validate_input(input_text, ['ko', 'en']):
return "μ ν¨νμ§ μμ μ
λ ₯μ
λλ€. νκ΅μ΄ λλ μμ΄ ν
μ€νΈλ₯Ό μ
λ ₯ν΄μ£ΌμΈμ."
try:
detected_lang = guess_lang(input_text)
logger.info(f"κ°μ§λ(μΆμ ) μΈμ΄: {detected_lang}")
if detected_lang == 'ko':
direction = "Korean to English"
input_lang = "Korean"
output_lang = "English"
else:
direction = "English to Korean"
input_lang = "English"
output_lang = "Korean"
logger.info(f"λ²μ λ°©ν₯: {direction}")
current_time = int(time.time() * 1000)
random.seed(current_time)
temperature = random.uniform(0.4, 0.85)
top_p = random.uniform(0.9, 0.98)
request_id = str(uuid.uuid4())[:8]
timestamp_micro = int(time.time() * 1000000) % 1000
current_hour = datetime.now().hour
time_context = f"Consider the current time is {current_hour}:00."
# νκ΅μ΄ μΆλ ₯ μ μμ°μ€λ¬μ΄ νκ΅μ΄ 쑰건 μΆκ°
korean_conditions = ""
if output_lang == "Korean":
korean_conditions = KO_EN_CONDITIONS
system_prompt = "You are a helpful translator."
prompt = f"""
Translate the following {input_lang} text into {output_lang}:
{input_text}
Rules:
1. Output ONLY the {output_lang} translation without additional labels or formatting.
2. Preserve the original meaning and intent.
3. No explanations or meta-commentary.
4. No formatting beyond basic text.
5. {time_context}
[Seed: {current_time}]
{korean_conditions}
"""
logger.debug(f"ν둬ννΈ:\n{prompt}")
# μλνλ API ν€ κ°μ Έμ€κΈ°
api_key = get_working_api_key()
genai.configure(api_key=api_key)
# Gemini λͺ¨λΈ μ€μ
generation_config = {
"max_output_tokens": 200,
"temperature": temperature,
"top_p": top_p,
}
# Gemini λͺ¨λΈ λΆλ¬μ€κΈ°
model = genai.GenerativeModel(
model_name="gemini-2.0-flash",
generation_config=generation_config,
)
# λ²μ μ€ν
full_prompt = f"{system_prompt}\n\n{prompt}"
response = model.generate_content(full_prompt)
translated = response.text.strip()
logger.info("Gemini λ²μ μλ£")
logger.debug(f"λ²μ κ²°κ³Ό:\n{translated}")
return translated
except Exception as e:
logger.error(f"λ²μ μ€ μμμΉ λͺ»ν μ€λ₯ λ°μ: {str(e)}")
# API ν€ λ¬Έμ μΈ κ²½μ° ν΄λΉ ν€λ₯Ό μ€ν¨ λͺ©λ‘μ μΆκ°
if "api" in str(e).lower() or "key" in str(e).lower() or "quota" in str(e).lower():
try:
current_key = api_key_manager['keys'][api_key_manager['current_index']]
mark_api_key_failed(current_key)
logger.info("API ν€ λ¬Έμ λ‘ μΈν μ€λ₯. λ€μ ν€λ‘ μ¬μλνμΈμ.")
except:
pass
return f"λ²μ μ€ μμμΉ λͺ»ν μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}"
def translate_ko_zh(input_text: str):
logger.info("ν-μ€ λ²μ μμ")
if not validate_input(input_text, ['ko', 'zh']):
return "μ ν¨νμ§ μμ μ
λ ₯μ
λλ€. νκ΅μ΄ λλ μ€κ΅μ΄ ν
μ€νΈλ₯Ό μ
λ ₯ν΄μ£ΌμΈμ."
try:
detected_lang = guess_lang(input_text)
logger.info(f"κ°μ§λ(μΆμ ) μΈμ΄: {detected_lang}")
if detected_lang == 'ko':
direction = "Korean to Chinese"
input_lang = "Korean"
output_lang = "Chinese"
else:
direction = "Chinese to Korean"
input_lang = "Chinese"
output_lang = "Korean"
logger.info(f"λ²μ λ°©ν₯: {direction}")
current_time = int(time.time() * 1000)
random.seed(current_time)
temperature = random.uniform(0.5, 0.8)
top_p = random.uniform(0.9, 0.98)
# μλνλ API ν€ κ°μ Έμ€κΈ°
api_key = get_working_api_key()
genai.configure(api_key=api_key)
# Gemini λͺ¨λΈ μ€μ
generation_config = {
"max_output_tokens": 1024,
"temperature": temperature,
"top_p": top_p,
}
# Gemini λͺ¨λΈ λΆλ¬μ€κΈ°
model = genai.GenerativeModel(
model_name="gemini-2.0-flash",
generation_config=generation_config,
)
# ν둬ννΈ μ€λΉ
prompt = f"{KO_ZH_SYSTEM_MESSAGE}\n\n{input_text}"
# λ²μ μ€ν
response = model.generate_content(prompt)
translated = response.text.strip()
logger.info("Gemini λ²μ μλ£")
logger.debug(f"λ²μ κ²°κ³Ό:\n{translated}")
return translated
except Exception as e:
logger.error(f"λ²μ μ€ μμμΉ λͺ»ν μ€λ₯ λ°μ: {str(e)}")
# API ν€ λ¬Έμ μΈ κ²½μ° ν΄λΉ ν€λ₯Ό μ€ν¨ λͺ©λ‘μ μΆκ°
if "api" in str(e).lower() or "key" in str(e).lower() or "quota" in str(e).lower():
try:
current_key = api_key_manager['keys'][api_key_manager['current_index']]
mark_api_key_failed(current_key)
logger.info("API ν€ λ¬Έμ λ‘ μΈν μ€λ₯. λ€μ ν€λ‘ μ¬μλνμΈμ.")
except:
pass
return f"λ²μ μ€ μμμΉ λͺ»ν μ€λ₯κ° λ°μνμ΅λλ€: {str(e)}"
def update_subcategories(category):
if category in categories:
return gr.update(choices=categories[category], value=None)
else:
return gr.update(choices=[], value=None)
def set_input_text(selected_text):
return selected_text
# 컀μ€ν
CSS μ€νμΌ
custom_css = """
:root {
--primary-color: #FB7F0D;
--secondary-color: #ff9a8b;
--accent-color: #FF6B6B;
--background-color: #FFF3E9;
--card-bg: #ffffff;
--text-color: #334155;
--border-radius: 18px;
--shadow: 0 8px 30px rgba(251, 127, 13, 0.08);
}
body {
font-family: 'Pretendard', 'Noto Sans KR', -apple-system, BlinkMacSystemFont, sans-serif;
background-color: var(--background-color);
color: var(--text-color);
line-height: 1.6;
margin: 0;
padding: 0;
}
.gradio-container {
width: 100%;
margin: 0 auto;
padding: 20px;
background-color: var(--background-color);
}
.custom-header {
background: #FF7F00;
padding: 2rem;
border-radius: 15px;
margin-bottom: 20px;
box-shadow: var(--shadow);
text-align: center;
}
.custom-header h1 {
margin: 0;
font-size: 2.5rem;
font-weight: 700;
color: black;
}
.custom-header p {
margin: 10px 0 0;
font-size: 1.2rem;
color: black;
}
.custom-frame {
background-color: var(--card-bg);
border: 1px solid rgba(0, 0, 0, 0.04);
border-radius: var(--border-radius);
padding: 20px;
margin: 10px 0;
box-shadow: var(--shadow);
}
.custom-section-group {
margin-top: 20px;
padding: 0;
border: none;
border-radius: 0;
background-color: var(--background-color);
box-shadow: none !important;
}
.custom-button {
border-radius: 30px !important;
background: linear-gradient(135deg, var(--primary-color), var(--secondary-color)) !important;
color: white !important;
font-size: 18px !important;
padding: 10px 20px !important;
border: none;
box-shadow: 0 4px 8px rgba(251, 127, 13, 0.25);
transition: transform 0.3s ease;
}
.custom-button:hover {
transform: translateY(-2px);
box-shadow: 0 6px 12px rgba(251, 127, 13, 0.3);
}
.custom-title {
font-size: 28px;
font-weight: bold;
margin-bottom: 10px;
color: var(--text-color);
border-bottom: 2px solid var(--primary-color);
padding-bottom: 5px;
}
.image-container {
border-radius: var(--border-radius);
overflow: hidden;
border: 1px solid rgba(0, 0, 0, 0.08);
transition: all 0.3s ease;
background-color: white;
}
.image-container:hover {
box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}
.gr-input, .gr-text-input, .gr-sample-inputs {
border-radius: var(--border-radius) !important;
border: 1px solid #dddddd !important;
padding: 12px !important;
box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05) !important;
transition: all 0.3s ease !important;
}
.gr-input:focus, .gr-text-input:focus {
border-color: var(--primary-color) !important;
outline: none !important;
box-shadow: 0 0 0 2px rgba(251, 127, 13, 0.2) !important;
}
::-webkit-scrollbar {
width: 8px;
height: 8px;
}
::-webkit-scrollbar-track {
background: rgba(0, 0, 0, 0.05);
border-radius: 10px;
}
::-webkit-scrollbar-thumb {
background: var(--primary-color);
border-radius: 10px;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(10px); }
to { opacity: 1; transform: translateY(0); }
}
.fade-in {
animation: fadeIn 0.5s ease-out;
}
@media (max-width: 768px) {
.button-grid {
grid-template-columns: repeat(2, 1fr);
}
}
.section-title {
display: flex;
align-items: center;
font-size: 20px;
font-weight: 700;
color: #333333;
margin-bottom: 10px;
padding-bottom: 5px;
border-bottom: 2px solid #FB7F0D;
font-family: 'Pretendard', 'Noto Sans KR', -apple-system, BlinkMacSystemFont, sans-serif;
}
.section-title img {
margin-right: 10px;
width: 24px;
height: 24px;
}
.guide-container {
background-color: var(--card-bg);
border-radius: var(--border-radius);
box-shadow: var(--shadow);
padding: 1.5rem;
margin-bottom: 1.5rem;
border: 1px solid rgba(0, 0, 0, 0.04);
}
.guide-title {
font-size: 1.5rem;
font-weight: 700;
color: var(--primary-color);
margin-bottom: 1.5rem;
padding-bottom: 0.5rem;
border-bottom: 2px solid var(--primary-color);
display: flex;
align-items: center;
}
.guide-title i {
margin-right: 0.8rem;
font-size: 1.5rem;
}
.guide-item {
display: flex;
margin-bottom: 1rem;
align-items: flex-start;
}
.guide-number {
background-color: var(--primary-color);
color: white;
width: 25px;
height: 25px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
margin-right: 10px;
flex-shrink: 0;
}
.guide-text {
flex: 1;
line-height: 1.6;
}
.guide-text a {
color: var(--primary-color);
text-decoration: underline;
font-weight: 600;
}
.guide-text a:hover {
color: var(--accent-color);
}
.guide-highlight {
background-color: rgba(251, 127, 13, 0.1);
padding: 2px 5px;
border-radius: 4px;
font-weight: 500;
}
"""
# FontAwesome μμ΄μ½ ν¬ν¨
fontawesome_link = """
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" crossorigin="anonymous" referrerpolicy="no-referrer" />
"""
def create_interface():
with gr.Blocks(css=custom_css, theme=gr.themes.Soft(
primary_hue=gr.themes.Color(
c50="#FFF7ED",
c100="#FFEDD5",
c200="#FED7AA",
c300="#FDBA74",
c400="#FB923C",
c500="#F97316",
c600="#EA580C",
c700="#C2410C",
c800="#9A3412",
c900="#7C2D12",
c950="#431407",
),
secondary_hue="zinc",
neutral_hue="zinc",
font=("Pretendard", "sans-serif")
)) as demo:
gr.HTML(fontawesome_link)
with gr.Tabs() as tabs:
with gr.TabItem("νκ΅μ΄-μ€κ΅μ΄ λ²μ"):
with gr.Column(elem_classes="custom-frame"):
gr.HTML('<div class="section-title"><img src="https://cdn-icons-png.flaticon.com/512/3097/3097412.png"> μΉ΄ν
κ³ λ¦¬ μ ν</div>')
with gr.Row():
category_dropdown = gr.Dropdown(
label="1μ°¨ μΉ΄ν
κ³ λ¦¬ μ ν",
choices=list(categories.keys()),
value=None
)
subcategory_dropdown = gr.Dropdown(
label="2μ°¨ μ§λ¬Έ μ ν",
choices=[],
value=None
)
with gr.Column(elem_classes="custom-frame"):
gr.HTML('<div class="section-title"><img src="https://cdn-icons-png.flaticon.com/512/4297/4297825.png"> λ²μ</div>')
with gr.Row():
with gr.Column(scale=1):
kz_input_box = gr.Textbox(
label="μ
λ ₯ (νκ΅μ΄ λλ μ€κ΅μ΄)",
lines=8,
placeholder="λ²μν ν
μ€νΈλ₯Ό μ
λ ₯νμΈμ..."
)
with gr.Column(scale=1):
kz_output_box = gr.Textbox(
label="λ²μ κ²°κ³Ό",
lines=8
)
with gr.Column(elem_classes="custom-frame"):
gr.HTML('<div class="section-title"><img src="https://cdn-icons-png.flaticon.com/512/1022/1022293.png"> λ²μ μ€ν</div>')
kz_translate_button = gr.Button("λ²μνκΈ°", elem_classes="custom-button")
# 1μ°¨ μ ν μ 2μ°¨ νλͺ© μ
λ°μ΄νΈ
category_dropdown.change(
fn=update_subcategories,
inputs=category_dropdown,
outputs=subcategory_dropdown
)
# 2μ°¨ μ ν μ μ
λ ₯λμ ν΄λΉ κ° μλ μ
λ ₯
subcategory_dropdown.change(
fn=set_input_text,
inputs=subcategory_dropdown,
outputs=kz_input_box
)
# λ²μ ν¨μ
kz_translate_button.click(
fn=translate_ko_zh,
inputs=kz_input_box,
outputs=kz_output_box
)
with gr.TabItem("νκ΅μ΄-μμ΄ λ²μ"):
with gr.Column(elem_classes="custom-frame"):
gr.HTML('<div class="section-title"><img src="https://cdn-icons-png.flaticon.com/512/4297/4297825.png"> λ²μ</div>')
with gr.Row():
with gr.Column(scale=1):
ke_input_box = gr.Textbox(
label="μ
λ ₯ ν
μ€νΈ (νκ΅μ΄ λλ μμ΄)",
placeholder="λ²μν ν
μ€νΈλ₯Ό μ
λ ₯νμΈμ...",
lines=8
)
with gr.Column(scale=1):
ke_output_box = gr.Textbox(
label="λ²μ κ²°κ³Ό",
lines=8,
interactive=False
)
with gr.Column(elem_classes="custom-frame"):
gr.HTML('<div class="section-title"><img src="https://cdn-icons-png.flaticon.com/512/1022/1022293.png"> λ²μ μ€ν</div>')
ke_translate_button = gr.Button("λ²μνκΈ°", elem_classes="custom-button")
# λ²μ ν¨μ
ke_translate_button.click(
fn=translate_ko_en,
inputs=ke_input_box,
outputs=ke_output_box
)
return demo
if __name__ == "__main__":
demo = create_interface()
demo.launch() |