Martico2432 commited on
Commit
e25dead
·
verified ·
1 Parent(s): 94f7efc

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +295 -0
app.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import gradio as gr
4
+ from game_config import CLOUD_TICK_SECONDS, HF_MAX_NEW_TOKENS, HF_MODEL_ID
5
+ from huggingface_hub import InferenceClient
6
+ from state import (
7
+ buy_upgrade,
8
+ chat_temperature,
9
+ cloud_tick,
10
+ new_game,
11
+ status_lines,
12
+ toggle_cloud,
13
+ train_model,
14
+ unlock_cloud,
15
+ upgrade_status,
16
+ )
17
+
18
+ CSS = """
19
+ <style>
20
+ @import url('https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;700&display=swap');
21
+ body, .gradio-container {
22
+ background-color: #0a0f0d !important;
23
+ font-family: 'Fira Code', monospace !important;
24
+ color: #33ff33 !important;
25
+ }
26
+ #terminal-card {
27
+ background-color: #0d1410 !important;
28
+ border: 2px solid #22aa22 !important;
29
+ box-shadow: 0 0 20px rgba(51, 255, 51, 0.15);
30
+ border-radius: 4px;
31
+ padding: 15px;
32
+ }
33
+ .gr-button, button {
34
+ background: #142218 !important;
35
+ color: #33ff33 !important;
36
+ border: 1px solid #33ff33 !important;
37
+ font-family: 'Fira Code', monospace !important;
38
+ border-radius: 2px !important;
39
+ cursor: pointer;
40
+ transition: all 0.2s ease;
41
+ }
42
+ .gr-button:hover, button:hover {
43
+ background: #33ff33 !important;
44
+ color: #0a0f0d !important;
45
+ box-shadow: 0 0 10px #33ff33;
46
+ }
47
+ .gr-text-input, textarea, input[type="text"] {
48
+ background-color: #050806 !important;
49
+ border: 1px solid #22aa22 !important;
50
+ color: #33ff33 !important;
51
+ font-family: 'Fira Code', monospace !important;
52
+ border-radius: 2px !important;
53
+ }
54
+ .gr-text-input:focus, textarea:focus, input[type="text"]:focus {
55
+ border-color: #33ff33 !important;
56
+ outline: none !important;
57
+ }
58
+ #console-log-area {
59
+ max-height: 350px;
60
+ overflow-y: auto;
61
+ }
62
+ footer { display: none !important; }
63
+ </style>
64
+ """
65
+
66
+
67
+ def get_huggingface_response(prompt: str, temperature: float, token: str) -> str:
68
+ """
69
+ Queries Hugging Face using the player's active OAuth token.
70
+ Uses chat_completion to satisfy the conversational task requirement.
71
+ """
72
+ try:
73
+ # Securely explicitly initializes InferenceClient with the player's token
74
+ client = InferenceClient(model=HF_MODEL_ID, token=token)
75
+
76
+ messages = [{"role": "user", "content": prompt}]
77
+
78
+ response = client.chat_completion(
79
+ messages=messages,
80
+ max_tokens=HF_MAX_NEW_TOKENS,
81
+ temperature=max(0.01, temperature),
82
+ )
83
+ return response.choices[0].message.content
84
+
85
+ except Exception as e:
86
+ return f"[FATAL_ERR] Model Inference Failed: {str(e)}"
87
+
88
+
89
+ def render_ui_panes(state: dict) -> tuple[str, str, str]:
90
+ stats = f"=== SYSTEM STATUS ===\n{status_lines(state)}\n====================="
91
+
92
+ upg_info = upgrade_status(state)
93
+ upg_lines = ["=== HARDWARE & ARCHITECTURE MARKETPLACE ==="]
94
+ for key, info in upg_info.items():
95
+ cost_str = f"${info['next_cost']:.0f}" if not info["maxed"] else "MAXED"
96
+ upg_lines.append(
97
+ f"{info['icon']} {info['label']} [{info['current_name']}]\n"
98
+ f" Tier: {info['current_tier']}/{info['max_tier']} | Cost: {cost_str}\n"
99
+ f" Desc: {info['description']}"
100
+ )
101
+ upg_lines.append("==========================================")
102
+
103
+ log_text = "\n".join(state.get("log", ["[SYS] Cluster Initialized."]))
104
+ return stats, "\n\n".join(upg_lines), log_text
105
+
106
+
107
+ # --- Interface Core Action Mappers ---
108
+
109
+
110
+ def handle_init():
111
+ state = new_game()
112
+ stats, upgs, logs = render_ui_panes(state)
113
+ return state, stats, upgs, logs, gr.update(choices=list(state["upgrades"].keys()))
114
+
115
+
116
+ def handle_train(state: dict):
117
+ new_state, _ = train_model(state)
118
+ stats, upgs, logs = render_ui_panes(new_state)
119
+ return new_state, stats, upgs, logs
120
+
121
+
122
+ def handle_upgrade(state: dict, upgrade_key: str):
123
+ if not upgrade_key:
124
+ return state, gr.update(), gr.update(), gr.update()
125
+ new_state, _ = buy_upgrade(state, upgrade_key)
126
+ stats, upgs, logs = render_ui_panes(new_state)
127
+ return new_state, stats, upgs, logs
128
+
129
+
130
+ def handle_cloud_unlock(state: dict):
131
+ new_state, _ = unlock_cloud(state)
132
+ stats, upgs, logs = render_ui_panes(new_state)
133
+ return new_state, stats, upgs, logs
134
+
135
+
136
+ def handle_cloud_toggle(state: dict):
137
+ new_state, _ = toggle_cloud(state)
138
+ stats, upgs, logs = render_ui_panes(new_state)
139
+ return new_state, stats, upgs, logs
140
+
141
+
142
+ def handle_tick(state: dict):
143
+ if not state.get("cloud_active", False):
144
+ return state, gr.update(), gr.update(), gr.update()
145
+ new_state, revenue = cloud_tick(state)
146
+ stats, upgs, logs = render_ui_panes(new_state)
147
+ return new_state, stats, upgs, logs
148
+
149
+
150
+ def handle_chat(
151
+ state: dict,
152
+ history: list,
153
+ message: str,
154
+ profile: gr.OAuthProfile | None,
155
+ oauth_token: gr.OAuthToken | None,
156
+ ):
157
+ if not message.strip():
158
+ return history, ""
159
+
160
+ if history is None:
161
+ history = []
162
+
163
+ # Block inference if the user isn't authenticated through the UI
164
+ if oauth_token is None:
165
+ history.append(
166
+ [
167
+ message,
168
+ "[SYS_ERR] Access Denied. Please authorize using the 'Sign in with Hugging Face' button.",
169
+ ]
170
+ )
171
+ return history, ""
172
+
173
+ temp = chat_temperature(state)
174
+
175
+ if temp > 1.4:
176
+ prompt = f"Produce dynamic fragmented word-salad, glitch texts, and chaotic tokens based loosely on: {message}"
177
+ else:
178
+ prompt = message
179
+
180
+ # Execute request using their injected token
181
+ response = get_huggingface_response(prompt, temp, oauth_token.token)
182
+
183
+ # Reverted to standard tuple arrays to fix TypeError in Chatbot init
184
+ history.append([message, response])
185
+
186
+ return history, ""
187
+
188
+
189
+ # --- Layout Assembly ---
190
+
191
+ with gr.Blocks(title="AI Training Simulator v2.026") as demo:
192
+ gr.HTML(CSS)
193
+ game_state = gr.State()
194
+ tick_trigger = gr.Button("tick_trigger", visible=False, elem_id="tick_trigger")
195
+
196
+ gr.Markdown("# 📟 THOUSAND TOKEN WOOD // STARTUP TERMINAL")
197
+
198
+ with gr.Column(elem_id="terminal-card"):
199
+ with gr.Row():
200
+ with gr.Column(scale=1):
201
+ status_pane = gr.Code(
202
+ label="System Mon", language="markdown", interactive=False
203
+ )
204
+ train_btn = gr.Button("⚡ RUN TRAINING PASS", variant="primary")
205
+
206
+ with gr.Row():
207
+ unlock_cloud_btn = gr.Button("🔓 UNLOCK CLOUD")
208
+ toggle_cloud_btn = gr.Button("⏯️ TOGGLE CLOUD")
209
+
210
+ with gr.Column(scale=1):
211
+ market_pane = gr.Code(
212
+ label="Stack Upgrade Hub", language="markdown", interactive=False
213
+ )
214
+ upgrade_dropdown = gr.Dropdown(
215
+ label="Select Component to Upgrade", choices=[]
216
+ )
217
+ buy_btn = gr.Button("💳 PURCHASE UPGRADE")
218
+
219
+ gr.Markdown("### 📜 Console System Output Logs")
220
+ log_pane = gr.Textbox(
221
+ label="", interactive=False, lines=8, elem_id="console-log-area"
222
+ )
223
+
224
+ gr.Markdown("### 💬 Live Model Inference Playground")
225
+
226
+ # Injected Native Hugging Face Auth Components
227
+ with gr.Row():
228
+ gr.LoginButton()
229
+
230
+ chatbot = gr.Chatbot(label="Model Output Channel")
231
+ with gr.Row():
232
+ chat_input = gr.Textbox(
233
+ placeholder="Query model parameter space...", scale=4, show_label=False
234
+ )
235
+ send_btn = gr.Button("📡 INFERENCE", scale=1)
236
+
237
+ # --- Wire UI action flows ---
238
+
239
+ demo.load(
240
+ handle_init,
241
+ outputs=[game_state, status_pane, market_pane, log_pane, upgrade_dropdown],
242
+ )
243
+
244
+ demo.load(
245
+ None,
246
+ js=f"""
247
+ function() {{
248
+ setInterval(() => {{
249
+ let btn = document.querySelector('#tick_trigger');
250
+ if (btn) btn.click();
251
+ }}, {CLOUD_TICK_SECONDS * 1000});
252
+ }}
253
+ """,
254
+ )
255
+
256
+ train_btn.click(
257
+ handle_train,
258
+ inputs=[game_state],
259
+ outputs=[game_state, status_pane, market_pane, log_pane],
260
+ )
261
+ buy_btn.click(
262
+ handle_upgrade,
263
+ inputs=[game_state, upgrade_dropdown],
264
+ outputs=[game_state, status_pane, market_pane, log_pane],
265
+ )
266
+ unlock_cloud_btn.click(
267
+ handle_cloud_unlock,
268
+ inputs=[game_state],
269
+ outputs=[game_state, status_pane, market_pane, log_pane],
270
+ )
271
+ toggle_cloud_btn.click(
272
+ handle_cloud_toggle,
273
+ inputs=[game_state],
274
+ outputs=[game_state, status_pane, market_pane, log_pane],
275
+ )
276
+ tick_trigger.click(
277
+ handle_tick,
278
+ inputs=[game_state],
279
+ outputs=[game_state, status_pane, market_pane, log_pane],
280
+ )
281
+
282
+ # Gradio handles mapping profile/oauth_token automatically, so we don't put them in the inputs array
283
+ send_btn.click(
284
+ handle_chat,
285
+ inputs=[game_state, chatbot, chat_input],
286
+ outputs=[chatbot, chat_input],
287
+ )
288
+ chat_input.submit(
289
+ handle_chat,
290
+ inputs=[game_state, chatbot, chat_input],
291
+ outputs=[chatbot, chat_input],
292
+ )
293
+
294
+ if __name__ == "__main__":
295
+ demo.launch()