Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,181 +1,195 @@
|
|
1 |
# -------- app_final.py --------
|
2 |
import os, json, math, pathlib, re, time, logging, requests
|
|
|
3 |
import numpy as np
|
|
|
4 |
import plotly.graph_objects as go
|
5 |
import gradio as gr
|
6 |
import openai
|
|
|
|
|
7 |
|
8 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
9 |
-
# 0. API keys & Brave Search
|
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 |
-
BRAVE_KEY = os.getenv("BRAVE_KEY", "")
|
16 |
BRAVE_ENDPOINT = "https://api.search.brave.com/res/v1/web/search"
|
17 |
logging.basicConfig(level=logging.INFO)
|
18 |
|
19 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
20 |
-
# 1. Cycle config
|
21 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
22 |
CENTER = 2025
|
23 |
-
CYCLES = {
|
24 |
-
|
25 |
-
"Business": 9, # Juglar investment cycle
|
26 |
-
"Finance": 80, # Long credit cycle
|
27 |
-
"Hegemony": 250 # Power-shift cycle
|
28 |
-
}
|
29 |
-
ORDERED_PERIODS = sorted(CYCLES.values()) # [9, 50, 80, 250]
|
30 |
COLOR = {9:"#66ff66", 50:"#ff3333", 80:"#ffcc00", 250:"#66ccff"}
|
31 |
-
AMPL = {9:0.6,
|
32 |
PERIOD_BY_CYCLE = {k:v for k,v in CYCLES.items()}
|
33 |
|
34 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
35 |
-
# 2. Load events JSON
|
36 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
37 |
EVENTS_PATH = pathlib.Path(__file__).with_name("cycle_events.json")
|
38 |
with open(EVENTS_PATH, encoding="utf-8") as f:
|
39 |
-
|
40 |
-
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
if not BRAVE_KEY:
|
47 |
-
logging.warning("โ ๏ธ BRAVE_KEY is empty; web search disabled.")
|
48 |
return []
|
|
|
|
|
|
|
|
|
49 |
try:
|
50 |
-
|
51 |
-
"Accept": "application/json",
|
52 |
-
"X-Subscription-Token": BRAVE_KEY
|
53 |
-
}
|
54 |
-
data = requests.get(
|
55 |
BRAVE_ENDPOINT,
|
56 |
-
headers=
|
57 |
-
params=
|
58 |
timeout=15
|
59 |
-
)
|
60 |
-
raw =
|
61 |
-
return [
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
}
|
68 |
-
for r in raw[:count]
|
69 |
-
]
|
70 |
except Exception as e:
|
71 |
-
logging.error(f"Brave
|
72 |
return []
|
73 |
|
74 |
def format_search_results(query: str) -> str:
|
75 |
-
|
76 |
-
|
77 |
-
if not arts:
|
78 |
return f"# [Web-Search] No live results for โ{query}โ.\n"
|
79 |
-
hdr = f"# [Web-Search] Top results for โ{query}
|
80 |
body = "\n".join(
|
81 |
-
f"**{
|
82 |
-
|
83 |
-
f"[Source]({a['url']})\n"
|
84 |
-
for i, a in enumerate(arts)
|
85 |
)
|
86 |
return hdr + body + "\n"
|
87 |
|
88 |
-
|
89 |
-
|
90 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
def half_sine(xs, period, amp):
|
92 |
-
"""Half-sine โtowerโ with zero bottom floor."""
|
93 |
phase = np.mod(xs - CENTER, period)
|
94 |
y = amp * np.sin(np.pi * phase / period)
|
95 |
y[y < 0] = 0
|
96 |
return y
|
97 |
|
98 |
-
def build_chart(start: int, end: int):
|
99 |
-
"""Return (Plotly figure, summary string) for the requested year range,
|
100 |
-
plus a transparent hover-trace so the cursor always shows โYear ####โ. """
|
101 |
xs = np.linspace(start, end, max(1000, (end - start) * 4))
|
102 |
fig = go.Figure()
|
103 |
|
104 |
-
#
|
105 |
for period in ORDERED_PERIODS:
|
106 |
-
|
107 |
-
for frac in np.linspace(
|
108 |
fig.add_trace(go.Scatter(
|
109 |
x=xs, y=half_sine(xs, period, frac),
|
110 |
-
mode="lines",
|
111 |
-
|
112 |
-
opacity=0.6,
|
113 |
-
hoverinfo="skip", showlegend=False))
|
114 |
fig.add_trace(go.Scatter(
|
115 |
-
x=xs, y=half_sine(xs, period,
|
116 |
-
mode="lines",
|
117 |
-
line=dict(color=color, width=1.6),
|
118 |
hoverinfo="skip", showlegend=False))
|
119 |
|
120 |
-
#
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
|
|
|
|
|
|
|
|
125 |
fig.add_trace(go.Scatter(
|
126 |
-
x=[
|
127 |
marker=dict(color="white", size=6),
|
128 |
-
customdata=[[cyc,
|
129 |
-
"<br>".join(e["event_en"] for e in evs),
|
130 |
-
"<br>".join(e["event_ko"] for e in evs)]],
|
131 |
hovertemplate=(
|
132 |
-
"Year %{x} โข %{customdata[0]}
|
133 |
-
"
|
134 |
-
"
|
135 |
),
|
136 |
showlegend=False))
|
137 |
|
138 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
139 |
fig.add_trace(go.Scatter(
|
140 |
-
x=xs,
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
showlegend=False))
|
146 |
-
|
147 |
-
# 4) Cosmetic touches: centre line & 250-yr arrow
|
148 |
fig.add_vline(x=CENTER, line_dash="dash", line_color="white", opacity=0.6)
|
149 |
arrow_y = AMPL[250] * 1.05
|
150 |
fig.add_annotation(
|
151 |
-
x=CENTER-125, y=arrow_y, ax=CENTER+125, ay=arrow_y,
|
152 |
xref="x", yref="y", axref="x", ayref="y",
|
153 |
showarrow=True, arrowhead=3, arrowsize=1,
|
154 |
arrowwidth=1.2, arrowcolor="white")
|
155 |
fig.add_annotation(
|
156 |
-
x=CENTER, y=arrow_y+0.15, text="250 yr",
|
157 |
showarrow=False, font=dict(color="white", size=10))
|
158 |
-
|
159 |
-
# 5) Layout
|
160 |
fig.update_layout(
|
161 |
template="plotly_dark",
|
162 |
paper_bgcolor="black", plot_bgcolor="black",
|
163 |
-
height=
|
164 |
-
margin=dict(t=30, l=40, r=40, b=40),
|
165 |
hoverlabel=dict(bgcolor="#222", font_size=11),
|
166 |
-
hovermode="x"
|
167 |
-
)
|
168 |
-
fig.
|
169 |
-
fig.update_yaxes(title="Relative amplitude",
|
170 |
-
showticklabels=False, showgrid=False)
|
171 |
|
172 |
-
summary = f"Range {start}-{end} | Events
|
173 |
-
f"{sum(1 for y in EVENTS if start <= y <= end)}"
|
174 |
return fig, summary
|
175 |
|
176 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
177 |
-
# 5. GPT chat helper
|
178 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
179 |
BASE_PROMPT = (
|
180 |
"๋น์ ์ **CycleNavigator AI**๋ก, ๊ฒฝ์ ์ฌยท๊ตญ์ ์ ์นยท์ฅ์ฃผ๊ธฐ(9y Business, 50y K-Wave, "
|
181 |
"80y Finance, 250y Hegemony) ๋ถ์์ ์ ํตํ ์ ๋ฌธ๊ฐ์
๋๋ค. "
|
@@ -189,106 +203,111 @@ BASE_PROMPT = (
|
|
189 |
"โฆ ๋ถํ์ํ ์ฅํฉํจ์ ์ผ๊ฐ๊ณ 3๊ฐ ๋จ๋ฝ ๋๋ 7๊ฐ ์ดํ bullets ๋ด๋ก ์์ฝํ์ญ์์ค."
|
190 |
)
|
191 |
|
192 |
-
def chat_with_gpt(
|
193 |
-
|
194 |
if chart_summary not in ("", "No chart yet."):
|
195 |
-
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
200 |
-
messages.append({"role": "user", "content": user_msg})
|
201 |
-
|
202 |
-
res = openai.chat.completions.create(
|
203 |
model="gpt-3.5-turbo",
|
204 |
-
messages=
|
205 |
max_tokens=600,
|
206 |
temperature=0.7
|
207 |
-
)
|
208 |
-
return res.choices[0].message.content.strip()
|
209 |
|
210 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
211 |
-
# 6. Gradio UI
|
212 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
213 |
def create_app():
|
214 |
-
with gr.Blocks(
|
215 |
-
|
|
|
|
|
|
|
|
|
|
|
216 |
gr.Markdown("## ๐ญ **CycleNavigator (Interactive)**")
|
217 |
-
|
218 |
-
|
219 |
-
|
220 |
-
|
221 |
-
"
|
222 |
-
"
|
223 |
-
"
|
224 |
-
|
225 |
-
"</sub>"
|
226 |
)
|
227 |
|
|
|
|
|
228 |
chart_summary_state = gr.State(value="No chart yet.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
229 |
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
|
234 |
-
|
235 |
-
chart_summary_state.value = summ0
|
236 |
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
-
end_year = gr.Number(label="End Year", value=2500, precision=0)
|
241 |
-
zoom_in = gr.Button("๐ Zoom In")
|
242 |
-
zoom_out = gr.Button("๐ Zoom Out")
|
243 |
-
|
244 |
-
|
245 |
-
|
246 |
-
def refresh(s, e):
|
247 |
-
fig, summ = build_chart(int(s), int(e))
|
248 |
-
return fig, summ
|
249 |
-
start_year.change(refresh, [start_year, end_year],
|
250 |
-
[plot, chart_summary_state])
|
251 |
-
end_year.change(refresh, [start_year, end_year],
|
252 |
-
[plot, chart_summary_state])
|
253 |
-
|
254 |
-
def zoom(s, e, factor):
|
255 |
-
mid = (s + e) / 2
|
256 |
-
span = (e - s) * factor / 2
|
257 |
-
ns, ne = int(mid - span), int(mid + span)
|
258 |
-
fig, summ = build_chart(ns, ne)
|
259 |
-
return ns, ne, fig, summ
|
260 |
-
|
261 |
-
zoom_in.click(lambda s, e: zoom(s, e, 0.5),
|
262 |
-
inputs=[start_year, end_year],
|
263 |
-
outputs=[start_year, end_year, plot, chart_summary_state])
|
264 |
-
zoom_out.click(lambda s, e: zoom(s, e, 2.0),
|
265 |
-
inputs=[start_year, end_year],
|
266 |
-
outputs=[start_year, end_year, plot, chart_summary_state])
|
267 |
-
|
268 |
-
gr.File(value=str(EVENTS_PATH), label="Download cycle_events.json")
|
269 |
-
|
270 |
-
# โโ Tab 2: GPT Chat โโ
|
271 |
with gr.TabItem("Deep Research Chat"):
|
272 |
chatbot = gr.Chatbot(label="Assistant")
|
273 |
user_input = gr.Textbox(lines=3, placeholder="๋ฉ์์ง๋ฅผ ์
๋ ฅํ์ธ์โฆ")
|
274 |
-
|
275 |
with gr.Row():
|
276 |
send_btn = gr.Button("Send", variant="primary")
|
277 |
-
web_btn = gr.Button("๐ Web Search")
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
|
282 |
-
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
reply = chat_with_gpt(history, combined, summ)
|
290 |
-
history.append((f"{msg}\n\n(์น๊ฒ์ ์คํ)", reply))
|
291 |
-
return history, gr.Textbox(value="")
|
292 |
|
293 |
send_btn.click(respond,
|
294 |
[chatbot, user_input, chart_summary_state],
|
@@ -296,20 +315,20 @@ def create_app():
|
|
296 |
user_input.submit(respond,
|
297 |
[chatbot, user_input, chart_summary_state],
|
298 |
[chatbot, user_input])
|
299 |
-
web_btn.click(
|
300 |
-
|
301 |
-
|
302 |
|
|
|
303 |
gr.HTML(
|
304 |
'<a href="https://discord.gg/openfreeai" target="_blank" id="discord-badge">'
|
305 |
'<img src="https://img.shields.io/static/v1?label=Discord&message=Openfree%20AI&'
|
306 |
'color=%230000ff&labelColor=%23800080&logo=discord&logoColor=white&style=for-the-badge"'
|
307 |
' alt="badge"></a>'
|
308 |
-
)
|
|
|
309 |
return demo
|
310 |
|
311 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
312 |
-
# 7. main
|
313 |
-
# โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
314 |
if __name__ == "__main__":
|
315 |
create_app().launch()
|
|
|
1 |
# -------- app_final.py --------
|
2 |
import os, json, math, pathlib, re, time, logging, requests
|
3 |
+
from datetime import datetime, timedelta
|
4 |
import numpy as np
|
5 |
+
import pandas as pd
|
6 |
import plotly.graph_objects as go
|
7 |
import gradio as gr
|
8 |
import openai
|
9 |
+
import torch
|
10 |
+
from sentence_transformers import SentenceTransformer, util
|
11 |
|
12 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ 0. API keys & Brave Search โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
|
|
|
13 |
if "OPENAI_API_KEY" not in os.environ:
|
14 |
os.environ["OPENAI_API_KEY"] = input("๐ Enter your OpenAI API key: ").strip()
|
15 |
openai.api_key = os.environ["OPENAI_API_KEY"]
|
16 |
|
17 |
+
BRAVE_KEY = os.getenv("BRAVE_KEY", "")
|
18 |
BRAVE_ENDPOINT = "https://api.search.brave.com/res/v1/web/search"
|
19 |
logging.basicConfig(level=logging.INFO)
|
20 |
|
21 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ 1. Cycle config โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
|
|
|
22 |
CENTER = 2025
|
23 |
+
CYCLES = { "K-Wave": 50, "Business": 9, "Finance": 80, "Hegemony": 250 }
|
24 |
+
ORDERED_PERIODS = sorted(CYCLES.values())
|
|
|
|
|
|
|
|
|
|
|
25 |
COLOR = {9:"#66ff66", 50:"#ff3333", 80:"#ffcc00", 250:"#66ccff"}
|
26 |
+
AMPL = {9:0.6, 50:1.0, 80:1.6, 250:4.0}
|
27 |
PERIOD_BY_CYCLE = {k:v for k,v in CYCLES.items()}
|
28 |
|
29 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ 2. Load events JSON & embeddings โโโโโโโโโโโโโโโโโโโ
|
|
|
|
|
30 |
EVENTS_PATH = pathlib.Path(__file__).with_name("cycle_events.json")
|
31 |
with open(EVENTS_PATH, encoding="utf-8") as f:
|
32 |
+
RAW_EVENTS = json.load(f)
|
33 |
+
EVENTS = {int(item["year"]): item["events"] for item in RAW_EVENTS}
|
34 |
+
|
35 |
+
logging.info("Embedding historical eventsโฆ")
|
36 |
+
_embed_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
37 |
+
_all_sentences = [(yr, ev["event_en"]) for yr, evs in EVENTS.items() for ev in evs]
|
38 |
+
_embeddings = _embed_model.encode([s for _, s in _all_sentences], convert_to_tensor=True)
|
39 |
+
|
40 |
+
# ์ ์ฌ ์ฌ๊ฑด top-3 year ์ฌ์
|
41 |
+
SIMILAR_MAP = {}
|
42 |
+
for idx, (yr, _) in enumerate(_all_sentences):
|
43 |
+
scores = util.cos_sim(_embeddings[idx], _embeddings)[0]
|
44 |
+
top_idx = torch.topk(scores, 4).indices.tolist()
|
45 |
+
sims = [_all_sentences[i][0] for i in top_idx if _all_sentences[i][0] != yr][:3]
|
46 |
+
SIMILAR_MAP.setdefault(yr, sims)
|
47 |
+
|
48 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ 3. Brave Search helpers โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
49 |
+
def brave_search(query: str, count: int = 8, freshness_days: int | None = None):
|
50 |
if not BRAVE_KEY:
|
|
|
51 |
return []
|
52 |
+
params = {"q": query, "count": str(count)}
|
53 |
+
if freshness_days:
|
54 |
+
dt_from = (datetime.utcnow() - timedelta(days=freshness_days)).strftime("%Y-%m-%d")
|
55 |
+
params["freshness"] = dt_from
|
56 |
try:
|
57 |
+
r = requests.get(
|
|
|
|
|
|
|
|
|
58 |
BRAVE_ENDPOINT,
|
59 |
+
headers={"Accept": "application/json", "X-Subscription-Token": BRAVE_KEY},
|
60 |
+
params=params,
|
61 |
timeout=15
|
62 |
+
)
|
63 |
+
raw = r.json().get("web", {}).get("results") or []
|
64 |
+
return [{
|
65 |
+
"title": r.get("title", ""),
|
66 |
+
"url": r.get("url", r.get("link", "")),
|
67 |
+
"snippet": r.get("description", r.get("text", "")),
|
68 |
+
"host": re.sub(r"https?://(www\.)?", "", r.get("url", "")).split("/")[0]
|
69 |
+
} for r in raw[:count]]
|
|
|
|
|
|
|
70 |
except Exception as e:
|
71 |
+
logging.error(f"Brave error: {e}")
|
72 |
return []
|
73 |
|
74 |
def format_search_results(query: str) -> str:
|
75 |
+
rows = brave_search(query, 6, freshness_days=3)
|
76 |
+
if not rows:
|
|
|
77 |
return f"# [Web-Search] No live results for โ{query}โ.\n"
|
78 |
+
hdr = f"# [Web-Search] Top results for โ{query}โ (last 3 days)\n\n"
|
79 |
body = "\n".join(
|
80 |
+
f"- **{r['title']}** ({r['host']})\n {r['snippet']}\n [link]({r['url']})"
|
81 |
+
for r in rows
|
|
|
|
|
82 |
)
|
83 |
return hdr + body + "\n"
|
84 |
|
85 |
+
NEWS_KEYWORDS = {
|
86 |
+
"Business": "recession OR GDP slowdown",
|
87 |
+
"K-Wave": "breakthrough technology innovation",
|
88 |
+
"Finance": "credit cycle debt crisis",
|
89 |
+
"Hegemony": "great power rivalry geopolitics"
|
90 |
+
}
|
91 |
+
def fetch_cycle_news():
|
92 |
+
markers = []
|
93 |
+
for cyc, kw in NEWS_KEYWORDS.items():
|
94 |
+
res = brave_search(kw, 1, freshness_days=2)
|
95 |
+
if res:
|
96 |
+
markers.append({
|
97 |
+
"cycle": cyc,
|
98 |
+
"title": res[0]["title"],
|
99 |
+
"year": datetime.utcnow().year,
|
100 |
+
"url": res[0]["url"]
|
101 |
+
})
|
102 |
+
return markers
|
103 |
+
NEWS_MARKERS = fetch_cycle_news()
|
104 |
+
|
105 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ 4. Chart helpers โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
106 |
def half_sine(xs, period, amp):
|
|
|
107 |
phase = np.mod(xs - CENTER, period)
|
108 |
y = amp * np.sin(np.pi * phase / period)
|
109 |
y[y < 0] = 0
|
110 |
return y
|
111 |
|
112 |
+
def build_chart(start: int, end: int, lang: str = "KO"):
|
|
|
|
|
113 |
xs = np.linspace(start, end, max(1000, (end - start) * 4))
|
114 |
fig = go.Figure()
|
115 |
|
116 |
+
# Gradient towers
|
117 |
for period in ORDERED_PERIODS:
|
118 |
+
base, col = AMPL[period], COLOR[period]
|
119 |
+
for frac in np.linspace(base / 30, base, 30):
|
120 |
fig.add_trace(go.Scatter(
|
121 |
x=xs, y=half_sine(xs, period, frac),
|
122 |
+
mode="lines", line=dict(color=col, width=0.8),
|
123 |
+
opacity=0.6, hoverinfo="skip", showlegend=False))
|
|
|
|
|
124 |
fig.add_trace(go.Scatter(
|
125 |
+
x=xs, y=half_sine(xs, period, base),
|
126 |
+
mode="lines", line=dict(color=col, width=1.6),
|
|
|
127 |
hoverinfo="skip", showlegend=False))
|
128 |
|
129 |
+
# Events + similar
|
130 |
+
text_key = "event_ko" if lang == "KO" else "event_en"
|
131 |
+
for yr, evs in EVENTS.items():
|
132 |
+
if start <= yr <= end:
|
133 |
+
cyc = evs[0]["cycle"]
|
134 |
+
period = PERIOD_BY_CYCLE[cyc]
|
135 |
+
yv = float(half_sine(np.array([yr]), period, AMPL[period]))
|
136 |
+
sim = ", ".join(map(str, SIMILAR_MAP.get(yr, []))) or "None"
|
137 |
+
txt = "<br>".join(e[text_key] for e in evs)
|
138 |
fig.add_trace(go.Scatter(
|
139 |
+
x=[yr], y=[yv], mode="markers",
|
140 |
marker=dict(color="white", size=6),
|
141 |
+
customdata=[[cyc, txt, sim]],
|
|
|
|
|
142 |
hovertemplate=(
|
143 |
+
"Year %{x} โข %{customdata[0]}<br>"
|
144 |
+
"%{customdata[1]}<br>"
|
145 |
+
"Similar: %{customdata[2]}<extra></extra>"
|
146 |
),
|
147 |
showlegend=False))
|
148 |
|
149 |
+
# Live-news markers
|
150 |
+
for m in NEWS_MARKERS:
|
151 |
+
if start <= m["year"] <= end:
|
152 |
+
p = PERIOD_BY_CYCLE[m["cycle"]]
|
153 |
+
yv = float(half_sine(np.array([m["year"]]), p, AMPL[p])) * 1.05
|
154 |
+
fig.add_trace(go.Scatter(
|
155 |
+
x=[m["year"]], y=[yv], mode="markers+text",
|
156 |
+
marker=dict(color="gold", size=8, symbol="star"),
|
157 |
+
text=["๐ฐ"], textposition="top center",
|
158 |
+
customdata=[[m["cycle"], m["title"], m["url"]]],
|
159 |
+
hovertemplate=("Live news โข %{customdata[0]}<br>"
|
160 |
+
"%{customdata[1]}<extra></extra>"),
|
161 |
+
showlegend=False))
|
162 |
+
|
163 |
+
# Hover Year trace
|
164 |
fig.add_trace(go.Scatter(
|
165 |
+
x=xs, y=np.full_like(xs, -0.05),
|
166 |
+
mode="lines", line=dict(color="rgba(0,0,0,0)", width=1),
|
167 |
+
hovertemplate="Year %{x:.0f}<extra></extra>", showlegend=False))
|
168 |
+
|
169 |
+
# Cosmetics
|
|
|
|
|
|
|
170 |
fig.add_vline(x=CENTER, line_dash="dash", line_color="white", opacity=0.6)
|
171 |
arrow_y = AMPL[250] * 1.05
|
172 |
fig.add_annotation(
|
173 |
+
x=CENTER - 125, y=arrow_y, ax=CENTER + 125, ay=arrow_y,
|
174 |
xref="x", yref="y", axref="x", ayref="y",
|
175 |
showarrow=True, arrowhead=3, arrowsize=1,
|
176 |
arrowwidth=1.2, arrowcolor="white")
|
177 |
fig.add_annotation(
|
178 |
+
x=CENTER, y=arrow_y + 0.15, text="250 yr",
|
179 |
showarrow=False, font=dict(color="white", size=10))
|
|
|
|
|
180 |
fig.update_layout(
|
181 |
template="plotly_dark",
|
182 |
paper_bgcolor="black", plot_bgcolor="black",
|
183 |
+
height=500, margin=dict(t=30, l=40, r=40, b=40),
|
|
|
184 |
hoverlabel=dict(bgcolor="#222", font_size=11),
|
185 |
+
hovermode="x")
|
186 |
+
fig.update_xaxes(title="Year", range=[start, end], showgrid=False)
|
187 |
+
fig.update_yaxes(title="Relative amplitude", showticklabels=False, showgrid=False)
|
|
|
|
|
188 |
|
189 |
+
summary = f"Range {start}-{end} | Events: {sum(1 for y in EVENTS if start <= y <= end)}"
|
|
|
190 |
return fig, summary
|
191 |
|
192 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ 5. GPT helper โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
|
|
|
193 |
BASE_PROMPT = (
|
194 |
"๋น์ ์ **CycleNavigator AI**๋ก, ๊ฒฝ์ ์ฌยท๊ตญ์ ์ ์นยท์ฅ์ฃผ๊ธฐ(9y Business, 50y K-Wave, "
|
195 |
"80y Finance, 250y Hegemony) ๋ถ์์ ์ ํตํ ์ ๋ฌธ๊ฐ์
๋๋ค. "
|
|
|
203 |
"โฆ ๋ถํ์ํ ์ฅํฉํจ์ ์ผ๊ฐ๊ณ 3๊ฐ ๋จ๋ฝ ๋๋ 7๊ฐ ์ดํ bullets ๋ด๋ก ์์ฝํ์ญ์์ค."
|
204 |
)
|
205 |
|
206 |
+
def chat_with_gpt(hist, msg, chart_summary):
|
207 |
+
msgs = [{"role": "system", "content": BASE_PROMPT}]
|
208 |
if chart_summary not in ("", "No chart yet."):
|
209 |
+
msgs.append({"role": "system", "content": f"[Chart summary]\n{chart_summary}"})
|
210 |
+
for u, a in hist:
|
211 |
+
msgs.extend([{"role": "user", "content": u}, {"role": "assistant", "content": a}])
|
212 |
+
msgs.append({"role": "user", "content": msg})
|
213 |
+
return openai.chat.completions.create(
|
|
|
|
|
|
|
214 |
model="gpt-3.5-turbo",
|
215 |
+
messages=msgs,
|
216 |
max_tokens=600,
|
217 |
temperature=0.7
|
218 |
+
).choices[0].message.content.strip()
|
|
|
219 |
|
220 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ 6. Gradio UI โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
|
|
|
221 |
def create_app():
|
222 |
+
with gr.Blocks(
|
223 |
+
theme=gr.themes.Soft(),
|
224 |
+
css="""
|
225 |
+
#discord-badge{position:fixed; bottom:10px; left:50%;
|
226 |
+
transform:translateX(-50%);}
|
227 |
+
"""
|
228 |
+
) as demo:
|
229 |
gr.Markdown("## ๐ญ **CycleNavigator (Interactive)**")
|
230 |
+
# โโ ์ธ์ด ์ ํ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
231 |
+
lang_state = gr.State(value="KO")
|
232 |
+
|
233 |
+
lang_radio = gr.Radio(
|
234 |
+
["English", "ํ๊ตญ์ด"],
|
235 |
+
value="English",
|
236 |
+
label="Language / ์ธ์ด",
|
237 |
+
interactive=True # โ ์ด๊ฒ๋ง ๋๊ณ
|
|
|
238 |
)
|
239 |
|
240 |
+
|
241 |
+
# ์ด๊ธฐ ์ฐจํธยท์ํ
|
242 |
chart_summary_state = gr.State(value="No chart yet.")
|
243 |
+
fig0, summ0 = build_chart(1500, 2500, "KO")
|
244 |
+
plot = gr.Plot(value=fig0)
|
245 |
+
chart_summary_state.value = summ0
|
246 |
+
|
247 |
+
with gr.Row():
|
248 |
+
start_year = gr.Number(label="Start Year", value=1500, precision=0)
|
249 |
+
end_year = gr.Number(label="End Year", value=2500, precision=0)
|
250 |
+
zoom_in = gr.Button("๐ Zoom In")
|
251 |
+
zoom_out = gr.Button("๐ Zoom Out")
|
252 |
+
|
253 |
+
# โโ functions โโ
|
254 |
+
def refresh(s, e, lang_code):
|
255 |
+
fig, summ = build_chart(int(s), int(e), lang_code)
|
256 |
+
return fig, summ
|
257 |
+
|
258 |
+
def zoom(s, e, f, lang_code):
|
259 |
+
mid = (s + e) / 2
|
260 |
+
span = (e - s) * f / 2
|
261 |
+
ns, ne = int(mid - span), int(mid + span)
|
262 |
+
fig, summ = build_chart(ns, ne, lang_code)
|
263 |
+
return ns, ne, fig, summ
|
264 |
+
|
265 |
+
def change_lang(lang_label, s, e):
|
266 |
+
code = "KO" if lang_label == "ํ๊ตญ์ด" else "EN"
|
267 |
+
fig, summ = build_chart(int(s), int(e), code)
|
268 |
+
return code, fig, summ
|
269 |
+
|
270 |
+
# โโ event wiring โโ
|
271 |
+
start_year.change(refresh, [start_year, end_year, lang_state], [plot, chart_summary_state])
|
272 |
+
end_year.change(refresh, [start_year, end_year, lang_state], [plot, chart_summary_state])
|
273 |
+
|
274 |
+
zoom_in.click(
|
275 |
+
lambda s, e, lc: zoom(s, e, 0.5, lc),
|
276 |
+
[start_year, end_year, lang_state],
|
277 |
+
[start_year, end_year, plot, chart_summary_state]
|
278 |
+
)
|
279 |
+
zoom_out.click(
|
280 |
+
lambda s, e, lc: zoom(s, e, 2.0, lc),
|
281 |
+
[start_year, end_year, lang_state],
|
282 |
+
[start_year, end_year, plot, chart_summary_state]
|
283 |
+
)
|
284 |
|
285 |
+
lang_radio.change(
|
286 |
+
change_lang,
|
287 |
+
[lang_radio, start_year, end_year],
|
288 |
+
[lang_state, plot, chart_summary_state]
|
289 |
+
)
|
|
|
290 |
|
291 |
+
gr.File(value=str(EVENTS_PATH), label="Download cycle_events.json")
|
292 |
+
|
293 |
+
with gr.Tabs():
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
294 |
with gr.TabItem("Deep Research Chat"):
|
295 |
chatbot = gr.Chatbot(label="Assistant")
|
296 |
user_input = gr.Textbox(lines=3, placeholder="๋ฉ์์ง๋ฅผ ์
๋ ฅํ์ธ์โฆ")
|
|
|
297 |
with gr.Row():
|
298 |
send_btn = gr.Button("Send", variant="primary")
|
299 |
+
web_btn = gr.Button("๐ Web Search")
|
300 |
+
|
301 |
+
def respond(hist, msg, summ):
|
302 |
+
reply = chat_with_gpt(hist, msg, summ)
|
303 |
+
hist.append((msg, reply))
|
304 |
+
return hist, gr.Textbox(value="")
|
305 |
+
|
306 |
+
def respond_ws(hist, msg, summ):
|
307 |
+
md = format_search_results(msg)
|
308 |
+
reply = chat_with_gpt(hist, f"{msg}\n\n{md}", summ)
|
309 |
+
hist.append((f"{msg}\n\n(์น๊ฒ์)", reply))
|
310 |
+
return hist, gr.Textbox(value="")
|
|
|
|
|
|
|
311 |
|
312 |
send_btn.click(respond,
|
313 |
[chatbot, user_input, chart_summary_state],
|
|
|
315 |
user_input.submit(respond,
|
316 |
[chatbot, user_input, chart_summary_state],
|
317 |
[chatbot, user_input])
|
318 |
+
web_btn.click(respond_ws,
|
319 |
+
[chatbot, user_input, chart_summary_state],
|
320 |
+
[chatbot, user_input])
|
321 |
|
322 |
+
# โโ fixed Discord badge โโ
|
323 |
gr.HTML(
|
324 |
'<a href="https://discord.gg/openfreeai" target="_blank" id="discord-badge">'
|
325 |
'<img src="https://img.shields.io/static/v1?label=Discord&message=Openfree%20AI&'
|
326 |
'color=%230000ff&labelColor=%23800080&logo=discord&logoColor=white&style=for-the-badge"'
|
327 |
' alt="badge"></a>'
|
328 |
+
)
|
329 |
+
|
330 |
return demo
|
331 |
|
332 |
+
# โโโโโโโโโโโโโโโโโโโโโโโโโโ main โโโโโโโโโโโโโโโโโโโโโโโโโโ
|
|
|
|
|
333 |
if __name__ == "__main__":
|
334 |
create_app().launch()
|