File size: 7,797 Bytes
0dcccdd
 
92cb9c8
0dcccdd
 
f56d744
 
0dcccdd
 
 
 
 
 
 
 
 
 
 
 
1471bad
 
0dcccdd
 
9518dda
0dcccdd
 
c8f9934
7712d70
1471bad
 
 
 
 
 
 
 
 
 
17b5457
f56d744
 
 
 
0e71afa
f56d744
 
0e71afa
 
 
 
 
 
 
 
 
 
 
 
 
 
f56d744
 
 
0e71afa
f56d744
004a5ed
f56d744
 
 
 
 
 
 
d82b5af
 
93af8bd
 
7712d70
0dcccdd
93af8bd
 
7712d70
0dcccdd
7712d70
93af8bd
d82b5af
93af8bd
 
 
 
 
 
d82b5af
93af8bd
d82b5af
61a8a3a
93af8bd
 
 
 
 
 
 
 
7712d70
93af8bd
 
 
 
 
 
 
 
7712d70
93af8bd
0dcccdd
e7ccefd
 
0dcccdd
7712d70
 
 
 
d82b5af
 
0dcccdd
 
 
 
 
ddc765d
 
7712d70
0dcccdd
 
9518dda
0dcccdd
93af8bd
7712d70
0dcccdd
d82b5af
0dcccdd
 
 
 
ddc765d
f56d744
0dcccdd
 
 
ddc765d
d82b5af
c8f9934
0dcccdd
f56d744
0dcccdd
 
 
 
ddc765d
 
037e668
 
0dcccdd
037e668
7ebf246
0dcccdd
 
 
 
 
 
42c0ab7
 
0dcccdd
 
ddc765d
9518dda
42c0ab7
9518dda
 
 
42c0ab7
9518dda
 
 
 
42c0ab7
ddc765d
42c0ab7
0dcccdd
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
import json
import os
import runpod
import numpy as np
import torch
import requests
import uuid
from diffusers import (AutoencoderKL, CogVideoXDDIMScheduler, DDIMScheduler,
                       DPMSolverMultistepScheduler,
                       EulerAncestralDiscreteScheduler, EulerDiscreteScheduler,
                       PNDMScheduler)
from transformers import T5EncoderModel, T5Tokenizer
from omegaconf import OmegaConf
from PIL import Image
from cogvideox.models.transformer3d import CogVideoXTransformer3DModel
from cogvideox.models.autoencoder_magvit import AutoencoderKLCogVideoX
from cogvideox.pipeline.pipeline_cogvideox import CogVideoX_Fun_Pipeline
from cogvideox.pipeline.pipeline_cogvideox_inpaint import CogVideoX_Fun_Pipeline_Inpaint
from cogvideox.utils.lora_utils import merge_lora, unmerge_lora
from cogvideox.utils.utils import get_image_to_video_latent, save_videos_grid
from cogvideox.data.bucket_sampler import ASPECT_RATIO_512, get_closest_ratio
from huggingface_hub import HfApi, HfFolder

tokenxf = os.getenv("HF_API_TOKEN")
# Low GPU memory mode
low_gpu_memory_mode = False
lora_path = "/content/shirtlift.safetensors"
weight_dtype = torch.bfloat16
def to_pil(image):
    if isinstance(image, Image.Image):
        return image
    if isinstance(image, torch.Tensor):
        return tensor2pil(image)
    if isinstance(image, np.ndarray):
        return numpy2pil(image)
    raise ValueError(f"Cannot convert {type(image)} to PIL.Image")


def download_image(url, download_dir="/content"):
    # Ensure the download directory exists
    if not os.path.exists(download_dir):
        os.makedirs(download_dir, exist_ok=True)
    
    # Send the request and check for successful response
    response = requests.get(url, stream=True)
    if response.status_code == 200:
        # Determine file extension based on content type
        content_type = response.headers.get("Content-Type")
        if content_type == "image/png":
            ext = "png"
        elif content_type == "image/jpeg":
            ext = "jpg"
        else:
            ext = "jpg"  # default to .jpg if content type is unrecognized
        
        # Generate a random filename with the correct extension
        filename = f"{uuid.uuid4().hex}.{ext}"
        file_path = os.path.join(download_dir, filename)
        
        # Save the image
        with open(file_path, "wb") as f:
            for chunk in response.iter_content(1024):
                f.write(chunk)
        
        print(f"Image downloaded to {file_path}")
        os.chmod(file_path, 0o777)
        return file_path
    else:
        raise Exception(f"Failed to download image from {url}, status code: {response.status_code}")

