thomson99 commited on
Commit
d94e7cf
·
verified ·
1 Parent(s): ef7c6f6

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +68 -48
  2. requirements.txt +5 -2
app.py CHANGED
@@ -1,24 +1,26 @@
1
  import gradio as gr
 
 
 
2
  from PIL import Image
3
  import numpy as np
4
  from moviepy.editor import ImageSequenceClip
5
  import os
6
  import tempfile
7
- import time
8
- import io
9
- from stability_sdk import client
10
- import stability_sdk.interfaces.gooseai.generation.generation_pb2 as generation
11
 
12
- # تكوين مفتاح API
13
- STABILITY_KEY = "sk-QG54FiG6g8hd7XUtLIX1n5EvNp8wJbPgeAr9R2YtXKEDVeNV"
14
-
15
- def create_video_from_text(text_prompt, duration=10, fps=30, resolution="480p"):
16
  try:
17
- # تهيئة عميل Stability AI
18
- stability_api = client.StabilityInference(
19
- key=STABILITY_KEY,
20
- verbose=False,
 
 
21
  )
 
 
22
 
23
  # إنشاء مجلد مؤقت لحفظ الصور
24
  temp_dir = tempfile.mkdtemp()
@@ -32,37 +34,48 @@ def create_video_from_text(text_prompt, duration=10, fps=30, resolution="480p"):
32
  else: # 1080p
33
  size = (1920, 1080)
34
 
35
- # توليد صورة واحدة فقط
36
- print("جاري توليد الصورة...")
 
37
 
38
- # توليد صورة باستخدام Stability AI
39
- answers = stability_api.generate(
40
- prompt=text_prompt,
41
- seed=int(time.time()), # رقم عشوائي
42
- steps=30,
43
- cfg_scale=8.0,
44
- width=512,
45
- height=512,
46
- samples=1,
47
- sampler=generation.SAMPLER_K_DPMPP_2M
48
- )
 
 
 
 
 
 
49
 
50
- for resp in answers:
51
- for artifact in resp.artifacts:
52
- if artifact.finish_reason == generation.FILTER:
53
- raise ValueError("المحتوى غير مناسب، يرجى تعديل الوصف")
54
- if artifact.type == generation.ARTIFACT_IMAGE:
55
- img = Image.open(io.BytesIO(artifact.binary))
56
- # تحويل حجم الصورة
57
- img = img.resize(size, Image.LANCZOS)
58
- # تحويل الصورة إلى مصفوفة numpy
59
- frame = np.array(img)
60
- # تكرار نفس الإطار لمدة الفيديو
61
- total_frames = int(duration * fps)
62
- frames = [frame] * total_frames
 
 
 
 
63
 
64
  if not frames:
65
- raise ValueError("لم يتم توليد الصورة")
66
 
67
  print("جاري إنشاء الفيديو...")
68
 
@@ -71,7 +84,11 @@ def create_video_from_text(text_prompt, duration=10, fps=30, resolution="480p"):
71
 
72
  # حفظ الفيديو في ملف مؤقت
73
  output_path = os.path.join(temp_dir, "output.mp4")
74
- clip.write_videofile(output_path, codec='libx264', fps=fps, verbose=False, logger=None)
 
 
 
 
75
 
76
  print("تم إنشاء الفيديو بنجاح!")
77
  return output_path
@@ -81,19 +98,21 @@ def create_video_from_text(text_prompt, duration=10, fps=30, resolution="480p"):
81
  print(f"حدث خطأ: {error_msg}")
82
  return f"حدث خطأ أثناء إنشاء الفيديو: {error_msg}"
83
 
84
- def video_generator(text_prompt, duration=10, resolution="480p"):
85
  if not text_prompt:
86
  return "الرجاء إدخال وصف للفيديو"
87
 
88
- print(f"بدء توليد فيديو بناءً على الوصف: {text_prompt}")
89
  print(f"المدة: {duration} ثواني")
90
  print(f"الدقة: {resolution}")
 
91
 
92
  try:
93
  result = create_video_from_text(
94
  text_prompt,
95
  duration=duration,
96
- resolution=resolution
 
97
  )
98
  return result
99
  except Exception as e:
@@ -105,13 +124,14 @@ def video_generator(text_prompt, duration=10, resolution="480p"):
105
  iface = gr.Interface(
106
  fn=video_generator,
107
  inputs=[
108
- gr.Textbox(label="وصف المشهد", placeholder="اكتب وصفاً للمشهد الذي تريد إنشاءه..."),
109
  gr.Slider(minimum=5, maximum=30, value=10, step=5, label="مدة الفيديو (بالثواني)"),
110
- gr.Radio(["480p", "720p", "1080p"], label="دقة الفيديو", value="480p")
 
111
  ],
112
- outputs=gr.Video(label="الفيديو المُنشأ"),
113
- title="مولد الفيديو الثابت بالذكاء الاصطناعي",
114
- description="قم بإدخال وصف للمشهد وسيقوم النظام بإنشاء فيديو ثابت باستخدام الذكاء الاصطناعي",
115
  theme="huggingface",
116
  cache_examples=False
117
  )
 
1
  import gradio as gr
2
+ import torch
3
+ from torch import autocast
4
+ from diffusers import StableDiffusionPipeline, DPMSolverMultistepScheduler
5
  from PIL import Image
6
  import numpy as np
7
  from moviepy.editor import ImageSequenceClip
8
  import os
9
  import tempfile
10
+ import random
11
+ from tqdm import tqdm
 
 
12
 
