alwaysgood commited on
Commit
0d6bf83
·
verified ·
1 Parent(s): e842fc4

Update ui.py

Browse files
Files changed (1) hide show
  1. ui.py +27 -88
ui.py CHANGED
@@ -1,105 +1,44 @@
1
- # ui.py (최종 통합 버전)
2
-
3
  import gradio as gr
4
- from datetime import datetime
5
  import os
6
-
7
- # --- 필요한 모듈에서 함수들을 가져옵니다 ---
8
- from config import STATIONS, STATION_NAMES
9
  from supabase_utils import get_supabase_client
10
- from prediction import single_prediction
11
- from chatbot import process_chatbot_query_with_llm
12
- from api_utils import (
13
- api_get_historical_tide,
14
- api_compare_dates,
15
- api_get_monthly_summary
16
- )
17
 
 
 
 
 
 
18
 
19
- def create_ui():
20
- """모든 기능이 통합된 Gradio UI를 생성하고 반환합니다."""
21
- with gr.Blocks(title="통합 조위 예측 시스템", theme=gr.themes.Soft()) as demo:
22
- gr.Markdown("# 🌊 통합 조위 예측 시스템 (최종 버전)")
23
-
24
- # --- 연결 상태 표시 ---
25
- client = get_supabase_client()
26
- supabase_status = "🟢 연결됨" if client else "🔴 연결 안됨"
27
- gemini_status = "🟢 연결됨" if os.getenv("GEMINI_API_KEY") else "🔴 연결 안됨"
28
- gr.Markdown(f"**Supabase 상태**: {supabase_status} | **Gemini 상태**: {gemini_status}")
29
 
30
  with gr.Tabs():
31
-
32
- # --- 1번 탭: 모델을 직접 실행하는 '통합 조위 예측' ---
33
- with gr.TabItem("🔮 통합 조위 예측"):
34
- # (이곳에는 두 번째 버전의 'Tide Prediction' UI 코드를 붙여넣습니다.)
35
- gr.Markdown("### TimeXer 모델을 실행하여 미래 조위를 예측하고 DB에 저장합니다.")
36
  with gr.Row():
37
  with gr.Column(scale=1):
38
- pred_station = gr.Dropdown(choices=[(STATION_NAMES.get(s, s), s) for s in STATIONS], label="관측소 선택", value="DT_0001")
39
- pred_csv_file = gr.File(label="과거 데이터 업로드 (.csv)")
40
- pred_btn = gr.Button("예측 실행", variant="primary")
41
  with gr.Column(scale=3):
42
- pred_plot = gr.Plot(label="예측 결과 시각화")
43
- pred_df = gr.DataFrame(label="예측 결과 데이터")
44
- pred_log = gr.Textbox(label="실행 로그", interactive=False)
 
 
45
 
46
- # --- 2번 탭: AI 챗봇 ---
47
- with gr.TabItem("💬 AI 조위 챗봇"):
48
- # (이곳에는 두 번째 버전의 'AI Tide Chatbot' UI 코드를 붙여넣습니다.)
49
  gr.ChatInterface(
50
- fn=process_chatbot_query_with_llm,
51
- title="AI 조위 챗봇",
52
- description="DB에 저장된 데이터를 바탕으로 조위에 대해 궁금한 점을 물어보세요."
53
  )
54
-
55
- # --- 3번 탭: 저장된 데이터를 분석하는 '데이터 조회 및 분석' ---
56
- with gr.TabItem("📜 데이터 조회 및 분석"):
57
- gr.Markdown("### 데이터베이스에 저장된 과거/미래 데이터를 조회하고 분석합니다.")
58
- with gr.Tabs():
59
- with gr.TabItem("일별 조회"):
60
- # (첫 번째 버전의 'Tide Data' UI)
61
- hist_station = gr.Dropdown(choices=[(STATION_NAMES.get(s, s), s) for s in STATIONS], label="관측소", value="DT_0001")
62
- hist_date = gr.Textbox(label="날짜 (YYYY-MM-DD)", value=datetime.now().strftime('%Y-%m-%d'))
63
- hist_btn = gr.Button("조회")
64
- hist_plot = gr.Plot(label="일별 조위 그래프")
65
-
66
- with gr.TabItem("날짜 비교"):
67
- # (첫 번째 버전의 'Compare Tides' UI)
68
- comp_station = gr.Dropdown(choices=[(STATION_NAMES.get(s, s), s) for s in STATIONS], label="관측소", value="DT_0001")
69
- comp_date1 = gr.Textbox(label="날짜 1 (YYYY-MM-DD)", value="2025-08-01")
70
- comp_date2 = gr.Textbox(label="날짜 2 (YYYY-MM-DD)", value="2025-08-02")
71
- comp_btn = gr.Button("비교")
72
- comp_plot = gr.Plot(label="날짜별 비교 그래프")
73
-
74
- with gr.TabItem("월간 요약"):
75
- # (첫 번째 버전의 'Monthly Summary' UI)
76
- sum_station = gr.Dropdown(choices=[(STATION_NAMES.get(s, s), s) for s in STATIONS], label="관측소", value="DT_0001")
77
- sum_year = gr.Textbox(label="년", value="2025")
78
- sum_month = gr.Textbox(label="월", value="08")
79
- sum_btn = gr.Button("요약 보기")
80
- sum_json = gr.JSON(label="월간 통계")
81
- sum_plot = gr.Plot(label="월간 그래프")
82
 
