openfree commited on
Commit
6e63c85
Β·
verified Β·
1 Parent(s): 18f7bef

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -122
app.py CHANGED
@@ -11,9 +11,6 @@ import time
11
  from functools import partial
12
  import json
13
  import gradio as gr
14
- import modelscope_studio.components.base as ms
15
- import modelscope_studio.components.legacy as legacy
16
- import modelscope_studio.components.antd as antd
17
 
18
  import html
19
  import urllib.parse
@@ -92,22 +89,6 @@ class Role:
92
  History = List[Tuple[str, str]]
93
  Messages = List[Dict[str, str]]
94
 
95
- # 이미지 μΊμ‹œ
96
- IMAGE_CACHE = {}
97
-
98
- def get_image_base64(image_path):
99
- # Improvement: Consider adding logging and handling specific exceptions
100
- if image_path in IMAGE_CACHE:
101
- return IMAGE_CACHE[image_path]
102
- try:
103
- with open(image_path, "rb") as image_file:
104
- encoded_string = base64.b64encode(image_file.read()).decode()
105
- IMAGE_CACHE[image_path] = encoded_string
106
- return encoded_string
107
- except Exception as e:
108
- # TODO: Log exception details
109
- return IMAGE_CACHE.get('default.png', '')
110
-
111
  def history_to_messages(history: History, system: str) -> Messages:
112
  messages = [{'role': Role.SYSTEM, 'content': system}]
113
  for h in history:
@@ -139,12 +120,7 @@ BUILTIN_MODULES = {
139
  'getopt', 'logging', 'platform', 'ctypes', 'typing', 'array', 'asyncio', 'concurrent',
140
  'contextlib', 'dataclasses', 'enum', 'graphlib', 'hashlib', 'hmac', 'io', 'pathlib',
141
  'pickle', 'shelve', 'shutil', 'signal', 'stat', 'struct', 'tempfile', 'warnings',
142
- 'weakref', 'zipfile', 'zlib', 'mmap', 'msvcrt', 'winreg', 'winsound', 'crypt',
143
- 'dbm', 'gzip', 'bz2', 'lzma', 'pwd', 'grp', 'termios', 'tty', 'pty', 'fcntl',
144
- 'pipes', 'resource', 'nis', 'syslog', 'optparse', 'imp', 'posix', '_thread',
145
- 'builtins', 'traceback', 'gc', 'inspect', 'site', 'user', 'distutils', 'test',
146
- 'unittest', 'venv', 'code', 'codeop', 'pdb', 'profile', 'pstats', 'timeit',
147
- 'trace', 'tracemalloc', 'sched', 'secrets', 'mimetypes'
148
  }
149
 
150
  # Import to Package Name Mapping Dictionary
@@ -156,10 +132,6 @@ IMPORT_TO_PACKAGE = {
156
  'yaml': 'pyyaml',
157
  'tensorflow': 'tensorflow-cpu',
158
  'tf': 'tensorflow-cpu',
159
- 'wx': 'wxPython',
160
- 'cairo': 'pycairo',
161
- 'MySQLdb': 'mysqlclient',
162
- 'psycopg2': 'psycopg2-binary',
163
  'magic': 'python-magic',
164
  'Image': 'pillow'
165
  }
@@ -316,9 +288,6 @@ async def try_openai_api(openai_messages):
316
  print(f"OpenAI API error: {str(e)}")
317
  raise e
318
 
319
- def history_render(history: History):
320
- return history
321
-
322
  def remove_code_block(text):
323
  text = re.sub(r'```[python|html]?\n', '', text)
324
  text = re.sub(r'\n```', '', text)
@@ -400,14 +369,6 @@ def boost_prompt(prompt: str) -> str:
400
  print(f"ν”„λ‘¬ν”„νŠΈ 증강 쀑 였λ₯˜ λ°œμƒ: {str(e)}")
401
  return prompt
402
 
403
- def handle_boost(prompt: str):
404
- try:
405
- boosted_prompt = boost_prompt(prompt)
406
- return boosted_prompt
407
- except Exception as e:
408
- print(f"Boost 처리 쀑 였λ₯˜: {str(e)}")
409
- return prompt
410
-
411
  # 배포 κ΄€λ ¨ ν•¨μˆ˜ μΆ”κ°€
