File size: 9,779 Bytes
0b4562b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
"""
Hugging Face Space for STARFlow
Text-to-Image and Text-to-Video Generation

This app allows you to run STARFlow inference on Hugging Face GPU infrastructure.
"""

import os
import gradio as gr
import torch
import subprocess
import pathlib
from pathlib import Path

# Check if running on Hugging Face Spaces
HF_SPACE = os.environ.get("SPACE_ID") is not None

# Verify CUDA availability (will be True on HF Spaces with GPU hardware)
if torch.cuda.is_available():
    print(f"✅ CUDA available! Device: {torch.cuda.get_device_name(0)}")
    print(f"   CUDA Version: {torch.version.cuda}")
    print(f"   PyTorch Version: {torch.__version__}")
else:
    print("⚠️  CUDA not available. Make sure GPU hardware is selected in Space settings.")

def generate_image(prompt, aspect_ratio, cfg, seed, checkpoint_file, config_path):
    """Generate image from text prompt."""
    if checkpoint_file is None:
        return None, "Error: Please upload a checkpoint file."
    
    # Handle Gradio file object
    if hasattr(checkpoint_file, 'name'):
        checkpoint_path = checkpoint_file.name
    else:
        checkpoint_path = str(checkpoint_file)
    
    if not os.path.exists(checkpoint_path):
        return None, f"Error: Checkpoint file not found at {checkpoint_path}."
    
    if not config_path or not os.path.exists(config_path):
        return None, "Error: Config file not found. Please ensure config file exists."
    
    try:
        # Create output directory
        output_dir = Path("outputs")
        output_dir.mkdir(exist_ok=True)
        
        # Run sampling command
        cmd = [
            "python", "sample.py",
            "--model_config_path", config_path,
            "--checkpoint_path", checkpoint_path,
            "--caption", prompt,
            "--sample_batch_size", "1",
            "--cfg", str(cfg),
            "--aspect_ratio", aspect_ratio,
            "--seed", str(seed),
            "--save_folder", "1",
            "--finetuned_vae", "none",
            "--jacobi", "1",
            "--jacobi_th", "0.001",
            "--jacobi_block_size", "16"
        ]
        
        result = subprocess.run(cmd, capture_output=True, text=True, cwd=os.getcwd())
        
        if result.returncode != 0:
            return None, f"Error: {result.stderr}"
        
        # Find the generated image
        # The sample.py script saves to logdir/model_name/...
        # We need to find the most recent output
        output_files = list(output_dir.glob("**/*.png")) + list(output_dir.glob("**/*.jpg"))
        if output_files:
            latest_file = max(output_files, key=lambda p: p.stat().st_mtime)
            return str(latest_file), "Success! Image generated."
        else:
            return None, "Error: Generated image not found."
            
    except Exception as e:
        return None, f"Error: {str(e)}"


def generate_video(prompt, aspect_ratio, cfg, seed, target_length, checkpoint_file, config_path, input_image):
    """Generate video from text prompt."""
    if checkpoint_file is None:
        return None, "Error: Please upload a checkpoint file."
    
    # Handle Gradio file object
    if hasattr(checkpoint_file, 'name'):
        checkpoint_path = checkpoint_file.name
    else:
        checkpoint_path = str(checkpoint_file)
    
    if not os.path.exists(checkpoint_path):
        return None, f"Error: Checkpoint file not found at {checkpoint_path}."
    
    if not config_path or not os.path.exists(config_path):
        return None, "Error: Config file not found. Please ensure config file exists."
    
    # Handle input image
    input_image_path = None
    if input_image is not None:
        if hasattr(input_image, 'name'):
            input_image_path = input_image.name
        else:
            input_image_path = str(input_image)
    
    try:
        # Create output directory
        output_dir = Path("outputs")
        output_dir.mkdir(exist_ok=True)
        
        # Run sampling command
        cmd = [
            "python", "sample.py",
            "--model_config_path", config_path,
            "--checkpoint_path", checkpoint_path,
            "--caption", prompt,
            "--sample_batch_size", "1",
            "--cfg", str(cfg),
            "--aspect_ratio", aspect_ratio,
            "--seed", str(seed),
            "--out_fps", "16",
            "--save_folder", "1",
            "--jacobi", "1",
            "--jacobi_th", "0.001",
            "--finetuned_vae", "none",
            "--disable_learnable_denoiser", "0",
            "--jacobi_block_size", "32",
            "--target_length", str(target_length)
        ]
        
        if input_image_path and os.path.exists(input_image_path):
            cmd.extend(["--input_image", input_image_path])
        else:
            cmd.extend(["--input_image", "none"])
        
        result = subprocess.run(cmd, capture_output=True, text=True, cwd=os.getcwd())
        
        if result.returncode != 0:
            return None, f"Error: {result.stderr}"
        
        # Find the generated video
        output_files = list(output_dir.glob("**/*.mp4")) + list(output_dir.glob("**/*.gif"))
        if output_files:
            latest_file = max(output_files, key=lambda p: p.stat().st_mtime)
            return str(latest_file), "Success! Video generated."
        else:
            return None, "Error: Generated video not found."
            
    except Exception as e:
        return None, f"Error: {str(e)}"


