File size: 5,427 Bytes
366df60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59940af
 
 
366df60
 
59940af
366df60
 
 
 
 
 
 
59940af
 
 
 
 
 
 
366df60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59940af
 
 
366df60
59940af
 
366df60
59940af
366df60
 
 
 
710a337
 
 
366df60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import gradio as gr
import pandas as pd
from openai import OpenAI
from inference import run_task, TASKS, API_BASE_URL, API_KEY

# -- App Logic -----------------------------------------------------------------

def launch_ceo_simulation(task_id):
    if not API_KEY:
        return "ERROR: HF_TOKEN missing.", None, None, None
    
    client = OpenAI(base_url=API_BASE_URL, api_key=API_KEY)
    
    # State for UI
    history = []
    budget_data = []
    rep_data = []
    clients_served = 0
    initial_budget = None
    initial_rep = None
    
    def on_step(data):
        nonlocal clients_served, initial_budget, initial_rep
        if "done" in data:
            return
        
        step = data["step"]
        obs = data["obs"]
        thought = data["thought"]
        
        if initial_budget is None: initial_budget = obs.budget
        if initial_rep is None: initial_rep = obs.reputation
        
        # Track clients served
        if data.get("reward", 0) > 0.1: 
            clients_served += 1
        
        # Update history
        history.append({
            "Quarter": obs.quarter,
            "Budget": obs.budget,
            "Reputation": obs.reputation,
            "Market": obs.market_phase.value,
            "Thought": thought
        })
        
        budget_data.append([obs.quarter, obs.budget])
        rep_data.append([obs.quarter, obs.reputation])

    # Yield updates to Gradio
    try:
        # We wrap the generator in a yield loop for Gradio
        gen_data = {"step": 0, "logs": ""}
        
        def ui_callback(d):
            gen_data["last"] = d
        
        # Run the task in a separate way or just yield manually
        # Since run_task is synchronous but we want live updates, 
        # we refactor run_task to be a generator in a real app, 
        # but here we'll simulate the live feel by yielding at the end or 
        # using a simple queue if needed. 
        # For this version, let's keep it robust.
        
        import threading
        import time
        
        results_queue = []
        def queue_callback(d):
            results_queue.append(d)
            
        thread = threading.Thread(target=run_task, args=(client, task_id, queue_callback))
        thread.start()
        
        while thread.is_alive() or results_queue:
            if results_queue:
                data = results_queue.pop(0)
                if "done" in data:
                    yield (
                        f"### Task Complete! \n**Final Score: {data.get('score', 0):.3f}**",
                        pd.DataFrame(history),
                        pd.DataFrame(budget_data, columns=["Quarter", "Budget"]),
                        pd.DataFrame(rep_data, columns=["Quarter", "Reputation"])
                    )
                    break
                
                obs = data["obs"]
                on_step(data)
                
                nw_growth = ((obs.budget - initial_budget) / initial_budget) * 100 if initial_budget else 0
                rep_growth = ((obs.reputation - initial_rep) / initial_rep) * 100 if initial_rep else 0
                
                status_md = f"""
                ## 🏒 CEO Command Center | {task_id}
                **Net Worth Growth**: `{nw_growth:+.1f}%` | **Reputation Growth**: `{rep_growth:+.1f}%` | **Clients Served**: `{clients_served}`
                ---
                **Quarter**: {obs.quarter} | **Budget**: ${obs.budget:,.0f} | **Reputation**: {obs.reputation:.2f}
                **CEO THOUGHTS**: 
                > {data['thought']}
                """
                
                if data.get("done"):
                    status_md = f"# πŸ† MISSION ACCOMPLISHED!\n## FINAL GROWTH: {nw_growth:+.1f}% \n{status_md}"
                
                yield (
                    status_md,
                    pd.DataFrame(history),
                    pd.DataFrame(budget_data, columns=["Quarter", "Budget"]),
                    pd.DataFrame(rep_data, columns=["Quarter", "Reputation"])
                )
            time.sleep(0.1)
            
    except Exception as e:
        yield f"Error: {str(e)}", None, None, None

# -- UI Layout -----------------------------------------------------------------

with gr.Blocks(title="AI CEO Dashboard") as demo:
    gr.Markdown("# 🏒 AI Strategic CEO Dashboard")
    gr.Markdown("### Meta PyTorch Hackathon β€” Business Simulation")
    
    with gr.Row():
        task_input = gr.Dropdown(choices=TASKS, value=TASKS[0], label="Select Business Task")
        run_btn = gr.Button("πŸš€ Start CEO Strategy", variant="primary")
    
    status_display = gr.Markdown("Click Start to begin the simulation...")
    
    with gr.Tabs():
        with gr.TabItem("πŸ“Š Financial Pulse"):
            with gr.Row():
                budget_plot = gr.LinePlot(x="Quarter", y="Budget", title="Budget Growth")
                rep_plot = gr.LinePlot(x="Quarter", y="Reputation", title="Reputation Trend")
        
        with gr.TabItem("πŸ“‹ Strategy Log"):
            log_table = gr.Dataframe(headers=["Quarter", "Budget", "Reputation", "Market", "Thought"], wrap=True)

    run_btn.click(
        fn=launch_ceo_simulation,
        inputs=[task_input],
        outputs=[status_display, log_table, budget_plot, rep_plot]
    )

if __name__ == "__main__":
    demo.queue()
    demo.launch(server_name="0.0.0.0", server_port=7861)