412
  def generate_space_name():
413
  """6자리 랜덀 영문 이름 생성"""
@@ -517,21 +478,11 @@ class Demo:
517
  openai_messages.append({"role": "user", "content": query})
518
 
519
  try:
520
- yield [
521
- "Generating code...",
522
- _history
523
- ]
524
- await asyncio.sleep(0)
525
-
526
  collected_content = None
527
  try:
528
  async for content in try_claude_api(system_message, claude_messages):
529
  code = content
530
- yield [
531
- code,
532
- _history
533
- ]
534
- await asyncio.sleep(0)
535
  collected_content = code
536
 
537
  except Exception as claude_error:
@@ -539,36 +490,23 @@ class Demo:
539
 
540
  async for content in try_openai_api(openai_messages):
541
  code = content
542
- yield [
543
- code,
544
- _history
545
- ]
546
- await asyncio.sleep(0)
547
  collected_content = code
548
 
549
  if collected_content:
550
- _history = messages_to_history([
551
- {'role': Role.SYSTEM, 'content': system_message}
552
- ] + claude_messages + [{
553
- 'role': Role.ASSISTANT,
554
- 'content': collected_content
555
- }])
556
-
557
- yield [
558
- collected_content,
559
- _history
560
- ]
561
  else:
562
  raise ValueError("No content was generated from either API")
563
 
564
  except Exception as e:
565
  print(f"Error details: {str(e)}")
566
  raise ValueError(f'Error calling APIs: {str(e)}')
 
 
567
 
568
  def clear_history(self):
569
  return []
570
 
571
-
572
  # 예제 ν”„λ‘¬ν”„νŠΈ
