dream2589632147 commited on
Commit
0421974
·
verified ·
1 Parent(s): 4fc32cf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -14
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import gradio as gr
2
  import torch
3
  import cv2
@@ -10,18 +11,17 @@ import shutil
10
  import tempfile
11
  import datetime
12
  import ffmpeg
13
- import spaces # <--- إضافة هامة لـ ZeroGPU
14
 
15
  # ==========================================
16
  # 1. إعدادات النموذج
17
  # ==========================================
18
- # ملاحظة: في ZeroGPU لا نرسل النموذج للـ CUDA فوراً عند البدء، بل ننتظر الدالة
19
  print("⏳ Loading Models...")
20
 
 
 
 
 
21
  try:
22
- # تحديد نوع البيانات
23
- torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
24
-
25
  # تحميل ControlNet
26
  controlnet_model = ControlNetModel.from_pretrained(
27
  "lllyasviel/sd-controlnet-canny", torch_dtype=torch_dtype
@@ -42,7 +42,8 @@ try:
42
 
43
  except Exception as e:
44
  print(f"❌ Error loading models: {e}")
45
- raise e
 
46
 
47
  canny_processor = CannyDetector()
48
 
@@ -50,13 +51,17 @@ canny_processor = CannyDetector()
50
  # 2. دالة المعالجة (مع تفعيل ZeroGPU)
51
  # ==========================================
52
 
53
- @spaces.GPU # <--- هذا هو السطر المفقود الذي سبب الخطأ!
54
  def colorize_video_multistyle(video_file, prompt, style_choice, steps=5):
55
  if not video_file:
56
  return None
57
 
58
- # نقل النموذج إلى GPU الآن فقط
 
59
  pipe.to("cuda")
 
 
 
60
 
61
  timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
62
  output_temp_video_no_audio = os.path.join(tempfile.gettempdir(), f"temp_vis_{timestamp}.mp4")
@@ -98,16 +103,18 @@ def colorize_video_multistyle(video_file, prompt, style_choice, steps=5):
98
 
99
  colored_frames = []
100
 
101
- print("🎬 Starting Frame Processing on GPU...")
102
 
103
  while True:
104
  ret, frame = cap.read()
105
  if not ret:
106
  break
107
 
 
108
  pil_image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
109
  canny_image = canny_processor(pil_image)
110
 
 
111
  with torch.inference_mode():
112
  image_out = pipe(
113
  prompt=full_prompt,
@@ -158,22 +165,22 @@ custom_css = """
158
 
159
  with gr.Blocks(css=custom_css, title="Turbo Video Colorizer") as demo:
160
  with gr.Column(elem_id="col-container"):
161
- gr.Markdown("# ⚡ Turbo Video Colorizer (LCM Accelerated)")
162
  gr.Markdown("تلوين الفيديو بسرعة عالية باستخدام ZeroGPU و LCM-LoRA.")
163
 
164
  with gr.Row():
165
- video_input = gr.Video(label="رفع الفيديو (يفضل فيديو قصير)")
166
 
167
  with gr.Row():
168
- prompt_input = gr.Textbox(label="وصف المشهد (اختياري)", placeholder="مثال: A man walking in the street")
169
  style_dropdown = gr.Dropdown(
170
  ["Auto Color", "Vivid", "Vintage", "Cyberpunk"],
171
  label="النمط", value="Auto Color"
172
  )
173
 
174
- steps_slider = gr.Slider(minimum=4, maximum=12, step=1, value=5, label="الخطوات (Steps)")
175
 
176
- submit_btn = gr.Button("🎨 تلوين الفيديو الآن", variant="primary")
177
  video_output = gr.Video(label="النتيجة")
178
 
179
  submit_btn.click(
 
1
+ import spaces # <--- يجب أن يكون هذا هو السطر رقم 1 دائماً وأبداً
2
  import gradio as gr
3
  import torch
4
  import cv2
 
11
  import tempfile
12
  import datetime
13
  import ffmpeg
 
14
 
15
  # ==========================================
16
  # 1. إعدادات النموذج
17
  # ==========================================
 
18
  print("⏳ Loading Models...")
19
 
20
+ # تحديد نوع البيانات (ملاحظة: مع ZeroGPU التحديد يتم لاحقاً، لكن نجهزه هنا)
21
+ # ملاحظة: لا تستخدم .to('cuda') هنا خارج الدالة في ZeroGPU
22
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
23
+
24
  try:
 
 
 
25
  # تحميل ControlNet
26
  controlnet_model = ControlNetModel.from_pretrained(
27
  "lllyasviel/sd-controlnet-canny", torch_dtype=torch_dtype
 
42
 
43
  except Exception as e:
44
  print(f"❌ Error loading models: {e}")
45
+ # لن نوقف البرنامج هنا، سنتركه يحاول العمل
46
+ pass
47
 
48
  canny_processor = CannyDetector()
49
 
 
51
  # 2. دالة المعالجة (مع تفعيل ZeroGPU)
52
  # ==========================================
53
 
54
+ @spaces.GPU(duration=120) # نمنح الدالة وقتاً كافياً (120 ثانية)
55
  def colorize_video_multistyle(video_file, prompt, style_choice, steps=5):
56
  if not video_file:
57
  return None
58
 
59
+ # === نقل النموذج إلى GPU الآن فقط (داخل الدالة) ===
60
+ print("🚀 Moving models to GPU...")
61
  pipe.to("cuda")
62
+
63
+ # تحسينات الذاكرة
64
+ pipe.enable_attention_slicing()
65
 
66
  timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
67
  output_temp_video_no_audio = os.path.join(tempfile.gettempdir(), f"temp_vis_{timestamp}.mp4")
 
103
 
104
  colored_frames = []
105
 
106
+ print("🎬 Starting Frame Processing on ZeroGPU...")
107
 
108
  while True:
109
  ret, frame = cap.read()
110
  if not ret:
111
  break
112
 
113
+ # تحويل من BGR إلى RGB
114
  pil_image = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
115
  canny_image = canny_processor(pil_image)
116
 
117
+ # التوليد
118
  with torch.inference_mode():
119
  image_out = pipe(
120
  prompt=full_prompt,
 
165
 
166
  with gr.Blocks(css=custom_css, title="Turbo Video Colorizer") as demo:
167
  with gr.Column(elem_id="col-container"):
168
+ gr.Markdown("# ⚡ Turbo Video Colorizer (LCM + ZeroGPU)")
169
  gr.Markdown("تلوين الفيديو بسرعة عالية باستخدام ZeroGPU و LCM-LoRA.")
170
 
171
  with gr.Row():
172
+ video_input = gr.Video(label="رفع الفيديو")
173
 
174
  with gr.Row():
175
+ prompt_input = gr.Textbox(label="وصف المشهد", placeholder="مثال: A sunny day in the park")
176
  style_dropdown = gr.Dropdown(
177
  ["Auto Color", "Vivid", "Vintage", "Cyberpunk"],
178
  label="النمط", value="Auto Color"
179
  )
180
 
181
+ steps_slider = gr.Slider(minimum=4, maximum=10, step=1, value=5, label="الخطوات (5 recommended)")
182
 
183
+ submit_btn = gr.Button("🎨 تلوين الفيديو", variant="primary")
184
  video_output = gr.Video(label="النتيجة")
185
 
186
  submit_btn.click(