alwaysgood commited on
Commit
7fc8e3a
·
verified ·
1 Parent(s): fba891d

Update ui.py

Browse files
Files changed (1) hide show
  1. ui.py +56 -22
ui.py CHANGED
@@ -1,44 +1,78 @@
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
 
1
  import gradio as gr
2
  import os
3
+ from datetime import datetime
4
  from config import STATIONS
5
  from supabase_utils import get_supabase_client
6
+ from api_utils import get_tide_data
7
+
8
+ def view_tide_data_handler(station_id, date):
9
+ """Handler to fetch and display tide data for a specific date."""
10
+ if not station_id or not date:
11
+ return None, None, "관측소와 날짜를 선택해주세요."
12
+
13
+ date_str = date.strftime('%Y-%m-%d')
14
+ try:
15
+ result = get_tide_data(station_id, start_date=date_str, include_extremes=True, return_plot=True)
16
+ if result['data'].empty:
17
+ return None, None, f"{date_str}에 대한 데이터가 없습니다."
18
+
19
+ extremes_df = result.get('extremes', None)
20
+ return result['plot'], extremes_df, f"{date_str}의 조위 데이터 조회 완료"
21
+ except Exception as e:
22
+ return None, None, f"오류 발생: {e}"
23
 
24
  def create_ui(prediction_handler, chatbot_handler):
25
+ """Gradio UI 생성하고 반환합니다."""
26
+ with gr.Blocks(title="통합 조위 예측 시스템", theme=gr.themes.Soft()) as demo:
27
+ gr.Markdown("# 🌊 통합 조위 예측 시스템 with Gemini")
 
28
 
29
+ # 연결 상태 표시
30
+ client = get_supabase_client()
31
+ supabase_status = "🟢 연결됨" if client else "🔴 연결 안됨 (환경변수 확인 필요)"
32
+ gemini_status = "🟢 연결됨" if os.getenv("GEMINI_API_KEY") else "🔴 연결 안됨 (환경변수 확인 필요)"
33
+ gr.Markdown(f"**Supabase 상태**: {supabase_status} | **Gemini 상태**: {gemini_status}")
34
 
35
  with gr.Tabs():
36
+ with gr.TabItem("통합 조위 예측"):
37
+ with gr.Row():
38
+ with gr.Column(scale=1):
39
+ station_id_input = gr.Dropdown(STATIONS, label="관측소 선택", value="DT_0001")
40
+ input_csv = gr.File(label="과거 데이터 업로드 (.csv)")
41
+ predict_btn = gr.Button("예측 실행", variant="primary")
42
+ with gr.Column(scale=3):
43
+ output_plot = gr.Plot(label="예측 결과 시각화")
44
+ output_df = gr.DataFrame(label="예측 결과 데이터")
45
+ output_log = gr.Textbox(label="실행 로그", lines=5, interactive=False)
46
+
47
+ with gr.TabItem("데이터 조회 및 분석"):
48
+ gr.Markdown("### 특정 날짜의 조위 데이터 조회")
49
  with gr.Row():
50
  with gr.Column(scale=1):
51
+ view_station_input = gr.Dropdown(STATIONS, label="관측소 선택", value="DT_0001")
52
+ view_date_input = gr.DatePicker(label="날짜 선택", value=datetime.now().strftime("%Y-%m-%d"))
53
+ view_btn = gr.Button("조회 실행", variant="primary")
54
  with gr.Column(scale=3):
55
+ view_output_plot = gr.Plot(label="조위 그래프")
56
+ view_output_extremes = gr.DataFrame(label="만조 및 간조 정보")
57
+ view_log = gr.Textbox(label="실행 로그", lines=2, interactive=False)
 
 
58
 
59
+ with gr.TabItem("AI 조위 챗봇"):
60
  gr.ChatInterface(
61
  fn=chatbot_handler,
62
+ title="AI 조위 챗봇",
63
+ description="조위에 대해 궁금한 점을 물어보세요. (예: '인천 오늘 현재 조위 알려줘')",
64
+ #examples=[]
65
  )
66
 
 
67
  predict_btn.click(
68
  fn=prediction_handler,
69
+ inputs=[station_id_input, input_csv],
70
+ outputs=[output_plot, output_df, output_log]
71
  )
72
 
73
+ view_btn.click(
74
+ fn=view_tide_data_handler,
75
+ inputs=[view_station_input, view_date_input],
76
+ outputs=[view_output_plot, view_output_extremes, view_log]
77
+ )
78
  return demo