Spaces:
Running
Running
Delete app-backup2.py
Browse files- app-backup2.py +0 -254
app-backup2.py
DELETED
@@ -1,254 +0,0 @@
|
|
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("### <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>")
|
180 |
-
gr.Markdown(
|
181 |
-
"<sub>"
|
182 |
-
"<b>Business 9y</b> (credit-investment business cycle) โข "
|
183 |
-
"<b>K-Wave 50y</b> (long technological-industrial wave) โข "
|
184 |
-
"<b>Finance 80y</b> (long credit-debt cycle) โข "
|
185 |
-
"<b>Hegemony 250y</b> (rise & fall of global powers cycle)"
|
186 |
-
"</sub>"
|
187 |
-
)
|
188 |
-
|
189 |
-
|
190 |
-
chart_summary_state = gr.State(value="No chart yet.")
|
191 |
-
|
192 |
-
with gr.Tabs():
|
193 |
-
# โโ Tab 1: Timeline Chart โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
194 |
-
with gr.TabItem("Timeline Chart"):
|
195 |
-
with gr.Row():
|
196 |
-
start_year = gr.Number(label="Start Year", value=1500, precision=0)
|
197 |
-
end_year = gr.Number(label="End Year", value=2500, precision=0)
|
198 |
-
zoom_in = gr.Button("๐ Zoom In")
|
199 |
-
zoom_out = gr.Button("๐ Zoom Out")
|
200 |
-
|
201 |
-
# initial plot
|
202 |
-
fig0, summ0 = build_chart(1500, 2500)
|
203 |
-
plot = gr.Plot(value=fig0)
|
204 |
-
chart_summary_state.value = summ0
|
205 |
-
|
206 |
-
# refresh on year change
|
207 |
-
def refresh(s, e):
|
208 |
-
fig, summ = build_chart(int(s), int(e))
|
209 |
-
return fig, summ
|
210 |
-
start_year.change(refresh, [start_year, end_year],
|
211 |
-
[plot, chart_summary_state])
|
212 |
-
end_year.change(refresh, [start_year, end_year],
|
213 |
-
[plot, chart_summary_state])
|
214 |
-
|
215 |
-
# zoom helpers
|
216 |
-
def zoom(s, e, factor):
|
217 |
-
mid = (s + e) / 2
|
218 |
-
span = (e - s) * factor / 2
|
219 |
-
ns, ne = int(mid - span), int(mid + span)
|
220 |
-
fig, summ = build_chart(ns, ne)
|
221 |
-
return ns, ne, fig, summ
|
222 |
-
|
223 |
-
zoom_in.click(lambda s, e: zoom(s, e, 0.5),
|
224 |
-
inputs = [start_year, end_year],
|
225 |
-
outputs = [start_year, end_year, plot, chart_summary_state])
|
226 |
-
zoom_out.click(lambda s, e: zoom(s, e, 2.0),
|
227 |
-
inputs = [start_year, end_year],
|
228 |
-
outputs = [start_year, end_year, plot, chart_summary_state])
|
229 |
-
|
230 |
-
# JSON download
|
231 |
-
gr.File(value=str(EVENTS_PATH), label="Download cycle_events.json")
|
232 |
-
|
233 |
-
# โโ Tab 2: GPT Chat โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
234 |
-
with gr.TabItem("GPT Chat"):
|
235 |
-
chatbot = gr.Chatbot(label="Assistant")
|
236 |
-
user_input = gr.Textbox(lines=3, placeholder="๋ฉ์์ง๋ฅผ ์
๋ ฅํ์ธ์โฆ")
|
237 |
-
send_btn = gr.Button("Send")
|
238 |
-
|
239 |
-
def respond(history, msg, summ):
|
240 |
-
reply = chat_with_gpt(history, msg, summ)
|
241 |
-
history.append((msg, reply))
|
242 |
-
return history, gr.Textbox(value="")
|
243 |
-
|
244 |
-
send_btn.click(respond,
|
245 |
-
[chatbot, user_input, chart_summary_state],
|
246 |
-
[chatbot, user_input])
|
247 |
-
user_input.submit(respond,
|
248 |
-
[chatbot, user_input, chart_summary_state],
|
249 |
-
[chatbot, user_input])
|
250 |
-
return demo
|
251 |
-
|
252 |
-
|
253 |
-
if __name__ == "__main__":
|
254 |
-
create_app().launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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