openfree commited on
Commit
b7fd69b
ยท
verified ยท
1 Parent(s): 82aa4fb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +216 -197
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", "") # Brave Search API 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
- "K-Wave": 50, # Kondratiev long wave
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, 50:1.0, 80:1.6, 250:4.0}
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
- EVENTS = {int(item["year"]): item["events"] for item in json.load(f)}
40
-
41
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
42
- # 3. Brave Search helpers
43
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
44
- def brave_search(query: str, count: int = 8):
45
- """Call Brave Search API; return list of dicts."""
 
 
 
 
 
 
 
 
 
 
 
46
  if not BRAVE_KEY:
47
- logging.warning("โš ๏ธ BRAVE_KEY is empty; web search disabled.")
48
  return []
 
 
 
 
49
  try:
50
- hdrs = {
51
- "Accept": "application/json",
52
- "X-Subscription-Token": BRAVE_KEY
53
- }
54
- data = requests.get(
55
  BRAVE_ENDPOINT,
56
- headers=hdrs,
57
- params={"q": query, "count": str(count)},
58
  timeout=15
59
- ).json()
60
- raw = data.get("web", {}).get("results") or []
61
- return [
62
- {
63
- "title": r.get("title", ""),
64
- "url": r.get("url", r.get("link", "")),
65
- "snippet": r.get("description", r.get("text", "")),
66
- "host": re.sub(r"https?://(www\.)?", "", r.get("url", "")).split("/")[0]
67
- }
68
- for r in raw[:count]
69
- ]
70
  except Exception as e:
71
- logging.error(f"Brave Search Error: {e}")
72
  return []
73
 
74
  def format_search_results(query: str) -> str:
75
- """Format search results as markdown for LLM context."""
76
- arts = brave_search(query)
77
- if not arts:
78
  return f"# [Web-Search] No live results for โ€œ{query}โ€.\n"
79
- hdr = f"# [Web-Search] Top results for โ€œ{query}โ€\n\n"
80
  body = "\n".join(
81
- f"**{i+1}. {a['title']}** ({a['host']})\n\n"
82
- f"{a['snippet']}\n\n"
83
- f"[Source]({a['url']})\n"
84
- for i, a in enumerate(arts)
85
  )
86
  return hdr + body + "\n"
87
 
88
- # โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
89
- # 4. Helper functions (chart)
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
- # 1) Gradient half-sine towers
105
  for period in ORDERED_PERIODS:
106
- base_amp, color = AMPL[period], COLOR[period]
107
- for frac in np.linspace(base_amp / 30, base_amp, 30):
108
  fig.add_trace(go.Scatter(
109
  x=xs, y=half_sine(xs, period, frac),
110
- mode="lines",
111
- line=dict(color=color, width=0.8),
112
- opacity=0.6,
113
- hoverinfo="skip", showlegend=False))
114
  fig.add_trace(go.Scatter(
115
- x=xs, y=half_sine(xs, period, base_amp),
116
- mode="lines",
117
- line=dict(color=color, width=1.6),
118
  hoverinfo="skip", showlegend=False))
119
 
120
- # 2) Event markers (bilingual hover)
121
- for year, evs in EVENTS.items():
122
- if start <= year <= end:
123
- cyc = evs[0]["cycle"]; period = PERIOD_BY_CYCLE[cyc]
124
- y_val = float(half_sine(np.array([year]), period, AMPL[period]))
 
 
 
 
125
  fig.add_trace(go.Scatter(
126
- x=[year], y=[y_val], mode="markers",
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]} cycle"
133
- "<br>%{customdata[1]}"
134
- "<br>%{customdata[2]}<extra></extra>"
135
  ),
136
  showlegend=False))
137
 