573
  example_prompts = [
574
  "λ§Œλ…„λ‹¬λ ₯을 λ§Œλ“€μ–΄μ£Όμ„Έμš”. 년도와 월을 μž…λ ₯ν•˜λ©΄ ν•΄λ‹Ή μ›”μ˜ 달λ ₯이 ν‘œμ‹œλ˜λŠ” μ•±μž…λ‹ˆλ‹€.",
@@ -578,26 +516,81 @@ example_prompts = [
578
  "포λͺ¨λ„λ‘œ 타이머λ₯Ό λ§Œλ“€μ–΄μ£Όμ„Έμš”. 25λΆ„ 집쀑, 5λΆ„ νœ΄μ‹μ„ λ°˜λ³΅ν•˜λŠ” νƒ€μ΄λ¨Έλ‘œ, 사이클 νšŸμˆ˜λ„ ν‘œμ‹œλ©λ‹ˆλ‹€."
579
  ]
580
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
581
  # Demo μΈμŠ€ν„΄μŠ€ 생성
582
  demo_instance = Demo()
583
 
584
- with gr.Blocks(css="body {background-color: #f7f7f7;}") as demo:
585
  history = gr.State([])
586
  setting = gr.State({
587
  "system": SystemPrompt,
588
  })
589
-
590
- # 메인 λ ˆμ΄μ•„μ›ƒ
591
- with gr.Row():
 
 
 
 
 
 
 
592
  # 쒌츑 νŒ¨λ„
593
- with gr.Column(scale=1):
594
- gr.HTML("""
595
- <div style="text-align: center; margin-bottom: 10px;">
596
- <h1 style="margin-bottom: 0px;">MOUSE</h1>
597
- <p>고양이도 발둜 μ½”λ”©ν•˜λŠ” 'MOUSE-II'</p>
598
- </div>
599
- """)
600
-
601
  input_text = gr.Textbox(
602
  label="μ›ν•˜λŠ” μ•± μ„€λͺ…을 μž…λ ₯ν•˜μ„Έμš”",
603
  placeholder=random.choice(DEMO_LIST)['description'],
@@ -614,57 +607,67 @@ with gr.Blocks(css="body {background-color: #f7f7f7;}") as demo:
614
  boost_btn = gr.Button("Boost", variant="secondary")
615
  clear_btn = gr.Button("클리어", variant="secondary")
616
 
617
- with gr.Accordion("μ—­λŒ€ ν”„λ‘¬ν”„νŠΈ", open=False):
618
- history_btn = gr.Button("이전 기둝 보기")
619
- history_output = gr.Chatbot(
620
- show_label=False,
621
- type="messages"
622
- )
623
 
624
  # 우츑 νŒ¨λ„
625
- with gr.Column(scale=1):
626
  with gr.Tabs():
627
  with gr.TabItem("μ½”λ“œ"):
628
- with gr.Row():
629
- loading_indicator = gr.HTML('<div id="loading" style="display:none; text-align:center;"><p>μ½”λ“œ 생성 쀑...</p></div>')
630
-
631
  code_output = gr.Code(
632
  language="python",
633
  label="μƒμ„±λœ μ½”λ“œ",
634
- lines=17
635
  )
636
 
637
  with gr.TabItem("뢄석"):
638
  code_analysis = gr.HTML(label="μ½”λ“œ 뢄석")
639
 
640
- gr.HTML("<h3>배포 μ„€μ •</h3>")
641
- hf_token = gr.Textbox(
642
- label="Hugging Face 토큰",
643
- type="password",
644
- placeholder="hf_..."
645
- )
646
-
647
- deploy_btn = gr.Button("λ°°ν¬ν•˜κΈ°", variant="primary")
648
- deploy_result = gr.HTML(label="배포 결과")
 
 
 
 
 
 
 
649
 
650
  # 이벀트 ν•Έλ“€λŸ¬
651
- async def generate_code_wrapper(query, setting, history):
652
- loading_indicator.update('<div id="loading" style="display:block; text-align:center;"><p>μ½”λ“œ 생성 쀑...</p></div>')
653
-
654
- result = None
655
-
656
- async for output in demo_instance.generation_code(query, setting, history):
657
- result = output[0] # μ½”λ“œ 좜λ ₯
658
-
659
- code_analysis_html = analyze_code(result)
660
- loading_indicator.update('<div id="loading" style="display:none;"></div>')
661
-
662
- return result, code_analysis_html
 
663
 
664
  generate_btn.click(
665
- fn=generate_code_wrapper,
 
 
 
666
  inputs=[input_text, setting, history],
667
- outputs=[code_output, code_analysis]
 
 
 
 
 
 
 
668
  )
669
 
670
  boost_btn.click(
@@ -680,20 +683,14 @@ with gr.Blocks(css="body {background-color: #f7f7f7;}") as demo:
680
  )
681
 
682
  deploy_btn.click(
683
- fn=lambda code, token: deploy_to_huggingface(remove_code_block(code), token) if code else "μ½”λ“œκ°€ μ—†μŠ΅λ‹ˆλ‹€.",
684
  inputs=[code_output, hf_token],
685
  outputs=[deploy_result]
686
  )
687
-
688
- history_btn.click(
689
- fn=history_render,
690
- inputs=[history],
691
- outputs=[history_output]
692
- )
693
 
694
  if __name__ == "__main__":
695
  try:
696
- demo.queue(default_concurrency_limit=20).launch(ssr_mode=False)
697
  except Exception as e:
698
  print(f"Initialization error: {e}")
699
  raise
 
11
  from functools import partial
12
  import json
13
  import gradio as gr
 
 
 
14
 
15
  import html
16
  import urllib.parse
 
89
  History = List[Tuple[str, str]]
90
  Messages = List[Dict[str, str]]
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  def history_to_messages(history: History, system: str) -> Messages:
93
  messages = [{'role': Role.SYSTEM, 'content': system}]
94
  for h in history:
 
120
  'getopt', 'logging', 'platform', 'ctypes', 'typing', 'array', 'asyncio', 'concurrent',
121
  'contextlib', 'dataclasses', 'enum', 'graphlib', 'hashlib', 'hmac', 'io', 'pathlib',
122
  'pickle', 'shelve', 'shutil', 'signal', 'stat', 'struct', 'tempfile', 'warnings',
123
+ 'weakref', 'zipfile', 'zlib'
 
 
 
 
 
124
  }
125
 
126
  # Import to Package Name Mapping Dictionary
 
132
  'yaml': 'pyyaml',
133
  'tensorflow': 'tensorflow-cpu',
134
  'tf': 'tensorflow-cpu',
 
 
 
 
135
  'magic': 'python-magic',
136
  'Image': 'pillow'
137
  }
 
