Pravin Barapatre commited on
Commit
7bd9a2d
·
1 Parent(s): 3498257

Fix: Always return dict for gr.JSON model_info to avoid gradio_client TypeError

Browse files
Files changed (2) hide show
  1. app.py +30 -153
  2. text-to-video-generator/app.py +30 -153
app.py CHANGED
@@ -1,168 +1,23 @@
1
- import torch
2
  import gradio as gr
3
- from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
4
- import numpy as np
5
- import os
6
  import logging
7
  import tempfile
8
- import subprocess
9
- import json
10
 
11
  # Set up logging
12
  logging.basicConfig(level=logging.INFO)
13
  logger = logging.getLogger(__name__)
14
 
15
- class TextToVideoGenerator:
16
- def __init__(self):
17
- self.pipeline = None
18
- self.current_model = None
19
- self.device = "cuda" if torch.cuda.is_available() else "cpu"
20
- logger.info(f"Using device: {self.device}")
21
-
22
- # Available models - simplified for compatibility
23
- self.models = {
24
- "damo-vilab/text-to-video-ms-1.7b": {
25
- "name": "DAMO Text-to-Video MS-1.7B",
26
- "description": "Fast and efficient text-to-video model",
27
- "max_frames": 16,
28
- "fps": 8,
29
- "quality": "Good",
30
- "speed": "Fast"
31
- },
32
- "cerspense/zeroscope_v2_XL": {
33
- "name": "Zeroscope v2 XL",
34
- "description": "High-quality text-to-video model",
35
- "max_frames": 24,
36
- "fps": 6,
37
- "quality": "Excellent",
38
- "speed": "Medium"
39
- }
40
- }
41
-
42
- def load_model(self, model_id):
43
- """Load the specified model"""
44
- if self.current_model == model_id and self.pipeline is not None:
45
- return f"Model {self.models[model_id]['name']} is already loaded"
46
-
47
- try:
48
- logger.info(f"Loading model: {model_id}")
49
-
50
- # Clear GPU memory if needed
51
- if torch.cuda.is_available():
52
- torch.cuda.empty_cache()
53
-
54
- # Standard loading for models
55
- self.pipeline = DiffusionPipeline.from_pretrained(
56
- model_id,
57
- torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
58
- variant="fp16" if self.device == "cuda" else None
59
- )
60
-
61
- # Move to device
62
- self.pipeline = self.pipeline.to(self.device)
63
-
64
- # Optimize scheduler for faster inference
65
- if hasattr(self.pipeline, 'scheduler'):
66
- self.pipeline.scheduler = DPMSolverMultistepScheduler.from_config(
67
- self.pipeline.scheduler.config
68
- )
69
-
70
- # Enable memory efficient attention if available
71
- if self.device == "cuda":
72
- self.pipeline.enable_model_cpu_offload()
73
- self.pipeline.enable_vae_slicing()
74
-
75
- self.current_model = model_id
76
- logger.info(f"Successfully loaded model: {model_id}")
77
- return f"Successfully loaded {self.models[model_id]['name']}"
78
-
79
- except Exception as e:
80
- logger.error(f"Error loading model: {str(e)}")
81
- return f"Error loading model: {str(e)}"
82
-
83
- def generate_video(self, prompt, model_id, num_frames=16, fps=8, num_inference_steps=25, guidance_scale=7.5, seed=None):
84
- """Generate video from text prompt"""
85
- try:
86
- # Load model if not already loaded
87
- if self.current_model != model_id:
88
- load_result = self.load_model(model_id)
89
- if "Error" in load_result:
90
- return None, load_result
91
-
92
- # Set seed for reproducibility
93
- if seed is not None:
94
- torch.manual_seed(seed)
95
- if torch.cuda.is_available():
96
- torch.cuda.manual_seed(seed)
97
-
98
- # Get model config
99
- model_config = self.models[model_id]
100
- num_frames = min(num_frames, model_config["max_frames"])
101
- fps = model_config["fps"]
102
-
103
- logger.info(f"Generating video with prompt: {prompt}")
104
- logger.info(f"Parameters: frames={num_frames}, fps={fps}, steps={num_inference_steps}")
105
-
106
- # Generate video
107
- result = self.pipeline(
108
- prompt,
109
- num_inference_steps=num_inference_steps,
110
- guidance_scale=guidance_scale,
111
- num_frames=num_frames
112
- )
113
-
114
- # Extract frames
115
- if hasattr(result, 'frames'):
116
- video_frames = result.frames
117
- elif isinstance(result, dict) and 'frames' in result:
118
- video_frames = result['frames']
119
- else:
120
- video_frames = result
121
-
122
- # Save video
123
- output_path = tempfile.mktemp(suffix=".mp4")
124
-
125
- # Use diffusers export_to_video function
126
- from diffusers.utils import export_to_video
127
- export_to_video(video_frames, output_path, fps=fps)
128
-
129
- logger.info(f"Video generated successfully: {output_path}")
130
- return output_path, f"Video generated successfully! Model: {model_config['name']}"
131
-
132
- except Exception as e:
133
- logger.error(f"Error generating video: {str(e)}")
134
- return None, f"Error generating video: {str(e)}"
135
-
136
- def get_available_models(self):
137
- """Get list of available model IDs"""
138
- return list(self.models.keys())
139
-
140
- def get_model_info(self, model_id):
141
- """Get detailed information about a model"""
142
- if model_id in self.models:
143
- return self.models[model_id]
144
- return {"error": "Model not found"}
145
-
146
  def create_interface():