# Create Gradio interface
with gr.Blocks(title="STARFlow - Text-to-Image & Video Generation") as demo:
    gr.Markdown("""
    # STARFlow: Scalable Transformer Auto-Regressive Flow
    
    Generate high-quality images and videos from text prompts using STARFlow models.
    
    **Note**: You'll need to upload model checkpoints. Check the README for model download links.
    """)
    
    with gr.Tabs():
        with gr.Tab("Text-to-Image"):
            with gr.Row():
                with gr.Column():
                    image_prompt = gr.Textbox(
                        label="Prompt",
                        placeholder="a film still of a cat playing piano",
                        lines=3
                    )
                    image_checkpoint = gr.File(
                        label="Model Checkpoint (.pth file)",
                        file_types=[".pth"]
                    )
                    image_config = gr.Textbox(
                        label="Config Path",
                        value="configs/starflow_3B_t2i_256x256.yaml",
                        placeholder="configs/starflow_3B_t2i_256x256.yaml"
                    )
                    image_aspect = gr.Dropdown(
                        choices=["1:1", "2:3", "3:2", "16:9", "9:16", "4:5", "5:4"],
                        value="1:1",
                        label="Aspect Ratio"
                    )
                    image_cfg = gr.Slider(1.0, 10.0, value=3.6, step=0.1, label="CFG Scale")
                    image_seed = gr.Number(value=999, label="Seed", precision=0)
                    image_btn = gr.Button("Generate Image", variant="primary")
                
                with gr.Column():
                    image_output = gr.Image(label="Generated Image")
                    image_status = gr.Textbox(label="Status", interactive=False)
            
            image_btn.click(
                fn=generate_image,
                inputs=[image_prompt, image_aspect, image_cfg, image_seed, image_checkpoint, image_config],
                outputs=[image_output, image_status],
                show_progress=True
            )
        
        with gr.Tab("Text-to-Video"):
            with gr.Row():
                with gr.Column():
                    video_prompt = gr.Textbox(
                        label="Prompt",
                        placeholder="a corgi dog looks at the camera",
                        lines=3
                    )
                    video_checkpoint = gr.File(
                        label="Model Checkpoint (.pth file)",
                        file_types=[".pth"]
                    )
                    video_config = gr.Textbox(
                        label="Config Path",
                        value="configs/starflow-v_7B_t2v_caus_480p.yaml",
                        placeholder="configs/starflow-v_7B_t2v_caus_480p.yaml"
                    )
                    video_aspect = gr.Dropdown(
                        choices=["16:9", "1:1", "4:3"],
                        value="16:9",
                        label="Aspect Ratio"
                    )
                    video_cfg = gr.Slider(1.0, 10.0, value=3.5, step=0.1, label="CFG Scale")
                    video_seed = gr.Number(value=99, label="Seed", precision=0)
                    video_length = gr.Slider(81, 481, value=81, step=80, label="Target Length (frames)")
                    video_input_image = gr.File(
                        label="Input Image (optional, for image-to-video)",
                        file_types=["image"]
                    )
                    video_btn = gr.Button("Generate Video", variant="primary")
                
                with gr.Column():
                    video_output = gr.Video(label="Generated Video")
                    video_status = gr.Textbox(label="Status", interactive=False)
            
            video_btn.click(
                fn=generate_video,
                inputs=[video_prompt, video_aspect, video_cfg, video_seed, video_length, 
                       video_checkpoint, video_config, video_input_image],
                outputs=[video_output, video_status],
                show_progress=True
            )

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