288
  print(f"OpenAI API error: {str(e)}")
289
  raise e
290
 
 
 
 
291
  def remove_code_block(text):
292
  text = re.sub(r'```[python|html]?\n', '', text)
293
  text = re.sub(r'\n```', '', text)
 
369
  print(f"ν”„λ‘¬ν”„νŠΈ 증강 쀑 였λ₯˜ λ°œμƒ: {str(e)}")
370
  return prompt
371
 
 
 
 
 
 
 
 
 
372
  # 배포 κ΄€λ ¨ ν•¨μˆ˜ μΆ”κ°€
373
  def generate_space_name():
374
  """6자리 랜덀 영문 이름 생성"""
 
478
  openai_messages.append({"role": "user", "content": query})
479
 
480
  try:
 
 
 
 
 
 
481
  collected_content = None
482
  try:
483
  async for content in try_claude_api(system_message, claude_messages):
484
  code = content
485
+ yield code
 
 
 
 
486
  collected_content = code
487
 
488
  except Exception as claude_error:
 
490
 
491
  async for content in try_openai_api(openai_messages):
492
  code = content
493
+ yield code
 
 
 
 
494
  collected_content = code
495
 
496
  if collected_content:
497
+ _history.append([query, collected_content])
 
 
 
 
 
 
 
 
 
 
498
  else:
499
  raise ValueError("No content was generated from either API")
500
 
501
  except Exception as e:
502
  print(f"Error details: {str(e)}")
503
  raise ValueError(f'Error calling APIs: {str(e)}')
504
+
505
+ return collected_content
506
 
507
  def clear_history(self):
508
  return []
509
 
 
510
  # 예제 ν”„λ‘¬ν”„νŠΈ
511
  example_prompts = [
512
  "λ§Œλ…„λ‹¬λ ₯을 λ§Œλ“€μ–΄μ£Όμ„Έμš”. 년도와 월을 μž…λ ₯ν•˜λ©΄ ν•΄λ‹Ή μ›”μ˜ 달λ ₯이 ν‘œμ‹œλ˜λŠ” μ•±μž…λ‹ˆλ‹€.",
 
516
  "포λͺ¨λ„λ‘œ 타이머λ₯Ό λ§Œλ“€μ–΄μ£Όμ„Έμš”. 25λΆ„ 집쀑, 5λΆ„ νœ΄μ‹μ„ λ°˜λ³΅ν•˜λŠ” νƒ€μ΄λ¨Έλ‘œ, 사이클 νšŸμˆ˜λ„ ν‘œμ‹œλ©λ‹ˆλ‹€."
517
  ]
518
 
519
+ # CSS μŠ€νƒ€μΌ
520
+ css = """
521
+ .container {
522
+ max-width: 1200px;
523
+ margin: auto;
524
+ }
525
+ .header {
526
+ text-align: center;
527
+ margin: 20px 0;
528
+ }
529
+ .header h1 {
530
+ margin-bottom: 5px;
531
+ color: #2c3e50;
532
+ }
533
+ .header p {
534
+ margin-top: 0;
535
+ color: #7f8c8d;
536
+ }
537
+ .content {
538
+ display: flex;
539
+ flex-direction: row;
540
+ gap: 20px;
541
+ }
542
+ .left-panel, .right-panel {
543
+ flex: 1;
544
+ padding: 15px;
545
+ border-radius: 10px;
546
+ background-color: #f9f9f9;
547
+ box-shadow: 0 2px 10px rgba(0,0,0,0.1);
548
+ }
549
+ .status {
550
+ text-align: center;
551
+ padding: 10px;
552
+ margin: 10px 0;
553
+ border-radius: 5px;
554
+ }
555
+ .generating {
556
+ background-color: #f39c12;
557
+ color: white;
558
+ }
559
+ .deploy-section {
560
+ margin-top: 20px;
561
+ padding: 15px;
562
+ border-radius: 10px;
563
+ background-color: #f0f0f0;
564
+ }
565
+ .footer {
566
+ text-align: center;
567
+ margin-top: 30px;
568
+ padding: 10px;
569
+ color: #7f8c8d;
570
+ font-size: 0.8em;
571
+ }
572
+ """
573
+
574
  # Demo μΈμŠ€ν„΄μŠ€ 생성
