King3Djbl commited on
Commit
3b031b9
ยท
verified ยท
1 Parent(s): 3ed63db

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -119
app.py CHANGED
@@ -2,19 +2,19 @@ import os
2
  import re
3
  import json
4
  import urllib.parse
 
5
  from pathlib import Path
6
  import gradio as gr
7
  from llama_cpp import Llama
8
 
9
  # ================== CONFIG ==================
10
- # Use a tiny 1.1B model for speed and memory
11
  MODEL_REPO = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF"
12
  GGUF_FILE = "tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf" # ~700 MB
13
  MAX_TURNS = 50
14
  HISTORY_WINDOW = 10
15
  LEADERBOARD_FILE = Path("/tmp/leaderboard.json")
16
 
17
- # Initialize leaderboard
18
  if not LEADERBOARD_FILE.exists():
19
  LEADERBOARD_FILE.write_text(json.dumps([
20
  {"Rank": "1", "Genre": "Dark Fantasy", "Actions": 24, "Fate": "Devoured by Mimic"},
@@ -31,7 +31,7 @@ try:
31
  n_ctx=1024,
32
  n_threads=2,
33
  use_mmap=True,
34
- chat_format="llama-2", # suitable for TinyLlama
35
  verbose=False,
36
  )
37
  model_ready = True
@@ -52,8 +52,7 @@ def generate_response(messages, max_tokens=200, temperature=0.9):
52
  top_p=0.9,
53
  )
54
  raw_output = out["choices"][0]["message"]["content"].strip()
55
- # Clean out any leftover Llama instruction tokens if they leak into text string
56
- raw_output = re.sub(r"\\[/?INST\\]|\\[/?SYS\\]|<<SYS>>|<</SYS>>", "", raw_output).strip()
57
  return raw_output
58
  except Exception as e:
59
  print("LLM error:", e)
@@ -94,7 +93,6 @@ def new_game(selected_genre="Dark Fantasy"):
94
  "hp": 100,
95
  "genre": selected_genre,
96
  "status_msg": f"๐ŸŽฒ Setting up theme: {selected_genre}...",
97
- "processing": False,
98
  }
99
 
100
  def _ctx(history, system, speaker):
@@ -119,23 +117,49 @@ def get_leaderboard_df():
119
  data = json.loads(LEADERBOARD_FILE.read_text())
120
  return [[r["Rank"], r["Genre"], r["Actions"], r["Fate"]] for r in data]
121
 
122
- def advance(state):
123
- if not state or not state["running"] or state["turn"] >= MAX_TURNS * 2 or state["hp"] <= 0:
124
- if state and state["hp"] <= 0 and state["running"]:
125
- state["running"] = False
126
- state["status_msg"] = "๐Ÿ’€ GAME OVER! The player has died."
127
- update_leaderboard(state["genre"], state["turn"], "Flatlined at 0 HP")
128
- return state
129
 
130
- if state.get("processing", False):
131
- return state
132
- state["processing"] = True
 
 
 
 
 
 
133
 
134
- try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  hist = state["history"]
136
  genre_cfg = GENRES.get(state["genre"], GENRES["Dark Fantasy"])
137
 
138
  if state["next"] == "gm":
 
 
 
139
  if not hist:
140
  ctx = [{"role": "system", "content": genre_cfg["gm"]},
141
  {"role": "user", "content": genre_cfg["start"]}]
@@ -146,7 +170,7 @@ def advance(state):
146
  response = generate_response(ctx, max_tokens=220)
147
  hist.append({"role": "gm", "content": response})
148
 
149
- hp_match = re.search(r"\\[HP\\s*([\\+\\-])\\s*(\\d+)\\]", response)
150
  if hp_match:
151
  op, val = hp_match.groups()
152
  delta = int(val) if op == "+" else -int(val)
@@ -154,119 +178,37 @@ def advance(state):
154
 
155
  state["next"] = "player"
156
  else:
 
 
 
157
  if state["intervention"]:
158
  player = state["intervention"]
159
  state["intervention"] = None
 
160
  else:
161
  ctx = _ctx(hist, genre_cfg["player"], "player")
162
  ctx.append({"role": "user", "content": "Declare what action you take next."})
163
  player = generate_response(ctx, max_tokens=180)
 
164
  hist.append({"role": "player", "content": player})
165
  state["next"] = "gm"
166
 
167
  state["turn"] += 1