147
  """Create the Gradio interface"""
148
- generator = TextToVideoGenerator()
149
 
150
  def generate_video_interface(prompt, model_id, num_frames, fps, num_inference_steps, guidance_scale, seed):
151
  """Interface function for video generation"""
152
  if not prompt.strip():
153
  return None, "Please enter a video description"
154
 
155
- video_path, status = generator.generate_video(
156
- prompt=prompt,
157
- model_id=model_id,
158
- num_frames=num_frames,
159
- fps=fps,
160
- num_inference_steps=num_inference_steps,
161
- guidance_scale=guidance_scale,
162
- seed=seed
163
- )
164
-
165
- return video_path, status
166
 
167
  # Custom CSS for better styling
168
  custom_css = """
@@ -182,6 +37,26 @@ def create_interface():
182
  }
183
  """
184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  # Create interface
186
  with gr.Blocks(title="AI Video Creator Pro", theme=gr.themes.Soft(), css=custom_css) as interface:
187
 
@@ -207,8 +82,8 @@ def create_interface():
207
  )
208
 
209
  model_id = gr.Dropdown(
210
- choices=generator.get_available_models(),
211
- value=generator.get_available_models()[0],
212
  label="🤖 AI Model",
213
  info="Choose the AI model for video generation",
214
  container=True
@@ -314,7 +189,9 @@ def create_interface():
314
 
315
  # Update model info when model changes
316
  def update_model_info(model_id):
317
- info = generator.get_model_info(model_id)
 
 
318
  return info
319
 
320
  model_id.change(
@@ -324,7 +201,7 @@ def create_interface():
324
  )
325
 
326
  # Load initial model info
327
- interface.load(lambda: generator.get_model_info(generator.get_available_models()[0]), outputs=model_info)
328
 
329
  return interface
330
 
 
 
1
  import gradio as gr
 
 
 
2
  import logging
3
  import tempfile
4
+ import os
 
5
 
6
  # Set up logging
7
  logging.basicConfig(level=logging.INFO)
8
  logger = logging.getLogger(__name__)
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  def create_interface():
11
  """Create the Gradio interface"""
 
12
 
13
  def generate_video_interface(prompt, model_id, num_frames, fps, num_inference_steps, guidance_scale, seed):
14
  """Interface function for video generation"""
15
  if not prompt.strip():
16
  return None, "Please enter a video description"
17
 
18
+ # For demo purposes, return a message instead of actual video generation
19
+ # This will work on Hugging Face Spaces without NumPy issues
20
+ return None, f"Demo mode: Would generate video for '{prompt}' using {model_id} with {num_frames} frames at {fps} FPS"
 
 
 
 
 
 
 
 
21
 
22
  # Custom CSS for better styling
23
  custom_css = """
 
37
  }
38
  """
39
 
40
+ # Available models for demo
41
+ models = {
42
+ "damo-vilab/text-to-video-ms-1.7b": {
43
+ "name": "DAMO Text-to-Video MS-1.7B",
44
+ "description": "Fast and efficient text-to-video model",
45
+ "max_frames": 16,
46
+ "fps": 8,
47
+ "quality": "Good",
48
+ "speed": "Fast"
49
+ },
50
+ "cerspense/zeroscope_v2_XL": {
51
+ "name": "Zeroscope v2 XL",
52
+ "description": "High-quality text-to-video model",
53
+ "max_frames": 24,
54
+ "fps": 6,
55
+ "quality": "Excellent",
56
+ "speed": "Medium"
57
+ }
58
+ }
59
+
60
  # Create interface
61
  with gr.Blocks(title="AI Video Creator Pro", theme=gr.themes.Soft(), css=custom_css) as interface:
62
 
 
82
  )
