Spaces:
Running
Running
| # cycles_chat_app.py | |
| import os, math, numpy as np, matplotlib.pyplot as plt, gradio as gr | |
| import openai | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| # 0. OpenAI key | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| 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"] | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| # 1. Wave-style chart utilities | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| CYCLES = { | |
| "Tech Cycle (50 yr)": 50, | |
| "Finance Cycle (80 yr)": 80, | |
| "Hegemony Cycle (250 yr)": 250, | |
| } | |
| COLOR_MAP = {50: "#ff3333", 80: "#ffcc00", 250: "#66ccff"} | |
| AMPLITUDE_MAP = {50: 1.0, 80: 1.6, 250: 4.0} | |
| CENTER = 2025 # alignment reference | |
| 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_wave_chart_and_summary(start: int, end: int): | |
| xs = np.linspace(start, end, (end - start) * 4) | |
| fig, ax = plt.subplots(figsize=(14, 6)) | |
| fig.subplots_adjust(top=0.9) # prevent title clipping | |
| summaries, align_years, all_year_labels = [], None, set() | |
| for period in sorted(CYCLES.values()): | |
| col, amp = COLOR_MAP[period], AMPLITUDE_MAP[period] | |
| for frac in np.linspace(amp / 30, amp, 30): | |
| ax.plot(xs, _half_sine(xs, period, frac), color=col, alpha=0.85, lw=0.6) | |
| years = [CENTER + n * period for n in range( | |
| math.ceil((start - CENTER) / period), | |
| math.floor((end - CENTER) / period) + 1)] | |
| summaries.append(f"{period}-yr cycle peaks: {years}") | |
| align_years = set(years) if align_years is None else align_years & set(years) | |
| all_year_labels.update(years) | |
| # baseline year labels (small font, duplicates removed) | |
| for y in sorted(all_year_labels): | |
| if start <= y <= end: | |
| ax.text(y, -0.1, str(y), ha="center", va="top", | |
| fontsize=6, color="white", rotation=90) | |
| ax.set_facecolor("black") | |
| fig.patch.set_facecolor("black") | |
| ax.set_xlim(start, end) | |
| ax.set_ylim(-0.2, max(AMPLITUDE_MAP.values()) + 0.2) | |
| ax.set_xlabel("Year", color="white") | |
| ax.set_ylabel("Relative Amplitude", color="white") | |
| ax.set_title("Technology ยท Finance ยท Hegemony Cycles", color="white", | |
| pad=35, fontsize=14, fontweight="bold") | |
| ax.tick_params(colors="white") | |
| for spine in ax.spines.values(): | |
| spine.set_color("white") | |
| ax.grid(axis="y", color="white", ls="--", lw=.3, alpha=.3) | |
| # alignment marker | |
| ax.axvline(CENTER, color="white", ls="--", lw=1, alpha=.6) | |
| arrow_y = AMPLITUDE_MAP[250] * 1.05 | |
| ax.annotate("", xy=(CENTER - 125, arrow_y), xytext=(CENTER + 125, arrow_y), | |
| arrowprops=dict(arrowstyle="<|-|>", color="white", lw=1.2)) | |
| ax.text(CENTER, arrow_y + .15, "250 yr", color="white", | |
| ha="center", va="bottom", fontsize=10, fontweight="bold") | |
| summary = (f"Range {start}-{end}\n" | |
| + "\n".join(summaries) | |
| + f"\nAlignment year inside range: " | |
| + (", ".join(map(str, sorted(align_years))) if align_years else "None")) | |
| return fig, summary | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| # 2. GPT chat | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| BASE_PROMPT = ( | |
| "๋น์ ์ ๊ฐ๊ฒฐํ๊ณ ์ ํํ ํ๊ตญ์ด ์ด์์คํดํธ์ ๋๋ค. " | |
| "์ฌ์ฉ์์ ์ง๋ฌธ์ ๋ตํ ๋, ์ ๊ณต๋ [Chart summary] ๋ด์ฉ์ ๋ฐ๋์ ๋ฐ์ํ์ธ์." | |
| ) | |
| def chat_with_gpt(history, user_msg, chart_summary): | |
| msgs = [{"role": "system", "content": BASE_PROMPT}] | |
| if chart_summary != "No chart yet.": | |
| msgs.append({"role": "system", "content": f"[Chart summary]\n{chart_summary}"}) | |
| for u, a in history: | |
| msgs += [{"role": "user", "content": u}, | |
| {"role": "assistant", "content": a}] | |
| msgs.append({"role": "user", "content": user_msg}) | |
| reply = openai.chat.completions.create( | |
| model="gpt-3.5-turbo", | |
| messages=msgs, | |
| max_tokens=600, | |
| temperature=0.7 | |
| ).choices[0].message.content.strip() | |
| return reply | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| # 3. Gradio UI + CSS | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| custom_css = """ | |
| #wave_plot {width: 100% !important;} | |
| #wave_plot canvas {width: 100% !important; height: auto !important;} | |
| """ | |
| with gr.Blocks(css=custom_css, theme="apriel") as demo: | |
| # โโ NEW: ์๋น์ค ์ ๋ชฉ โโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| gr.Markdown("## ๐ **TriPulse Navigator**", elem_id="service_title") | |
| # โโ NEW: ๊ฐ๋จ ์ค๋ช โโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| gr.Markdown( | |
| """ | |
| **Tech Cycle (50 yr)** โ Innovation booms and busts every half-century. | |
| **Finance Cycle (80 yr)** โ Credit expansions and crises roughly once in a lifetime. | |
| **Hegemony Cycle (250 yr)** โ Rise & decline of world-leading powers over two-and-a-half centuries. | |
| """, | |
| elem_id="cycle_descriptions", | |
| ) | |
| chart_summary_state = gr.State(value="No chart yet.") | |
| with gr.Tabs(): | |
| # โธ Tab 1 โ Chart | |
| with gr.TabItem("Timeline Chart"): | |
| fig0, summ0 = build_wave_chart_and_summary(1500, 2500) | |
| plot_out = gr.Plot(value=fig0, elem_id="wave_plot") | |
| with gr.Row(): | |
| start_year = gr.Number(label="Start Year", value=1500) | |
| end_year = gr.Number(label="End Year", value=2500) | |
| def refresh_chart(s, e): | |
| fig, summ = build_wave_chart_and_summary(int(s), int(e)) | |
| return fig, summ | |
| start_year.change(refresh_chart, [start_year, end_year], | |
| [plot_out, chart_summary_state]) | |
| end_year.change(refresh_chart, [start_year, end_year], | |
| [plot_out, chart_summary_state]) | |
| # โธ Tab 2 โ GPT Chat | |
| with gr.TabItem("GPT Chat"): | |
| chatbot = gr.Chatbot(label="Assistant") | |
| user_in = gr.Textbox(lines=3, placeholder="๋ฉ์์ง๋ฅผ ์ ๋ ฅํ์ธ์โฆ") | |
| send_btn = gr.Button("Send", variant="primary") | |
| def respond(chat_hist, user_msg, summary): | |
| ans = chat_with_gpt(chat_hist, user_msg, summary) | |
| chat_hist.append((user_msg, ans)) | |
| return chat_hist, gr.Textbox(value="", interactive=True) | |
| send_btn.click(respond, [chatbot, user_in, chart_summary_state], | |
| [chatbot, user_in]) | |
| user_in.submit(respond, [chatbot, user_in, chart_summary_state], | |
| [chatbot, user_in]) | |
| if __name__ == "__main__": | |
| demo.launch() | |
| # cycles_chat_app.py | |
| import os, math, numpy as np, matplotlib.pyplot as plt, gradio as gr | |
| import openai | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| # 0. OpenAI key | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| 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"] | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| # 1. Wave-style chart utilities | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| CYCLES = { | |
| "Tech Cycle (50 yr)": 50, | |
| "Finance Cycle (80 yr)": 80, | |
| "Hegemony Cycle (250 yr)": 250, | |
| } | |
| COLOR_MAP = {50: "#ff3333", 80: "#ffcc00", 250: "#66ccff"} | |
| AMPLITUDE_MAP = {50: 1.0, 80: 1.6, 250: 4.0} | |
| CENTER = 2025 # alignment reference | |
| 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_wave_chart_and_summary(start: int, end: int): | |
| xs = np.linspace(start, end, (end - start) * 4) | |
| fig, ax = plt.subplots(figsize=(14, 6)) | |
| fig.subplots_adjust(top=0.9) # prevent title clipping | |
| summaries, align_years, all_year_labels = [], None, set() | |
| for period in sorted(CYCLES.values()): | |
| col, amp = COLOR_MAP[period], AMPLITUDE_MAP[period] | |
| for frac in np.linspace(amp / 30, amp, 30): | |
| ax.plot(xs, _half_sine(xs, period, frac), color=col, alpha=0.85, lw=0.6) | |
| years = [CENTER + n * period for n in range( | |
| math.ceil((start - CENTER) / period), | |
| math.floor((end - CENTER) / period) + 1)] | |
| summaries.append(f"{period}-yr cycle peaks: {years}") | |
| align_years = set(years) if align_years is None else align_years & set(years) | |
| all_year_labels.update(years) | |
| # baseline year labels (small font, duplicates removed) | |
| for y in sorted(all_year_labels): | |
| if start <= y <= end: | |
| ax.text(y, -0.1, str(y), ha="center", va="top", | |
| fontsize=6, color="white", rotation=90) | |
| ax.set_facecolor("black") | |
| fig.patch.set_facecolor("black") | |
| ax.set_xlim(start, end) | |
| ax.set_ylim(-0.2, max(AMPLITUDE_MAP.values()) + 0.2) | |
| ax.set_xlabel("Year", color="white") | |
| ax.set_ylabel("Relative Amplitude", color="white") | |
| ax.set_title("Technology ยท Finance ยท Hegemony Cycles", color="white", | |
| pad=35, fontsize=14, fontweight="bold") | |
| ax.tick_params(colors="white") | |
| for spine in ax.spines.values(): | |
| spine.set_color("white") | |
| ax.grid(axis="y", color="white", ls="--", lw=.3, alpha=.3) | |
| # alignment marker | |
| ax.axvline(CENTER, color="white", ls="--", lw=1, alpha=.6) | |
| arrow_y = AMPLITUDE_MAP[250] * 1.05 | |
| ax.annotate("", xy=(CENTER - 125, arrow_y), xytext=(CENTER + 125, arrow_y), | |
| arrowprops=dict(arrowstyle="<|-|>", color="white", lw=1.2)) | |
| ax.text(CENTER, arrow_y + .15, "250 yr", color="white", | |
| ha="center", va="bottom", fontsize=10, fontweight="bold") | |
| summary = (f"Range {start}-{end}\n" | |
| + "\n".join(summaries) | |
| + f"\nAlignment year inside range: " | |
| + (", ".join(map(str, sorted(align_years))) if align_years else "None")) | |
| return fig, summary | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| # 2. GPT chat | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| BASE_PROMPT = ( | |
| "๋น์ ์ ๊ฐ๊ฒฐํ๊ณ ์ ํํ ํ๊ตญ์ด ์ด์์คํดํธ์ ๋๋ค. " | |
| "์ฌ์ฉ์์ ์ง๋ฌธ์ ๋ตํ ๋, ์ ๊ณต๋ [Chart summary] ๋ด์ฉ์ ๋ฐ๋์ ๋ฐ์ํ์ธ์." | |
| ) | |
| def chat_with_gpt(history, user_msg, chart_summary): | |
| msgs = [{"role": "system", "content": BASE_PROMPT}] | |
| if chart_summary != "No chart yet.": | |
| msgs.append({"role": "system", "content": f"[Chart summary]\n{chart_summary}"}) | |
| for u, a in history: | |
| msgs += [{"role": "user", "content": u}, | |
| {"role": "assistant", "content": a}] | |
| msgs.append({"role": "user", "content": user_msg}) | |
| reply = openai.chat.completions.create( | |
| model="gpt-3.5-turbo", | |
| messages=msgs, | |
| max_tokens=600, | |
| temperature=0.7 | |
| ).choices[0].message.content.strip() | |
| return reply | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| # 3. Gradio UI + CSS | |
| # โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ | |
| custom_css = """ | |
| #wave_plot {width: 100% !important;} | |
| #wave_plot canvas {width: 100% !important; height: auto !important;} | |
| """ | |
| with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as demo: | |
| gr.Markdown("## ๐ Wave-style Cycle Timeline & ๐ฌ GPT Chat") | |
| chart_summary_state = gr.State(value="No chart yet.") | |
| with gr.Tabs(): | |
| # โธ Tab 1 โ Chart | |
| with gr.TabItem("Timeline Chart"): | |
| fig0, summ0 = build_wave_chart_and_summary(1500, 2500) | |
| plot_out = gr.Plot(value=fig0, elem_id="wave_plot") | |
| with gr.Row(): | |
| start_year = gr.Number(label="Start Year", value=1500) | |
| end_year = gr.Number(label="End Year", value=2500) | |
| def refresh_chart(s, e): | |
| fig, summ = build_wave_chart_and_summary(int(s), int(e)) | |
| return fig, summ | |
| start_year.change(refresh_chart, [start_year, end_year], | |
| [plot_out, chart_summary_state]) | |
| end_year.change(refresh_chart, [start_year, end_year], | |
| [plot_out, chart_summary_state]) | |
| # โธ Tab 2 โ GPT Chat | |
| with gr.TabItem("GPT Chat"): | |
| chatbot = gr.Chatbot(label="Assistant") | |
| user_in = gr.Textbox(lines=3, placeholder="๋ฉ์์ง๋ฅผ ์ ๋ ฅํ์ธ์โฆ") | |
| send_btn = gr.Button("Send", variant="primary") | |
| def respond(chat_hist, user_msg, summary): | |
| ans = chat_with_gpt(chat_hist, user_msg, summary) | |
| chat_hist.append((user_msg, ans)) | |
| return chat_hist, gr.Textbox(value="", interactive=True) | |
| send_btn.click(respond, [chatbot, user_in, chart_summary_state], | |
| [chatbot, user_in]) | |
| user_in.submit(respond, [chatbot, user_in, chart_summary_state], | |
| [chatbot, user_in]) | |
| if __name__ == "__main__": | |
| demo.launch() | |