83
- # --- 모든 버튼의 이벤트 핸들러를 정의합니다 ---
84
- pred_btn.click(
85
- fn=single_prediction, # prediction.py에 있어야 함
86
- inputs=[pred_station, pred_csv_file],
87
- outputs=[pred_plot, pred_df, pred_log]
88
- )
89
- hist_btn.click(
90
- fn=api_get_historical_tide, # api_utils.py에 있어야 함
91
- inputs=[hist_station, hist_date],
92
- outputs=hist_plot
93
- )
94
- comp_btn.click(
95
- fn=api_compare_dates, # api_utils.py에 있어야 함
96
- inputs=[comp_station, comp_date1, comp_date2],
97
- outputs=comp_plot
98
- )
99
- sum_btn.click(
100
- fn=api_get_monthly_summary, # api_utils.py에 있어야 함
101
- inputs=[sum_station, sum_year, sum_month],
102
- outputs=[sum_json, sum_plot]
103
  )
104
 
105
  return demo
 
 
 
1
  import gradio as gr
 
2
  import os
3
+ from config import STATIONS
 
 
4
  from supabase_utils import get_supabase_client
 
 
 
 
 
 
 
5
 
6
+ def create_ui(prediction_handler, chatbot_handler):
7
+ """Gradio UI for Tide Prediction System."""
8
+ client = get_supabase_client()
9
+ supabase_status = "🟢 Connected" if client else "🔴 Disconnected (Check env variables)"
10
+ gemini_status = "🟢 Connected" if os.getenv("GEMINI_API_KEY") else "🔴 Disconnected (Check env variables)"
11
 
12
+ with gr.Blocks(title="Tide Prediction System", theme=gr.themes.Default()) as demo:
13
+ gr.Markdown("# 🌊 Tide Prediction System")
14
+ gr.Markdown(f"**Supabase**: {supabase_status} | **Gemini**: {gemini_status}")
 
 
 
 
 
 
 
15
 
16
  with gr.Tabs():
17
+ with gr.TabItem("Tide Prediction"):
 
 
 
 
18
  with gr.Row():
19
  with gr.Column(scale=1):
20
+ station = gr.Dropdown(choices=STATIONS, label="Station", value="DT_0001")
21
+ csv_file = gr.File(label="Historical Data (.csv)")
22
+ predict_btn = gr.Button("Run Prediction", variant="primary")
23
  with gr.Column(scale=3):
24
+ plot_output = gr.Plot(label="Prediction Visualization")
25
+ df_output = gr.DataFrame(label="Prediction Data")
26
+
27
+ # log_output은 Row 바깥에 위치해야 전체 너비를 사용합니다.
28
+ log_output = gr.Textbox(label="Execution Log", interactive=False)
29
 
30
+ with gr.TabItem("AI Tide Chatbot"):
 
 
31
  gr.ChatInterface(
32
+ fn=chatbot_handler,
33
+ title="AI Tide Chatbot",
34
+ description="Ask about tide information (e.g., 'What's the current tide in Incheon?')"
35
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ # .click 이벤트는 with gr.Blocks() 블록 안에 있어야 합니다.
38
+ predict_btn.click(
39
+ fn=prediction_handler,
40
+ inputs=[station, csv_file],
41
+ outputs=[plot_output, df_output, log_output]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  )
43
 
44
  return demo