코딩 컨벤션 및 드롭다운팝업해결 #7
Browse files- gradio_app.py +52 -31
gradio_app.py
CHANGED
|
@@ -6,11 +6,10 @@ import time
|
|
| 6 |
from pathlib import Path
|
| 7 |
from queue import Empty, Queue
|
| 8 |
from threading import Thread
|
| 9 |
-
from typing import Generator, List, Tuple
|
| 10 |
|
| 11 |
import gradio as gr
|
| 12 |
import requests
|
| 13 |
-
|
| 14 |
|
| 15 |
PERSONA_FILE = Path(os.environ.get("PERSONA_FILE", "persona.jsonl"))
|
| 16 |
|
|
@@ -52,11 +51,13 @@ AUTO_SCROLL_SCRIPT = """
|
|
| 52 |
"""
|
| 53 |
|
| 54 |
|
| 55 |
-
def to_markdown(text
|
|
|
|
| 56 |
return text or ""
|
| 57 |
|
| 58 |
|
| 59 |
-
def loading_markdown(message
|
|
|
|
| 60 |
safe_message = html_lib.escape(message or "")
|
| 61 |
return (
|
| 62 |
'<div class="ws-loading shimmer">'
|
|
@@ -66,11 +67,23 @@ def loading_markdown(message: str) -> str:
|
|
| 66 |
)
|
| 67 |
|
| 68 |
|
| 69 |
-
def timer_text(elapsed
|
|
|
|
| 70 |
return f"⏱ {elapsed}"
|
| 71 |
|
| 72 |
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
# persona.jsonl에서 persona 이름 목록 로드
|
| 75 |
choices = ["없음"]
|
| 76 |
if PERSONA_FILE.exists():
|
|
@@ -81,28 +94,36 @@ def load_persona_choices() -> List[str]:
|
|
| 81 |
continue
|
| 82 |
try:
|
| 83 |
data = json.loads(line)
|
| 84 |
-
|
|
|
|
| 85 |
if name and name not in choices:
|
| 86 |
choices.append(name)
|
| 87 |
-
except json.JSONDecodeError:
|
| 88 |
continue
|
| 89 |
return choices
|
| 90 |
|
| 91 |
|
| 92 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
# API 서버 /persona/ 를 호출하여 persona 생성 (generator: 타이머 + 진행 메시지 표시)
|
| 94 |
if not info or not info.strip():
|
| 95 |
yield "인물 정보를 입력해주세요.", "{}", timer_text("0.0초")
|
| 96 |
return
|
| 97 |
|
| 98 |
persona_endpoint = endpoint.rstrip("/").rsplit("/", 1)[0] + "/persona/"
|
| 99 |
-
|
| 100 |
-
result_queue
|
| 101 |
-
|
| 102 |
-
def elapsed_str() -> str:
|
| 103 |
-
return f"{time.time() - start_time:.1f}초"
|
| 104 |
|
| 105 |
-
def worker()
|
| 106 |
try:
|
| 107 |
resp = requests.post(
|
| 108 |
persona_endpoint,
|
|
@@ -154,9 +175,8 @@ def make_persona_gradio(info: str, endpoint: str):
|
|
| 154 |
yield result_md, json.dumps(data, ensure_ascii=False, indent=2), timer_text(elapsed_str())
|
| 155 |
|
| 156 |
|
| 157 |
-
def stream_analyze(
|
| 158 |
-
|
| 159 |
-
) -> Generator[Tuple[str, str, str], None, None]:
|
| 160 |
query = (query or "").strip()
|
| 161 |
endpoint = (endpoint or "").strip()
|
| 162 |
persona_name = (persona_name or "").strip()
|
|
@@ -174,14 +194,11 @@ def stream_analyze(
|
|
| 174 |
loading_msg = "요청 중..."
|
| 175 |
worker_finished = False
|
| 176 |
terminal_event = False
|
| 177 |
-
|
| 178 |
|
| 179 |
-
event_queue
|
| 180 |
|
| 181 |
-
def
|
| 182 |
-
return f"{time.time() - start_time:.1f}초"
|
| 183 |
-
|
| 184 |
-
def reader_worker() -> None:
|
| 185 |
try:
|
| 186 |
payload = {"query": query}
|
| 187 |
if persona_name and persona_name != "없음":
|
|
@@ -293,7 +310,8 @@ def stream_analyze(
|
|
| 293 |
break
|
| 294 |
|
| 295 |
|
| 296 |
-
def create_app(default_endpoint
|
|
|
|
| 297 |
custom_css = """
|
| 298 |
@import url("https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+KR:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap");
|
| 299 |
|
|
@@ -523,6 +541,11 @@ def create_app(default_endpoint: str) -> gr.Blocks:
|
|
| 523 |
padding: 16px 20px !important;
|
| 524 |
box-shadow: 0 8px 24px rgba(16, 24, 40, 0.06) !important;
|
| 525 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 526 |
"""
|
| 527 |
|
| 528 |
theme = gr.themes.Soft(
|
|
@@ -537,7 +560,6 @@ def create_app(default_endpoint: str) -> gr.Blocks:
|
|
| 537 |
gr.Markdown("A finance AI that combines earnings, news, and market trends in one place.")
|
| 538 |
|
| 539 |
with gr.Tabs():
|
| 540 |
-
# ── Tab 1: 질문하기 ��─────────────────────────────────────
|
| 541 |
with gr.Tab("💬 질문하기"):
|
| 542 |
with gr.Row():
|
| 543 |
with gr.Column(scale=3):
|
|
@@ -547,7 +569,7 @@ def create_app(default_endpoint: str) -> gr.Blocks:
|
|
| 547 |
)
|
| 548 |
persona_dropdown = gr.Dropdown(
|
| 549 |
label="페르소나 선택",
|
| 550 |
-
choices=
|
| 551 |
value="없음",
|
| 552 |
interactive=True,
|
| 553 |
)
|
|
@@ -589,11 +611,10 @@ def create_app(default_endpoint: str) -> gr.Blocks:
|
|
| 589 |
outputs=[answer, timer, meta],
|
| 590 |
)
|
| 591 |
refresh_btn.click(
|
| 592 |
-
fn=lambda: gr.Dropdown(choices=
|
| 593 |
outputs=[persona_dropdown],
|
| 594 |
)
|
| 595 |
|
| 596 |
-
# ── Tab 2: 페르소나 만들기 ────────────────────────────────
|
| 597 |
with gr.Tab("🧑💼 페르소나 만들기"):
|
| 598 |
gr.Markdown("### 새 페르소나 생성")
|
| 599 |
gr.Markdown(
|
|
@@ -631,7 +652,7 @@ def create_app(default_endpoint: str) -> gr.Blocks:
|
|
| 631 |
)
|
| 632 |
|
| 633 |
persona_gen_btn.click(
|
| 634 |
-
fn=
|
| 635 |
inputs=[persona_info_input, endpoint],
|
| 636 |
outputs=[persona_result_md, persona_result_json, persona_timer],
|
| 637 |
)
|
|
@@ -661,4 +682,4 @@ def main():
|
|
| 661 |
|
| 662 |
|
| 663 |
if __name__ == "__main__":
|
| 664 |
-
main()
|
|
|
|
| 6 |
from pathlib import Path
|
| 7 |
from queue import Empty, Queue
|
| 8 |
from threading import Thread
|
|
|
|
| 9 |
|
| 10 |
import gradio as gr
|
| 11 |
import requests
|
| 12 |
+
from pydantic import BaseModel
|
| 13 |
|
| 14 |
PERSONA_FILE = Path(os.environ.get("PERSONA_FILE", "persona.jsonl"))
|
| 15 |
|
|
|
|
| 51 |
"""
|
| 52 |
|
| 53 |
|
| 54 |
+
def to_markdown(text):
|
| 55 |
+
# 텍스트를 마크다운 문자열로 반환
|
| 56 |
return text or ""
|
| 57 |
|
| 58 |
|
| 59 |
+
def loading_markdown(message):
|
| 60 |
+
# 로딩 메시지를 안전하게 HTML로 감싸서 반환
|
| 61 |
safe_message = html_lib.escape(message or "")
|
| 62 |
return (
|
| 63 |
'<div class="ws-loading shimmer">'
|
|
|
|
| 67 |
)
|
| 68 |
|
| 69 |
|
| 70 |
+
def timer_text(elapsed):
|
| 71 |
+
# 타이머 텍스트 형식으로 변환
|
| 72 |
return f"⏱ {elapsed}"
|
| 73 |
|
| 74 |
|
| 75 |
+
class PersonaLine(BaseModel):
|
| 76 |
+
# persona.jsonl 파일 한 줄 스키마
|
| 77 |
+
name: str = ""
|
| 78 |
+
background: str = ""
|
| 79 |
+
financial_mindset: str = ""
|
| 80 |
+
data_analysis_approach: str = ""
|
| 81 |
+
response_style: str = ""
|
| 82 |
+
key_principles: list = []
|
| 83 |
+
famous_quotes: list = []
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def load_persona_names():
|
| 87 |
# persona.jsonl에서 persona 이름 목록 로드
|
| 88 |
choices = ["없음"]
|
| 89 |
if PERSONA_FILE.exists():
|
|
|
|
| 94 |
continue
|
| 95 |
try:
|
| 96 |
data = json.loads(line)
|
| 97 |
+
persona = PersonaLine(**data)
|
| 98 |
+
name = persona.name.strip()
|
| 99 |
if name and name not in choices:
|
| 100 |
choices.append(name)
|
| 101 |
+
except (json.JSONDecodeError, TypeError):
|
| 102 |
continue
|
| 103 |
return choices
|
| 104 |
|
| 105 |
|
| 106 |
+
def _make_elapsed_factory():
|
| 107 |
+
# 경과시간 문자열 생성기 팩토리 반환
|
| 108 |
+
start_time = time.time()
|
| 109 |
+
|
| 110 |
+
def elapsed_str():
|
| 111 |
+
return f"{time.time() - start_time:.1f}초"
|
| 112 |
+
|
| 113 |
+
return elapsed_str, start_time
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def generate_persona_stream(info, endpoint):
|
| 117 |
# API 서버 /persona/ 를 호출하여 persona 생성 (generator: 타이머 + 진행 메시지 표시)
|
| 118 |
if not info or not info.strip():
|
| 119 |
yield "인물 정보를 입력해주세요.", "{}", timer_text("0.0초")
|
| 120 |
return
|
| 121 |
|
| 122 |
persona_endpoint = endpoint.rstrip("/").rsplit("/", 1)[0] + "/persona/"
|
| 123 |
+
elapsed_str, _ = _make_elapsed_factory()
|
| 124 |
+
result_queue = Queue()
|
|
|
|
|
|
|
|
|
|
| 125 |
|
| 126 |
+
def worker():
|
| 127 |
try:
|
| 128 |
resp = requests.post(
|
| 129 |
persona_endpoint,
|
|
|
|
| 175 |
yield result_md, json.dumps(data, ensure_ascii=False, indent=2), timer_text(elapsed_str())
|
| 176 |
|
| 177 |
|
| 178 |
+
def stream_analyze(query, persona_name, endpoint):
|
| 179 |
+
# 질의에 대해 SSE 스트림을 받아 점진적으로 응답과 메타데이터를 반환
|
|
|
|
| 180 |
query = (query or "").strip()
|
| 181 |
endpoint = (endpoint or "").strip()
|
| 182 |
persona_name = (persona_name or "").strip()
|
|
|
|
| 194 |
loading_msg = "요청 중..."
|
| 195 |
worker_finished = False
|
| 196 |
terminal_event = False
|
| 197 |
+
elapsed_str, _ = _make_elapsed_factory()
|
| 198 |
|
| 199 |
+
event_queue = Queue()
|
| 200 |
|
| 201 |
+
def reader_worker():
|
|
|
|
|
|
|
|
|
|
| 202 |
try:
|
| 203 |
payload = {"query": query}
|
| 204 |
if persona_name and persona_name != "없음":
|
|
|
|
| 310 |
break
|
| 311 |
|
| 312 |
|
| 313 |
+
def create_app(default_endpoint):
|
| 314 |
+
# Gradio 앱 생성 및 레이아웃 구성
|
| 315 |
custom_css = """
|
| 316 |
@import url("https://fonts.googleapis.com/css2?family=IBM+Plex+Sans+KR:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500;600&display=swap");
|
| 317 |
|
|
|
|
| 541 |
padding: 16px 20px !important;
|
| 542 |
box-shadow: 0 8px 24px rgba(16, 24, 40, 0.06) !important;
|
| 543 |
}
|
| 544 |
+
|
| 545 |
+
/* 드롭다운 열릴 때 페이지 스크롤 고정 */
|
| 546 |
+
body:has(.options:not(.hide)) {
|
| 547 |
+
overflow: hidden !important;
|
| 548 |
+
}
|
| 549 |
"""
|
| 550 |
|
| 551 |
theme = gr.themes.Soft(
|
|
|
|
| 560 |
gr.Markdown("A finance AI that combines earnings, news, and market trends in one place.")
|
| 561 |
|
| 562 |
with gr.Tabs():
|
|
|
|
| 563 |
with gr.Tab("💬 질문하기"):
|
| 564 |
with gr.Row():
|
| 565 |
with gr.Column(scale=3):
|
|
|
|
| 569 |
)
|
| 570 |
persona_dropdown = gr.Dropdown(
|
| 571 |
label="페르소나 선택",
|
| 572 |
+
choices=load_persona_names(),
|
| 573 |
value="없음",
|
| 574 |
interactive=True,
|
| 575 |
)
|
|
|
|
| 611 |
outputs=[answer, timer, meta],
|
| 612 |
)
|
| 613 |
refresh_btn.click(
|
| 614 |
+
fn=lambda: gr.Dropdown(choices=load_persona_names(), value="없음"),
|
| 615 |
outputs=[persona_dropdown],
|
| 616 |
)
|
| 617 |
|
|
|
|
| 618 |
with gr.Tab("🧑💼 페르소나 만들기"):
|
| 619 |
gr.Markdown("### 새 페르소나 생성")
|
| 620 |
gr.Markdown(
|
|
|
|
| 652 |
)
|
| 653 |
|
| 654 |
persona_gen_btn.click(
|
| 655 |
+
fn=generate_persona_stream,
|
| 656 |
inputs=[persona_info_input, endpoint],
|
| 657 |
outputs=[persona_result_md, persona_result_json, persona_timer],
|
| 658 |
)
|
|
|
|
| 682 |
|
| 683 |
|
| 684 |
if __name__ == "__main__":
|
| 685 |
+
main()
|