thomson99 commited on
Commit
a7061b5
·
verified ·
1 Parent(s): ed8662b

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -66
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import gradio as gr
2
  import torch
3
- from diffusers import StableDiffusionPipeline, EulerAncestralDiscreteScheduler
4
  from PIL import Image
5
  import numpy as np
6
  from moviepy.editor import ImageSequenceClip
@@ -11,91 +11,87 @@ from tqdm import tqdm
11
  def create_video_from_text(text_prompt, duration=10, fps=30, resolution="480p", motion_scale=30):
12
  try:
13
  # تهيئة نموذج Stable Diffusion
14
- model_id = "runwayml/stable-diffusion-v1-5"
15
- device = "cpu" # استخدام CPU
16
 
17
  pipe = StableDiffusionPipeline.from_pretrained(
18
  model_id,
19
- torch_dtype=torch.float32, # استخدام float32 للـ CPU
20
  )
21
- pipe.scheduler = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
22
- pipe.enable_attention_slicing()
23
  pipe = pipe.to(device)
24
 
25
- # إنشاء مجلد مؤقت لحفظ الصور
 
 
 
 
26
  temp_dir = tempfile.mkdtemp()
27
  frames = []
28
 
29
- # تحديد حجم الصورة حسب الدقة المطلوبة
30
  if resolution == "480p":
31
- size = (854, 480)
32
  elif resolution == "720p":
33
  size = (1280, 720)
34
- else: # 1080p
35
  size = (1920, 1080)
36
 
37
- # تقليل عدد الإطارات للأداء على CPU
38
- fps_reduced = 15 # تقليل معدل الإطارات
39
- num_frames = int(duration * fps_reduced / 2) # تقليل عدد الإطارات
40
- print(f"جاري توليد {num_frames} إطار...")
41
-
42
- # توليد الإطار الأول
43
- generator = torch.Generator(device=device).manual_seed(42)
44
- latents = torch.randn(
45
- (1, pipe.unet.config.in_channels, 64, 64),
46
- generator=generator,
47
- device=device,
48
- dtype=torch.float32
49
- )
50
-
51
- # توليد الصورة الأولى
52
- image = pipe(
53
- prompt=text_prompt,
54
- latents=latents,
55
- num_inference_steps=20, # تقليل خطوات الاستدلال
56
- guidance_scale=7.5,
57
- generator=generator
58
- ).images[0]
59
 
60
- frames.append(np.array(image.resize(size)))
61
-
62
- # توليد الإطارات المتتالية مع حركة تدريجية
63
- for i in tqdm(range(1, num_frames)):
64
- # إضافة اضطراب تدريجي للكمون
65
- time_embed = torch.tensor([i / num_frames], device=device, dtype=torch.float32)
66
- noise = torch.randn_like(latents) * (motion_scale / 100)
67
- current_latents = latents + noise * time_embed.view(-1, 1, 1, 1)
68
 
69
- # توليد الإطار الجديد
70
  image = pipe(
71
- prompt=text_prompt,
72
- latents=current_latents,
73
- num_inference_steps=20,
74
- guidance_scale=7.5,
75
- generator=generator
76
  ).images[0]
77
 
78
- frames.append(np.array(image.resize(size)))
 
 
79
 
80
  if not frames:
81
- raise ValueError("فشل في توليد الإطارات")
82
-
83
  print("جاري إنشاء الفيديو...")
84
 
85
- # تكرار الإطارات للوصول إلى FPS المطلوب
86
- frames_extended = []
87
- for frame in frames:
88
- repeat_times = int(fps / fps_reduced)
89
- frames_extended.extend([frame] * repeat_times)
 
 
 
 
 
 
 
 
 
 
90
 
91
- # إنشاء الفيديو من الإطارات
92
- clip = ImageSequenceClip(frames_extended, fps=fps)
 
 
 
93
 
94
- # حفظ الفيديو في ملف مؤقت
 
95
  output_path = os.path.join(temp_dir, "output.mp4")
96
  clip.write_videofile(output_path, codec='libx264', fps=fps)
