my-tide-env / ui.py
alwaysgood's picture
Update ui.py
6266aa3 verified
raw
history blame
13.6 kB
import gradio as gr
import os
import json
from datetime import datetime
from config import STATIONS, STATION_NAMES
from supabase_utils import get_supabase_client
from api_utils import (
api_get_tide_level,
api_get_tide_series,
api_get_extremes_info,
api_check_tide_alert,
api_compare_stations,
api_health_check
)
def create_ui(prediction_handler, chatbot_handler):
"""Gradio UI를 생성하고 반환합니다."""
with gr.Blocks(title="통합 조위 예측 시스템", theme=gr.themes.Soft()) as demo:
gr.Markdown("# 🌊 통합 조위 예측 시스템 with Gemini")
# 연결 상태 표시
client = get_supabase_client()
supabase_status = "🟢 연결됨" if client else "🔴 연결 안됨 (환경변수 확인 필요)"
gemini_status = "🟢 연결됨" if os.getenv("GEMINI_API_KEY") else "🔴 연결 안됨 (환경변수 확인 필요)"
gr.Markdown(f"**Supabase 상태**: {supabase_status} | **Gemini 상태**: {gemini_status}")
with gr.Tabs():
# 1. 예측 탭
with gr.TabItem("🔮 통합 조위 예측"):
gr.Markdown("""
### TimeXer 모델을 활용한 조위 예측
- 과거 기상 데이터를 업로드하여 미래 72시간 조위 예측
- 잔차 예측 + 조화 예측 = 최종 조위
""")
with gr.Row():
with gr.Column(scale=1):
station_id_input = gr.Dropdown(
choices=[(f"{STATION_NAMES[s]} ({s})", s) for s in STATIONS],
label="관측소 선택",
value="DT_0001"
)
input_csv = gr.File(label="과거 데이터 업로드 (.csv)")
predict_btn = gr.Button("🚀 예측 실행", variant="primary")
with gr.Column(scale=3):
output_plot = gr.Plot(label="예측 결과 시각화")
output_df = gr.DataFrame(label="예측 결과 데이터")
output_log = gr.Textbox(label="실행 로그", lines=5, interactive=False)
# 2. 챗봇 탭
with gr.TabItem("💬 AI 조위 챗봇"):
gr.ChatInterface(
fn=chatbot_handler,
title="",
description="조위에 대해 궁금한 점을 물어보세요.",
# examples=[
# "인천 현재 조위 알려줘",
# "오늘 만조 시간은?"
# ]
)
# 3. API 탭 (새로 추가)
with gr.TabItem("🔌 API"):
gr.Markdown("""
## RESTful API 엔드포인트
실무에서 바로 사용 가능한 API 기능을 제공합니다.
""")
with gr.Tabs():
# 3-1. 현재 조위
with gr.TabItem("현재 조위"):
with gr.Row():
with gr.Column():
gr.Markdown("### 특정 시간 조위 조회")
api1_station = gr.Dropdown(
choices=[(f"{STATION_NAMES[s]} ({s})", s) for s in STATIONS],
label="관측소",
value="DT_0001"
)
api1_time = gr.Textbox(
label="조회 시간 (비워두면 현재)",
placeholder="2024-12-25T15:00:00"
)
api1_fallback = gr.Checkbox(
label="조화 예측 폴백 사용",
value=True
)
api1_btn = gr.Button("조회")
with gr.Column():
api1_output = gr.JSON(label="API 응답")
api1_btn.click(
fn=lambda s, t, f: api_get_tide_level(s, t if t else None, f),
inputs=[api1_station, api1_time, api1_fallback],
outputs=api1_output,
api_name="tide_level"
)
# 3-2. 시계열 데이터
with gr.TabItem("시계열"):
with gr.Row():
with gr.Column():
gr.Markdown("### 시간대별 조위 데이터")
api2_station = gr.Dropdown(
choices=[(f"{STATION_NAMES[s]} ({s})", s) for s in STATIONS],
label="관측소",
value="DT_0001"
)
api2_start = gr.Textbox(
label="시작 시간",
placeholder="2024-12-25T00:00:00"
)
api2_end = gr.Textbox(
label="종료 시간",
placeholder="2024-12-26T00:00:00"
)
api2_interval = gr.Number(
label="간격(분)",
value=60,
minimum=5,
maximum=360
)
api2_btn = gr.Button("조회")
with gr.Column():
api2_output = gr.JSON(label="API 응답 (공공 API 형식)")
api2_btn.click(
fn=lambda s, st, et, i: api_get_tide_series(
s, st if st else None, et if et else None, int(i)
),
inputs=[api2_station, api2_start, api2_end, api2_interval],
outputs=api2_output,
api_name="tide_series"
)
# 3-3. 만조/간조
with gr.TabItem("만조/간조"):
with gr.Row():
with gr.Column():
gr.Markdown("### 만조/간조 정보")
api3_station = gr.Dropdown(
choices=[(f"{STATION_NAMES[s]} ({s})", s) for s in STATIONS],
label="관측소",
value="DT_0001"
)
api3_date = gr.Textbox(
label="날짜 (YYYY-MM-DD)",
placeholder=datetime.now().strftime("%Y-%m-%d")
)
api3_secondary = gr.Checkbox(
label="부차 만조/간조 포함",
value=False
)
api3_btn = gr.Button("조회")
with gr.Column():
api3_output = gr.JSON(label="만조/간조 정보")
api3_btn.click(
fn=lambda s, d, sec: api_get_extremes_info(
s, d if d else None, sec
),
inputs=[api3_station, api3_date, api3_secondary],
outputs=api3_output,
api_name="extremes"
)
# 3-4. 위험 수위
with gr.TabItem("위험 알림"):
with gr.Row():
with gr.Column():
gr.Markdown("### 위험 수위 체크")
api4_station = gr.Dropdown(
choices=[(f"{STATION_NAMES[s]} ({s})", s) for s in STATIONS],
label="관측소",
value="DT_0001"
)
api4_hours = gr.Number(
label="확인 시간(시간)",
value=24,
minimum=1,
maximum=72
)
api4_warning = gr.Number(
label="주의 수위(cm)",
value=700
)
api4_danger = gr.Number(
label="경고 수위(cm)",
value=750
)
api4_btn = gr.Button("체크")
with gr.Column():
api4_output = gr.JSON(label="위험 수위 정보")
api4_btn.click(
fn=lambda s, h, w, d: api_check_tide_alert(s, int(h), w, d),
inputs=[api4_station, api4_hours, api4_warning, api4_danger],
outputs=api4_output,
api_name="alert"
)
# 3-5. 관측소 비교
with gr.TabItem("비교"):
with gr.Row():
with gr.Column():
gr.Markdown("### 다중 관측소 비교")
api5_stations = gr.CheckboxGroup(
choices=[(f"{STATION_NAMES[s]}", s) for s in STATIONS],
label="비교할 관측소 선택",
value=["DT_0001", "DT_0002", "DT_0003"]
)
api5_time = gr.Textbox(
label="비교 시간 (비워두면 현재)",
placeholder="2024-12-25T15:00:00"
)
api5_btn = gr.Button("비교")
with gr.Column():
api5_output = gr.JSON(label="비교 결과")
api5_btn.click(
fn=lambda s, t: api_compare_stations(s, t if t else None),
inputs=[api5_stations, api5_time],
outputs=api5_output,
api_name="compare"
)
# 3-6. 상태 체크
with gr.TabItem("상태"):
gr.Markdown("### API 및 시스템 상태")
api6_btn = gr.Button("🔍 상태 확인", variant="secondary")
api6_output = gr.JSON(label="시스템 상태")
api6_btn.click(
fn=api_health_check,
inputs=[],
outputs=api6_output,
api_name="health"
)
# API 사용 안내
gr.Markdown("""
---
### 📚 API 사용 안내
**Python 예제:**
```python
from gradio_client import Client
client = Client("https://your-space.hf.space/")
# 현재 조위 조회
result = client.predict(
"DT_0001", # station_id
"", # time (empty = current)
True, # use_fallback
api_name="/tide_level"
)
```
**특징:**
- 🔄 **조화 예측 폴백**: 최종 예측이 없을 때 자동으로 조화 예측 사용
- 📊 **공공 API 호환**: 기상청 API와 유사한 응답 형식
- ⚠️ **위험 수위 알림**: 2단계 경보 시스템
- 🏢 **다중 관측소**: 여러 관측소 동시 비교
""")
# 이벤트 핸들러 연결
predict_btn.click(
fn=prediction_handler,
inputs=[station_id_input, input_csv],
outputs=[output_plot, output_df, output_log],
api_name="predict"
)
return demo