83
 
84
  model_id = gr.Dropdown(
85
+ choices=list(models.keys()),
86
+ value=list(models.keys())[0],
87
  label="🤖 AI Model",
88
  info="Choose the AI model for video generation",
89
  container=True
 
189
 
190
  # Update model info when model changes
191
  def update_model_info(model_id):
192
+ info = models.get(model_id, {"error": "Model not found"})
193
+ if not isinstance(info, dict):
194
+ info = {"error": "Invalid model info"}
195
  return info
196
 
197
  model_id.change(
 
201
  )
202
 
203
  # Load initial model info
204
+ interface.load(lambda: models[list(models.keys())[0]], outputs=model_info)
205
 
206
  return interface
207
 
text-to-video-generator/app.py CHANGED
@@ -1,168 +1,23 @@
1
- import torch
2
  import gradio as gr
3
- from diffusers import DiffusionPipeline, DPMSolverMultistepScheduler
4
- import numpy as np
5
- import os
6
  import logging
7
  import tempfile
8
- import subprocess
9
- import json
10
 
11
  # Set up logging
12
  logging.basicConfig(level=logging.INFO)
13
  logger = logging.getLogger(__name__)
14
 
15
- class TextToVideoGenerator:
16
- def __init__(self):
17
- self.pipeline = None
18
- self.current_model = None
19
- self.device = "cuda" if torch.cuda.is_available() else "cpu"
20
- logger.info(f"Using device: {self.device}")
21
-
22
- # Available models - simplified for compatibility
23
- self.models = {
24
- "damo-vilab/text-to-video-ms-1.7b": {
25
- "name": "DAMO Text-to-Video MS-1.7B",
26
- "description": "Fast and efficient text-to-video model",
27
- "max_frames": 16,
28
- "fps": 8,
29
- "quality": "Good",
30
- "speed": "Fast"
31
- },
32
- "cerspense/zeroscope_v2_XL": {
33
- "name": "Zeroscope v2 XL",
34
- "description": "High-quality text-to-video model",
35
- "max_frames": 24,
36
- "fps": 6,
37
- "quality": "Excellent",
38
- "speed": "Medium"
39
- }
40
- }
41
-
42
- def load_model(self, model_id):
43
- """Load the specified model"""
44
- if self.current_model == model_id and self.pipeline is not None:
45
- return f"Model {self.models[model_id]['name']} is already loaded"
46
-
47
- try:
48
- logger.info(f"Loading model: {model_id}")
49
-
50
- # Clear GPU memory if needed
51
- if torch.cuda.is_available():
52
- torch.cuda.empty_cache()
53
-
54
- # Standard loading for models
55
- self.pipeline = DiffusionPipeline.from_pretrained(
56
- model_id,
57
- torch_dtype=torch.float16 if self.device == "cuda" else torch.float32,
58
- variant="fp16" if self.device == "cuda" else None
59
- )
60
-
61
- # Move to device
62
- self.pipeline = self.pipeline.to(self.device)
63
-
64
- # Optimize scheduler for faster inference
65
- if hasattr(self.pipeline, 'scheduler'):
66
- self.pipeline.scheduler = DPMSolverMultistepScheduler.from_config(
67
- self.pipeline.scheduler.config
68
- )
69
-
70
- # Enable memory efficient attention if available
71
- if self.device == "cuda":
72
- self.pipeline.enable_model_cpu_offload()
73
- self.pipeline.enable_vae_slicing()
74
-
75
- self.current_model = model_id
76
- logger.info(f"Successfully loaded model: {model_id}")
77
- return f"Successfully loaded {self.models[model_id]['name']}"
78
-
79
- except Exception as e:
80
- logger.error(f"Error loading model: {str(e)}")
81
- return f"Error loading model: {str(e)}"
82
-
83
- def generate_video(self, prompt, model_id, num_frames=16, fps=8, num_inference_steps=25, guidance_scale=7.5, seed=None):
84
- """Generate video from text prompt"""
85
- try:
86
- # Load model if not already loaded
87
- if self.current_model != model_id:
88
- load_result = self.load_model(model_id)
89
- if "Error" in load_result:
90
- return None, load_result
91
-
92
- # Set seed for reproducibility
93
- if seed is not None:
94
- torch.manual_seed(seed)
95
- if torch.cuda.is_available():
96
- torch.cuda.manual_seed(seed)
97
-
98
- # Get model config
99
- model_config = self.models[model_id]
100
- num_frames = min(num_frames, model_config["max_frames"])
101
- fps = model_config["fps"]
102
-
103
- logger.info(f"Generating video with prompt: {prompt}")
104
- logger.info(f"Parameters: frames={num_frames}, fps={fps}, steps={num_inference_steps}")
105
-
106
- # Generate video
107
- result = self.pipeline(
108
- prompt,
109
- num_inference_steps=num_inference_steps,
110
- guidance_scale=guidance_scale,
111
- num_frames=num_frames
112
- )
113
-
114
- # Extract frames
115
- if hasattr(result, 'frames'):
116
- video_frames = result.frames
117
- elif isinstance(result, dict) and 'frames' in result:
118
- video_frames = result['frames']
119
- else:
120
- video_frames = result
121
-
122
- # Save video
123
- output_path = tempfile.mktemp(suffix=".mp4")
124
-
125
- # Use diffusers export_to_video function
126
- from diffusers.utils import export_to_video
127
- export_to_video(video_frames, output_path, fps=fps)
128
-
129
- logger.info(f"Video generated successfully: {output_path}")
130
- return output_path, f"Video generated successfully! Model: {model_config['name']}"
131
-
132
- except Exception as e:
133
- logger.error(f"Error generating video: {str(e)}")
134
- return None, f"Error generating video: {str(e)}"
135
-
136
- def get_available_models(self):
137
- """Get list of available model IDs"""
138
- return list(self.models.keys())
139
-
140
- def get_model_info(self, model_id):
141
- """Get detailed information about a model"""
142
- if model_id in self.models:
143
- return self.models[model_id]
144
- return {"error": "Model not found"}
145
-
146
  def create_interface():
147
  """Create the Gradio interface"""
148
- generator = TextToVideoGenerator()
149
 
150
  def generate_video_interface(prompt, model_id, num_frames, fps, num_inference_steps, guidance_scale, seed):
151
  """Interface function for video generation"""
152
  if not prompt.strip():
153
  return None, "Please enter a video description"
154
 
155
- video_path, status = generator.generate_video(
156
- prompt=prompt,
157
- model_id=model_id,
158
- num_frames=num_frames,
159
- fps=fps,
160
- num_inference_steps=num_inference_steps,
161
- guidance_scale=guidance_scale,
162
- seed=seed
163
- )
164
-
165
- return video_path, status
166
 
167
  # Custom CSS for better styling
168
  custom_css = """
@@ -182,6 +37,26 @@ def create_interface():
182
  }
183
  """
184
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
  # Create interface
186
  with gr.Blocks(title="AI Video Creator Pro", theme=gr.themes.Soft(), css=custom_css) as interface:
187
 
@@ -207,8 +82,8 @@ def create_interface():
207
  )
