gagndeep commited on
Commit
9f27f59
·
verified ·
1 Parent(s): 5675e61

Upload folder using huggingface_hub

Browse files
Files changed (7) hide show
  1. .gitignore +10 -0
  2. .python-version +1 -0
  3. README.md +38 -7
  4. app.py +309 -0
  5. main.py +6 -0
  6. pyproject.toml +7 -0
  7. requirements.txt +19 -0
.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
.python-version ADDED
@@ -0,0 +1 @@
 
 
1
+ 3.13
README.md CHANGED
@@ -1,12 +1,43 @@
1
  ---
2
- title: HY WorldPlay
3
- emoji: 🏃
4
- colorFrom: red
5
- colorTo: red
6
  sdk: gradio
7
- sdk_version: 6.1.0
8
  app_file: app.py
9
- pinned: false
 
 
10
  ---
11
 
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: HY-WorldPlay
3
+ emoji: 🌍
4
+ colorFrom: blue
5
+ colorTo: green
6
  sdk: gradio
7
+ python_version: 3.10
8
  app_file: app.py
9
+ hardware: zero-gpu
10
+ license: apache-2.0
11
+ short_description: HY-World 1.5 - Interactive World Modeling
12
  ---
13
 
14
+ # HY-WorldPlay (HunyuanWorld 1.5)
15
+
16
+ This Space demonstrates **HY-WorldPlay**: a streaming video diffusion model for real-time interactive world modeling.
17
+
18
+ ## Model Details
19
+ - **Base Model**: HunyuanVideo-1.5
20
+ - **Architecture**: Latent Video Diffusion with Dual Action Representation
21
+ - **Capability**: Generates long-horizon streaming video with geometric consistency.
22
+
23
+ ## Usage
24
+ 1. **Prompt**: Enter a text description of the scene.
25
+ 2. **Image**: (Optional) Upload a starting image for Image-to-Video generation.
26
+ 3. **Camera Path**: Upload a JSON file defining the camera trajectory (Pose).
27
+ - *Note*: You can find example pose files in the official repository or use the default provided in the demo if implemented.
28
+ 4. **Generate**: Click generate to create the video.
29
+
30
+ ## Notes
31
+ - This Space uses **ZeroGPU** for inference.
32
+ - The first run might take longer to download the model weights (~30GB+).
33
+ - The model is running in **Bidirectional** mode by default for quality.
34
+
35
+ ## Citation
36
+ ```bibtex
37
+ @article{worldplay2025,
38
+ title={WorldPlay: Towards Long-Term Geometric Consistency for Real-Time Interactive World Model},
39
+ author={Wenqiang Sun and Haiyu Zhang and Haoyuan Wang and Junta Wu and Zehan Wang and Zhenwei Wang and Yunhong Wang and Jun Zhang and Tengfei Wang and Chunchao Guo},
40
+ year={2025},
41
+ journal={arXiv preprint}
42
+ }
43
+ ```
app.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import shutil
4
+ import tempfile
5
+ import argparse
6
+ import subprocess
7
+ import json
8
+ import torch
9
+ import numpy as np
10
+ import spaces
11
+ import gradio as gr
12
+ from huggingface_hub import snapshot_download
13
+
14
+ # Clone the repository if not already present
15
+ REPO_URL = "https://github.com/Tencent-Hunyuan/HY-WorldPlay.git"
16
+ REPO_DIR = "HY-WorldPlay"
17
+
18
+ if not os.path.exists(REPO_DIR):
19
+ print(f"Cloning {REPO_URL}...")
20
+ subprocess.run(["git", "clone", REPO_URL, REPO_DIR], check=True)
21
+
22
+ sys.path.append(os.path.abspath(REPO_DIR))
23
+
24
+ # Now importing specific modules from the cloned repo
25
+ try:
26
+ from hyvideo.pipelines.worldplay_video_pipeline import HunyuanVideo_1_5_Pipeline
27
+ from hyvideo.commons.parallel_states import initialize_parallel_state
28
+ from hyvideo.commons.infer_state import initialize_infer_state
29
+ except ImportError as e:
30
+ print(f"Error importing hyvideo: {e}")
31
+ print("Dependencies might be missing. Ensure requirements.txt is correct.")
32
+
33
+ # Mapping for pose actions if needed
34
+ mapping = {
35
+ (0,0,0,0): 0,
36
+ (1,0,0,0): 1, # forward
37
+ (0,1,0,0): 2, # backward
38
+ (0,0,1,0): 3, # right
39
+ (0,0,0,1): 4, # left
40
+ (1,0,1,0): 5,
41
+ (1,0,0,1): 6,
42
+ (0,1,1,0): 7,
43
+ (0,1,0,1): 8,
44
+ }
45
+
46
+ # --- Utility Functions adapted from generate.py ---
47
+
48
+ def one_hot_to_one_dimension(one_hot):
49
+ y = torch.tensor([mapping[tuple(row.tolist())] for row in one_hot])
50
+ return y
51
+
52
+ def pose_to_input(pose_json_path, latent_chunk_num, tps=False):
53
+ # This function is adapted to handle the JSON structure used in the repo
54
+ import json
55
+ from scipy.spatial.transform import Rotation as R
56
+
57
+ pose_json = json.load(open(pose_json_path, 'r'))
58
+ pose_keys = list(pose_json.keys())
59
+ intrinsic_list = []
60
+ w2c_list = []
61
+
62
+ # Simple sort to ensure chronological order if keys are timestamps or numbered
63
+ pose_keys.sort()
64
+
65
+ # We need to make sure we don't go out of bounds if JSON has fewer frames
66
+ iterations = min(latent_chunk_num, len(pose_keys))
67
+
68
+ for i in range(iterations):
69
+ t_key = pose_keys[i]
70
+ c2w = np.array(pose_json[t_key]["extrinsic"])
71
+ w2c = np.linalg.inv(c2w)
72
+ w2c_list.append(w2c)
73
+ intrinsic = np.array(pose_json[t_key]["K"])
74
+ intrinsic[0, 0] /= intrinsic[0, 2] * 2
75
+ intrinsic[1, 1] /= intrinsic[1, 2] * 2
76
+ intrinsic[0, 2] = 0.5
77
+ intrinsic[1, 2] = 0.5
78
+ intrinsic_list.append(intrinsic)
79
+
80
+ # Pad if we have fewer frames than requested chunks
81
+ if len(w2c_list) < latent_chunk_num:
82
+ # Repeat last frame
83
+ last_w2c = w2c_list[-1]
84
+ last_intrinsic = intrinsic_list[-1]
85
+ for _ in range(latent_chunk_num - len(w2c_list)):
86
+ w2c_list.append(last_w2c)
87
+ intrinsic_list.append(last_intrinsic)
88
+
89
+ w2c_list = np.array(w2c_list)
90
+ intrinsic_list = torch.tensor(np.array(intrinsic_list))
91
+
92
+ c2ws = np.linalg.inv(w2c_list)
93
+ C_inv = np.linalg.inv(c2ws[:-1])
94
+ relative_c2w = np.zeros_like(c2ws)
95
+ relative_c2w[0, ...] = c2ws[0, ...]
96
+ relative_c2w[1:, ...] = C_inv @ c2ws[1:, ...]
97
+ trans_one_hot = np.zeros((relative_c2w.shape[0], 4), dtype=np.int32)
98
+ rotate_one_hot = np.zeros((relative_c2w.shape[0], 4), dtype=np.int32)
99
+
100
+ move_norm_valid = 0.0001
101
+ for i in range(1, relative_c2w.shape[0]):
102
+ move_dirs = relative_c2w[i, :3, 3]
103
+ move_norms = np.linalg.norm(move_dirs)
104
+ if move_norms > move_norm_valid:
105
+ move_norm_dirs = move_dirs / move_norms
106
+ angles_rad = np.arccos(move_norm_dirs.clip(-1.0, 1.0))
107
+ trans_angles_deg = angles_rad * (180.0 / np.pi)
108
+ else:
109
+ trans_angles_deg = np.zeros(3)
110
+
111
+ R_rel = relative_c2w[i, :3, :3]
112
+ r = R.from_matrix(R_rel)
113
+ rot_angles_deg = r.as_euler('xyz', degrees=True)
114
+
115
+ if move_norms > move_norm_valid:
116
+ if (not tps) or (tps == True and abs(rot_angles_deg[1]) < 5e-2 and abs(rot_angles_deg[0]) < 5e-2):
117
+ if trans_angles_deg[2] < 60:
118
+ trans_one_hot[i, 0] = 1
119
+ elif trans_angles_deg[2] > 120:
120
+ trans_one_hot[i, 1] = 1
121
+ if trans_angles_deg[0] < 60:
122
+ trans_one_hot[i, 2] = 1
123
+ elif trans_angles_deg[0] > 120:
124
+ trans_one_hot[i, 3] = 1
125
+
126
+ if rot_angles_deg[1] > 5e-2:
127
+ rotate_one_hot[i, 0] = 1
128
+ elif rot_angles_deg[1] < -5e-2:
129
+ rotate_one_hot[i, 1] = 1
130
+ if rot_angles_deg[0] > 5e-2:
131
+ rotate_one_hot[i, 2] = 1
132
+ elif rot_angles_deg[0] < -5e-2:
133
+ rotate_one_hot[i, 3] = 1
134
+
135
+ trans_one_hot = torch.tensor(trans_one_hot)
136
+ rotate_one_hot = torch.tensor(rotate_one_hot)
137
+
138
+ trans_one_label = one_hot_to_one_dimension(trans_one_hot)
139
+ rotate_one_label = one_hot_to_one_dimension(rotate_one_hot)
140
+ action_one_label = trans_one_label * 9 + rotate_one_label
141
+
142
+ return torch.tensor(w2c_list), torch.tensor(intrinsic_list), action_one_label
143
+
144
+
145
+ # --- Model Loading and Inference ---
146
+
147
+ MODEL_PATH = "tencent/HunyuanVideo-1.5"
148
+ ACTION_CKPT = "tencent/HY-WorldPlay"
149
+
150
+ # Global pipeline variable
151
+ pipe = None
152
+
153
+ def load_model():
154
+ global pipe
155
+ if pipe is None:
156
+ print("Loading Model...")
157
+ # Ensure we have weights
158
+ # We might rely on the diffusers pipeline to download, but for custom pipeline it often expects local path
159
+ # Let's use snapshot_download to be safe and clear
160
+
161
+ # Check if we are in an environment where we can download
162
+ model_dir = snapshot_download(repo_id=MODEL_PATH, allow_patterns=["*.safetensors", "*.json", "*.txt"])
163
+ action_dir = snapshot_download(repo_id=ACTION_CKPT) # Downloads everything from HY-WorldPlay repo (checkpoints)
164
+
165
+ # We need to pinpoint the specific subfolder for action checkpoint if it has one
166
+ # Based on user description: "ar_distilled_action_model", "bidirectional_model", etc.
167
+ # Let's assume we use bidirectional for better quality or whatever default is best
168
+ # The user provided paths like "ar_model", "bidirectional_model".
169
+ # Let's use bidirectional_model from the snapshot.
170
+ action_subpath = os.path.join(action_dir, "bidirectional_model")
171
+
172
+ # Configs from args
173
+ transformer_dtype = torch.bfloat16
174
+
175
+ # Initialize parallel state (for single GPU usually world_size=1)
176
+ # Check if initialized
177
+ if not torch.distributed.is_initialized():
178
+ initialize_parallel_state(sp=1)
179
+
180
+ pipe = HunyuanVideo_1_5_Pipeline.create_pipeline(
181
+ pretrained_model_name_or_path=model_dir,
182
+ transformer_version="480p_i2v", # Hardcoded based on provided args in snippets
183
+ enable_offloading=True,
184
+ enable_group_offloading=True,
185
+ create_sr_pipeline=True, # Enable SR by default
186
+ force_sparse_attn=False,
187
+ transformer_dtype=transformer_dtype,
188
+ action_ckpt=action_subpath,
189
+ )
190
+ print("Model Loaded Successfully!")
191
+ return pipe
192
+
193
+ @spaces.GPU(duration=300)
194
+ def generate(prompt, image_input, pose_json, seed, num_inference_steps, video_length):
195
+ pipeline = load_model()
196
+
197
+ # Handle Pose JSON
198
+ pose_path = None
199
+ if pose_json is not None:
200
+ pose_path = pose_json.name
201
+ else:
202
+ # Create a default forward movement pose if not provided
203
+ default_pose_content = {
204
+ "0": {
205
+ "extrinsic": [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]],
206
+ "K": [[500.0, 0.0, 400.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]]
207
+ }
208
+ }
209
+ # Expand for a few frames to simulate forward movement
210
+ for i in range(1, 16):
211
+ # Move forward along Z (just a dummy generic forward)
212
+ # In camera conventions often Z is forward or -Z.
213
+ # Here we just keep static as safe default or minimal drift
214
+ default_pose_content[str(i)] = default_pose_content["0"]
215
+
216
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.json') as tmp_json:
217
+ json.dump(default_pose_content, tmp_json)
218
+ pose_path = tmp_json.name
219
+
220
+ # Prepare inputs
221
+ latent_chunk_num = (video_length - 1) // 4 + 1
222
+
223
+ viewmats, Ks, action = pose_to_input(pose_path, latent_chunk_num)
224
+
225
+ # Handle Image Input (I2V vs T2V)
226
+ extra_kwargs = {}
227
+ if image_input is not None:
228
+ extra_kwargs['reference_image'] = image_input
229
+
230
+ # Run inference
231
+ out = pipeline(
232
+ enable_sr=True,
233
+ prompt=prompt,
234
+ aspect_ratio="16:9",
235
+ num_inference_steps=num_inference_steps,
236
+ sr_num_inference_steps=None,
237
+ video_length=video_length,
238
+ negative_prompt="",
239
+ seed=seed,
240
+ output_type="pt",
241
+ prompt_rewrite=False,
242
+ return_pre_sr_video=False,
243
+ viewmats=viewmats.unsqueeze(0),
244
+ Ks=Ks.unsqueeze(0),
245
+ action=action.unsqueeze(0),
246
+ few_step=False,
247
+ chunk_latent_frames=16,
248
+ model_type="bi",
249
+ user_height=480,
250
+ user_width=832,
251
+ **extra_kwargs
252
+ )
253
+
254
+ # Save video
255
+ output_path = "output.mp4"
256
+ import imageio
257
+ import einops
258
+
259
+ def save_vid(video, path):
260
+ if video.ndim == 5:
261
+ video = video[0]
262
+ vid = (video * 255).clamp(0, 255).to(torch.uint8)
263
+ vid = einops.rearrange(vid, 'c f h w -> f h w c')
264
+ imageio.mimwrite(path, vid, fps=24)
265
+
266
+ if hasattr(out, 'sr_videos'):
267
+ save_vid(out.sr_videos, output_path)
268
+ else:
269
+ save_vid(out.videos, output_path)
270
+
271
+ return output_path
272
+
273
+ # --- Gradio UI ---
274
+
275
+ default_pose_json_content = """
276
+ {
277
+ "0": {
278
+ "extrinsic": [[1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]],
279
+ "K": [[500, 0, 400], [0, 500, 240], [0, 0, 1]]
280
+ }
281
+ }
282
+ """ # Very minimal dummy, ideally we want a real trajectory
283
+
284
+ with gr.Blocks() as app:
285
+ gr.Markdown("# HY-WorldPlay (HunyuanWorld 1.5) Demo")
286
+ gr.Markdown("Generate streaming videos with camera control using WorldPlay.")
287
+
288
+ with gr.Row():
289
+ with gr.Column():
290
+ prompt = gr.Textbox(label="Prompt", value="A cinematic shot of a forest.")
291
+ image = gr.Image(label="Input Image", type="filepath")
292
+ pose_file = gr.File(label="Camera Path JSON", file_types=[".json"])
293
+ seed = gr.Number(label="Seed", value=123)
294
+ steps = gr.Slider(label="Inference Steps", minimum=10, maximum=100, value=50, step=1)
295
+ length = gr.Slider(label="Video Length (frames)", minimum=17, maximum=129, value=65, step=16) # 16*4 + 1
296
+
297
+ submit = gr.Button("Generate")
298
+
299
+ with gr.Column():
300
+ output_video = gr.Video(label="Generated Video")
301
+
302
+ submit.click(
303
+ fn=generate,
304
+ inputs=[prompt, image, pose_file, seed, steps, length],
305
+ outputs=[output_video]
306
+ )
307
+
308
+ if __name__ == "__main__":
309
+ app.launch()
main.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ def main():
2
+ print("Hello from huggingface-hf-wordplay!")
3
+
4
+
5
+ if __name__ == "__main__":
6
+ main()
pyproject.toml ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "huggingface-hf-wordplay"
3
+ version = "0.1.0"
4
+ description = "Add your description here"
5
+ readme = "README.md"
6
+ requires-python = ">=3.13"
7
+ dependencies = []
requirements.txt ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ git+https://github.com/Tencent-Hunyuan/HY-WorldPlay.git
2
+ torch>=2.6.0
3
+ diffusers==0.35.0
4
+ transformers==4.46.0
5
+ huggingface-hub==0.26.1
6
+ gradio
7
+ spaces
8
+ peft==0.17.0
9
+ loguru==0.7.3
10
+ numpy==1.26.4
11
+ pillow==11.0.0
12
+ imageio==2.36.0
13
+ imageio-ffmpeg==0.5.1
14
+ omegaconf>=2.3.0
15
+ safetensors==0.4.5
16
+ torchvision>=0.17.0
17
+ scipy
18
+ accelerate
19
+ sentencepiece