Shadowartificialintelligence commited on
Commit
c320a6c
·
verified ·
1 Parent(s): 8106f02

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -25
app.py CHANGED
@@ -7,7 +7,7 @@ import os
7
  import sys
8
  from PIL import Image
9
 
10
- # Отладочная информация
11
  print(f"Python: {sys.version}")
12
  print(f"Torch: {torch.__version__}")
13
  print(f"CUDA available: {torch.cuda.is_available()}")
@@ -18,22 +18,22 @@ if torch.cuda.is_available():
18
  from diffusers import AnimateDiffPipeline, MotionAdapter, EulerDiscreteScheduler
19
  from diffusers.utils import export_to_video
20
 
21
- # Загрузка адаптера движения
22
  adapter = MotionAdapter.from_pretrained(
23
  "guoyww/animatediff-motion-adapter-v1-5-2",
24
  torch_dtype=torch.float16
25
  )
26
 
27
- # Загрузка базовой модели (стиль изображения)
28
  pipe = AnimateDiffPipeline.from_pretrained(
29
  "emilianJR/epiCRealism",
30
  motion_adapter=adapter,
31
  torch_dtype=torch.float16
32
- ).to("cuda")
33
 
34
- # Оптимизации для T4
35
  pipe.enable_vae_slicing()
36
- pipe.enable_model_cpu_offload()
37
 
38
  # Настройка планировщика
39
  pipe.scheduler = EulerDiscreteScheduler.from_config(
@@ -43,23 +43,24 @@ pipe.scheduler = EulerDiscreteScheduler.from_config(
43
 
44
  def generate_video(image, prompt, negative_prompt="blurry, low quality"):
45
  try:
46
- print(f"Generating video from image with prompt: '{prompt}'")
 
47
 
48
- # Конвертация изображения в PIL
49
  if isinstance(image, np.ndarray):
50
- image = Image.fromarray(image)
51
 
52
- # Генерация видео
53
  output = pipe(
54
  prompt=prompt,
55
  negative_prompt=negative_prompt,
56
  num_frames=16,
57
  guidance_scale=7.5,
58
  num_inference_steps=25,
59
- generator=torch.Generator("cuda").manual_seed(42)
60
  )
61
 
62
- # Сохранение в /tmp
63
  output_path = "/tmp/output.mp4"
64
  export_to_video(output.frames[0], output_path, fps=8)
65
 
@@ -72,7 +73,7 @@ def generate_video(image, prompt, negative_prompt="blurry, low quality"):
72
  traceback.print_exc()
73
  return None
74
 
75
- # Интерфейс Gradio
76
  demo = gr.Interface(
77
  fn=generate_video,
78
  inputs=[
@@ -88,7 +89,7 @@ demo = gr.Interface(
88
  lines=2
89
  ),
90
  gr.Textbox(
91
- label="Negative Prompt (optional)",
92
  value="blurry, low quality, jittery motion",
93
  lines=1
94
  )
@@ -98,19 +99,14 @@ demo = gr.Interface(
98
  width=512,
99
  height=512
100
  ),
101
- title="🎥 Commercial-Safe Image-to-Video Generator",
102
- description="""
103
- ✅ **Fully commercial-friendly** (Apache 2.0 license)
104
- ✅ Sell generated videos without legal risks
105
- ✅ Powered by AnimateDiff + epiCRealism
106
- """,
107
  examples=[
108
- ["example1.jpg", "slow panning camera movement", "blurry"],
109
- ["example2.jpg", "gentle breeze blowing through hair", "jittery motion"],
110
- ["example3.jpg", "subtle floating particles", "low quality"]
111
  ],
112
- cache_examples=False,
113
- theme=gr.themes.Soft()
114
  )
115
 
116
  if __name__ == "__main__":
 
7
  import sys
8
  from PIL import Image
9
 
10
+ # Отладочная информация (выполняется ДО загрузки модели)
11
  print(f"Python: {sys.version}")
12
  print(f"Torch: {torch.__version__}")
13
  print(f"CUDA available: {torch.cuda.is_available()}")
 
18
  from diffusers import AnimateDiffPipeline, MotionAdapter, EulerDiscreteScheduler
19
  from diffusers.utils import export_to_video
20
 
21
+ # Загрузка адаптера движения БЕЗ указания устройства
22
  adapter = MotionAdapter.from_pretrained(
23
  "guoyww/animatediff-motion-adapter-v1-5-2",
24
  torch_dtype=torch.float16
25
  )
26
 
27
+ # Загрузка базовой модели БЕЗ .to("cuda")
28
  pipe = AnimateDiffPipeline.from_pretrained(
29
  "emilianJR/epiCRealism",
30
  motion_adapter=adapter,
31
  torch_dtype=torch.float16
32
+ )
33
 
34
+ # КРИТИЧЕСКИ ВАЖНО: оптимизации ДО любой генерации
35
  pipe.enable_vae_slicing()
36
+ pipe.enable_model_cpu_offload() # Сам управляет устройствами
37
 
38
  # Настройка планировщика
39
  pipe.scheduler = EulerDiscreteScheduler.from_config(
 
43
 
44
  def generate_video(image, prompt, negative_prompt="blurry, low quality"):
45
  try:
46
+ print(f"Generating video with prompt: '{prompt}'")
47
+ print(f"CUDA available at runtime: {torch.cuda.is_available()}")
48
 
49
+ # Конвертация изображения
50
  if isinstance(image, np.ndarray):
51
+ image = Image.fromarray(image).convert("RGB")
52
 
53
+ # Генерация видео (без .to("cuda") — pipe сам управляет устройствами)
54
  output = pipe(
55
  prompt=prompt,
56
  negative_prompt=negative_prompt,
57
  num_frames=16,
58
  guidance_scale=7.5,
59
  num_inference_steps=25,
60
+ generator=torch.Generator(device="cuda" if torch.cuda.is_available() else "cpu").manual_seed(42)
61
  )
62
 
63
+ # Сохранение
64
  output_path = "/tmp/output.mp4"
65
  export_to_video(output.frames[0], output_path, fps=8)
66
 
 
73
  traceback.print_exc()
74
  return None
75
 
76
+ # Минималистичный интерфейс без устаревших параметров
77
  demo = gr.Interface(
78
  fn=generate_video,
79
  inputs=[
 
89
  lines=2
90
  ),
91
  gr.Textbox(
92
+ label="Negative Prompt",
93
  value="blurry, low quality, jittery motion",
94
  lines=1
95
  )
 
99
  width=512,
100
  height=512
101
  ),
102
+ title="🎥 Commercial-Safe Image-to-Video",
103
+ description="✅ Apache 2.0 license — sell videos legally",
 
 
 
 
104
  examples=[
105
+ [None, "slow panning camera movement", "blurry"],
106
+ [None, "gentle breeze blowing through hair", "jittery motion"],
107
+ [None, "subtle floating particles", "low quality"]
108
  ],
109
+ cache_examples=False
 
110
  )
111
 
112
  if __name__ == "__main__":