138
- # 3) Transparent hover-trace so any x shows โ€˜Year ####โ€™
 
 
 
 
 
 
 
 
 
 
 
 
 
 
139
  fig.add_trace(go.Scatter(
140
- x=xs,
141
- y=np.full_like(xs, -0.05), # just below baseline
142
- mode="lines",
143
- line=dict(color="rgba(0,0,0,0)", width=1), # invisible
144
- hovertemplate="Year %{x:.0f}<extra></extra>",
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=450,
164
- margin=dict(t=30, l=40, r=40, b=40),
165
  hoverlabel=dict(bgcolor="#222", font_size=11),
166
- hovermode="x" # unified x-hover
167
- )
168
- fig.update_xaxes(title="Year", range=[start, end], showgrid=False)
169
- fig.update_yaxes(title="Relative amplitude",
170
- showticklabels=False, showgrid=False)
171
 
172
- summary = f"Range {start}-{end} | Events plotted: " \
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(history, user_msg, chart_summary):
193
- messages = [{"role": "system", "content": BASE_PROMPT}]
194
  if chart_summary not in ("", "No chart yet."):
195
- messages.append({"role": "system", "content": f"[Chart summary]\n{chart_summary}"})
196
-
197
- for u, a in history:
198
- messages.extend([{"role": "user", "content": u},
199
- {"role": "assistant", "content": a}])
200
- messages.append({"role": "user", "content": user_msg})
201
-
202
- res = openai.chat.completions.create(
203
  model="gpt-3.5-turbo",
204
- messages=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(theme=gr.themes.Soft()) as demo:
215
- # Title & subtitles
 
 
 
 
 
216
  gr.Markdown("## ๐Ÿ”ญ **CycleNavigator (Interactive)**")
217
- gr.Markdown(
218
- "<sub>"
219
- "<b>Interactive visual service delivering insights at a glance into the four major long cyclesโ€” </b>"
220
- "<b>Business 9y</b> (credit-investment business cycle) โ€ข "
221
- "<b>K-Wave 50y</b> (long technological-industrial wave) โ€ข "
222
- "<b>Finance 80y</b> (long credit-debt cycle) โ€ข "
223
- "<b>Hegemony 250y</b> (rise & fall of global powers cycle)"
224
- "<b> โ€”through dynamic charts and AI chat.</b>"
225
- "</sub>"
226
  )
227
 
 
 
228
  chart_summary_state = gr.State(value="No chart yet.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
 
230
- with gr.Tabs():
231
- with gr.TabItem("Timeline Chart"):
232
- # 1๏ธโƒฃ ๋จผ์ € ์ฐจํŠธ๋ฅผ ๋งŒ๋“ค๊ณ  ํ™”๋ฉด์— ๋ฐฐ์น˜
233
- fig0, summ0 = build_chart(1500, 2500)
234
- plot = gr.Plot(value=fig0) # โฌ†๏ธ ์ฐจํŠธ๊ฐ€ ๋งจ ์œ„์— ์œ„์น˜
235
- chart_summary_state.value = summ0
236
 
237
- # 2๏ธโƒฃ ์ฐจํŠธ ์•„๋ž˜์— ์ปจํŠธ๋กค(์—ฐ๋„ ์ž…๋ ฅ + ์คŒ ๋ฒ„ํŠผ) ๋ฐฐ์น˜
238
- with gr.Row():
239
- start_year = gr.Number(label="Start Year", value=1500, precision=0)
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") # NEW
278
-
279
- # ๊ธฐ๋ณธ ๋‹ต๋ณ€
280
- def respond(history, msg, summ):
281
- reply = chat_with_gpt(history, msg, summ)
282
- history.append((msg, reply))
283
- return history, gr.Textbox(value="")
284
-
285
- # ์›น ๊ฒ€์ƒ‰ ํ›„ ๋‹ต๋ณ€
286
- def respond_with_search(history, msg, summ):
287
- search_md = format_search_results(msg)
288
- combined = f"{msg}\n\n{search_md}"
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(respond_with_search,
300
- [chatbot, user_input, chart_summary_state],
301
- [chatbot, user_input])
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()