168
- finally:
169
- state["processing"] = False
170
-
171
- return state
172
-
173
- # ================== RENDER UTILITIES ==================
174
- def _dice(text):
175
- text = re.sub(r"\\[roll\\s+d(\\d+)\\]", r'<span class="dice">๐ŸŽฒ d\\1</span>', text)
176
- text = re.sub(r"\\[HP\\s*([\\+\\-Outside]\\d+)\\]", r'<span class="hp-change">๐Ÿ’” \\1 HP</span>', text)
177
- return text
178
-
179
- def render(state):
180
- if not state:
181
- return []
182
- msgs = []
183
- for e in state["history"]:
184
- role = "assistant" if e["role"] == "gm" else "user"
185
- prefix = "๐Ÿ”ฎ **GM**: " if e["role"] == "gm" else "โš”๏ธ **Player**: "
186
- msgs.append({"role": role, "content": prefix + _dice(e["content"])})
187
- return msgs
188
-
189
- def make_share_link(state):
190
- if not state or not state["history"]:
191
- return gr.update(visible=False)
192
- base_text = f"๐Ÿฟ Survival Level: {state['turn']} actions inside the unhinged '{state['genre']}' AI simulation! Can you survive longer? ๐Ÿ‘‡"
193
- encoded_text = urllib.parse.quote(base_text)
194
- encoded_url = urllib.parse.quote("https://huggingface.co/spaces/King3Djbl/dual-gm-simulator")
195
- twitter_url = f"https://twitter.com/intent/tweet?text={encoded_text}&url={encoded_url}"
196
- return gr.update(value=f'<a href="{twitter_url}" target="_blank" class="share-btn">๐Ÿฆ Broadcast Score to X</a>', visible=True)
197
 
198
  # ================== APP LAYOUT & CORE THEME ==================
199
  custom_css = """
200
  .dice { display:inline-block; background:#1e1e2e; border-radius:6px; padding:2px 8px; font-weight:bold; color:#f9e2af; border:1px solid #f38ba8; }
201
- .hp-change { display:inline-block; background:#2a1414; border-radius:6px; padding:2px 8px; font-weight:bold; color:#f38ba8; border:1px solid red; }
202
- .share-btn { display: block; text-align: center; background: #1da1f2; color: white !important; font-weight: bold; padding: 12px; border-radius: 8px; text-decoration: none; margin-top: 10px; box-shadow: 0 4px 15px rgba(29, 161, 242, 0.3); }
203
- """
204
-
205
- with gr.Blocks(title="๐ŸŽญ Tiny Mythos Arena", theme=gr.themes.Default(primary_hue="rose"), css=custom_css) as demo:
206
- gr.Markdown("# ๐ŸŽญ Unhinged Dual-AI Simulation Arena\n### *Two instances of TinyLlama-1.1B cross-talk endless storylines under competing game parameters.*")
207
-
208
- state = gr.State(new_game())
209
-
210
- with gr.Row():
211
- with gr.Column(scale=2):
212
- genre_dd = gr.Dropdown(choices=list(GENRES.keys()), value="Dark Fantasy", label="๐Ÿš€ 1. Choose Adventure Dimension (Genre)")
213
- hp_bar = gr.Slider(label="โค๏ธ Player Health Pool", value=100, minimum=0, maximum=100, interactive=False)
214
- status = gr.Textbox(label="๐ŸŽฌ Arena Director Feed", value="โœ… System Ready", interactive=False)
215
- with gr.Column(scale=1):
216
- start_btn = gr.Button("๐ŸŽฌ Boot Simulation", variant="primary", size="lg")
217
- stop_btn = gr.Button("โน๏ธ Halt Simulation", variant="stop")
218
- share_html = gr.HTML(visible=False)
219
-
220
- with gr.Tabs():
221
- with gr.TabItem("๐Ÿ“บ Live Stream Monitor"):
222
- chatbot = gr.Chatbot(label="Interactive Thread Logs", height=500, type="messages")
223
- with gr.Row():
224
- intervene_box = gr.Textbox(label="๐Ÿ’ฅ Inject Neural Hack (Player Mind Intervention)", placeholder="Force the player to execute a specific move...", lines=2, scale=4)
225
- send_intervene = gr.Button("โšก Inject Move", variant="secondary", scale=1)
226
-
227
- with gr.TabItem("๐Ÿ† Global Hall of Fame (Leaderboard)"):
228
- gr.Markdown("### ๐Ÿ’€ Top Simulations Survived Across Active Container Lifespan")
229
- leaderboard_view = gr.Dataframe(
230
- headers=["Rank", "World Dimension", "Actions", "Ending Fate"],
231
- value=get_leaderboard_df(),
232
- interactive=False
233
- )
234
-
235
- # Hidden background runner clock loop setup
236
- timer = gr.Timer(value=2, active=False)
237
-
238
- def start_action(chosen_genre):
239
- s = new_game(chosen_genre)
240
- s["running"] = True
241
- return s, f"๐ŸŽฌ Running dimension: '{chosen_genre}'... Generating introduction...", gr.Timer(active=True), s["hp"]
242
-
243
- def stop_action(s):
244
- if s: s["running"] = False
245
- return s, "โน๏ธ Simulation frozen manually.", gr.Timer(active=False), s["hp"] if s else 100
246
-
247
- def intervene_action(msg, s):
248
- if s and s.get("running") and msg.strip():
249
- s["intervention"] = msg.strip()
250
- s["next"] = "player"
251
- return s, f"๐Ÿ”ฎ Mind Control Override queued: '{msg.strip()}'", ""
252
- return s, "Boot a simulation before hacking the neural stream!", ""
253
-
254
- def tick(s):
255
- s = advance(s)
256
- timer_update = gr.Timer(active=s["running"])
257
- return s, render(s), s["status_msg"], s["hp"], timer_update, get_leaderboard_df()
258
-
259
- # Event Connections
260
- start_btn.click(start_action, inputs=genre_dd, outputs=[state, status, timer, hp_bar])
261
- stop_btn.click(stop_action, inputs=state, outputs=[state, status, timer, hp_bar])
262
-
263
- send_intervene.click(intervene_action, inputs=[intervene_box, state], outputs=[state, status, intervene_box])
264
- intervene_box.submit(intervene_action, inputs=[intervene_box, state], outputs=[state, status, intervene_box])
265
-
266
- timer.tick(tick, inputs=state, outputs=[state, chatbot, status, hp_bar, timer, leaderboard_view]).then(
267
- make_share_link, inputs=state, outputs=share_html
268
- )
269
-
270
- if __name__ == "__main__":
271
- demo.queue(default_concurrency_limit=1).launch(server_name="0.0.0.0", server_port=7860)
272
-
 