# Usage
# validation_image_start = values.get("validation_image_start", "https://example.com/path/to/image.png")
# downloaded_image_path = download_image(validation_image_start)
with torch.inference_mode():
    model_id = "/runpod-volume/model"
    transformer = CogVideoXTransformer3DModel.from_pretrained_2d(
        model_id, subfolder="transformer"
    ).to(weight_dtype)

    vae = AutoencoderKLCogVideoX.from_pretrained(
        model_id, subfolder="vae"
    ).to(weight_dtype)

    text_encoder = T5EncoderModel.from_pretrained(model_id, subfolder="text_encoder", torch_dtype=weight_dtype)

    sampler_dict = {
        "Euler": EulerDiscreteScheduler,
        "Euler A": EulerAncestralDiscreteScheduler,
        "DPM++": DPMSolverMultistepScheduler,
        "PNDM": PNDMScheduler,
        "DDIM_Cog": CogVideoXDDIMScheduler,
        "DDIM_Origin": DDIMScheduler,
    }
    
    scheduler = sampler_dict["DPM++"].from_pretrained(model_id, subfolder="scheduler")


    if transformer.config.in_channels != vae.config.latent_channels:
        pipeline = CogVideoX_Fun_Pipeline_Inpaint.from_pretrained(
            model_id, 
            vae=vae, 
            text_encoder=text_encoder,
            transformer=transformer, 
            scheduler=scheduler,
            torch_dtype=weight_dtype
        )
    else:
        pipeline = CogVideoX_Fun_Pipeline.from_pretrained(
            model_id, 
            vae=vae, 
            text_encoder=text_encoder,
            transformer=transformer, 
            scheduler=scheduler,
            torch_dtype=weight_dtype
        )

    pipeline = merge_lora(pipeline, lora_path, 1.00)


if low_gpu_memory_mode:
    pipeline.enable_sequential_cpu_offload()
else:
    pipeline.enable_model_cpu_offload()



@torch.inference_mode()
def generate(input):
    values = input["input"]
    prompt = values["prompt"]
    print("starting Generate function")
    print(prompt)
    negative_prompt = values.get("negative_prompt", "The video is not of a high quality, it has a low resolution. Watermark present in each frame. Strange motion trajectory. blurry, blurred, grainy, distortion, blurry face")
    guidance_scale = values.get("guidance_scale", 6.0)
    seed = values.get("seed", 42)
    num_inference_steps = values.get("num_inference_steps", 18)
    base_resolution = values.get("base_resolution", 512)
    
    video_length = values.get("video_length", 49)
    fps = values.get("fps", 10)
    
    save_path = "samples"
    partial_video_length = values.get("partial_video_length", None)
    overlap_video_length = values.get("overlap_video_length", 4)
    validation_image_start = values.get("validation_image_start", "asset/1.png")
    print(validation_image_start)
    downloaded_image_path = download_image(validation_image_start)
    validation_image_end = values.get("validation_image_end", None)
    
    generator = torch.Generator(device="cuda").manual_seed(seed)
    print("Generator started")

    
    aspect_ratio_sample_size = {key : [x / 512 * base_resolution for x in ASPECT_RATIO_512[key]] for key in ASPECT_RATIO_512.keys()}
    start_img = Image.open(downloaded_image_path)
    original_width, original_height = start_img.size
    closest_size, closest_ratio = get_closest_ratio(original_height, original_width, ratios=aspect_ratio_sample_size)
    height, width = [int(x / 16) * 16 for x in closest_size]
    sample_size = [height, width]
    print("Getting closest ratio")
    print(closest_ratio)
    video_length = int((video_length - 1) // vae.config.temporal_compression_ratio * vae.config.temporal_compression_ratio) + 1 if video_length != 1 else 1
    input_video, input_video_mask, clip_image = get_image_to_video_latent(downloaded_image_path, validation_image_end, video_length=video_length, sample_size=sample_size)
        
    with torch.no_grad():
        sample = pipeline(prompt=prompt,num_frames=video_length,negative_prompt=negative_prompt,height=sample_size[0],width=sample_size[1],generator=generator,guidance_scale=guidance_scale,num_inference_steps=num_inference_steps,video=input_video,mask_video=input_video_mask).videos        
    
    if not os.path.exists(save_path):
        os.makedirs(save_path, exist_ok=True)

    index = len([path for path in os.listdir(save_path)]) + 1
    prefix = str(index).zfill(8)
    filename2 = f"{uuid.uuid4().hex}.mp4"
    video_path = os.path.join(save_path, filename2)
    save_videos_grid(sample, video_path, fps=fps)

    print("Video saved to grid, uploading to huggingface")
    hf_api = HfApi()
    
    repo_id = "meepmoo/h4h4jejdf"  # Set your HF repo
    hf_api.upload_file(
       path_or_fileobj=video_path,
       path_in_repo=filename2,
       repo_id=repo_id,
       token=tokenxf,
       repo_type="model"
    )
    
    print("Video uploaded to huggingface returing output")
    result_url = f"https://huggingface.co/{repo_id}/resolve/main/{filename2}"
    job_id = values.get("job_id", "default-job-id")  # For RunPod job tracking
    return {"jobId": job_id, "result": result_url, "status": "DONE"}

runpod.serverless.start({"handler": generate})