# -------- app_final.py -------- import os, json, math, pathlib import numpy as np import plotly.graph_objects as go import gradio as gr import openai # ────────────────────────── # 0. OpenAI API key # ────────────────────────── if "OPENAI_API_KEY" not in os.environ: os.environ["OPENAI_API_KEY"] = input("🔑 Enter your OpenAI API key: ").strip() openai.api_key = os.environ["OPENAI_API_KEY"] # ────────────────────────── # 1. Cycle config # ────────────────────────── CENTER = 2025 CYCLES = { "K-Wave": 50, # Kondratiev long wave "Business": 9, # Juglar investment cycle "Finance": 80, # Long credit cycle "Hegemony": 250 # Power-shift cycle } ORDERED_PERIODS = sorted(CYCLES.values()) # [9, 50, 80, 250] COLOR = {9:"#66ff66", 50:"#ff3333", 80:"#ffcc00", 250:"#66ccff"} AMPL = {9:0.6, 50:1.0, 80:1.6, 250:4.0} PERIOD_BY_CYCLE = {k:v for k,v in CYCLES.items()} # ────────────────────────── # 2. Load events JSON # ────────────────────────── EVENTS_PATH = pathlib.Path(__file__).with_name("cycle_events.json") with open(EVENTS_PATH, encoding="utf-8") as f: EVENTS = {int(item["year"]): item["events"] for item in json.load(f)} # ────────────────────────── # 3. Helper functions # ────────────────────────── def half_sine(xs, period, amp): phase = np.mod(xs - CENTER, period) y = amp * np.sin(np.pi * phase / period) y[y < 0] = 0 return y def build_chart(start: int, end: int): xs = np.linspace(start, end, max(1000, (end-start)*4)) fig = go.Figure() # draw half-sine “towers” for period in ORDERED_PERIODS: ys = half_sine(xs, period, AMPL[period]) fig.add_trace(go.Scatter( x=xs, y=ys, mode="lines", line=dict(color=COLOR[period], width=1), hoverinfo="skip", showlegend=False)) # annotate events with hover for year, evs in EVENTS.items(): if start <= year <= end: cycle_name = evs[0]["cycle"] period = PERIOD_BY_CYCLE.get(cycle_name, 50) y = float(half_sine(np.array([year]), period, AMPL[period])) txt_en = "
".join(e["event_en"] for e in evs) txt_ko = "
".join(e["event_ko"] for e in evs) fig.add_trace(go.Scatter( x=[year], y=[y], mode="markers", marker=dict(color="white", size=6), customdata=[[cycle_name, txt_en, txt_ko]], hovertemplate=( "Year %{x} • %{customdata[0]} cycle" "
%{customdata[1]}" "
%{customdata[2]}" ), showlegend=False )) # styling fig.update_layout( template="plotly_dark", height=450, margin=dict(t=30, l=40, r=40, b=40), hoverlabel=dict(bgcolor="#222", font_size=11) ) fig.update_xaxes(title="Year", range=[start, end]) fig.update_yaxes(title="Relative amplitude", showticklabels=False) summary = f"Range {start}-{end} | Events plotted: {sum(1 for y in EVENTS if start<=y<=end)}" return fig, summary # ────────────────────────── # 4. GPT chat helper # ────────────────────────── BASE_PROMPT = ( "You are a concise and accurate Korean assistant. " "If a chart summary is provided, incorporate it in your answer." ) def chat_with_gpt(history, user_msg, chart_summary): messages = [{"role": "system", "content": BASE_PROMPT}] if chart_summary not in ("", "No chart yet."): messages.append({"role": "system", "content": f"[Chart summary]\n{chart_summary}"}) for u, a in history: messages.extend([{"role":"user","content":u},{"role":"assistant","content":a}]) messages.append({"role":"user","content":user_msg}) res = openai.chat.completions.create( model="gpt-3.5-turbo", messages=messages, max_tokens=600, temperature=0.7 ) return res.choices[0].message.content.strip() # ────────────────────────── # 5. Gradio UI # ────────────────────────── def create_app(): with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("## 🔭 **CycleNavigator (Interactive)**") gr.Markdown( "" "K-Wave 50y • Business 9y • Finance 80y • Hegemony 250y" "" ) chart_summary_state = gr.State(value="No chart yet.") with gr.Tabs(): # ── Chart Tab ─────────────── with gr.TabItem("Timeline Chart"): with gr.Row(): start_year = gr.Number(label="Start Year", value=1775, precision=0) end_year = gr.Number(label="End Year", value=2025, precision=0) zoom_in = gr.Button("🔍 Zoom In") zoom_out = gr.Button("🔎 Zoom Out") fig0, summ0 = build_chart(1775, 2025) plot = gr.Plot(value=fig0) chart_summary_state.value = summ0 def refresh(s, e): fig, summ = build_chart(int(s), int(e)) return fig, summ start_year.change(refresh, [start_year, end_year], [plot, chart_summary_state]) end_year.change(refresh, [start_year, end_year], [plot, chart_summary_state]) def zoom(s, e, factor): mid = (s+e)/2 span = (e-s)*factor/2 ns, ne = int(mid-span), int(mid+span) fig, summ = build_chart(ns, ne) return ns, ne, fig, summ zoom_in.click(lambda s,e: zoom(s,e,0.5), inputs=[start_year,end_year], outputs=[start_year,end_year,plot,chart_summary_state]) zoom_out.click(lambda s,e: zoom(s,e,2.0), inputs=[start_year,end_year], outputs=[start_year,end_year,plot,chart_summary_state]) gr.File(value=str(EVENTS_PATH), label="Download cycle_events.json") # ── GPT Chat Tab ──────────── with gr.TabItem("GPT Chat"): chatbot = gr.Chatbot(label="Assistant") user_input = gr.Textbox(lines=3, placeholder="메시지를 입력하세요…") send_btn = gr.Button("Send") def respond(history, msg, summ): reply = chat_with_gpt(history, msg, summ) history.append((msg, reply)) return history, gr.Textbox(value="") send_btn.click(respond, [chatbot, user_input, chart_summary_state], [chatbot, user_input]) user_input.submit(respond, [chatbot, user_input, chart_summary_state], [chatbot, user_input]) return demo if __name__ == "__main__": create_app().launch()