2
  import re
3
  import json
4
  import urllib.parse
5
+ import time
6
  from pathlib import Path
7
  import gradio as gr
8
  from llama_cpp import Llama
9
 
10
  # ================== CONFIG ==================
 
11
  MODEL_REPO = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF"
12
  GGUF_FILE = "tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf" # ~700 MB
13
  MAX_TURNS = 50
14
  HISTORY_WINDOW = 10
15
  LEADERBOARD_FILE = Path("/tmp/leaderboard.json")
16
 
17
+ # Initialize leaderboard safely
18
  if not LEADERBOARD_FILE.exists():
19
  LEADERBOARD_FILE.write_text(json.dumps([
20
  {"Rank": "1", "Genre": "Dark Fantasy", "Actions": 24, "Fate": "Devoured by Mimic"},
 
31
  n_ctx=1024,
32
  n_threads=2,
33
  use_mmap=True,
34
+ chat_format="llama-2",
35
  verbose=False,
36
  )
37
  model_ready = True
 
52
  top_p=0.9,
53
  )
54
  raw_output = out["choices"][0]["message"]["content"].strip()
55
+ raw_output = re.sub(r"\[/?INST\]|\[/?SYS\]|<<SYS>>|<</SYS>>", "", raw_output).strip()
 
56
  return raw_output
57
  except Exception as e:
58
  print("LLM error:", e)
 
93
  "hp": 100,
94
  "genre": selected_genre,
95
  "status_msg": f"๐ŸŽฒ Setting up theme: {selected_genre}...",
 
96
  }
97
 
98
  def _ctx(history, system, speaker):
 
117
  data = json.loads(LEADERBOARD_FILE.read_text())
118
  return [[r["Rank"], r["Genre"], r["Actions"], r["Fate"]] for r in data]
119
 
120
+ # ================== RENDER UTILITIES ==================
121
+ def _dice(text):
122
+ text = re.sub(r"\[roll\s+d(\d+)\]", r'<span class="dice">๐ŸŽฒ d\1</span>', text)
123
+ text = re.sub(r"\[HP\s*([\+\-]\d+)\]", r'<span class="hp-change">๐Ÿ’” \1 HP</span>', text)
124
+ return text
 
 
125
 
