seawolf2357 commited on
Commit
d88d351
·
verified ·
1 Parent(s): 262467e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +50 -28
app.py CHANGED
@@ -397,20 +397,39 @@ def update_session_list():
397
  print(f"Error updating session list: {e}")
398
  return gr.update(choices=[])
399
 
400
- # db.json 파일 읽기 함수 추가
401
  def load_json_data():
402
  try:
403
- with open('db.json', 'r', encoding='utf-8') as f:
404
- return json.load(f)
 
 
 
 
 
 
405
  except Exception as e:
406
- print(f"Error loading db.json: {e}")
407
- return []
 
 
 
 
 
 
 
 
 
 
 
 
408
 
409
- # 세션 히스토리 로드 함수 수정
410
  def load_session_history(selected_session=None):
411
  try:
412
- # db.json 데이터 로드
413
  json_data = load_json_data()
 
 
 
414
 
415
  html_content = """
416
  <style>
@@ -428,6 +447,7 @@ def load_session_history(selected_session=None):
428
  cursor: pointer;
429
  transition: all 0.3s ease;
430
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
 
431
  }
432
  .prompt-card:hover {
433
  transform: translateY(-2px);
@@ -443,6 +463,7 @@ def load_session_history(selected_session=None):
443
  .card-name {
444
  font-weight: bold;
445
  margin-bottom: 8px;
 
446
  }
447
  .card-prompt {
448
  font-size: 0.9em;
@@ -453,21 +474,20 @@ def load_session_history(selected_session=None):
453
  overflow: hidden;
454
  }
455
  </style>
456
- """
457
-
458
- html_content += """
459
- <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
460
  <div class="prompt-grid">
461
  """
462
 
463
  for item in json_data:
464
  name = html.escape(item.get('name', ''))
465
- image_url = html.escape(item.get('image_url', ''))
466
  prompt = html.escape(item.get('prompt', ''))
467
 
 
 
 
468
  html_content += f"""
469
  <div class="prompt-card" data-prompt="{prompt}" onclick="handleCardClick(this)">
470
- <img src="{image_url}" class="card-image" alt="{name}">
471
  <div class="card-name">{name}</div>
472
  <div class="card-prompt">{prompt}</div>
473
  </div>
@@ -477,20 +497,24 @@ def load_session_history(selected_session=None):
477
  </div>
478
  <script>
479
  function handleCardClick(card) {
 
480
  const prompt = card.getAttribute('data-prompt');
481
  const textarea = document.querySelector('textarea');
482
  if (textarea) {
 
483
  textarea.value = prompt;
484
 
485
- setTimeout(() => {
486
- const executeButton = $('button:contains("Code 실행")');
487
- if (executeButton.length) {
488
- executeButton[0].click();
489
- }
490
- }, 100);
491
 
 
492
  const drawer = document.querySelector('.session-drawer');
493
  if (drawer) {
 
494
  drawer.style.display = 'none';
495
  }
496
  }
@@ -498,11 +522,12 @@ def load_session_history(selected_session=None):
498
  </script>
499
  """
500
 
 
501
  return gr.HTML(value=html_content)
502
 
503
  except Exception as e:
504
- print(f"Error loading session history: {e}")
505
- return gr.HTML("Error loading history")
506
 
507
  # 히스토리 아이템 선택 처리 함수
508
  def handle_history_selection(evt: gr.SelectData):
@@ -584,9 +609,6 @@ with gr.Blocks(css_paths="app.css",theme=theme) as demo:
584
  with antd.Drawer(open=False, title="history", placement="left", width="900px") as history_drawer:
585
  history_output = legacy.Chatbot(show_label=False, flushing=False, height=960, elem_classes="history_chatbot")
586
 
587
-
588
- # session_list 관련 코드를 모두 제거하고 수정된 버전입니다
589
-
590
  with antd.Drawer(
591
  open=False,
592
  title="Templates",
@@ -595,6 +617,7 @@ with gr.Blocks(css_paths="app.css",theme=theme) as demo:
595
  elem_classes="session-drawer"
596
  ) as session_drawer:
597
  with antd.Flex(vertical=True, gap="middle"):
 
598
  session_history = gr.HTML(
599
  elem_classes="session-history"
600
  )
@@ -604,8 +627,6 @@ with gr.Blocks(css_paths="app.css",theme=theme) as demo:
604
  elem_classes="close-btn"
605
  )
606
 
607
-
608
-
609
  # 세션 드로어에서 카드 클릭 시 실행할 함수 (Drawer 컴포넌트들 다음에 위치)
610
  def execute_history_item(evt: gr.SelectData): # gr.SelectData로 이벤트 데이터 받기
611
  try:
@@ -823,12 +844,12 @@ with gr.Blocks(css_paths="app.css",theme=theme) as demo:
823
 
824
 
825
  # 세션 버튼 클릭 이벤트 수정
 
826
  sessionBtn.click(
827
- lambda: (gr.update(open=True), load_session_history()),
828
  inputs=[],
829
  outputs=[session_drawer, session_history]
830
  )
831
-
832
  # 세션 드로어 닫기 이벤트 수정
833
  session_drawer.close(
834
  lambda: (gr.update(open=False), gr.HTML("")),
@@ -840,6 +861,7 @@ with gr.Blocks(css_paths="app.css",theme=theme) as demo:
840
  outputs=[session_drawer, session_history]
841
  )
842
 
 
843
 