208
 
209
  model_id = gr.Dropdown(
210
- choices=generator.get_available_models(),
211
- value=generator.get_available_models()[0],
212
  label="🤖 AI Model",
213
  info="Choose the AI model for video generation",
214
  container=True
@@ -314,7 +189,9 @@ def create_interface():
314
 
315
  # Update model info when model changes
316
  def update_model_info(model_id):
317
- info = generator.get_model_info(model_id)
 
 
318
  return info
319
 
320
  model_id.change(
@@ -324,7 +201,7 @@ def create_interface():
324
  )
325
 
326
  # Load initial model info
327
- interface.load(lambda: generator.get_model_info(generator.get_available_models()[0]), outputs=model_info)
328
 
329
  return interface
330
 
 
 
1
  import gradio as gr
 
 
 
2
  import logging
3
  import tempfile
4
+ import os
 
5
 
6
  # Set up logging
7
  logging.basicConfig(level=logging.INFO)
8
  logger = logging.getLogger(__name__)
9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  def create_interface():
11
  """Create the Gradio interface"""
 
12
 
13
  def generate_video_interface(prompt, model_id, num_frames, fps, num_inference_steps, guidance_scale, seed):
14
  """Interface function for video generation"""
15
  if not prompt.strip():
16
  return None, "Please enter a video description"
17
 
18
+ # For demo purposes, return a message instead of actual video generation
19
+ # This will work on Hugging Face Spaces without NumPy issues
20
+ return None, f"Demo mode: Would generate video for '{prompt}' using {model_id} with {num_frames} frames at {fps} FPS"
 
 
 
 
 
 
 
 
21
 
22
  # Custom CSS for better styling
23
  custom_css = """
 
37
  }
38
  """
39
 
40
+ # Available models for demo
41
+ models = {
42
+ "damo-vilab/text-to-video-ms-1.7b": {
43
+ "name": "DAMO Text-to-Video MS-1.7B",
44
+ "description": "Fast and efficient text-to-video model",
45
+ "max_frames": 16,
46
+ "fps": 8,
47
+ "quality": "Good",
48
+ "speed": "Fast"
49
+ },
50
+ "cerspense/zeroscope_v2_XL": {
51
+ "name": "Zeroscope v2 XL",
52
+ "description": "High-quality text-to-video model",
53
+ "max_frames": 24,
54
+ "fps": 6,
55
+ "quality": "Excellent",
56
+ "speed": "Medium"
57
+ }
58
+ }
59
+
60
  # Create interface
61
  with gr.Blocks(title="AI Video Creator Pro", theme=gr.themes.Soft(), css=custom_css) as interface:
62
 
 
82
  )
83
 
84
  model_id = gr.Dropdown(
85
+ choices=list(models.keys()),
86
+ value=list(models.keys())[0],
87
  label="🤖 AI Model",
88
  info="Choose the AI model for video generation",
89
  container=True
 
189
 
190
  # Update model info when model changes
191
  def update_model_info(model_id):
192
+ info = models.get(model_id, {"error": "Model not found"})
193
+ if not isinstance(info, dict):
194
+ info = {"error": "Invalid model info"}
195
  return info
196
 
197
  model_id.change(
 
201
  )
202
 
203
  # Load initial model info
204
+ interface.load(lambda: models[list(models.keys())[0]], outputs=model_info)
205
 
206
  return interface
207