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|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# -------- app_final.py --------
|
2 |
+
import os, json, math, pathlib
|
3 |
+
import numpy as np
|
4 |
+
import plotly.graph_objects as go
|
5 |
+
import gradio as gr
|
6 |
+
import openai
|
7 |
+
|
8 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
9 |
+
# 0. OpenAI API key
|
10 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
11 |
+
if "OPENAI_API_KEY" not in os.environ:
|
12 |
+
os.environ["OPENAI_API_KEY"] = input("๐ Enter your OpenAI API key: ").strip()
|
13 |
+
openai.api_key = os.environ["OPENAI_API_KEY"]
|
14 |
+
|
15 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
16 |
+
# 1. Cycle config
|
17 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
18 |
+
CENTER = 2025
|
19 |
+
CYCLES = {
|
20 |
+
"K-Wave": 50, # Kondratiev long wave
|
21 |
+
"Business": 9, # Juglar investment cycle
|
22 |
+
"Finance": 80, # Long credit cycle
|
23 |
+
"Hegemony": 250 # Power-shift cycle
|
24 |
+
}
|
25 |
+
ORDERED_PERIODS = sorted(CYCLES.values()) # [9, 50, 80, 250]
|
26 |
+
COLOR = {9:"#66ff66", 50:"#ff3333", 80:"#ffcc00", 250:"#66ccff"}
|
27 |
+
AMPL = {9:0.6, 50:1.0, 80:1.6, 250:4.0}
|
28 |
+
PERIOD_BY_CYCLE = {k:v for k,v in CYCLES.items()}
|
29 |
+
|
30 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
31 |
+
# 2. Load events JSON
|
32 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
33 |
+
EVENTS_PATH = pathlib.Path(__file__).with_name("cycle_events.json")
|
34 |
+
with open(EVENTS_PATH, encoding="utf-8") as f:
|
35 |
+
EVENTS = {int(item["year"]): item["events"] for item in json.load(f)}
|
36 |
+
|
37 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
38 |
+
# 3. Helper functions
|
39 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
40 |
+
def half_sine(xs, period, amp):
|
41 |
+
"""Half-sine โtowerโ with zero bottom floor."""
|
42 |
+
phase = np.mod(xs - CENTER, period)
|
43 |
+
y = amp * np.sin(np.pi * phase / period)
|
44 |
+
y[y < 0] = 0
|
45 |
+
return y
|
46 |
+
|
47 |
+
def build_chart(start: int, end: int):
|
48 |
+
"""Return (Plotly figure, summary string) for the requested year range."""
|
49 |
+
xs = np.linspace(start, end, max(1000, (end - start) * 4))
|
50 |
+
fig = go.Figure()
|
51 |
+
|
52 |
+
# โผ 1) Draw gradient half-sine โtowersโ (30 layers each, like old matplotlib version)
|
53 |
+
for period in ORDERED_PERIODS:
|
54 |
+
base_amp = AMPL[period]
|
55 |
+
color = COLOR[period]
|
56 |
+
|
57 |
+
# โโ gradient layers (thin, semi-transparent) โโโโโโโโโโโโโโโโโโโโโโ
|
58 |
+
for frac in np.linspace(base_amp / 30, base_amp, 30):
|
59 |
+
ys = half_sine(xs, period, frac)
|
60 |
+
fig.add_trace(go.Scatter(
|
61 |
+
x = xs,
|
62 |
+
y = ys,
|
63 |
+
mode = "lines",
|
64 |
+
line = dict(color=color, width=0.8),
|
65 |
+
opacity = 0.6,
|
66 |
+
hoverinfo = "skip",
|
67 |
+
showlegend = False
|
68 |
+
))
|
69 |
+
|
70 |
+
# โโ outer edge line (slightly thicker) โโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
71 |
+
ys = half_sine(xs, period, base_amp)
|
72 |
+
fig.add_trace(go.Scatter(
|
73 |
+
x = xs,
|
74 |
+
y = ys,
|
75 |
+
mode = "lines",
|
76 |
+
line = dict(color=color, width=1.6),
|
77 |
+
hoverinfo = "skip",
|
78 |
+
showlegend = False
|
79 |
+
))
|
80 |
+
|
81 |
+
# โผ 2) Event markers with bilingual hover text โโโโโโโโโโโโโโโโโโโโโโโโโ
|
82 |
+
for year, evs in EVENTS.items():
|
83 |
+
if start <= year <= end:
|
84 |
+
cycle_name = evs[0]["cycle"]
|
85 |
+
period = PERIOD_BY_CYCLE.get(cycle_name, 50)
|
86 |
+
y_val = float(half_sine(np.array([year]), period, AMPL[period]))
|
87 |
+
txt_en = "<br>".join(e["event_en"] for e in evs)
|
88 |
+
txt_ko = "<br>".join(e["event_ko"] for e in evs)
|
89 |
+
|
90 |
+
fig.add_trace(go.Scatter(
|
91 |
+
x = [year], y = [y_val],
|
92 |
+
mode = "markers",
|
93 |
+
marker = dict(color="white", size=6),
|
94 |
+
customdata = [[cycle_name, txt_en, txt_ko]],
|
95 |
+
hovertemplate = (
|
96 |
+
"Year %{x} โข %{customdata[0]} cycle"
|
97 |
+
"<br>%{customdata[1]}"
|
98 |
+
"<br>%{customdata[2]}<extra></extra>"
|
99 |
+
),
|
100 |
+
showlegend = False
|
101 |
+
))
|
102 |
+
|
103 |
+
# โผ 3) Cosmetic touches: centre line, 250-yr arrow, background, axes โโโโ
|
104 |
+
# centre alignment marker
|
105 |
+
fig.add_vline(
|
106 |
+
x = CENTER,
|
107 |
+
line_dash = "dash",
|
108 |
+
line_color = "white",
|
109 |
+
opacity = 0.6
|
110 |
+
)
|
111 |
+
|
112 |
+
# 250-year span arrow (โ) across the top of chart
|
113 |
+
arrow_y = AMPL[250] * 1.05
|
114 |
+
fig.add_annotation(
|
115 |
+
x = CENTER - 125, y = arrow_y,
|
116 |
+
ax = CENTER + 125, ay = arrow_y,
|
117 |
+
xref = "x", yref = "y", axref = "x", ayref = "y",
|
118 |
+
showarrow = True,
|
119 |
+
arrowhead = 3,
|
120 |
+
arrowsize = 1,
|
121 |
+
arrowwidth = 1.2,
|
122 |
+
arrowcolor = "white"
|
123 |
+
)
|
124 |
+
fig.add_annotation(
|
125 |
+
x = CENTER, y = arrow_y + 0.15,
|
126 |
+
text = "250 yr",
|
127 |
+
showarrow = False,
|
128 |
+
font = dict(color="white", size=10)
|
129 |
+
)
|
130 |
+
|
131 |
+
# global styling
|
132 |
+
fig.update_layout(
|
133 |
+
template = "plotly_dark",
|
134 |
+
paper_bgcolor = "black",
|
135 |
+
plot_bgcolor = "black",
|
136 |
+
height = 450,
|
137 |
+
margin = dict(t=30, l=40, r=40, b=40),
|
138 |
+
hoverlabel = dict(bgcolor="#222", font_size=11)
|
139 |
+
)
|
140 |
+
fig.update_xaxes(title="Year", range=[start, end], showgrid=False)
|
141 |
+
fig.update_yaxes(title="Relative amplitude", showticklabels=False, showgrid=False)
|
142 |
+
|
143 |
+
summary = f"Range {start}-{end} | Events plotted: {sum(1 for y in EVENTS if start <= y <= end)}"
|
144 |
+
return fig, summary
|
145 |
+
|
146 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
147 |
+
# 4. GPT chat helper
|
148 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
149 |
+
BASE_PROMPT = (
|
150 |
+
"You are a concise and accurate Korean assistant. "
|
151 |
+
"If a chart summary is provided, incorporate it in your answer."
|
152 |
+
)
|
153 |
+
|
154 |
+
def chat_with_gpt(history, user_msg, chart_summary):
|
155 |
+
messages = [{"role": "system", "content": BASE_PROMPT}]
|
156 |
+
if chart_summary not in ("", "No chart yet."):
|
157 |
+
messages.append({"role": "system", "content": f"[Chart summary]\n{chart_summary}"})
|
158 |
+
|
159 |
+
for u, a in history:
|
160 |
+
messages.extend([{"role": "user", "content": u},
|
161 |
+
{"role": "assistant", "content": a}])
|
162 |
+
messages.append({"role": "user", "content": user_msg})
|
163 |
+
|
164 |
+
res = openai.chat.completions.create(
|
165 |
+
model = "gpt-3.5-turbo",
|
166 |
+
messages = messages,
|
167 |
+
max_tokens = 600,
|
168 |
+
temperature = 0.7
|
169 |
+
)
|
170 |
+
return res.choices[0].message.content.strip()
|
171 |
+
|
172 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
173 |
+
# 5. Gradio UI
|
174 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
175 |
+
def create_app():
|
176 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
177 |
+
# โโ Title & subtitle
|
178 |
+
gr.Markdown("## ๐ญ **CycleNavigator (Interactive)**")
|
179 |
+
gr.Markdown(
|
180 |
+
"<sub>"
|
181 |
+
"K-Wave 50y โข Business 9y โข Finance 80y โข Hegemony 250y"
|
182 |
+
"</sub>"
|
183 |
+
)
|
184 |
+
|
185 |
+
chart_summary_state = gr.State(value="No chart yet.")
|
186 |
+
|
187 |
+
with gr.Tabs():
|
188 |
+
# โโ Tab 1: Timeline Chart โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
189 |
+
with gr.TabItem("Timeline Chart"):
|
190 |
+
with gr.Row():
|
191 |
+
start_year = gr.Number(label="Start Year", value=1500, precision=0)
|
192 |
+
end_year = gr.Number(label="End Year", value=2500, precision=0)
|
193 |
+
zoom_in = gr.Button("๐ Zoom In")
|
194 |
+
zoom_out = gr.Button("๐ Zoom Out")
|
195 |
+
|
196 |
+
# initial plot
|
197 |
+
fig0, summ0 = build_chart(1500, 2500)
|
198 |
+
plot = gr.Plot(value=fig0)
|
199 |
+
chart_summary_state.value = summ0
|
200 |
+
|
201 |
+
# refresh on year change
|
202 |
+
def refresh(s, e):
|
203 |
+
fig, summ = build_chart(int(s), int(e))
|
204 |
+
return fig, summ
|
205 |
+
start_year.change(refresh, [start_year, end_year],
|
206 |
+
[plot, chart_summary_state])
|
207 |
+
end_year.change(refresh, [start_year, end_year],
|
208 |
+
[plot, chart_summary_state])
|
209 |
+
|
210 |
+
# zoom helpers
|
211 |
+
def zoom(s, e, factor):
|
212 |
+
mid = (s + e) / 2
|
213 |
+
span = (e - s) * factor / 2
|
214 |
+
ns, ne = int(mid - span), int(mid + span)
|
215 |
+
fig, summ = build_chart(ns, ne)
|
216 |
+
return ns, ne, fig, summ
|
217 |
+
|
218 |
+
zoom_in.click(lambda s, e: zoom(s, e, 0.5),
|
219 |
+
inputs = [start_year, end_year],
|
220 |
+
outputs = [start_year, end_year, plot, chart_summary_state])
|
221 |
+
zoom_out.click(lambda s, e: zoom(s, e, 2.0),
|
222 |
+
inputs = [start_year, end_year],
|
223 |
+
outputs = [start_year, end_year, plot, chart_summary_state])
|
224 |
+
|
225 |
+
# JSON download
|
226 |
+
gr.File(value=str(EVENTS_PATH), label="Download cycle_events.json")
|
227 |
+
|
228 |
+
# โโ Tab 2: GPT Chat โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
229 |
+
with gr.TabItem("GPT Chat"):
|
230 |
+
chatbot = gr.Chatbot(label="Assistant")
|
231 |
+
user_input = gr.Textbox(lines=3, placeholder="๋ฉ์์ง๋ฅผ ์
๋ ฅํ์ธ์โฆ")
|
232 |
+
send_btn = gr.Button("Send")
|
233 |
+
|
234 |
+
def respond(history, msg, summ):
|
235 |
+
reply = chat_with_gpt(history, msg, summ)
|
236 |
+
history.append((msg, reply))
|
237 |
+
return history, gr.Textbox(value="")
|
238 |
+
|
239 |
+
send_btn.click(respond,
|
240 |
+
[chatbot, user_input, chart_summary_state],
|
241 |
+
[chatbot, user_input])
|
242 |
+
user_input.submit(respond,
|
243 |
+
[chatbot, user_input, chart_summary_state],
|
244 |
+
[chatbot, user_input])
|
245 |
+
return demo
|
246 |
+
|
247 |
+
|
248 |
+
if __name__ == "__main__":
|
249 |
+
create_app().launch()
|