Spaces:
Running
Running
File size: 15,789 Bytes
adaea4d 7781d26 b7fd69b adaea4d b7fd69b adaea4d b7fd69b adaea4d efed56b |
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 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 |
# -------- app_final.py --------
import os, json, math, pathlib, re, time, logging, requests
from datetime import datetime, timedelta
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import gradio as gr
import openai
import torch
from sentence_transformers import SentenceTransformer, util
# โโโโโโโโโโโโโโโโโโโโโโโโโโ 0. API keys & Brave Search โโโโโโโโโโโโโโโโโโโโโโโโโโ
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"]
BRAVE_KEY = os.getenv("BRAVE_KEY", "")
BRAVE_ENDPOINT = "https://api.search.brave.com/res/v1/web/search"
logging.basicConfig(level=logging.INFO)
# โโโโโโโโโโโโโโโโโโโโโโโโโโ 1. Cycle config โโโโโโโโโโโโโโโโโโโโโโโโโโ
CENTER = 2025
CYCLES = { "K-Wave": 50, "Business": 9, "Finance": 80, "Hegemony": 250 }
ORDERED_PERIODS = sorted(CYCLES.values())
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 & embeddings โโโโโโโโโโโโโโโโโโโ
EVENTS_PATH = pathlib.Path(__file__).with_name("cycle_events.json")
with open(EVENTS_PATH, encoding="utf-8") as f:
RAW_EVENTS = json.load(f)
EVENTS = {int(item["year"]): item["events"] for item in RAW_EVENTS}
logging.info("Embedding historical eventsโฆ")
_embed_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
_all_sentences = [(yr, ev["event_en"]) for yr, evs in EVENTS.items() for ev in evs]
_embeddings = _embed_model.encode([s for _, s in _all_sentences], convert_to_tensor=True)
# ์ ์ฌ ์ฌ๊ฑด top-3 year ์ฌ์
SIMILAR_MAP = {}
for idx, (yr, _) in enumerate(_all_sentences):
scores = util.cos_sim(_embeddings[idx], _embeddings)[0]
top_idx = torch.topk(scores, 4).indices.tolist()
sims = [_all_sentences[i][0] for i in top_idx if _all_sentences[i][0] != yr][:3]
SIMILAR_MAP.setdefault(yr, sims)
# โโโโโโโโโโโโโโโโโโโโโโโโโโ 3. Brave Search helpers โโโโโโโโโโโโโโโโโโโโโโโโโโ
def brave_search(query: str, count: int = 8, freshness_days: int | None = None):
if not BRAVE_KEY:
return []
params = {"q": query, "count": str(count)}
if freshness_days:
dt_from = (datetime.utcnow() - timedelta(days=freshness_days)).strftime("%Y-%m-%d")
params["freshness"] = dt_from
try:
r = requests.get(
BRAVE_ENDPOINT,
headers={"Accept": "application/json", "X-Subscription-Token": BRAVE_KEY},
params=params,
timeout=15
)
raw = r.json().get("web", {}).get("results") or []
return [{
"title": r.get("title", ""),
"url": r.get("url", r.get("link", "")),
"snippet": r.get("description", r.get("text", "")),
"host": re.sub(r"https?://(www\.)?", "", r.get("url", "")).split("/")[0]
} for r in raw[:count]]
except Exception as e:
logging.error(f"Brave error: {e}")
return []
def format_search_results(query: str) -> str:
rows = brave_search(query, 6, freshness_days=3)
if not rows:
return f"# [Web-Search] No live results for โ{query}โ.\n"
hdr = f"# [Web-Search] Top results for โ{query}โ (last 3 days)\n\n"
body = "\n".join(
f"- **{r['title']}** ({r['host']})\n {r['snippet']}\n [link]({r['url']})"
for r in rows
)
return hdr + body + "\n"
NEWS_KEYWORDS = {
"Business": "recession OR GDP slowdown",
"K-Wave": "breakthrough technology innovation",
"Finance": "credit cycle debt crisis",
"Hegemony": "great power rivalry geopolitics"
}
def fetch_cycle_news():
markers = []
for cyc, kw in NEWS_KEYWORDS.items():
res = brave_search(kw, 1, freshness_days=2)
if res:
markers.append({
"cycle": cyc,
"title": res[0]["title"],
"year": datetime.utcnow().year,
"url": res[0]["url"]
})
return markers
NEWS_MARKERS = fetch_cycle_news()
# โโโโโโโโโโโโโโโโโโโโโโโโโโ 4. Chart helpers โโโโโโโโโโโโโโโโโโโโโโโโโโ
def half_sine(xs, period, amp):
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, lang: str = "KO"):
xs = np.linspace(start, end, max(1000, (end - start) * 4))
fig = go.Figure()
# Gradient towers
for period in ORDERED_PERIODS:
base, col = AMPL[period], COLOR[period]
for frac in np.linspace(base / 30, base, 30):
fig.add_trace(go.Scatter(
x=xs, y=half_sine(xs, period, frac),
mode="lines", line=dict(color=col, width=0.8),
opacity=0.6, hoverinfo="skip", showlegend=False))
fig.add_trace(go.Scatter(
x=xs, y=half_sine(xs, period, base),
mode="lines", line=dict(color=col, width=1.6),
hoverinfo="skip", showlegend=False))
# Events + similar
text_key = "event_ko" if lang == "KO" else "event_en"
for yr, evs in EVENTS.items():
if start <= yr <= end:
cyc = evs[0]["cycle"]
period = PERIOD_BY_CYCLE[cyc]
yv = float(half_sine(np.array([yr]), period, AMPL[period]))
sim = ", ".join(map(str, SIMILAR_MAP.get(yr, []))) or "None"
txt = "<br>".join(e[text_key] for e in evs)
fig.add_trace(go.Scatter(
x=[yr], y=[yv], mode="markers",
marker=dict(color="white", size=6),
customdata=[[cyc, txt, sim]],
hovertemplate=(
"Year %{x} โข %{customdata[0]}<br>"
"%{customdata[1]}<br>"
"Similar: %{customdata[2]}<extra></extra>"
),
showlegend=False))
# Live-news markers
for m in NEWS_MARKERS:
if start <= m["year"] <= end:
p = PERIOD_BY_CYCLE[m["cycle"]]
yv = float(half_sine(np.array([m["year"]]), p, AMPL[p])) * 1.05
fig.add_trace(go.Scatter(
x=[m["year"]], y=[yv], mode="markers+text",
marker=dict(color="gold", size=8, symbol="star"),
text=["๐ฐ"], textposition="top center",
customdata=[[m["cycle"], m["title"], m["url"]]],
hovertemplate=("Live news โข %{customdata[0]}<br>"
"%{customdata[1]}<extra></extra>"),
showlegend=False))
# Hover Year trace
fig.add_trace(go.Scatter(
x=xs, y=np.full_like(xs, -0.05),
mode="lines", line=dict(color="rgba(0,0,0,0)", width=1),
hovertemplate="Year %{x:.0f}<extra></extra>", showlegend=False))
# Cosmetics
fig.add_vline(x=CENTER, line_dash="dash", line_color="white", opacity=0.6)
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))
fig.update_layout(
template="plotly_dark",
paper_bgcolor="black", plot_bgcolor="black",
height=500, margin=dict(t=30, l=40, r=40, b=40),
hoverlabel=dict(bgcolor="#222", font_size=11),
hovermode="x")
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: {sum(1 for y in EVENTS if start <= y <= end)}"
return fig, summary
# โโโโโโโโโโโโโโโโโโโโโโโโโโ 5. GPT helper โโโโโโโโโโโโโโโโโโโโโโโโโโ
BASE_PROMPT = (
"๋น์ ์ **CycleNavigator AI**๋ก, ๊ฒฝ์ ์ฌยท๊ตญ์ ์ ์นยท์ฅ์ฃผ๊ธฐ(9y Business, 50y K-Wave, "
"80y Finance, 250y Hegemony) ๋ถ์์ ์ ํตํ ์ ๋ฌธ๊ฐ์
๋๋ค. "
"๋ชจ๋ ๋ต๋ณ์ ํ๊ตญ์ด๋ก ํ๋ ํ์ ์ ์ ํ์ฑ๊ณผ ์ค๋ฌด์ ๋ช
๋ฃ์ฑ์ ๋์์ ๊ฐ์ถ์ญ์์ค. "
"โฆ ๋ต๋ณ ๊ตฌ์กฐ ์ง์นจ: โ ์ง๋ฌธ ํต์ฌ ์์ฝ โ โก 4๋ ์ฃผ๊ธฐ์์ ๊ด๋ จ์ฑ ๋ช
์ โ "
"โข ์ญ์ฌยท๋ฐ์ดํฐ ๊ทผ๊ฑฐ ์ค๋ช
โ โฃ ์์ฌ์ ยท์ ๋ง ์์ผ๋ก ์์ ํ๋ฉฐ, "
"๋ฒํธโง๊ธ๋จธ๋ฆฌํยท์งง์ ๋ฌธ๋จ์ ํ์ฉํด ๋
ผ๋ฆฌ์ ์ผ๋ก ๋ฐฐ์ดํฉ๋๋ค. "
"โฆ ์ ๊ณต๋ [Chart summary]๋ ๋ฐ๋์ ํด์ยท์ธ์ฉํ๊ณ , "
"๊ฐ๊ด์ ์ฌ์คยท์ฐ๋ยท์ฌ๊ฑด์ ๊ทผ๊ฑฐ๋ก ํฉ๋๋ค. "
"โฆ ๊ทผ๊ฑฐ๊ฐ ๋ถ์ถฉ๋ถํ ๋ โํ์คํ์ง ์์ต๋๋คโ๋ผ๊ณ ๋ช
์ํด ์ถ์ธก์ ํผํ์ญ์์ค. "
"โฆ ๋ถํ์ํ ์ฅํฉํจ์ ์ผ๊ฐ๊ณ 3๊ฐ ๋จ๋ฝ ๋๋ 7๊ฐ ์ดํ bullets ๋ด๋ก ์์ฝํ์ญ์์ค."
)
def chat_with_gpt(hist, msg, chart_summary):
msgs = [{"role": "system", "content": BASE_PROMPT}]
if chart_summary not in ("", "No chart yet."):
msgs.append({"role": "system", "content": f"[Chart summary]\n{chart_summary}"})
for u, a in hist:
msgs.extend([{"role": "user", "content": u}, {"role": "assistant", "content": a}])
msgs.append({"role": "user", "content": msg})
return openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=msgs,
max_tokens=600,
temperature=0.7
).choices[0].message.content.strip()
# โโโโโโโโโโโโโโโโโโโโโโโโโโ 6. Gradio UI โโโโโโโโโโโโโโโโโโโโโโโโโโ
def create_app():
with gr.Blocks(
theme=gr.themes.Soft(),
css="""
#discord-badge{position:fixed; bottom:10px; left:50%;
transform:translateX(-50%);}
"""
) as demo:
gr.Markdown("## ๐ญ **CycleNavigator (Interactive)**")
gr.Markdown(
"<sub>"
"<b>Interactive visual service delivering insights at a glance into the four major long cyclesโ </b>"
"<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)"
"<b> โthrough dynamic charts and AI chat.</b>"
"</sub>"
)
# โโ ์ธ์ด ์ ํ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
# โโ ์ธ์ด ์ ํ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
lang_state = gr.State(value="EN") # โ ๊ธฐ๋ณธ์ EN์ผ๋ก
lang_radio = gr.Radio(
["English", "ํ๊ตญ์ด"],
value="English",
label="Language / ์ธ์ด",
interactive=True
)
# ์ด๊ธฐ ์ฐจํธยท์ํ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
chart_summary_state = gr.State(value="No chart yet.")
fig0, summ0 = build_chart(1500, 2500, lang_state.value) # โก ๋์ผ ์ํ๊ฐ ์ฌ์ฉ
plot = gr.Plot(value=fig0)
chart_summary_state.value = summ0
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")
# โโ functions โโ
def refresh(s, e, lang_code):
fig, summ = build_chart(int(s), int(e), lang_code)
return fig, summ
def zoom(s, e, f, lang_code):
mid = (s + e) / 2
span = (e - s) * f / 2
ns, ne = int(mid - span), int(mid + span)
fig, summ = build_chart(ns, ne, lang_code)
return ns, ne, fig, summ
def change_lang(lang_label, s, e):
code = "KO" if lang_label == "ํ๊ตญ์ด" else "EN"
fig, summ = build_chart(int(s), int(e), code)
return code, fig, summ
# โโ event wiring โโ
start_year.change(refresh, [start_year, end_year, lang_state], [plot, chart_summary_state])
end_year.change(refresh, [start_year, end_year, lang_state], [plot, chart_summary_state])
zoom_in.click(
lambda s, e, lc: zoom(s, e, 0.5, lc),
[start_year, end_year, lang_state],
[start_year, end_year, plot, chart_summary_state]
)
zoom_out.click(
lambda s, e, lc: zoom(s, e, 2.0, lc),
[start_year, end_year, lang_state],
[start_year, end_year, plot, chart_summary_state]
)
lang_radio.change(
change_lang,
[lang_radio, start_year, end_year],
[lang_state, plot, chart_summary_state]
)
gr.File(value=str(EVENTS_PATH), label="Download cycle_events.json")
with gr.Tabs():
with gr.TabItem("Deep Research Chat"):
chatbot = gr.Chatbot(label="Assistant")
user_input = gr.Textbox(lines=3, placeholder="๋ฉ์์ง๋ฅผ ์
๋ ฅํ์ธ์โฆ")
with gr.Row():
send_btn = gr.Button("Send", variant="primary")
web_btn = gr.Button("๐ Web Search")
def respond(hist, msg, summ):
reply = chat_with_gpt(hist, msg, summ)
hist.append((msg, reply))
return hist, gr.Textbox(value="")
def respond_ws(hist, msg, summ):
md = format_search_results(msg)
reply = chat_with_gpt(hist, f"{msg}\n\n{md}", summ)
hist.append((f"{msg}\n\n(์น๊ฒ์)", reply))
return hist, 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])
web_btn.click(respond_ws,
[chatbot, user_input, chart_summary_state],
[chatbot, user_input])
# โโ fixed Discord badge โโ
gr.HTML(
'<a href="https://discord.gg/openfreeai" target="_blank" id="discord-badge">'
'<img src="https://img.shields.io/static/v1?label=Discord&message=Openfree%20AI&'
'color=%230000ff&labelColor=%23800080&logo=discord&logoColor=white&style=for-the-badge"'
' alt="badge"></a>'
)
return demo
# โโโโโโโโโโโโโโโโโโโโโโโโโโ main โโโโโโโโโโโโโโโโโโโโโโโโโโ
if __name__ == "__main__":
create_app().launch()
|