126
+ def render(state):
127
+ if not state:
128
+ return []
129
+ msgs = []
130
+ for e in state["history"]:
131
+ role = "assistant" if e["role"] == "gm" else "user"
132
+ prefix = "๐Ÿ”ฎ **GM**: " if e["role"] == "gm" else "โš”๏ธ **Player**: "
133
+ msgs.append({"role": role, "content": prefix + _dice(e["content"])})
134
+ return msgs
135
 
136
+ def make_share_link(state):
137
+ if not state or not state["history"]:
138
+ return gr.update(visible=False)
139
+ base_text = f"๐Ÿฟ Survival Level: {state['turn']} actions inside the unhinged '{state['genre']}' AI simulation! Can you survive longer? ๐Ÿ‘‡"
140
+ encoded_text = urllib.parse.quote(base_text)
141
+ encoded_url = urllib.parse.quote("https://huggingface.co")
142
+ twitter_url = f"https://twitter.com{encoded_text}&url={encoded_url}"
143
+ return gr.update(value=f'<a href="{twitter_url}" target="_blank" class="share-btn">๐Ÿฆ Broadcast Score to X</a>', visible=True)
144
+
145
+ # ================== MAIN GAME GENERATOR ENGINE ==================
146
+ def run_simulation_loop(state):
147
+ """
148
+ Fixed native generation engine loop.
149
+ Bypasses broken background clocks by yielding updates directly.
150
+ """
151
+ if not state or not state["running"]:
152
+ yield state, render(state), "โธ๏ธ Simulation stopped.", state["hp"] if state else 100, get_leaderboard_df()
153
+ return
154
+
155
+ while state["running"] and state["turn"] < MAX_TURNS * 2 and state["hp"] > 0:
156
  hist = state["history"]
157
  genre_cfg = GENRES.get(state["genre"], GENRES["Dark Fantasy"])
158
 
159
  if state["next"] == "gm":
160
+ state["status_msg"] = "๐Ÿ”ฎ GM is writing the next scenario turn..."
161
+ yield state, render(state), state["status_msg"], state["hp"], get_leaderboard_df()
162
+
163
  if not hist:
164
  ctx = [{"role": "system", "content": genre_cfg["gm"]},
165
  {"role": "user", "content": genre_cfg["start"]}]
 
170
  response = generate_response(ctx, max_tokens=220)
171
  hist.append({"role": "gm", "content": response})
172
 
173
+ hp_match = re.search(r"\[HP\s*([\+\-])\s*(\d+)\]", response)
174
  if hp_match:
175
  op, val = hp_match.groups()
176
  delta = int(val) if op == "+" else -int(val)
 
178
 
179
  state["next"] = "player"
180
  else:
181
+ state["status_msg"] = "โš”๏ธ Player is formulating an action..."
182
+ yield state, render(state), state["status_msg"], state["hp"], get_leaderboard_df()
183
+
184
  if state["intervention"]:
185
  player = state["intervention"]
186
  state["intervention"] = None
187
+ state["status_msg"] = "๐Ÿ”ฎ Neural Hack Override Successful!"
188
  else:
189
  ctx = _ctx(hist, genre_cfg["player"], "player")
190
  ctx.append({"role": "user", "content": "Declare what action you take next."})
191
  player = generate_response(ctx, max_tokens=180)
192
+
193
  hist.append({"role": "player", "content": player})
194
  state["next"] = "gm"
195
 
196
  state["turn"] += 1
197
+ time.sleep(1) # Visual pacing padding gap
198
+ yield state, render(state), state["status_msg"], state["hp"], get_leaderboard_df()
199
+
200
+ # Game Over validation parameters
201
+ if state["hp"] <= 0:
202
+ state["running"] = False
203
+ state["status_msg"] = "๐Ÿ’€ GAME OVER! The player has died."
204
+ update_leaderboard(state["genre"], state["turn"], "Flatlined at 0 HP")
205
+ elif state["turn"] >= MAX_TURNS * 2:
206
+ state["running"] = False
207
+ state["status_msg"] = "๐Ÿ† VICTORY! You survived the entire timeline arena!"
208
+ update_leaderboard(state["genre"], state["turn"], "Escaped the Arena Alive")
209
+
210
+ yield state, render(state), state["status_msg"], state["hp"], get_leaderboard_df()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
 
212
  # ================== APP LAYOUT & CORE THEME ==================
213
  custom_css = """
214
  .dice { display:inline-block; background:#1e1e2e; border-radius:6px; padding:2px 8px; font-weight:bold; color:#f9e2af; border:1px solid #f38ba8; }