844
  btn.click(
845
  demo_instance.generation_code,
 
397
  print(f"Error updating session list: {e}")
398
  return gr.update(choices=[])
399
 
 
400
  def load_json_data():
401
  try:
402
+ current_dir = os.path.dirname(os.path.abspath(__file__))
403
+ json_path = os.path.join(current_dir, 'db.json')
404
+ print(f"Attempting to load JSON from: {json_path}")
405
+
406
+ with open(json_path, 'r', encoding='utf-8') as f:
407
+ data = json.load(f)
408
+ print(f"Successfully loaded {len(data)} items from db.json")
409
+ return data
410
  except Exception as e:
411
+ print(f"Error loading db.json: {str(e)}")
412
+ # 에러 시 기본 데이터 반환
413
+ return [
414
+ {
415
+ "name": "MBTI 진단 서비스",
416
+ "image_url": "mbti.png",
417
+ "prompt": "MBTI 진단을 위해 15개의 질문과 객관식 답변을 통해 MBTI 진단 결과 및 해당 성격에 대한 상세한 결과를 출력하라"
418
+ },
419
+ {
420
+ "name": "투자 포트폴리오 대시보드",
421
+ "image_url": "chart.png",
422
+ "prompt": "Create an interactive dashboard with Chart.js showing different types of charts..."
423
+ }
424
+ ]
425
 
 
426
  def load_session_history(selected_session=None):
427
  try:
428
+ print("Loading session history...")
429
  json_data = load_json_data()
430
+ print(f"Loaded {len(json_data)} items from JSON")
431
+
432
+ current_dir = os.path.dirname(os.path.abspath(__file__))
433
 
434
  html_content = """
435
  <style>
 
447
  cursor: pointer;
448
  transition: all 0.3s ease;
449
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
450
+ min-height: 300px;
451
  }
452
  .prompt-card:hover {
453
  transform: translateY(-2px);
 
463
  .card-name {
464
  font-weight: bold;
465
  margin-bottom: 8px;
466
+ font-size: 16px;
467
  }
468
  .card-prompt {
469
  font-size: 0.9em;
 
474
  overflow: hidden;
475
  }
476
  </style>
 
 
 
 
477
  <div class="prompt-grid">
478
  """
479
 
480
  for item in json_data:
481
  name = html.escape(item.get('name', ''))
482
+ image_url = os.path.join(current_dir, item.get('image_url', ''))
483
  prompt = html.escape(item.get('prompt', ''))
484
 
485
+ print(f"Processing item: {name}")
486
+ print(f"Image path: {image_url}")
487
+
488
  html_content += f"""
489
  <div class="prompt-card" data-prompt="{prompt}" onclick="handleCardClick(this)">
490
+ <img src="{image_url}" class="card-image" alt="{name}" onerror="this.src='default.png'">
491
  <div class="card-name">{name}</div>
492
  <div class="card-prompt">{prompt}</div>
493
  </div>
 
497
  </div>
498
  <script>
499
  function handleCardClick(card) {
500
+ console.log('Card clicked');
501
  const prompt = card.getAttribute('data-prompt');
502
  const textarea = document.querySelector('textarea');
503
  if (textarea) {
504
+ console.log('Setting prompt:', prompt);
505
  textarea.value = prompt;
506
 
507
+ // Send 버튼 클릭
508
+ const sendButton = document.querySelector('button:contains("Send")');
509
+ if (sendButton) {
510
+ console.log('Clicking Send button');
511
+ sendButton.click();
512
+ }
513
 
514
+ // 드로어 닫기
515
  const drawer = document.querySelector('.session-drawer');
516
  if (drawer) {
517
+ console.log('Closing drawer');
518
  drawer.style.display = 'none';
519
  }
520
  }
 
522
  </script>
523
  """
524
 
525
+ print("Generated HTML content length:", len(html_content))
526
  return gr.HTML(value=html_content)
527
 
528
  except Exception as e:
529
+ print(f"Error in load_session_history: {str(e)}")
530
+ return gr.HTML("Error loading templates")
531
 
532
  # 히스토리 아이템 선택 처리 함수
533
  def handle_history_selection(evt: gr.SelectData):
 
609
  with antd.Drawer(open=False, title="history", placement="left", width="900px") as history_drawer:
610
  history_output = legacy.Chatbot(show_label=False, flushing=False, height=960, elem_classes="history_chatbot")
611
 
 
 
 
612
  with antd.Drawer(
613
  open=False,
614
  title="Templates",
 
617
  elem_classes="session-drawer"
618
  ) as session_drawer:
619
  with antd.Flex(vertical=True, gap="middle"):
620
+ gr.Markdown("### Available Templates")
621
  session_history = gr.HTML(
622
  elem_classes="session-history"
623
  )
 
627
  elem_classes="close-btn"
628
  )
629
 
 
 
630
  # 세션 드로어에서 카드 클릭 시 실행할 함수 (Drawer 컴포넌트들 다음에 위치)
631
  def execute_history_item(evt: gr.SelectData): # gr.SelectData로 이벤트 데이터 받기
632
  try:
 
844
 
845
 
846
  # 세션 버튼 클릭 이벤트 수정
847
+
848
  sessionBtn.click(
849
+ fn=lambda: (gr.update(open=True), load_session_history()),
850
  inputs=[],
851
  outputs=[session_drawer, session_history]
852
  )
 
853
  # 세션 드로어 닫기 이벤트 수정
854
  session_drawer.close(
855
  lambda: (gr.update(open=False), gr.HTML("")),
 
861
  outputs=[session_drawer, session_history]
862
  )
863
 
864
+
865
 
866
  btn.click(
867
  demo_instance.generation_code,