Shadowartificialintelligence commited on
Commit
3cd5cfd
·
verified ·
1 Parent(s): 34adf1a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +42 -41
app.py CHANGED
@@ -3,7 +3,7 @@ import torch
3
  import numpy as np
4
  import sys
5
  from PIL import Image
6
- from diffusers import DiffusionPipeline
7
  from diffusers.utils import export_to_video
8
 
9
  # Отладка
@@ -13,14 +13,22 @@ print(f"CUDA available: {torch.cuda.is_available()}")
13
  if torch.cuda.is_available():
14
  print(f"GPU: {torch.cuda.get_device_name(0)}")
15
 
16
- # Загрузка модели Wan 2.2 (Image-to-Video)
17
- pipe = DiffusionPipeline.from_pretrained(
18
- "Wan-AI/Wan2.2-T2V-A14B",
19
  torch_dtype=torch.float16,
20
  variant="fp16"
21
  )
22
 
23
- # Единственная безопасная оптимизация
 
 
 
 
 
 
 
 
24
  pipe.enable_vae_slicing()
25
 
26
  # Перемещение на GPU
@@ -28,38 +36,31 @@ if torch.cuda.is_available():
28
  pipe = pipe.to("cuda")
29
  print("✓ Model loaded on GPU")
30
 
31
- def generate_video(prompt, image=None, negative_prompt="blurry, low quality, jittery"):
 
 
 
 
 
 
32
  try:
33
- print(f"Generating video for prompt: '{prompt}'")
34
-
35
- # Генерация (если есть изображение — img2vid, иначе text2vid)
36
  if image is not None and isinstance(image, np.ndarray):
37
- image_pil = Image.fromarray(image).convert("RGB")
38
- # Для Wan 2.2 img2vid требуется специальный режим — используем text2vid как fallback
39
- output = pipe(
40
- prompt=prompt,
41
- negative_prompt=negative_prompt,
42
- num_frames=24, # 1 секунда @ 24fps
43
- height=480, # 480p для стабильности на T4
44
- width=720,
45
- num_inference_steps=30,
46
- generator=torch.Generator(device="cuda").manual_seed(42)
47
- )
48
- else:
49
- # Text-to-Video (основной режим)
50
- output = pipe(
51
- prompt=prompt,
52
- negative_prompt=negative_prompt,
53
- num_frames=24,
54
- height=480,
55
- width=720,
56
- num_inference_steps=30,
57
- generator=torch.Generator(device="cuda").manual_seed(42)
58
- )
59
 
60
  # Сохранение
61
  output_path = "/tmp/output.mp4"
62
- export_to_video(output.frames[0], output_path, fps=24)
63
 
64
  return output_path
65
 
@@ -73,17 +74,17 @@ def generate_video(prompt, image=None, negative_prompt="blurry, low quality, jit
73
  demo = gr.Interface(
74
  fn=generate_video,
75
  inputs=[
76
- gr.Textbox(label="Prompt (English)", value="a panda eating bamboo in a forest, cinematic, 4k"),
77
- gr.Image(label="Optional Image (for img2vid)", type="numpy"),
78
- gr.Textbox(label="Negative Prompt", value="blurry, low quality, jittery motion")
79
  ],
80
- outputs=gr.Video(label="Generated Video (720×480, 24 frames, 1 second)"),
81
- title="🎥 Wan 2.2 Video Generator (Apache 2.0 License)",
82
- description="✅ Commercial use allowed 720p resolutionBased on Alibaba's open-source model",
83
  examples=[
84
- ["a robot dancing in cyberpunk city, neon lights, cinematic", None, "blurry"],
85
- ["a cat wearing sunglasses riding a skateboard, cartoon style", None, "jittery motion"],
86
- ["a spaceship flying through nebula, sci-fi, 4k", None, "low quality"]
87
  ],
88
  cache_examples=False
89
  )
 
3
  import numpy as np
4
  import sys
5
  from PIL import Image
6
+ from diffusers import AnimateDiffPipeline, MotionAdapter, EulerDiscreteScheduler
7
  from diffusers.utils import export_to_video
8
 
9
  # Отладка
 
13
  if torch.cuda.is_available():
14
  print(f"GPU: {torch.cuda.get_device_name(0)}")
15
 
16
+ # Загрузка адаптера движения
17
+ adapter = MotionAdapter.from_pretrained(
18
+ "guoyww/animatediff-motion-adapter-v1-5-2",
19
  torch_dtype=torch.float16,
20
  variant="fp16"
21
  )
22
 
23
+ # Загрузка базовой модели (КАЧЕСТВЕННАЯ)
24
+ pipe = AnimateDiffPipeline.from_pretrained(
25
+ "emilianJR/epiCRealism",
26
+ motion_adapter=adapter,
27
+ torch_dtype=torch.float16,
28
+ variant="fp16"
29
+ )
30
+
31
+ # ЕДИНСТВЕННАЯ безопасная оптимизация
32
  pipe.enable_vae_slicing()
33
 
34
  # Перемещение на GPU
 
36
  pipe = pipe.to("cuda")
37
  print("✓ Model loaded on GPU")
38
 
39
+ # Настройка планировщика
40
+ pipe.scheduler = EulerDiscreteScheduler.from_config(
41
+ pipe.scheduler.config,
42
+ timestep_spacing="trailing"
43
+ )
44
+
45
+ def generate_video(image, prompt, negative_prompt="blurry, low quality, jittery"):
46
  try:
47
+ # Конвертация изображения
 
 
48
  if image is not None and isinstance(image, np.ndarray):
49
+ image = Image.fromarray(image).convert("RGB")
50
+
51
+ # Генерация видео (с изображением как стартовый кадр)
52
+ output = pipe(
53
+ prompt=prompt,
54
+ negative_prompt=negative_prompt,
55
+ num_frames=16,
56
+ guidance_scale=7.5,
57
+ num_inference_steps=25,
58
+ generator=torch.Generator(device="cuda" if torch.cuda.is_available() else "cpu").manual_seed(42)
59
+ )
 
 
 
 
 
 
 
 
 
 
 
60
 
61
  # Сохранение
62
  output_path = "/tmp/output.mp4"
63
+ export_to_video(output.frames[0], output_path, fps=8)
64
 
65
  return output_path
66
 
 
74
  demo = gr.Interface(
75
  fn=generate_video,
76
  inputs=[
77
+ gr.Image(label="Upload Image (512×512 recommended)", type="numpy"),
78
+ gr.Textbox(label="Prompt (describe motion)", value="gentle breeze blowing through hair, soft cinematic movement"),
79
+ gr.Textbox(label="Negative Prompt", value="blurry, low quality, jittery motion, flickering")
80
  ],
81
+ outputs=gr.Video(label="Generated Video (512×512, 16 frames, 2 seconds)"),
82
+ title="🎥 High-Quality Image-to-Video Generator",
83
+ description="✅ Apache 2.0 license sell videos legally Real img2vid support",
84
  examples=[
85
+ [None, "slow cinematic camera pan, film grain", "blurry, jittery"],
86
+ [None, "gentle breeze blowing through hair, soft movement", "low quality, flickering"],
87
+ [None, "subtle floating particles, dreamy atmosphere", "jittery motion, artifacts"]
88
  ],
89
  cache_examples=False
90
  )