multimodalart HF Staff commited on
Commit
021e8d0
·
verified ·
1 Parent(s): e53743c

Upload folder using huggingface_hub

Browse files
.gitattributes CHANGED
@@ -33,3 +33,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ examples/memory_match.png filter=lfs diff=lfs merge=lfs -text
37
+ examples/simon_sequence.png filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,13 +1,43 @@
1
  ---
2
- title: Game2player
3
- emoji: 👁
4
  colorFrom: red
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
- python_version: '3.12'
9
  app_file: app.py
10
- pinned: false
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Game2Player
3
+ emoji: 🎮
4
  colorFrom: red
5
+ colorTo: gray
6
  sdk: gradio
7
  sdk_version: 6.32.0
 
8
  app_file: app.py
9
+ short_description: Visual game-playing agent — screenshot + task to next action
10
+ python_version: "3.12"
11
+ startup_duration_timeout: 30m
12
  ---
13
 
14
+ # Game2Player — Visual Game-Playing Agent
15
+
16
+ **Game2Player: Scaling Gameplay Experience for Visual Agents through Environment-Player Co-Development**
17
+ ([paper](https://arxiv.org/abs/2611.24154) · [code](https://github.com/game2player/Game2Player))
18
+
19
+ This Space runs the released **Game2Player-9B** checkpoint (a Qwen3.5-9B fine-tune) with
20
+ transformers, replicating the authors' serving recipe — bf16, ≤1,048,576 pixels per
21
+ screenshot, thinking disabled, temperature 1.0 — and their PlayerBench prompt and
22
+ action decoder, both ported 1:1 from the official repository.
23
+
24
+ Give the model a **game screenshot** and a **task description** (plus the game's rules
25
+ and allowed keys), and it returns the next keyboard or mouse action as a
26
+ `computer_use` tool call, decoded to a canonical action and drawn on the screenshot:
27
+ click coordinates, drag segments, key presses.
28
+
29
+ The bundled examples are real tasks from **PlayerBench**, the paper's benchmark:
30
+ screenshots captured from the benchmark's own games (`107_simon-sequence` and
31
+ `105_memory-match`, Apache-2.0), with the exact game-rule, role, and control strings
32
+ from the benchmark's task definitions.
33
+
34
+ ## Usage
35
+
36
+ 1. Pick an example, or upload your own screenshot and describe the task and rules.
37
+ 2. Hit **Predict next action**.
38
+ 3. The red crosshair on the output image is where the agent would click; the action
39
+ summary line shows the decoded action (pixel and normalized 0–1000 coordinates).
40
+
41
+ The model is trained on a 1280×720 viewport; any input image is rescaled by the
42
+ processor to the training pixel budget. Coordinates in the raw tool call are
43
+ normalized 0–1000 and mapped back to the viewport by the decoder.
app.py ADDED
@@ -0,0 +1,572 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Game2Player demo: game screenshot + task -> next keyboard/mouse action.
2
+
3
+ Game2Player (https://arxiv.org/abs/2611.24154) is a visual game-playing agent
4
+ fine-tuned from Qwen3.5. This Space runs the released 9B checkpoint with
5
+ transformers, replicating the authors' vLLM serving recipe (bf16, max_pixels
6
+ 1048576, thinking off, temperature 1.0) and their PlayerBench prompt/decoder.
7
+ """
8
+
9
+ import json
10
+ import math
11
+ import re
12
+ import time
13
+ from pathlib import Path
14
+
15
+ import spaces # must be imported before torch / transformers
16
+ import torch
17
+ import gradio as gr
18
+ from PIL import Image, ImageDraw
19
+ from transformers import AutoProcessor, Qwen3_5ForConditionalGeneration
20
+
21
+ MODEL_ID = "game2player/Game2Player-9B"
22
+ VIEWPORT_W, VIEWPORT_H = 1280, 720
23
+ # Authors' vLLM --mm-processor-kwargs max_pixels=1048576 (min_pixels default 3136).
24
+ # New-style processor kwarg: size={'longest_edge': max_pixels, 'shortest_edge': min_pixels}.
25
+ IMAGE_SIZE = {"longest_edge": 1048576, "shortest_edge": 3136}
26
+
27
+ EXAMPLES_DIR = Path(__file__).parent / "examples"
28
+
29
+ processor = AutoProcessor.from_pretrained(MODEL_ID)
30
+ model = Qwen3_5ForConditionalGeneration.from_pretrained(
31
+ MODEL_ID,
32
+ torch_dtype=torch.bfloat16,
33
+ attn_implementation="sdpa",
34
+ ).to("cuda")
35
+ model.eval()
36
+
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # Prompt construction, ported 1:1 from the Game2Player repo
40
+ # (agents/qwen_prompting.py + catalog/prompt_templates/computer_use_agent_template.j2)
41
+ # ---------------------------------------------------------------------------
42
+
43
+ MEMORY_NOTE = (
44
+ "The user message may contain explicitly labelled previous steps. Treat them "
45
+ "as chronological short-term context; act on the labelled current step."
46
+ )
47
+
48
+ CANONICAL_ACTIONS = (
49
+ "click", "click_hold", "mouse_move", "drag", "scroll", "type",
50
+ "press_key", "press_keys", "set_keys", "key_chunk", "wait",
51
+ )
52
+
53
+ KEY_ALIASES = {
54
+ "arrowleft": "ArrowLeft", "left": "ArrowLeft", "arrowright": "ArrowRight",
55
+ "right": "ArrowRight", "arrowup": "ArrowUp", "up": "ArrowUp",
56
+ "arrowdown": "ArrowDown", "down": "ArrowDown", "space": "Space",
57
+ "spacebar": "Space", "enter": "Enter", "return": "Enter", "esc": "Escape",
58
+ "escape": "Escape", "tab": "Tab", "backspace": "Backspace",
59
+ "delete": "Delete", "del": "Delete", "shift": "Shift",
60
+ "shiftleft": "ShiftLeft", "shiftright": "ShiftRight",
61
+ "control": "Control", "ctrl": "Control", "controlleft": "ControlLeft",
62
+ "controlright": "ControlRight", "alt": "Alt", "altleft": "AltLeft",
63
+ "altright": "AltRight", "slash": "/", "period": ".", "comma": ",",
64
+ "quote": "'", "apostrophe": "'", "semicolon": ";", "backslash": "\\",
65
+ "bracketleft": "[", "bracketright": "]", "minus": "-", "equal": "=",
66
+ }
67
+
68
+
69
+ def normalize_key(key):
70
+ text = str(key).strip()
71
+ if not text:
72
+ return None
73
+ if len(text) == 1:
74
+ return text.lower()
75
+ return KEY_ALIASES.get(text.lower(), text)
76
+
77
+
78
+ NOTE_RULE = (
79
+ "In `note`, write one short sentence on why you chose this action; your later "
80
+ "steps show it."
81
+ )
82
+ KEYBOARD_RULE = (
83
+ "\npress_keys presses its keys simultaneously, then releases them; repeated key "
84
+ "names do not create repeated taps. set_keys keeps its keys held until another "
85
+ "keyboard action changes them; empty keys releases them. wait advances time "
86
+ "without releasing held keys."
87
+ )
88
+ TC_OPEN = "<tool" + "_call>"
89
+ TC_CLOSE = "</tool" + "_call>"
90
+
91
+
92
+ def build_output_format_block(allowed_keys, thinking=False):
93
+ """Port of build_qwen_action_instruction with the repo's ACTION_CONTRACT
94
+ (max_actions=1, duration_policy='optional', note=True)."""
95
+ keys = sorted({str(k).strip() for k in allowed_keys if str(k).strip()})
96
+ lines = []
97
+ if keys:
98
+ lines.extend([
99
+ "- press_key: key, optional duration.",
100
+ "- press_keys: keys, optional duration; press simultaneously, then release.",
101
+ "- set_keys: keys, optional duration; keep these keys held after the action. Empty keys releases all held keys.",
102
+ "- key_chunk: ordered steps containing keys and duration, plus release_after.",
103
+ ])
104
+ lines.extend([
105
+ "- type: text.",
106
+ "- click: coordinate, optional button (left/right/middle, default left); omit duration.",
107
+ "- click_hold: coordinate, optional button and duration.",
108
+ "- mouse_move: coordinate.",
109
+ "- drag: start_coordinate, end_coordinate, optional button, duration, and steps.",
110
+ "- scroll: delta_x and delta_y.",
111
+ "- wait: optional duration; advance time without changing held keys.",
112
+ "Every action also takes note: one short sentence on why.",
113
+ ])
114
+ example_action = (
115
+ {"action": "press_key", "key": keys[0]} if keys
116
+ else {"action": "click", "coordinate": [500, 500]}
117
+ )
118
+ example_action["note"] = "why this action"
119
+ example = json.dumps(
120
+ {"name": "computer_use", "arguments": example_action},
121
+ ensure_ascii=False, separators=(",", ":"),
122
+ )
123
+ key_rule = (
124
+ "Allowed key values: " + ", ".join(json.dumps(k) for k in keys) + ". Do not use any other value as a key."
125
+ if keys else "This game has no keyboard controls; do not emit a keyboard action."
126
+ )
127
+ response_rule = (
128
+ "Think in the thinking channel, then emit only the " + TC_OPEN + " as the final "
129
+ "answer, with no prose outside the tool-call tags."
130
+ if thinking else
131
+ "Encode the action plan as one JSON object inside " + TC_OPEN + TC_CLOSE + ". "
132
+ "Do not write prose outside the tool-call tags or a Markdown fence."
133
+ )
134
+ instructions = (
135
+ "Return exactly one action.\n"
136
+ "Duration is optional, in seconds, at most 10. Without a duration, press_key, "
137
+ "press_keys and click are 0.05-second taps, and wait, click_hold and drag "
138
+ "last the game's default time."
139
+ + KEYBOARD_RULE
140
+ + "\n" + NOTE_RULE
141
+ )
142
+ return "# Computer-use output\n" + instructions + "\n" + response_rule + (
143
+ " Put every action parameter directly inside\n"
144
+ "`arguments`; never put function-call syntax inside the `action` string.\n\n"
145
+ "Example:\n" + TC_OPEN + example + TC_CLOSE + "\n\n"
146
+ "Coordinates are [x, y] in a normalized 0-1000 range mapped to the "
147
+ f"{VIEWPORT_W}x{VIEWPORT_H} viewport.\n"
148
+ + key_rule + "\n"
149
+ "Mouse actions are allowed.\n\n"
150
+ "Available actions and fields:\n" + chr(10).join(lines)
151
+ )
152
+
153
+
154
+ def build_system_prompt(game_rules, role_description, control_notes, task, allowed_keys):
155
+ role_block = "\n\n".join(
156
+ part.strip() for part in (role_description, control_notes, MEMORY_NOTE) if part and part.strip()
157
+ )
158
+ return f"""You are an expert game agent. Use the current screenshot and any explicitly
159
+ labelled previous steps to choose the next action that best advances the task.
160
+ Follow the game rules and control restrictions exactly.
161
+
162
+ # Game Rules
163
+ {game_rules.strip()}
164
+
165
+ # Role and Controls
166
+ {role_block}
167
+
168
+ # Task Instruction
169
+ {task.strip()}
170
+
171
+ # Output Format
172
+ {build_output_format_block(allowed_keys)}"""
173
+
174
+
175
+ # ---------------------------------------------------------------------------
176
+ # Output decoding, ported from agents/codecs.py (parse_qwen_action path)
177
+ # ---------------------------------------------------------------------------
178
+
179
+ TOOL_CALL_RE = re.compile(
180
+ r"<tool(?:\s+|_)call>\s*(\{[\s\S]*?\})\s*</tool(?:\s+|_)call>", re.IGNORECASE
181
+ )
182
+
183
+
184
+ def _point(value, width, height):
185
+ """0-1000 normalized coords -> viewport pixels (agents/codecs._point)."""
186
+ if isinstance(value, dict):
187
+ x, y = value.get("x"), value.get("y")
188
+ elif isinstance(value, (list, tuple)) and len(value) >= 2:
189
+ x, y = value[0], value[1]
190
+ elif isinstance(value, str):
191
+ nums = re.findall(r"-?\d+(?:\.\d+)?", value)
192
+ if len(nums) < 2:
193
+ return None
194
+ x, y = nums[0], nums[1]
195
+ else:
196
+ return None
197
+ try:
198
+ x, y = float(x), float(y)
199
+ except (TypeError, ValueError):
200
+ return None
201
+ if not (math.isfinite(x) and math.isfinite(y)):
202
+ return None
203
+ return (
204
+ max(0.0, min(1000.0, x)) / 1000.0 * width,
205
+ max(0.0, min(1000.0, y)) / 1000.0 * height,
206
+ )
207
+
208
+
209
+ def canonicalize_action(args, width=VIEWPORT_W, height=VIEWPORT_H):
210
+ """Port of _canonicalize_args (normalized=True) for one action dict."""
211
+ action_type = str(args.get("action") or "").lower()
212
+ if action_type not in CANONICAL_ACTIONS:
213
+ return None
214
+
215
+ if action_type in {"click", "click_hold", "mouse_move"}:
216
+ point = _point(
217
+ args.get("coordinate") or args.get("point") or args.get("start_box")
218
+ or ([args.get("x"), args.get("y")] if "x" in args and "y" in args else None),
219
+ width, height,
220
+ )
221
+ if point is None:
222
+ return None
223
+ out = {"action": action_type, "x": point[0], "y": point[1]}
224
+ if args.get("button") in ("left", "right", "middle"):
225
+ out["button"] = args["button"]
226
+ return out
227
+
228
+ if action_type == "drag":
229
+ start = _point(args.get("start_coordinate") or args.get("start"), width, height)
230
+ end = _point(args.get("end_coordinate") or args.get("end") or args.get("coordinate"), width, height)
231
+ if start is None or end is None:
232
+ return None
233
+ return {"action": "drag", "x1": start[0], "y1": start[1],
234
+ "x2": end[0], "y2": end[1]}
235
+
236
+ if action_type in {"press_key", "press_keys", "set_keys"}:
237
+ raw = args.get("keys", args.get("key"))
238
+ if isinstance(raw, str):
239
+ keys = [k for part in re.split(r"[,+\s]+", raw.strip()) if part for k in [normalize_key(part)] if k]
240
+ elif isinstance(raw, (list, tuple)):
241
+ keys = [k for k in (normalize_key(i) for i in raw) if k]
242
+ else:
243
+ keys = []
244
+ if not keys:
245
+ return None
246
+ if action_type == "press_key":
247
+ return {"action": "press_key", "key": keys[0]}
248
+ return {"action": action_type, "keys": keys}
249
+
250
+ if action_type == "type":
251
+ text = args.get("text", args.get("content"))
252
+ if text in (None, ""):
253
+ return None
254
+ return {"action": "type", "text": str(text)}
255
+
256
+ if action_type == "scroll":
257
+ def _f(v):
258
+ try:
259
+ n = float(v)
260
+ except (TypeError, ValueError):
261
+ return 0.0
262
+ return n if math.isfinite(n) else 0.0
263
+ return {"action": "scroll", "delta_x": _f(args.get("delta_x")), "delta_y": _f(args.get("delta_y"))}
264
+
265
+ if action_type == "key_chunk":
266
+ return None # rare in practice; skip complex chunk parsing in the demo
267
+
268
+ return {"action": "wait"} if action_type == "wait" else None
269
+
270
+
271
+ def parse_model_output(text):
272
+ """Port of parse_qwen_action: tool-call JSON -> canonical action; fall back to raw JSON."""
273
+ for match in TOOL_CALL_RE.finditer(text or ""):
274
+ try:
275
+ payload = json.loads(match.group(1))
276
+ except json.JSONDecodeError:
277
+ continue
278
+ if not isinstance(payload, dict):
279
+ continue
280
+ args = payload.get("arguments")
281
+ if isinstance(args, str):
282
+ try:
283
+ args = json.loads(args)
284
+ except json.JSONDecodeError:
285
+ continue
286
+ if not isinstance(args, dict):
287
+ continue
288
+ nested = args.get("actions")
289
+ candidates = nested if isinstance(nested, list) and nested else [args]
290
+ for candidate in candidates:
291
+ if not isinstance(candidate, dict):
292
+ continue
293
+ action = canonicalize_action(candidate)
294
+ if action is not None:
295
+ note = str(candidate.get("note") or candidate.get("reasoning") or "").strip()
296
+ return action, note
297
+ final = (text or "").strip()
298
+ if final.startswith("```json"):
299
+ final = final[len("```json"):].strip()
300
+ if final.endswith("```"):
301
+ final = final[:-3].strip()
302
+ if final.startswith("{"):
303
+ try:
304
+ payload = json.loads(final)
305
+ except json.JSONDecodeError:
306
+ payload = None
307
+ if isinstance(payload, dict):
308
+ args = payload.get("arguments") or payload.get("action") or payload
309
+ if isinstance(args, dict):
310
+ action = canonicalize_action(args)
311
+ if action is not None:
312
+ note = str(args.get("note") or args.get("reasoning") or "").strip()
313
+ return action, note
314
+ return None, None
315
+
316
+
317
+ # ---------------------------------------------------------------------------
318
+ # PlayerBench example presets (games bundled in the Game2Player repo, Apache-2.0)
319
+ # ---------------------------------------------------------------------------
320
+
321
+ # Exact strings from benchmark/playerbench/tasks/{107_simon-sequence,105_memory-match}.yaml
322
+ PRESETS = {
323
+ "simon": dict(
324
+ screenshot=str(EXAMPLES_DIR / "simon_sequence.png"),
325
+ task="Repeat Rose Circuit exactly.",
326
+ game_rules=(
327
+ "You are playing Simon Sequence, a deterministic signal-memory game.\n\n"
328
+ "## Objective\n- Repeat the displayed color sequence in exact order.\n\n"
329
+ "## Rules\n"
330
+ "- The assigned sequence is displayed before input begins and is public to the player.\n"
331
+ "- Click one color at a time from left to right.\n"
332
+ "- A wrong color fails the attempt; the task ends successfully after the final correct color.\n"
333
+ "- The assigned level is selected by the task URL and starts immediately."
334
+ ),
335
+ role_description="You are repeating the displayed signal. Memorize its order and enter it without mistakes.",
336
+ control_notes=(
337
+ "- Left-click the color buttons.\n"
338
+ "- Follow the numbered signal chips from left to right.\n"
339
+ "- The assigned level starts immediately; do not select another level."
340
+ ),
341
+ allowed_keys="",
342
+ ),
343
+ "memory": dict(
344
+ screenshot=str(EXAMPLES_DIR / "memory_match.png"),
345
+ task="Complete Dawn Sprint by finding all three symbol pairs.",
346
+ game_rules=(
347
+ "You are playing Memory Match, a deterministic offline concentration game. The assigned "
348
+ "memory file is already loaded and ready to play.\n\n"
349
+ "## Objective\n- Find every matching pair of symbols on the board.\n\n"
350
+ "## Rules\n"
351
+ "- Click a face-down card to reveal it, then click a second face-down card.\n"
352
+ "- Matching symbols stay face up and count as a pair.\n"
353
+ "- A mismatch remains visible until you click either revealed card to hide both, then you may continue.\n"
354
+ "- The board is deterministic for each URL level and contains no remote assets.\n"
355
+ "- Press R or click Restart to reset the assigned memory file."
356
+ ),
357
+ role_description=(
358
+ "You are the memory solver. Reveal cards, remember every visible symbol and its "
359
+ "position, then recover all pairs with as few mismatches as possible."
360
+ ),
361
+ control_notes=(
362
+ "- Click the center of any face-down card to reveal it.\n"
363
+ "- After a mismatch, click either of the two revealed cards to hide both before selecting another pair.\n"
364
+ "- A matched card stays face up and does not need to be clicked again.\n"
365
+ "- The assigned level is already open from the URL; do not select another level.\n"
366
+ "- R restarts the assigned memory file."
367
+ ),
368
+ allowed_keys="r",
369
+ ),
370
+ }
371
+
372
+
373
+ # ---------------------------------------------------------------------------
374
+ # Inference
375
+ # ---------------------------------------------------------------------------
376
+
377
+ def annotate(image, action):
378
+ """Draw the predicted click/drag point on a copy of the screenshot."""
379
+ canvas = image.copy().convert("RGB")
380
+ draw = ImageDraw.Draw(canvas)
381
+ if action.get("action") in {"click", "click_hold", "mouse_move"}:
382
+ x, y = action.get("x"), action.get("y")
383
+ if x is not None and y is not None:
384
+ r = 12
385
+ draw.ellipse([x - r, y - r, x + r, y + r], outline=(255, 60, 60), width=4)
386
+ draw.line([x - r - 6, y, x + r + 6, y], fill=(255, 60, 60), width=2)
387
+ draw.line([x, y - r - 6, x, y + r + 6], fill=(255, 60, 60), width=2)
388
+ elif action.get("action") == "drag":
389
+ x1, y1, x2, y2 = action.get("x1"), action.get("y1"), action.get("x2"), action.get("y2")
390
+ if None not in (x1, y1, x2, y2):
391
+ draw.line([x1, y1, x2, y2], fill=(255, 60, 60), width=4)
392
+ draw.ellipse([x1 - 10, y1 - 10, x1 + 10, y1 + 10], outline=(255, 60, 60), width=3)
393
+ draw.ellipse([x2 - 10, y2 - 10, x2 + 10, y2 + 10], outline=(255, 200, 0), width=3)
394
+ return canvas
395
+
396
+
397
+ def describe_action(action, note):
398
+ """One-line human rendering of the canonical action."""
399
+ if action is None:
400
+ return None
401
+ a = action["action"]
402
+ if a in {"click", "click_hold", "mouse_move"}:
403
+ text = f"{a} at pixel ({int(action['x'])}, {int(action['y'])})"
404
+ if a == "click":
405
+ text += f" [normalized 0-1000: ({round(action['x'] / VIEWPORT_W * 1000)}, {round(action['y'] / VIEWPORT_H * 1000)})]"
406
+ elif a == "drag":
407
+ text = f"drag from ({int(action['x1'])}, {int(action['y1'])}) to ({int(action['x2'])}, {int(action['y2'])})"
408
+ elif a == "press_key":
409
+ text = f"press_key {action['key']}"
410
+ elif a in {"press_keys", "set_keys"}:
411
+ text = f"{a} {'+'.join(action['keys'])}"
412
+ elif a == "type":
413
+ text = f'type "{action["text"]}"'
414
+ elif a == "scroll":
415
+ text = f"scroll dx={action['delta_x']} dy={action['delta_y']}"
416
+ else:
417
+ text = "wait"
418
+ if note:
419
+ text += f" — {note}"
420
+ return text
421
+
422
+
423
+ @spaces.GPU(duration=120)
424
+ def predict_next_action(
425
+ screenshot,
426
+ task,
427
+ game_rules=PRESETS["simon"]["game_rules"],
428
+ role_description=PRESETS["simon"]["role_description"],
429
+ control_notes=PRESETS["simon"]["control_notes"],
430
+ allowed_keys="",
431
+ thinking=False,
432
+ max_new_tokens=512,
433
+ temperature=1.0,
434
+ seed=-1,
435
+ progress=gr.Progress(track_tqdm=True),
436
+ ):
437
+ """Predict the next game action from a screenshot and task description.
438
+
439
+ Args:
440
+ screenshot: current game screenshot (any size; rescaled to ~1M pixels as in training).
441
+ task: the task instruction, e.g. "Repeat Warm Signal exactly."
442
+ game_rules: the game's rules block (pre-filled from PlayerBench examples).
443
+ role_description: the player role description.
444
+ control_notes: notes on how controls work.
445
+ allowed_keys: comma-separated list of keys the game accepts (empty for mouse-only).
446
+ thinking: let the model reason in a thinking channel before the tool call.
447
+ max_new_tokens: generation budget.
448
+ temperature: sampling temperature.
449
+ seed: random seed; -1 keeps sampling random.
450
+
451
+ Returns:
452
+ (annotated screenshot, action summary, raw model output, elapsed seconds).
453
+ """
454
+ if screenshot is None:
455
+ raise gr.Error("Please provide a game screenshot first.")
456
+ if isinstance(screenshot, str):
457
+ image = Image.open(screenshot).convert("RGB")
458
+ else:
459
+ image = screenshot.convert("RGB")
460
+
461
+ keys = [k.strip() for k in re.split(r"[,+\s]+", (allowed_keys or "").strip()) if k.strip()]
462
+ system_prompt = build_system_prompt(game_rules, role_description, control_notes, task, keys)
463
+ messages = [
464
+ {"role": "system", "content": [{"type": "text", "text": system_prompt}]},
465
+ {"role": "user", "content": [
466
+ {"type": "text", "text": "# Current step\nCurrent game screen:\n"},
467
+ {"type": "image", "image": image},
468
+ {"type": "text", "text": "\nReturn the next action."},
469
+ ]},
470
+ ]
471
+
472
+ torch.manual_seed(seed if seed is not None and seed >= 0 else int(time.time()))
473
+ inputs = processor.apply_chat_template(
474
+ messages,
475
+ tokenize=True,
476
+ add_generation_prompt=True,
477
+ return_dict=True,
478
+ return_tensors="pt",
479
+ enable_thinking=bool(thinking),
480
+ processor_kwargs={"size": IMAGE_SIZE},
481
+ ).to("cuda")
482
+ start = time.perf_counter()
483
+ with torch.inference_mode():
484
+ generated = model.generate(
485
+ **inputs,
486
+ max_new_tokens=int(max_new_tokens),
487
+ temperature=float(temperature),
488
+ do_sample=float(temperature) > 0,
489
+ top_p=1.0,
490
+ )
491
+ elapsed = time.perf_counter() - start
492
+ trimmed = generated[0][inputs["input_ids"].shape[1]:]
493
+ raw = processor.decode(trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)
494
+
495
+ action, note = parse_model_output(raw)
496
+ summary = describe_action(action, note)
497
+ if summary is None:
498
+ summary = "Could not parse an action from the model output — see the raw output below."
499
+ annotated = annotate(image, action) if action and action.get("action") in {
500
+ "click", "click_hold", "mouse_move", "drag",
501
+ } else image
502
+ return annotated, summary, raw, f"{elapsed:.1f}s"
503
+
504
+
505
+ with gr.Blocks(theme=gr.themes.Citrus(), title="Game2Player — Visual Game-Playing Agent") as demo:
506
+ gr.Markdown(
507
+ f"""
508
+ # 🎮 Game2Player — Visual Game-Playing Agent
509
+
510
+ **Game2Player: Scaling Gameplay Experience for Visual Agents through Environment-Player Co-Development**
511
+ ([paper](https://arxiv.org/abs/2611.24154) · [code](https://github.com/game2player/Game2Player) · [model card](https://huggingface.co/{MODEL_ID}))
512
+
513
+ This demo runs the released **Game2Player-9B** checkpoint (Qwen3.5-9B fine-tune) with transformers,
514
+ reproducing the authors' serving recipe (bf16, ≤1M pixels per screenshot, temperature 1.0).
515
+ Give it a **game screenshot** and the **task + rules**, and it predicts the next
516
+ keyboard or mouse action as a `computer_use` tool call.
517
+
518
+ The two presets are real tasks from **PlayerBench**, the paper's benchmark — screenshots
519
+ captured from the benchmark's bundled games (`107_simon-sequence`, `105_memory-match`, Apache-2.0).
520
+ """
521
+ )
522
+ with gr.Row():
523
+ with gr.Column():
524
+ screenshot = gr.Image(
525
+ type="pil", label="Game screenshot", height=420,
526
+ sources=["upload", "clipboard"],
527
+ )
528
+ task = gr.Textbox(
529
+ label="Task instruction", lines=1,
530
+ value="Repeat Rose Circuit exactly.",
531
+ )
532
+ with gr.Accordion("Game rules and controls (advanced)", open=False):
533
+ game_rules = gr.Textbox(label="Game rules", lines=8, value=PRESETS["simon"]["game_rules"])
534
+ role_description = gr.Textbox(label="Role description", lines=2, value=PRESETS["simon"]["role_description"])
535
+ control_notes = gr.Textbox(label="Control notes", lines=3, value=PRESETS["simon"]["control_notes"])
536
+ allowed_keys = gr.Textbox(label="Allowed keys (comma-separated; empty = mouse-only)", value="")
537
+ with gr.Accordion("Generation settings", open=False):
538
+ thinking = gr.Checkbox(label="Enable thinking channel", value=False)
539
+ max_new_tokens = gr.Slider(64, 2048, value=512, step=64, label="Max new tokens")
540
+ temperature = gr.Slider(0.0, 2.0, value=1.0, step=0.1, label="Temperature")
541
+ seed = gr.Number(value=-1, label="Seed (-1 = random)")
542
+ predict_btn = gr.Button("Predict next action", variant="primary")
543
+ with gr.Column():
544
+ annotated_out = gr.Image(type="pil", label="Predicted action on screen", height=420)
545
+ action_out = gr.Textbox(label="Next action", lines=2)
546
+ raw_out = gr.Textbox(label="Raw model output", lines=6)
547
+ elapsed_out = gr.Textbox(label="Inference time", show_label=False)
548
+
549
+ predict_btn.click(
550
+ predict_next_action,
551
+ inputs=[screenshot, task, game_rules, role_description, control_notes,
552
+ allowed_keys, thinking, max_new_tokens, temperature, seed],
553
+ outputs=[annotated_out, action_out, raw_out, elapsed_out],
554
+ api_name="predict_next_action",
555
+ )
556
+
557
+ example_inputs = [screenshot, task, game_rules, role_description, control_notes, allowed_keys]
558
+ gr.Examples(
559
+ examples=[
560
+ [p["screenshot"], p["task"], p["game_rules"], p["role_description"],
561
+ p["control_notes"], p["allowed_keys"]]
562
+ for p in (PRESETS["simon"], PRESETS["memory"])
563
+ ],
564
+ inputs=example_inputs,
565
+ fn=predict_next_action,
566
+ outputs=[annotated_out, action_out, raw_out, elapsed_out],
567
+ cache_examples=True,
568
+ cache_mode="lazy",
569
+ label="PlayerBench examples (real tasks from the paper's benchmark)",
570
+ )
571
+
572
+ demo.launch(mcp_server=True)
examples/memory_match.png ADDED

Git LFS Details

  • SHA256: f9441904abee48d63f54f1580763bc5faee9c9b0ba75f07b4b4da8690e3984ab
  • Pointer size: 131 Bytes
  • Size of remote file: 278 kB
examples/simon_sequence.png ADDED

Git LFS Details

  • SHA256: c2a6d36f62afd602611e8b649a03312061ba505cd57bfd5a526a1af8b6d0ec73
  • Pointer size: 131 Bytes
  • Size of remote file: 160 kB
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ torch
2
+ torchvision
3
+ transformers
4
+ accelerate
5
+ Pillow