Spaces:
Sleeping
Sleeping
Update ui.py
Browse files
ui.py
CHANGED
|
@@ -1,42 +1,283 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
-
|
|
|
|
|
|
|
| 4 |
from supabase_utils import get_supabase_client
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
def create_ui(prediction_handler, chatbot_handler):
|
| 7 |
"""Gradio UI를 생성하고 반환합니다."""
|
|
|
|
| 8 |
with gr.Blocks(title="통합 조위 예측 시스템", theme=gr.themes.Soft()) as demo:
|
| 9 |
gr.Markdown("# 🌊 통합 조위 예측 시스템 with Gemini")
|
| 10 |
-
|
| 11 |
# 연결 상태 표시
|
| 12 |
client = get_supabase_client()
|
| 13 |
supabase_status = "🟢 연결됨" if client else "🔴 연결 안됨 (환경변수 확인 필요)"
|
| 14 |
gemini_status = "🟢 연결됨" if os.getenv("GEMINI_API_KEY") else "🔴 연결 안됨 (환경변수 확인 필요)"
|
| 15 |
gr.Markdown(f"**Supabase 상태**: {supabase_status} | **Gemini 상태**: {gemini_status}")
|
| 16 |
-
|
| 17 |
with gr.Tabs():
|
| 18 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
with gr.Row():
|
| 20 |
with gr.Column(scale=1):
|
| 21 |
-
station_id_input = gr.Dropdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
input_csv = gr.File(label="과거 데이터 업로드 (.csv)")
|
| 23 |
-
predict_btn = gr.Button("예측 실행", variant="primary")
|
|
|
|
| 24 |
with gr.Column(scale=3):
|
| 25 |
output_plot = gr.Plot(label="예측 결과 시각화")
|
| 26 |
output_df = gr.DataFrame(label="예측 결과 데이터")
|
|
|
|
| 27 |
output_log = gr.Textbox(label="실행 로그", lines=5, interactive=False)
|
| 28 |
-
|
| 29 |
-
|
|
|
|
| 30 |
gr.ChatInterface(
|
| 31 |
fn=chatbot_handler,
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
predict_btn.click(
|
| 38 |
fn=prediction_handler,
|
| 39 |
inputs=[station_id_input, input_csv],
|
| 40 |
outputs=[output_plot, output_df, output_log]
|
| 41 |
)
|
|
|
|
| 42 |
return demo
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import os
|
| 3 |
+
import json
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from config import STATIONS, STATION_NAMES
|
| 6 |
from supabase_utils import get_supabase_client
|
| 7 |
+
from api_utils import (
|
| 8 |
+
api_get_tide_level,
|
| 9 |
+
api_get_tide_series,
|
| 10 |
+
api_get_extremes_info,
|
| 11 |
+
api_check_tide_alert,
|
| 12 |
+
api_compare_stations,
|
| 13 |
+
api_health_check
|
| 14 |
+
)
|
| 15 |
|
| 16 |
def create_ui(prediction_handler, chatbot_handler):
|
| 17 |
"""Gradio UI를 생성하고 반환합니다."""
|
| 18 |
+
|
| 19 |
with gr.Blocks(title="통합 조위 예측 시스템", theme=gr.themes.Soft()) as demo:
|
| 20 |
gr.Markdown("# 🌊 통합 조위 예측 시스템 with Gemini")
|
| 21 |
+
|
| 22 |
# 연결 상태 표시
|
| 23 |
client = get_supabase_client()
|
| 24 |
supabase_status = "🟢 연결됨" if client else "🔴 연결 안됨 (환경변수 확인 필요)"
|
| 25 |
gemini_status = "🟢 연결됨" if os.getenv("GEMINI_API_KEY") else "🔴 연결 안됨 (환경변수 확인 필요)"
|
| 26 |
gr.Markdown(f"**Supabase 상태**: {supabase_status} | **Gemini 상태**: {gemini_status}")
|
| 27 |
+
|
| 28 |
with gr.Tabs():
|
| 29 |
+
# 1. 예측 탭
|
| 30 |
+
with gr.TabItem("🔮 통합 조위 예측"):
|
| 31 |
+
gr.Markdown("""
|
| 32 |
+
### TimeXer 모델을 활용한 조위 예측
|
| 33 |
+
- 과거 기상 데이터를 업로드하여 미래 72시간 조위 예측
|
| 34 |
+
- 잔차 예측 + 조화 예측 = 최종 조위
|
| 35 |
+
""")
|
| 36 |
+
|
| 37 |
with gr.Row():
|
| 38 |
with gr.Column(scale=1):
|
| 39 |
+
station_id_input = gr.Dropdown(
|
| 40 |
+
choices=[(f"{STATION_NAMES[s]} ({s})", s) for s in STATIONS],
|
| 41 |
+
label="관측소 선택",
|
| 42 |
+
value="DT_0001"
|
| 43 |
+
)
|
| 44 |
input_csv = gr.File(label="과거 데이터 업로드 (.csv)")
|
| 45 |
+
predict_btn = gr.Button("🚀 예측 실행", variant="primary")
|
| 46 |
+
|
| 47 |
with gr.Column(scale=3):
|
| 48 |
output_plot = gr.Plot(label="예측 결과 시각화")
|
| 49 |
output_df = gr.DataFrame(label="예측 결과 데이터")
|
| 50 |
+
|
| 51 |
output_log = gr.Textbox(label="실행 로그", lines=5, interactive=False)
|
| 52 |
+
|
| 53 |
+
# 2. 챗봇 탭
|
| 54 |
+
with gr.TabItem("💬 AI 조위 챗봇"):
|
| 55 |
gr.ChatInterface(
|
| 56 |
fn=chatbot_handler,
|
| 57 |
+
title="",
|
| 58 |
+
description="조위에 대해 궁금한 점을 물어보세요.",
|
| 59 |
+
examples=[
|
| 60 |
+
"인천 현재 조위 알려줘",
|
| 61 |
+
"내일 오후 3시 평택 조위는?",
|
| 62 |
+
"오늘 만조 시간은?"
|
| 63 |
+
]
|
| 64 |
)
|
| 65 |
+
|
| 66 |
+
# 3. API 탭 (새로 추가)
|
| 67 |
+
with gr.TabItem("🔌 API"):
|
| 68 |
+
gr.Markdown("""
|
| 69 |
+
## RESTful API 엔드포인트
|
| 70 |
+
실무에서 바로 사용 가능한 API 기능을 제공합니다.
|
| 71 |
+
""")
|
| 72 |
+
|
| 73 |
+
with gr.Tabs():
|
| 74 |
+
# 3-1. 현재 조위
|
| 75 |
+
with gr.TabItem("현재 조위"):
|
| 76 |
+
with gr.Row():
|
| 77 |
+
with gr.Column():
|
| 78 |
+
gr.Markdown("### 특정 시간 조위 조회")
|
| 79 |
+
api1_station = gr.Dropdown(
|
| 80 |
+
choices=[(f"{STATION_NAMES[s]} ({s})", s) for s in STATIONS],
|
| 81 |
+
label="관측소",
|
| 82 |
+
value="DT_0001"
|
| 83 |
+
)
|
| 84 |
+
api1_time = gr.Textbox(
|
| 85 |
+
label="조회 시간 (비워두면 현재)",
|
| 86 |
+
placeholder="2024-12-25T15:00:00"
|
| 87 |
+
)
|
| 88 |
+
api1_fallback = gr.Checkbox(
|
| 89 |
+
label="조화 예측 폴백 사용",
|
| 90 |
+
value=True
|
| 91 |
+
)
|
| 92 |
+
api1_btn = gr.Button("조회")
|
| 93 |
+
|
| 94 |
+
with gr.Column():
|
| 95 |
+
api1_output = gr.JSON(label="API 응답")
|
| 96 |
+
|
| 97 |
+
api1_btn.click(
|
| 98 |
+
fn=lambda s, t, f: api_get_tide_level(s, t if t else None, f),
|
| 99 |
+
inputs=[api1_station, api1_time, api1_fallback],
|
| 100 |
+
outputs=api1_output,
|
| 101 |
+
api_name="tide_level"
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
# 3-2. 시계열 데이터
|
| 105 |
+
with gr.TabItem("시계열"):
|
| 106 |
+
with gr.Row():
|
| 107 |
+
with gr.Column():
|
| 108 |
+
gr.Markdown("### 시간대별 조위 데이터")
|
| 109 |
+
api2_station = gr.Dropdown(
|
| 110 |
+
choices=[(f"{STATION_NAMES[s]} ({s})", s) for s in STATIONS],
|
| 111 |
+
label="관측소",
|
| 112 |
+
value="DT_0001"
|
| 113 |
+
)
|
| 114 |
+
api2_start = gr.Textbox(
|
| 115 |
+
label="시작 시간",
|
| 116 |
+
placeholder="2024-12-25T00:00:00"
|
| 117 |
+
)
|
| 118 |
+
api2_end = gr.Textbox(
|
| 119 |
+
label="종료 시간",
|
| 120 |
+
placeholder="2024-12-26T00:00:00"
|
| 121 |
+
)
|
| 122 |
+
api2_interval = gr.Number(
|
| 123 |
+
label="간격(분)",
|
| 124 |
+
value=60,
|
| 125 |
+
minimum=5,
|
| 126 |
+
maximum=360
|
| 127 |
+
)
|
| 128 |
+
api2_btn = gr.Button("조회")
|
| 129 |
+
|
| 130 |
+
with gr.Column():
|
| 131 |
+
api2_output = gr.JSON(label="API 응답 (공공 API 형식)")
|
| 132 |
+
|
| 133 |
+
api2_btn.click(
|
| 134 |
+
fn=lambda s, st, et, i: api_get_tide_series(
|
| 135 |
+
s, st if st else None, et if et else None, int(i)
|
| 136 |
+
),
|
| 137 |
+
inputs=[api2_station, api2_start, api2_end, api2_interval],
|
| 138 |
+
outputs=api2_output,
|
| 139 |
+
api_name="tide_series"
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
# 3-3. 만조/간조
|
| 143 |
+
with gr.TabItem("만조/간조"):
|
| 144 |
+
with gr.Row():
|
| 145 |
+
with gr.Column():
|
| 146 |
+
gr.Markdown("### 만조/간조 정보")
|
| 147 |
+
api3_station = gr.Dropdown(
|
| 148 |
+
choices=[(f"{STATION_NAMES[s]} ({s})", s) for s in STATIONS],
|
| 149 |
+
label="관측소",
|
| 150 |
+
value="DT_0001"
|
| 151 |
+
)
|
| 152 |
+
api3_date = gr.Textbox(
|
| 153 |
+
label="날짜 (YYYY-MM-DD)",
|
| 154 |
+
placeholder=datetime.now().strftime("%Y-%m-%d")
|
| 155 |
+
)
|
| 156 |
+
api3_secondary = gr.Checkbox(
|
| 157 |
+
label="부차 만조/간조 포함",
|
| 158 |
+
value=False
|
| 159 |
+
)
|
| 160 |
+
api3_btn = gr.Button("조회")
|
| 161 |
+
|
| 162 |
+
with gr.Column():
|
| 163 |
+
api3_output = gr.JSON(label="만조/간조 정보")
|
| 164 |
+
|
| 165 |
+
api3_btn.click(
|
| 166 |
+
fn=lambda s, d, sec: api_get_extremes_info(
|
| 167 |
+
s, d if d else None, sec
|
| 168 |
+
),
|
| 169 |
+
inputs=[api3_station, api3_date, api3_secondary],
|
| 170 |
+
outputs=api3_output,
|
| 171 |
+
api_name="extremes"
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
# 3-4. 위험 수위
|
| 175 |
+
with gr.TabItem("위험 알림"):
|
| 176 |
+
with gr.Row():
|
| 177 |
+
with gr.Column():
|
| 178 |
+
gr.Markdown("### 위험 수위 체크")
|
| 179 |
+
api4_station = gr.Dropdown(
|
| 180 |
+
choices=[(f"{STATION_NAMES[s]} ({s})", s) for s in STATIONS],
|
| 181 |
+
label="관측소",
|
| 182 |
+
value="DT_0001"
|
| 183 |
+
)
|
| 184 |
+
api4_hours = gr.Number(
|
| 185 |
+
label="확인 시간(시간)",
|
| 186 |
+
value=24,
|
| 187 |
+
minimum=1,
|
| 188 |
+
maximum=72
|
| 189 |
+
)
|
| 190 |
+
api4_warning = gr.Number(
|
| 191 |
+
label="주의 수위(cm)",
|
| 192 |
+
value=700
|
| 193 |
+
)
|
| 194 |
+
api4_danger = gr.Number(
|
| 195 |
+
label="경고 수위(cm)",
|
| 196 |
+
value=750
|
| 197 |
+
)
|
| 198 |
+
api4_btn = gr.Button("체크")
|
| 199 |
+
|
| 200 |
+
with gr.Column():
|
| 201 |
+
api4_output = gr.JSON(label="위험 수위 정보")
|
| 202 |
+
|
| 203 |
+
api4_btn.click(
|
| 204 |
+
fn=lambda s, h, w, d: api_check_tide_alert(s, int(h), w, d),
|
| 205 |
+
inputs=[api4_station, api4_hours, api4_warning, api4_danger],
|
| 206 |
+
outputs=api4_output,
|
| 207 |
+
api_name="alert"
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# 3-5. 관측소 비교
|
| 211 |
+
with gr.TabItem("비교"):
|
| 212 |
+
with gr.Row():
|
| 213 |
+
with gr.Column():
|
| 214 |
+
gr.Markdown("### 다중 관측소 비교")
|
| 215 |
+
api5_stations = gr.CheckboxGroup(
|
| 216 |
+
choices=[(f"{STATION_NAMES[s]}", s) for s in STATIONS],
|
| 217 |
+
label="비교할 관측소 선택",
|
| 218 |
+
value=["DT_0001", "DT_0002", "DT_0003"]
|
| 219 |
+
)
|
| 220 |
+
api5_time = gr.Textbox(
|
| 221 |
+
label="비교 시간 (비워두면 현재)",
|
| 222 |
+
placeholder="2024-12-25T15:00:00"
|
| 223 |
+
)
|
| 224 |
+
api5_btn = gr.Button("비교")
|
| 225 |
+
|
| 226 |
+
with gr.Column():
|
| 227 |
+
api5_output = gr.JSON(label="비교 결과")
|
| 228 |
+
|
| 229 |
+
api5_btn.click(
|
| 230 |
+
fn=lambda s, t: api_compare_stations(s, t if t else None),
|
| 231 |
+
inputs=[api5_stations, api5_time],
|
| 232 |
+
outputs=api5_output,
|
| 233 |
+
api_name="compare"
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
# 3-6. 상태 체크
|
| 237 |
+
with gr.TabItem("상태"):
|
| 238 |
+
gr.Markdown("### API 및 시스템 상태")
|
| 239 |
+
api6_btn = gr.Button("🔍 상태 확인", variant="secondary")
|
| 240 |
+
api6_output = gr.JSON(label="시스템 상태")
|
| 241 |
+
|
| 242 |
+
api6_btn.click(
|
| 243 |
+
fn=api_health_check,
|
| 244 |
+
inputs=[],
|
| 245 |
+
outputs=api6_output,
|
| 246 |
+
api_name="health"
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
# API 사용 안내
|
| 250 |
+
gr.Markdown("""
|
| 251 |
+
---
|
| 252 |
+
### 📚 API 사용 안내
|
| 253 |
+
|
| 254 |
+
**Python 예제:**
|
| 255 |
+
```python
|
| 256 |
+
from gradio_client import Client
|
| 257 |
+
|
| 258 |
+
client = Client("https://your-space.hf.space/")
|
| 259 |
+
|
| 260 |
+
# 현재 조위 조회
|
| 261 |
+
result = client.predict(
|
| 262 |
+
"DT_0001", # station_id
|
| 263 |
+
"", # time (empty = current)
|
| 264 |
+
True, # use_fallback
|
| 265 |
+
api_name="/tide_level"
|
| 266 |
+
)
|
| 267 |
+
```
|
| 268 |
+
|
| 269 |
+
**특징:**
|
| 270 |
+
- 🔄 **조화 예측 폴백**: 최종 예측이 없을 때 자동으로 조화 예측 사용
|
| 271 |
+
- 📊 **공공 API 호환**: 기상청 API와 유사한 응답 형식
|
| 272 |
+
- ⚠️ **위험 수위 알림**: 2단계 경보 시스템
|
| 273 |
+
- 🏢 **다중 관측소**: 여러 관측소 동시 비교
|
| 274 |
+
""")
|
| 275 |
+
|
| 276 |
+
# 이벤트 핸들러 연결
|
| 277 |
predict_btn.click(
|
| 278 |
fn=prediction_handler,
|
| 279 |
inputs=[station_id_input, input_csv],
|
| 280 |
outputs=[output_plot, output_df, output_log]
|
| 281 |
)
|
| 282 |
+
|
| 283 |
return demo
|