13
+ def create_video_from_text(text_prompt, duration=10, fps=30, resolution="480p", motion_scale=30):
 
 
 
14
  try:
15
+ # تهيئة نموذج Stable Diffusion مع جدولة DPM-Solver
16
+ model_id = "runwayml/stable-diffusion-v1-5"
17
+ pipe = StableDiffusionPipeline.from_pretrained(
18
+ model_id,
19
+ torch_dtype=torch.float16,
20
+ safety_checker=None
21
  )
22
+ pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
23
+ pipe = pipe.to("cuda")
24
 
25
  # إنشاء مجلد مؤقت لحفظ الصور
26
  temp_dir = tempfile.mkdtemp()
 
34
  else: # 1080p
35
  size = (1920, 1080)
36
 
37
+ # عدد الإطارات المطلوبة
38
+ num_frames = int(duration * fps)
39
+ print(f"جاري توليد {num_frames} إطار...")
40
 
41
+ # توليد الإطار الأول
42
+ with autocast("cuda"):
43
+ initial_latents = torch.randn(
44
+ (1, pipe.unet.in_channels, 64, 64),
45
+ device="cuda",
46
+ dtype=torch.float16
47
+ )
48
+
49
+ # توليد الصورة الأولى
50
+ image = pipe(
51
+ prompt=text_prompt,
52
+ latents=initial_latents,
53
+ num_inference_steps=50,
54
+ guidance_scale=7.5
55
+ ).images[0]
56
+
57
+ frames.append(np.array(image.resize(size)))
58
 
59
+ # توليد الإطارات المتتالية مع حركة تدريجية
60
+ for i in tqdm(range(1, num_frames)):
61
+ with autocast("cuda"):
62
+ # إضافة اضطراب صغير للكمون لإنشاء حركة سلسة
63
+ noise_scale = (i / num_frames) * motion_scale
64
+ noise = torch.randn_like(initial_latents) * 0.1 * noise_scale
65
+ current_latents = initial_latents + noise
66
+
67
+ # توليد الإطار الجديد
68
+ image = pipe(
69
+ prompt=text_prompt,
70
+ latents=current_latents,
71
+ num_inference_steps=50,
72
+ guidance_scale=7.5
73
+ ).images[0]
74
+
75
+ frames.append(np.array(image.resize(size)))
76
 
77
  if not frames:
78
+ raise ValueError("فشل في توليد الإطارات")
79
 
80
  print("جاري إنشاء الفيديو...")
81
 
 
84
 
85
  # حفظ الفيديو في ملف مؤقت
86
  output_path = os.path.join(temp_dir, "output.mp4")
87
+ clip.write_videofile(output_path, codec='libx264', fps=fps)
88
+
89
+ # تحرير الذاكرة
90
+ pipe = None
91
+ torch.cuda.empty_cache()
92
 
93
  print("تم إنشاء الفيديو بنجاح!")
94
  return output_path
 
98
  print(f"حدث خطأ: {error_msg}")
99
  return f"حدث خطأ أثناء إنشاء الفيديو: {error_msg}"
100
 
101
+ def video_generator(text_prompt, duration=10, resolution="480p", motion_scale=30):
102
  if not text_prompt:
103
  return "الرجاء إدخال وصف للفيديو"
104
 
105
+ print(f"بدء توليد فيديو متحرك بناءً على الوصف: {text_prompt}")
106
  print(f"المدة: {duration} ثواني")
107
  print(f"الدقة: {resolution}")
108
+ print(f"مقياس الحركة: {motion_scale}")
109
 
110
  try:
111
  result = create_video_from_text(
112
  text_prompt,
113
  duration=duration,
114
+ resolution=resolution,
115
+ motion_scale=motion_scale
116
  )
117
  return result
118
  except Exception as e:
 
124
  iface = gr.Interface(
125
  fn=video_generator,
126
  inputs=[
127
+ gr.Textbox(label="وصف المشهد", placeholder="اكتب وصفاً للمشهد المتحرك الذي تريد إنشاءه..."),
128
  gr.Slider(minimum=5, maximum=30, value=10, step=5, label="مدة الفيديو (بالثواني)"),
129
+ gr.Radio(["480p", "720p", "1080p"], label="دقة الفيديو", value="480p"),
130
+ gr.Slider(minimum=10, maximum=50, value=30, step=5, label="مقياس الحركة")
131
  ],
132
+ outputs=gr.Video(label="الفيديو المتحرك المُنشأ"),
133
+ title="مولد الفيديو المتحرك بالذكاء الاصطناعي",
134
+ description="قم بإدخال وصف للمشهد وسيقوم النظام بإنشاء فيديو متحرك باستخدام الذكاء الاصطناعي. يمكنك التحكم في مقدار الحركة باستخدام شريط التمرير.",
135
  theme="huggingface",
136
  cache_examples=False
137
  )
requirements.txt CHANGED
@@ -1,6 +1,9 @@
1
  gradio==3.50.2
 
 
 
 
2
  pillow==9.5.0
3
  moviepy==1.0.3
4
  numpy==1.24.3
5
- stability-sdk==0.8.5
6
- requests==2.31.0
 
1
  gradio==3.50.2
2
+ torch==2.0.1
3
+ diffusers==0.19.3
4
+ transformers==4.30.2
5
+ accelerate==0.21.0
6
  pillow==9.5.0
7
  moviepy==1.0.3
8
  numpy==1.24.3
9
+ tqdm==4.65.0