97
 
98
- # تحرير الذاكرة
99
  pipe = None
100
  torch.cuda.empty_cache()
101
 
@@ -114,7 +110,6 @@ def video_generator(text_prompt, duration=10, resolution="480p", motion_scale=30
114
  print(f"بدء توليد فيديو متحرك بناءً على الوصف: {text_prompt}")
115
  print(f"المدة: {duration} ثواني")
116
  print(f"الدقة: {resolution}")
117
- print(f"مقياس الحركة: {motion_scale}")
118
 
119
  try:
120
  result = create_video_from_text(
@@ -129,25 +124,26 @@ def video_generator(text_prompt, duration=10, resolution="480p", motion_scale=30
129
  print(f"حدث خطأ في المولد: {error_msg}")
130
  return f"حدث خطأ: {error_msg}"
131
 
132
- # إنشاء واجهة المستخدم باستخدام Gradio
133
  iface = gr.Interface(
134
  fn=video_generator,
135
  inputs=[
136
  gr.Textbox(label="وصف المشهد", placeholder="اكتب وصفاً للمشهد المتحرك الذي تريد إنشاءه..."),
137
- gr.Slider(minimum=5, maximum=30, value=10, step=5, label="مدة الفيديو (بالثواني)"),
138
  gr.Radio(["480p", "720p", "1080p"], label="دقة الفيديو", value="480p"),
139
  gr.Slider(minimum=10, maximum=100, value=30, step=5, label="مقياس الحركة (%)")
140
  ],
141
  outputs=gr.Video(label="الفيديو المتحرك المُنشأ"),
142
- title="مولد الفيديو المتحرك بالذكاء الاصطناعي",
143
  description="""
144
  قم بإدخال وصف للمشهد وسيقوم النظام بإنشاء فيديو متحرك باستخدام الذكاء الاصطناعي.
145
 
146
- - استخدم مقياس الحركة للتحكم في مقدار الحركة في الفيديو (10% لحركة بسيطة، 100% لحركة كبيرة)
147
- - اختر الدقة المناسبة (480p للسرعة، 1080p للجودة العالية)
148
- - اكتب وصفاً تفصيلياً للمشهد للحصول على أفضل النتائج
 
149
 
150
- ملاحظة: يتم تشغيل النموذج على CPU مما قد يؤدي إلى بطء في الأداء. للحصول على أداء أفضل، يُنصح باستخدام GPU.
151
  """,
152
  theme="huggingface",
153
  cache_examples=False
 
1
  import gradio as gr
2
  import torch
3
+ from diffusers import StableDiffusionPipeline
4
  from PIL import Image
5
  import numpy as np
6
  from moviepy.editor import ImageSequenceClip
 
11
  def create_video_from_text(text_prompt, duration=10, fps=30, resolution="480p", motion_scale=30):
12
  try:
13
  # تهيئة نموذج Stable Diffusion
14
+ model_id = "CompVis/stable-diffusion-v1-4" # نموذج أخف
15
+ device = "cpu"
16
 
17
  pipe = StableDiffusionPipeline.from_pretrained(
18
  model_id,
19
+ torch_dtype=torch.float32
20
  )
 
 
21
  pipe = pipe.to(device)
22
 
23
+ # تحسين الأداء
24
+ pipe.enable_attention_slicing()
25
+ pipe.enable_model_cpu_offload()
26
+
27
+ # إنشاء مجلد مؤقت
28
  temp_dir = tempfile.mkdtemp()
29
  frames = []
30
 
31
+ # تحديد الحجم
32
  if resolution == "480p":
33
+ size = (640, 480) # حجم أصغر للأداء
34
  elif resolution == "720p":
35
  size = (1280, 720)
36
+ else:
37
  size = (1920, 1080)
38
 
39
+ # توليد 3 صور فقط
40
+ num_images = 3
41
+ print(f"جاري توليد {num_images} صور...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ for i in tqdm(range(num_images)):
44
+ # تعديل البرومبت لكل صورة
45
+ current_prompt = text_prompt
46
+ if i == 1:
47
+ current_prompt += " , slight movement"
48
+ elif i == 2:
49
+ current_prompt += " , more movement"
 
50
 
51
+ # توليد الصورة
52
  image = pipe(
53
+ prompt=current_prompt,
54
+ num_inference_steps=20, # تقليل خطوات الاستدلال
55
+ guidance_scale=7.0
 
 
56
  ).images[0]
57
 
58
+ # تغيير الحجم
59
+ image = image.resize(size, Image.LANCZOS)
60
+ frames.append(np.array(image))
61
 
62
  if not frames:
63
+ raise ValueError("فشل في توليد الصور")
64
+
65
  print("جاري إنشاء الفيديو...")
66
 
67
+ # إنشاء الإطارات الوسيطة
68
+ final_frames = []
69
+ for i in range(len(frames)-1):
70
+ # إضافة الإطار الحالي
71
+ final_frames.append(frames[i])
72
+
73
+ # إنشاء إطارات وسيطة
74
+ num_transitions = 10 # عدد الإطارات الوسيطة
75
+ for t in range(num_transitions):
76
+ alpha = t / num_transitions
77
+ transition_frame = (1 - alpha) * frames[i] + alpha * frames[i+1]
78
+ final_frames.append(transition_frame.astype(np.uint8))
79
+
80
+ # إضافة الإطار الأخير
81
+ final_frames.append(frames[-1])
82
 
83
+ # تكرار الإطارات للوصول للمدة المطلوبة
84
+ target_frames = int(duration * fps)
85
+ if len(final_frames) < target_frames:
86
+ final_frames = final_frames * (target_frames // len(final_frames) + 1)
87
+ final_frames = final_frames[:target_frames]
88
 
89
+ # إنشاء الفيديو
90
+ clip = ImageSequenceClip(final_frames, fps=fps)
91
  output_path = os.path.join(temp_dir, "output.mp4")
92
  clip.write_videofile(output_path, codec='libx264', fps=fps)
93
 
94
+ # تنظيف الذاكرة
95
  pipe = None
96
  torch.cuda.empty_cache()
97
 
 
110
  print(f"بدء توليد فيديو متحرك بناءً على الوصف: {text_prompt}")
111
  print(f"المدة: {duration} ثواني")
112
  print(f"الدقة: {resolution}")
 
113
 
114
  try:
115
  result = create_video_from_text(
 
124
  print(f"حدث خطأ في المولد: {error_msg}")
125
  return f"حدث خطأ: {error_msg}"
126
 
127
+ # إنشاء واجهة المستخدم
128
  iface = gr.Interface(
129
  fn=video_generator,
130
  inputs=[
131
  gr.Textbox(label="وصف المشهد", placeholder="اكتب وصفاً للمشهد المتحرك الذي تريد إنشاءه..."),
132
+ gr.Slider(minimum=3, maximum=15, value=5, step=1, label="مدة الفيديو (بالثواني)"),
133
  gr.Radio(["480p", "720p", "1080p"], label="دقة الفيديو", value="480p"),
134
  gr.Slider(minimum=10, maximum=100, value=30, step=5, label="مقياس الحركة (%)")
135
  ],
136
  outputs=gr.Video(label="الفيديو المتحرك المُنشأ"),
137
+ title="مولد الفيديو المتحرك بالذكاء الاصطناعي (نسخة سريعة)",
138
  description="""
139
  قم بإدخال وصف للمشهد وسيقوم النظام بإنشاء فيديو متحرك باستخدام الذكاء الاصطناعي.
140
 
141
+ نصائح للأداء الأفضل:
142
+ - استخدم دقة 480p للحصول على أسرع أداء
143
+ - اختر مدة قصيرة (3-5 ثواني) للتجربة الأولى
144
+ - اكتب وصفاً واضحاً وبسيطاً
145
 
146
+ ملاحظة: هذه نسخة مُحسنة للأداء على CPU. تم تبسيط عملية توليد الفيديو للحصول على نتائج أسرع.
147
  """,
148
  theme="huggingface",
149
  cache_examples=False