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()