Update app.py
Browse files
app.py
CHANGED
|
@@ -1,139 +1,129 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import torch
|
| 3 |
-
import cv2
|
| 4 |
-
import numpy as np
|
| 5 |
-
from PIL import Image
|
| 6 |
-
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, DDIMScheduler
|
| 7 |
-
from controlnet_aux import CannyDetector
|
| 8 |
-
from diffusers.utils import load_image
|
| 9 |
-
from moviepy.editor import VideoFileClip
|
| 10 |
-
import os
|
| 11 |
-
import shutil
|
| 12 |
-
import tempfile
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
#
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
try:
|
| 21 |
-
controlnet_model = ControlNetModel.from_pretrained(
|
| 22 |
-
"lllyasviel/sd-controlnet-canny", torch_dtype=torch_dtype
|
| 23 |
-
)
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
)
|
| 29 |
-
pipe.
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
pipe
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
clip
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
gr.Slider(minimum=10, maximum=50, step=5, value=25, label="خطوات التوليد (للسرعة/الجودة)")
|
| 131 |
-
],
|
| 132 |
-
outputs=gr.Video(label="الفيديو الملون (MP4)"),
|
| 133 |
-
title="🎨 Multi-Style Video Colorizer (Dockerized)",
|
| 134 |
-
description="تلوين الفيديو مع الحفاظ على الهيكل باستخدام ControlNet."
|
| 135 |
-
)
|
| 136 |
-
|
| 137 |
-
if __name__ == "__main__":
|
| 138 |
-
# تشغيل Gradio على 0.0.0.0 والمنفذ 7860 للسماح بالوصول من خارج الحاوية
|
| 139 |
-
iface.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import torch
|
| 3 |
+
import cv2
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from diffusers import StableDiffusionControlNetPipeline, ControlNetModel, DDIMScheduler
|
| 7 |
+
from controlnet_aux import CannyDetector
|
| 8 |
+
from diffusers.utils import load_image
|
| 9 |
+
from moviepy.editor import VideoFileClip
|
| 10 |
+
import os
|
| 11 |
+
import shutil
|
| 12 |
+
import tempfile
|
| 13 |
+
import datetime
|
| 14 |
+
|
| 15 |
+
# 1. تهيئة النموذج
|
| 16 |
+
# تحديد جهاز التشغيل (GPU إذا كان متاحًا محليًا)
|
| 17 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 18 |
+
torch_dtype = torch.float16 if device == "cuda" else torch.float32
|
| 19 |
+
|
| 20 |
+
try:
|
| 21 |
+
controlnet_model = ControlNetModel.from_pretrained(
|
| 22 |
+
"lllyasviel/sd-controlnet-canny", torch_dtype=torch_dtype
|
| 23 |
+
)
|
| 24 |
+
model_id = "runwayml/stable-diffusion-v1-5"
|
| 25 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 26 |
+
model_id, controlnet=controlnet_model, torch_dtype=torch_dtype
|
| 27 |
+
)
|
| 28 |
+
pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
|
| 29 |
+
pipe.to(device)
|
| 30 |
+
print("Models loaded successfully on:", device)
|
| 31 |
+
except Exception as e:
|
| 32 |
+
print(f"Error loading models on CUDA: {e}. Switching to CPU.")
|
| 33 |
+
controlnet_model = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny")
|
| 34 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(model_id, controlnet=controlnet_model)
|
| 35 |
+
pipe.to("cpu")
|
| 36 |
+
|
| 37 |
+
canny_processor = CannyDetector()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# 2. دالة معالجة الفيديو والنموذج (بدون تغيير)
|
| 41 |
+
def colorize_video_multistyle(video_file, reference_image_path, prompt, style_choice, steps=25):
|
| 42 |
+
|
| 43 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 44 |
+
final_output_name = f"colored_output_{timestamp}.mp4"
|
| 45 |
+
|
| 46 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 47 |
+
|
| 48 |
+
clip = VideoFileClip(video_file)
|
| 49 |
+
audio_file = None
|
| 50 |
+
if clip.audio:
|
| 51 |
+
audio_file = os.path.join(temp_dir, "temp_audio.mp3")
|
| 52 |
+
clip.audio.write_audiofile(audio_file, verbose=False, logger=None)
|
| 53 |
+
|
| 54 |
+
fps = clip.fps
|
| 55 |
+
|
| 56 |
+
style_prompts = {
|
| 57 |
+
"Auto Color": "photorealistic color photo, cinematic, detailed, masterpiece",
|
| 58 |
+
"Vivid": "highly saturated, vibrant color photo, pop art colors",
|
| 59 |
+
"Vintage": "sepia tone, old film grain, 1940s vintage look",
|
| 60 |
+
}
|
| 61 |
+
final_prompt = f"{prompt}, {style_prompts.get(style_choice, '')}"
|
| 62 |
+
negative_prompt = "lowres, bad anatomy, bad hands, blurry, distorted, nsfw, frame, border, changed details, monochrome"
|
| 63 |
+
|
| 64 |
+
colored_frames = []
|
| 65 |
+
|
| 66 |
+
for i, frame in enumerate(clip.iter_frames(fps=fps, dtype='uint8')):
|
| 67 |
+
|
| 68 |
+
pil_image = Image.fromarray(frame).convert("RGB")
|
| 69 |
+
canny_image = canny_processor(pil_image)
|
| 70 |
+
|
| 71 |
+
# يمكنك إزالة هذه الأسطر إذا لم تقم بتحميل IP-Adapter
|
| 72 |
+
# ip_adapter_images = []
|
| 73 |
+
# if reference_image_path:
|
| 74 |
+
# ref_image = load_image(reference_image_path).convert("RGB")
|
| 75 |
+
# ip_adapter_images.append(ref_image)
|
| 76 |
+
# # pipe.set_ip_adapter_images(ip_adapter_images)
|
| 77 |
+
|
| 78 |
+
image_out = pipe(
|
| 79 |
+
prompt=final_prompt,
|
| 80 |
+
negative_prompt=negative_prompt,
|
| 81 |
+
image=canny_image,
|
| 82 |
+
num_inference_steps=steps,
|
| 83 |
+
guidance_scale=7.5
|
| 84 |
+
).images[0]
|
| 85 |
+
|
| 86 |
+
colored_frames.append(np.array(image_out))
|
| 87 |
+
|
| 88 |
+
output_video_path = os.path.join(temp_dir, "colored_temp_video.mp4")
|
| 89 |
+
height, width, layers = colored_frames[0].shape
|
| 90 |
+
|
| 91 |
+
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
| 92 |
+
out = cv2.VideoWriter(output_video_path, fourcc, fps, (width, height))
|
| 93 |
+
|
| 94 |
+
for frame in colored_frames:
|
| 95 |
+
out.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
|
| 96 |
+
|
| 97 |
+
out.release()
|
| 98 |
+
|
| 99 |
+
if audio_file and os.path.exists(audio_file):
|
| 100 |
+
video_clip = VideoFileClip(output_video_path)
|
| 101 |
+
final_clip = video_clip.set_audio(clip.audio)
|
| 102 |
+
final_clip.write_videofile(final_output_name, codec='libx264', audio_codec='aac', verbose=False, logger=None)
|
| 103 |
+
else:
|
| 104 |
+
shutil.copy(output_video_path, final_output_name)
|
| 105 |
+
|
| 106 |
+
clip.close()
|
| 107 |
+
|
| 108 |
+
return final_output_name
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
# 3. واجهة Gradio النهائية والتشغيل
|
| 112 |
+
iface = gr.Interface(
|
| 113 |
+
fn=colorize_video_multistyle,
|
| 114 |
+
inputs=[
|
| 115 |
+
gr.Video(label="ملف الفيديو (إلزامي)"),
|
| 116 |
+
gr.Image(label="الصورة المرجعية (لنقل الألوان)", type="filepath", required=False),
|
| 117 |
+
gr.Textbox(label="المطالبة النصية (لتوجيه التلوين)", required=False, value=""),
|
| 118 |
+
gr.Dropdown(["Auto Color", "Vivid", "Vintage"], label="اختيار النمط المسبق", value="Auto Color"),
|
| 119 |
+
gr.Slider(minimum=10, maximum=50, step=5, value=25, label="خطوات التوليد (للسرعة/الجودة)")
|
| 120 |
+
],
|
| 121 |
+
outputs=gr.Video(label="الفيديو الملون (MP4)"),
|
| 122 |
+
title="🎨 Multi-Style Video Colorizer (Gradio)",
|
| 123 |
+
description="تلوين احترافي للفيديو باستخدام ControlNet: يُحافظ على الهيكل وتتغير الألوان فقط."
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
if __name__ == "__main__":
|
| 127 |
+
# هذا السطر يشغل الواجهة على عنوان محلي يمكن الوصول إليه عبر المتصفح
|
| 128 |
+
# يمكنك استخدام share=True لمشاركة الواجهة مؤقتاً عبر الإنترنت
|
| 129 |
+
iface.launch() # تم حذف server_name و server_port للاعتماد على إعدادات Gradio الافتراضية
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|