575
  demo_instance = Demo()
576
 
577
+ with gr.Blocks(css=css) as demo:
578
  history = gr.State([])
579
  setting = gr.State({
580
  "system": SystemPrompt,
581
  })
582
+ is_generating = gr.State(False)
583
+
584
+ gr.HTML("""
585
+ <div class="header">
586
+ <h1>MOUSE</h1>
587
+ <p>고양이도 발둜 μ½”λ”©ν•˜λŠ” 'MOUSE-II'</p>
588
+ </div>
589
+ """)
590
+
591
+ with gr.Row(elem_classes="content"):
592
  # 쒌츑 νŒ¨λ„
593
+ with gr.Column(elem_classes="left-panel"):
 
 
 
 
 
 
 
594
  input_text = gr.Textbox(
595
  label="μ›ν•˜λŠ” μ•± μ„€λͺ…을 μž…λ ₯ν•˜μ„Έμš”",
596
  placeholder=random.choice(DEMO_LIST)['description'],
 
607
  boost_btn = gr.Button("Boost", variant="secondary")
608
  clear_btn = gr.Button("클리어", variant="secondary")
609
 
610
+ status_html = gr.HTML("", elem_classes="status")
 
 
 
 
 
611
 
612
  # 우츑 νŒ¨λ„
613
+ with gr.Column(elem_classes="right-panel"):
614
  with gr.Tabs():
615
  with gr.TabItem("μ½”λ“œ"):
 
 
 
616
  code_output = gr.Code(
617
  language="python",
618
  label="μƒμ„±λœ μ½”λ“œ",
619
+ lines=12
620
  )
621
 
622
  with gr.TabItem("뢄석"):
623
  code_analysis = gr.HTML(label="μ½”λ“œ 뢄석")
624
 
625
+ with gr.Box(elem_classes="deploy-section"):
626
+ gr.HTML("<h3>배포 μ„€μ •</h3>")
627
+ hf_token = gr.Textbox(
628
+ label="Hugging Face 토큰",
629
+ type="password",
630
+ placeholder="hf_..."
631
+ )
632
+
633
+ deploy_btn = gr.Button("λ°°ν¬ν•˜κΈ°", variant="primary")
634
+ deploy_result = gr.HTML(label="배포 결과")
635
+
636
+ gr.HTML("""
637
+ <div class="footer">
638
+ MOUSE-II - 문의: [email protected]
639
+ </div>
640
+ """)
641
 
642
  # 이벀트 ν•Έλ“€λŸ¬
643
+ def start_generating():
644
+ return "πŸ”„ μ½”λ“œ 생성 쀑...", gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), True
645
+
646
+ def end_generating():
647
+ return "", gr.update(interactive=True), gr.update(interactive=True), gr.update(interactive=True), False
648
+
649
+ def update_code_analysis(code):
650
+ analysis = analyze_code(code)
651
+ return analysis
652
+
653
+ def handle_boost(prompt):
654
+ boosted = boost_prompt(prompt)
655
+ return boosted
656
 
657
  generate_btn.click(
658
+ fn=start_generating,
659
+ outputs=[status_html, generate_btn, boost_btn, clear_btn, is_generating]
660
+ ).then(
661
+ fn=demo_instance.generation_code,
662
  inputs=[input_text, setting, history],
663
+ outputs=code_output
664
+ ).then(
665
+ fn=update_code_analysis,
666
+ inputs=[code_output],
667
+ outputs=[code_analysis]
668
+ ).then(
669
+ fn=end_generating,
670
+ outputs=[status_html, generate_btn, boost_btn, clear_btn, is_generating]
671
  )
672
 
673
  boost_btn.click(
 
683
  )
684
 
685
  deploy_btn.click(
686
+ fn=lambda code, token: deploy_to_huggingface(code, token) if code else "μ½”λ“œκ°€ μ—†μŠ΅λ‹ˆλ‹€.",
687
  inputs=[code_output, hf_token],
688
  outputs=[deploy_result]
689
  )
 
 
 
 
 
 
690
 
691
  if __name__ == "__main__":
692
  try:
693
+ demo.queue().launch(ssr_mode=False)
694
  except Exception as e:
695
  print(f"Initialization error: {e}")
696
  raise