Cycle-Navigator / app.py
openfree's picture
Update app.py
2cde57f verified
raw
history blame
13.8 kB
# -------- app_final.py --------
import os, json, math, pathlib, re, time, logging, requests
import numpy as np
import plotly.graph_objects as go
import gradio as gr
import openai
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# 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 Search API 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, # Kondratiev long wave
"Business": 9, # Juglar investment cycle
"Finance": 80, # Long credit cycle
"Hegemony": 250 # Power-shift cycle
}
ORDERED_PERIODS = sorted(CYCLES.values()) # [9, 50, 80, 250]
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
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
EVENTS_PATH = pathlib.Path(__file__).with_name("cycle_events.json")
with open(EVENTS_PATH, encoding="utf-8") as f:
EVENTS = {int(item["year"]): item["events"] for item in json.load(f)}
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# 3. Brave Search helpers
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def brave_search(query: str, count: int = 8):
"""Call Brave Search API; return list of dicts."""
if not BRAVE_KEY:
logging.warning("โš ๏ธ BRAVE_KEY is empty; web search disabled.")
return []
try:
hdrs = {
"Accept": "application/json",
"X-Subscription-Token": BRAVE_KEY
}
data = requests.get(
BRAVE_ENDPOINT,
headers=hdrs,
params={"q": query, "count": str(count)},
timeout=15
).json()
raw = data.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 Search Error: {e}")
return []
def format_search_results(query: str) -> str:
"""Format search results as markdown for LLM context."""
arts = brave_search(query)
if not arts:
return f"# [Web-Search] No live results for โ€œ{query}โ€.\n"
hdr = f"# [Web-Search] Top results for โ€œ{query}โ€\n\n"
body = "\n".join(
f"**{i+1}. {a['title']}** ({a['host']})\n\n"
f"{a['snippet']}\n\n"
f"[Source]({a['url']})\n"
for i, a in enumerate(arts)
)
return hdr + body + "\n"
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# 4. Helper functions (chart)
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def half_sine(xs, period, amp):
"""Half-sine โ€˜towerโ€™ with zero bottom floor."""
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):
"""Return (Plotly figure, summary string) for the requested year range,
plus a transparent hover-trace so the cursor always shows โ€˜Year ####โ€™. """
xs = np.linspace(start, end, max(1000, (end - start) * 4))
fig = go.Figure()
# 1) Gradient half-sine towers
for period in ORDERED_PERIODS:
base_amp, color = AMPL[period], COLOR[period]
for frac in np.linspace(base_amp / 30, base_amp, 30):
fig.add_trace(go.Scatter(
x=xs, y=half_sine(xs, period, frac),
mode="lines",
line=dict(color=color, width=0.8),
opacity=0.6,
hoverinfo="skip", showlegend=False))
fig.add_trace(go.Scatter(
x=xs, y=half_sine(xs, period, base_amp),
mode="lines",
line=dict(color=color, width=1.6),
hoverinfo="skip", showlegend=False))
# 2) Event markers (bilingual hover)
for year, evs in EVENTS.items():
if start <= year <= end:
cyc = evs[0]["cycle"]; period = PERIOD_BY_CYCLE[cyc]
y_val = float(half_sine(np.array([year]), period, AMPL[period]))
fig.add_trace(go.Scatter(
x=[year], y=[y_val], mode="markers",
marker=dict(color="white", size=6),
customdata=[[cyc,
"<br>".join(e["event_en"] for e in evs),
"<br>".join(e["event_ko"] for e in evs)]],
hovertemplate=(
"Year %{x} โ€ข %{customdata[0]} cycle"
"<br>%{customdata[1]}"
"<br>%{customdata[2]}<extra></extra>"
),
showlegend=False))
# 3) Transparent hover-trace so any x shows โ€˜Year ####โ€™
fig.add_trace(go.Scatter(
x=xs,
y=np.full_like(xs, -0.05), # just below baseline
mode="lines",
line=dict(color="rgba(0,0,0,0)", width=1), # invisible
hovertemplate="Year %{x:.0f}<extra></extra>",
showlegend=False))
# 4) Cosmetic touches: centre line & 250-yr arrow
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))
# 5) Layout
fig.update_layout(
template="plotly_dark",
paper_bgcolor="black", plot_bgcolor="black",
height=450,
margin=dict(t=30, l=40, r=40, b=40),
hoverlabel=dict(bgcolor="#222", font_size=11),
hovermode="x" # unified x-hover
)
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 plotted: " \
f"{sum(1 for y in EVENTS if start <= y <= end)}"
return fig, summary
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# 5. GPT chat helper
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
BASE_PROMPT = (
"๋‹น์‹ ์€ **CycleNavigator AI**๋กœ, ๊ฒฝ์ œ์‚ฌยท๊ตญ์ œ์ •์น˜ยท์žฅ์ฃผ๊ธฐ(9y Business, 50y K-Wave, "
"80y Finance, 250y Hegemony) ๋ถ„์„์— ์ •ํ†ตํ•œ ์ „๋ฌธ๊ฐ€์ž…๋‹ˆ๋‹ค. "
"๋ชจ๋“  ๋‹ต๋ณ€์€ ํ•œ๊ตญ์–ด๋กœ ํ•˜๋˜ ํ•™์ˆ ์  ์ •ํ™•์„ฑ๊ณผ ์‹ค๋ฌด์  ๋ช…๋ฃŒ์„ฑ์„ ๋™์‹œ์— ๊ฐ–์ถ”์‹ญ์‹œ์˜ค. "
"โœฆ ๋‹ต๋ณ€ ๊ตฌ์กฐ ์ง€์นจ: โ‘  ์งˆ๋ฌธ ํ•ต์‹ฌ ์š”์•ฝ โ†’ โ‘ก 4๋Œ€ ์ฃผ๊ธฐ์™€์˜ ๊ด€๋ จ์„ฑ ๋ช…์‹œ โ†’ "
"โ‘ข ์—ญ์‚ฌยท๋ฐ์ดํ„ฐ ๊ทผ๊ฑฐ ์„ค๋ช… โ†’ โ‘ฃ ์‹œ์‚ฌ์ ยท์ „๋ง ์ˆœ์œผ๋กœ ์„œ์ˆ ํ•˜๋ฉฐ, "
"๋ฒˆํ˜ธโ€ง๊ธ€๋จธ๋ฆฌํ‘œยท์งง์€ ๋ฌธ๋‹จ์„ ํ™œ์šฉํ•ด ๋…ผ๋ฆฌ์ ์œผ๋กœ ๋ฐฐ์—ดํ•ฉ๋‹ˆ๋‹ค. "
"โœฆ ์ œ๊ณต๋œ [Chart summary]๋Š” ๋ฐ˜๋“œ์‹œ ํ•ด์„ยท์ธ์šฉํ•˜๊ณ , "
"๊ฐ๊ด€์  ์‚ฌ์‹คยท์—ฐ๋„ยท์‚ฌ๊ฑด์„ ๊ทผ๊ฑฐ๋กœ ํ•ฉ๋‹ˆ๋‹ค. "
"โœฆ ๊ทผ๊ฑฐ๊ฐ€ ๋ถˆ์ถฉ๋ถ„ํ•  ๋• โ€˜ํ™•์‹คํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹คโ€™๋ผ๊ณ  ๋ช…์‹œํ•ด ์ถ”์ธก์„ ํ”ผํ•˜์‹ญ์‹œ์˜ค. "
"โœฆ ๋ถˆํ•„์š”ํ•œ ์žฅํ™ฉํ•จ์€ ์‚ผ๊ฐ€๊ณ  3๊ฐœ ๋‹จ๋ฝ ๋˜๋Š” 7๊ฐœ ์ดํ•˜ bullets ๋‚ด๋กœ ์š”์•ฝํ•˜์‹ญ์‹œ์˜ค."
)
def chat_with_gpt(history, user_msg, chart_summary):
messages = [{"role": "system", "content": BASE_PROMPT}]
if chart_summary not in ("", "No chart yet."):
messages.append({"role": "system", "content": f"[Chart summary]\n{chart_summary}"})
for u, a in history:
messages.extend([{"role": "user", "content": u},
{"role": "assistant", "content": a}])
messages.append({"role": "user", "content": user_msg})
res = openai.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
max_tokens=600,
temperature=0.7
)
return res.choices[0].message.content.strip()
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# 6. Gradio UI
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
def create_app():
with gr.Blocks(theme=gr.themes.Soft()) as demo:
# Title & subtitles
gr.Markdown("## ๐Ÿ”ญ **CycleNavigator (Interactive)**")
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>"
)
gr.Markdown(
"<sub>"
"<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)"
"</sub>"
)
chart_summary_state = gr.State(value="No chart yet.")
with gr.Tabs():
with gr.TabItem("Timeline Chart"):
# 1๏ธโƒฃ ๋จผ์ € ์ฐจํŠธ๋ฅผ ๋งŒ๋“ค๊ณ  ํ™”๋ฉด์— ๋ฐฐ์น˜
fig0, summ0 = build_chart(1500, 2500)
plot = gr.Plot(value=fig0) # โฌ†๏ธ ์ฐจํŠธ๊ฐ€ ๋งจ ์œ„์— ์œ„์น˜
chart_summary_state.value = summ0
# 2๏ธโƒฃ ์ฐจํŠธ ์•„๋ž˜์— ์ปจํŠธ๋กค(์—ฐ๋„ ์ž…๋ ฅ + ์คŒ ๋ฒ„ํŠผ) ๋ฐฐ์น˜
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")
def refresh(s, e):
fig, summ = build_chart(int(s), int(e))
return fig, summ
start_year.change(refresh, [start_year, end_year],
[plot, chart_summary_state])
end_year.change(refresh, [start_year, end_year],
[plot, chart_summary_state])
def zoom(s, e, factor):
mid = (s + e) / 2
span = (e - s) * factor / 2
ns, ne = int(mid - span), int(mid + span)
fig, summ = build_chart(ns, ne)
return ns, ne, fig, summ
zoom_in.click(lambda s, e: zoom(s, e, 0.5),
inputs=[start_year, end_year],
outputs=[start_year, end_year, plot, chart_summary_state])
zoom_out.click(lambda s, e: zoom(s, e, 2.0),
inputs=[start_year, end_year],
outputs=[start_year, end_year, plot, chart_summary_state])
gr.File(value=str(EVENTS_PATH), label="Download cycle_events.json")
# โ”€โ”€ Tab 2: GPT Chat โ”€โ”€
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") # NEW
# ๊ธฐ๋ณธ ๋‹ต๋ณ€
def respond(history, msg, summ):
reply = chat_with_gpt(history, msg, summ)
history.append((msg, reply))
return history, gr.Textbox(value="")
# ์›น ๊ฒ€์ƒ‰ ํ›„ ๋‹ต๋ณ€
def respond_with_search(history, msg, summ):
search_md = format_search_results(msg)
combined = f"{msg}\n\n{search_md}"
reply = chat_with_gpt(history, combined, summ)
history.append((f"{msg}\n\n(์›น๊ฒ€์ƒ‰ ์‹คํ–‰)", reply))
return history, 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_with_search,
[chatbot, user_input, chart_summary_state],
[chatbot, user_input])
return demo
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
# 7. main
# โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
if __name__ == "__main__":
create_app().launch()