File size: 10,741 Bytes
9db4c9b
 
 
 
 
4fb7e13
 
9db4c9b
4fb7e13
9db4c9b
4fb7e13
 
 
 
9db4c9b
 
 
 
4fb7e13
9db4c9b
 
 
 
4fb7e13
9db4c9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea8be35
4fb7e13
 
 
 
 
9db4c9b
ea8be35
 
9db4c9b
 
ea8be35
9db4c9b
ea8be35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9db4c9b
ea8be35
 
 
 
 
 
 
 
 
 
 
 
9db4c9b
 
 
ea8be35
 
 
 
 
9db4c9b
ea8be35
 
 
 
 
9db4c9b
 
 
 
ea8be35
9db4c9b
 
ea8be35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9db4c9b
ea8be35
 
 
 
 
 
9db4c9b
ea8be35
 
9db4c9b
ea8be35
4fb7e13
 
9db4c9b
 
 
4fb7e13
 
9db4c9b
4fb7e13
 
 
9db4c9b
 
 
ea8be35
4fb7e13
ea8be35
 
 
 
9db4c9b
ea8be35
 
 
 
4fb7e13
9db4c9b
 
 
 
 
 
 
ea8be35
9db4c9b
ea8be35
9db4c9b
 
ea8be35
 
 
 
9db4c9b
 
ea8be35
9db4c9b
 
 
 
ea8be35
9db4c9b
 
ea8be35
 
9db4c9b
 
 
ea8be35
 
9db4c9b
 
 
ea8be35
9db4c9b
 
 
ea8be35
 
 
 
9db4c9b
ea8be35
9db4c9b
ea8be35
 
 
9db4c9b
 
 
ea8be35
 
 
 
 
 
 
 
9db4c9b
 
ea8be35
9db4c9b
ea8be35
9db4c9b
ea8be35
9db4c9b
 
 
 
 
ea8be35
 
 
9db4c9b
ea8be35
 
9db4c9b
 
4fb7e13
ea8be35
4fb7e13
9db4c9b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
# -------- 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):
    """Half-sine โ€˜towerโ€™ with zero bottom floor."""
    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):
    """Return (Plotly figure, summary string) for the requested year range."""
    xs = np.linspace(start, end, max(1000, (end - start) * 4))
    fig = go.Figure()

    # โ—ผ 1) Draw gradient half-sine โ€˜towersโ€™ (30 layers each, like old matplotlib version)
    for period in ORDERED_PERIODS:
        base_amp = AMPL[period]
        color    = COLOR[period]

        # โ”€โ”€ gradient layers (thin, semi-transparent) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        for frac in np.linspace(base_amp / 30, base_amp, 30):
            ys = half_sine(xs, period, frac)
            fig.add_trace(go.Scatter(
                x = xs,
                y = ys,
                mode = "lines",
                line = dict(color=color, width=0.8),
                opacity = 0.6,
                hoverinfo = "skip",
                showlegend = False
            ))

        # โ”€โ”€ outer edge line (slightly thicker) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
        ys = half_sine(xs, period, base_amp)
        fig.add_trace(go.Scatter(
            x = xs,
            y = ys,
            mode = "lines",
            line = dict(color=color, width=1.6),
            hoverinfo = "skip",
            showlegend = False
        ))

    # โ—ผ 2) Event markers with bilingual hover text โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
    for year, evs in EVENTS.items():
        if start <= year <= end:
            cycle_name = evs[0]["cycle"]
            period     = PERIOD_BY_CYCLE.get(cycle_name, 50)
            y_val      = float(half_sine(np.array([year]), period, AMPL[period]))
            txt_en     = "<br>".join(e["event_en"] for e in evs)
            txt_ko     = "<br>".join(e["event_ko"] for e in evs)

            fig.add_trace(go.Scatter(
                x = [year], y = [y_val],
                mode = "markers",
                marker = dict(color="white", size=6),
                customdata = [[cycle_name, txt_en, txt_ko]],
                hovertemplate = (
                    "Year %{x} โ€ข %{customdata[0]} cycle"
                    "<br>%{customdata[1]}"
                    "<br>%{customdata[2]}<extra></extra>"
                ),
                showlegend = False
            ))

    # โ—ผ 3) Cosmetic touches: centre line, 250-yr arrow, background, axes โ”€โ”€โ”€โ”€
    # centre alignment marker
    fig.add_vline(
        x = CENTER,
        line_dash = "dash",
        line_color = "white",
        opacity = 0.6
    )

    # 250-year span arrow (โ†”) across the top of chart
    arrow_y = AMPL[250] * 1.05
    fig.add_annotation(
        x = CENTER - 125, y = arrow_y,
        ax = CENTER + 125, ay = arrow_y,
        xref = "x", yref = "y", axref = "x", ayref = "y",
        showarrow = True,
        arrowhead = 3,
        arrowsize = 1,
        arrowwidth = 1.2,
        arrowcolor = "white"
    )
    fig.add_annotation(
        x = CENTER, y = arrow_y + 0.15,
        text = "250 yr",
        showarrow = False,
        font = dict(color="white", size=10)
    )

    # global styling
    fig.update_layout(
        template = "plotly_dark",
        paper_bgcolor = "black",
        plot_bgcolor  = "black",
        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], showgrid=False)
    fig.update_yaxes(title="Relative amplitude", showticklabels=False, showgrid=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:
        # โ”€โ”€ Title & subtitle
        gr.Markdown("## ๐Ÿ”ญ **CycleNavigator (Interactive)**")
        gr.Markdown("### <sub>Interactive visual service delivering insights at a glance into the four major long cyclesโ€”9-year business cycle, 50-year Kondratiev wave, 80-year financial credit cycle, and 250-year hegemony cycleโ€”through dynamic charts and AI chat.</sub>")        
        gr.Markdown(
            "<sub>"
            "<b>Business 9y</b> (credit-investment business cycle) โ€ข "
            "<b>K-Wave 50y</b> (long technological-industrial wave) โ€ข "
            "<b>Finance 80y</b> (long credit-debt cycle) โ€ข "
            "<b>Hegemony 250y</b> (rise & fall of global powers cycle)"
            "</sub>"
        )
    

        chart_summary_state = gr.State(value="No chart yet.")

        with gr.Tabs():
            # โ”€โ”€ Tab 1: Timeline Chart โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
            with gr.TabItem("Timeline Chart"):
                with gr.Row():
                    start_year = gr.Number(label="Start Year", value=1500, precision=0)
                    end_year   = gr.Number(label="End Year",   value=2500, precision=0)
                    zoom_in  = gr.Button("๐Ÿ” Zoom In")
                    zoom_out = gr.Button("๐Ÿ”Ž Zoom Out")

                # initial plot
                fig0, summ0 = build_chart(1500, 2500)
                plot = gr.Plot(value=fig0)
                chart_summary_state.value = summ0

                # refresh on year change
                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])

                # zoom helpers
                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])

                # JSON download
                gr.File(value=str(EVENTS_PATH), label="Download cycle_events.json")

            # โ”€โ”€ Tab 2: GPT Chat โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
            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()