File size: 14,093 Bytes
f41d114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21d4393
0e406cc
f8c13b4
f41d114
 
1198eae
81a1f6d
 
 
1198eae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81a1f6d
1198eae
81a1f6d
1198eae
 
 
 
9c88c69
1198eae
81a1f6d
1198eae
 
 
 
 
feb87be
 
1198eae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
feb87be
1198eae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
789c5b7
1198eae
 
 
 
 
789c5b7
feb87be
1198eae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2aca82a
feb87be
 
1198eae
 
 
 
0e406cc
1198eae
 
 
 
 
 
 
f8c13b4
 
 
 
 
 
 
 
 
 
1198eae
 
feb87be
3b4ef39
 
 
 
 
 
 
f41d114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c88c69
 
feb87be
bbc3e9e
8132e49
 
 
 
f41d114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9c88c69
 
feb87be
f41d114
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1198eae
 
 
f41d114
 
 
 
1198eae
f41d114
 
 
 
81a1f6d
1198eae
 
f8c13b4
f41d114
 
 
 
1198eae
f41d114
 
 
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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import gradio as gr
import requests
import time
import json
from contextlib import closing
from websocket import create_connection
from deep_translator import GoogleTranslator
from langdetect import detect
import os
from PIL import Image
import io
import base64
import os
import random
import tempfile
import re
from gradio_client import Client
import moviepy.editor as mp


def animate_img(encoded_string, model):
    url_hg1 = os.getenv("url_hg1")
    url_hg2 = os.getenv("url_hg2")
    
    if model == "Stable Video Diffusion":
        try:   
            r = requests.post("https://stable-video-diffusion.com/api/upload", files={"file": open(encoded_string, 'rb')})
            hash_ = r.json()['hash']
            time.sleep(10)
            c = 0
            while c < 10:
                r2 = requests.get(f"https://stable-video-diffusion.com/result?hash={hash_}")
                source_string = r2.text
                if "Generation has been in progress for" in source_string:
                    time.sleep(15)
                    c += 1
                    continue
                if "Generation has been in progress for" not in source_string:
                    pattern = r'https://storage.stable-video-diffusion.com/([a-f0-9]{32})\.mp4'
                    matches = re.findall(pattern, source_string)
                    sd_video = []
                    for match in matches:
                        sd_video.append(f"https://storage.stable-video-diffusion.com/{match}.mp4")
                    if len(sd_video) != 0:
                        print("s_1")
                        return sd_video[0]
                    else:
                        _ = 1/0
            print("f_1")
        except:
            print("2")
            client1 = Client(url_hg1)
            result1 = client1.predict(encoded_string, api_name="/resize_image")        
            client = Client(url_hg1)
            result = client.predict(result1, 0, True, 1, 15, api_name="/video")
            res = result[0]['video']
            print("s_2")
            return res

    if model == "AnimateDiff":
        client = Client(url_hg2)
        result = client.predict(encoded_string, "zoom-out", api_name="/predict")
        return result
    
    
def create_video(prompt, model):
    url_sd3 = os.getenv("url_sd3")
    url_sd4 = os.getenv("url_sd4")
    if model == "Stable Video Diffusion":
        try:
            with closing(create_connection(f"{url_sd3}", timeout=120)) as conn:
                conn.send('{"fn_index":3,"session_hash":""}')
                conn.send(f'{{"data":["{prompt}","[deformed | disfigured], poorly drawn, [bad : wrong] anatomy, [extra | missing | floating | disconnected] limb, (mutated hands and fingers), blurry",7.5,"(No style)"],"event_data":null,"fn_index":3,"session_hash":""}}')
                c = 0
                while c < 60:
                    status = json.loads(conn.recv())['msg']
                    if status == 'estimation':
                        c += 1
                        time.sleep(1)
                        continue
                    if status == 'process_starts':
                        break
                photo = json.loads(conn.recv())['output']['data'][0][0]
                base64_string = photo.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '')
            
                image_bytes = base64.b64decode(base64_string)
                with tempfile.NamedTemporaryFile(delete=False) as temp:
                    temp.write(image_bytes)
                    temp_file_path = temp.name
                    print("cs_1")
    
                
        except:
            print("c_2")
            with closing(create_connection(f"{url_sd4}", timeout=120)) as conn:
                conn.send('{"fn_index":0,"session_hash":""}')
                conn.send(f'{{"data":["{prompt}","[deformed | disfigured], poorly drawn, [bad : wrong] anatomy, [extra | missing | floating | disconnected] limb, (mutated hands and fingers), blurry","dreamshaperXL10_alpha2.safetensors [c8afe2ef]",30,"DPM++ 2M Karras",7,1024,1024,-1],"event_data":null,"fn_index":0,"session_hash":""}}')
                conn.recv()
                conn.recv()
                conn.recv()
                conn.recv()
                photo = json.loads(conn.recv())['output']['data'][0]
                base64_string = photo.replace('data:image/jpeg;base64,', '').replace('data:image/png;base64,', '')
            
                image_bytes = base64.b64decode(base64_string)
                with tempfile.NamedTemporaryFile(delete=False) as temp:
                    temp.write(image_bytes)
                    temp_file_path = temp.name
                    print("cs_2")
    
        try:
            r = requests.post("https://stable-video-diffusion.com/api/upload", files={"file": open(temp_file_path, 'rb')})
            print(r.text)
            hash_ = r.json()['hash']
            time.sleep(10)
            c = 0
            while c < 10:
                r2 = requests.get(f"https://stable-video-diffusion.com/result?hash={hash_}")
                source_string = r2.text
                if "Generation has been in progress for" in source_string:
                    time.sleep(15)
                    c += 1
                    continue
                if "Generation has been in progress for" not in source_string:
                    pattern = r'https://storage.stable-video-diffusion.com/([a-f0-9]{32})\.mp4'
                    matches = re.findall(pattern, source_string)
                    sd_video = []
                    for match in matches:
                        sd_video.append(f"https://storage.stable-video-diffusion.com/{match}.mp4")
                    print(sd_video[0])
                    if len(sd_video) != 0:
                        return sd_video[0]
                    else:
                        _ = 1/0
        except:
            client1 = Client("https://emmadrex-stable-video-diffusion.hf.space")
            result1 = client1.predict(encoded_string, api_name="/resize_image")        
            client = Client("https://emmadrex-stable-video-diffusion.hf.space")
            result = client.predict(result1, 0, True, 1, 15, api_name="/video")
            return result[0]['video']
        
            


    if model == "AnimateDiff":
        data = {"prompt": prompt, "negative_prompt": "EasyNegative"}
        r = requests.post("https://sd.cuilutech.com/sdapi/async/txt2gif", json=data)
        c = 0
        while c < 60:
            r2 = requests.post("https://sd.cuilutech.com/sdapi/get_task_info", json={'task_id': r.json()['data']['task_id']})
            time.sleep(2)
            if r2.json()['data']:
                photo = r2.json()['data']['image_urls'][0]
                break
            c += 1
        image = base64.b64encode(requests.get(photo).content).decode("utf-8")
        
        with tempfile.NamedTemporaryFile(delete=False) as temp:
            temp.write(base64.decodebytes(bytes(image, "utf-8")))
            temp_file_path = temp.name
            
        clip = mp.VideoFileClip(temp_file_path)
        temp_file2 = tempfile.NamedTemporaryFile(delete=False)
        clip.write_videofile(temp_file2.name)
        return temp_file2.name


def flip_text1(prompt, motion):
    try:
        language = detect(prompt)
        if language == 'ru':
            prompt = GoogleTranslator(source='ru', target='en').translate(prompt)
            print(prompt)
    except:
        prompt = 'video'

    url_video_g = os.getenv("url_video_g")
    url_video_c = os.getenv("url_video_c")

    if motion == "Приближение →←":
        motion = 'zoom in'
    if motion == "Отдаление ←→":
        motion = 'zoom out'
    if motion == "Вверх ↑":
        motion = 'up'
    if motion == "Вниз ↓":
        motion = 'down'
    if motion == "Влево ←":
        motion = 'left'
    if motion == "Вправо →":
        motion = 'right'
    if motion == "По часовой стрелке ⟳":
        motion = 'rotate cw'
    if motion == "Против часовой стрелки ⟲":
        motion = 'rotate ccw'
    
    data = {"prompt": f"{prompt}","image": "null", "denoise": 0.75,"motion": motion}
    r = requests.post(f"{url_video_g}", json=data)
    while True:
        data2 = {"task_id": f"{r.json()['task_id']}"}
        r2 = requests.post(f"{url_video_c}", json=data2)
        time.sleep(3)
        try:
            if r2.json()['status'] == "QUEUED":
                continue
            if r2.json()['status'] == "PROCESSING":
                continue
        except:
            try:
                n_im2 = f"{time.time()}"
                with tempfile.NamedTemporaryFile(prefix=f'aaafff{n_im2}', suffix='.mp4', delete=False) as file:
                    for chunk in r2.iter_content(chunk_size=1024):
                        if chunk:
                            file.write(chunk)
                    return file.name
            except Exception as e:
                print(e)
                break





def flip_text2(encoded_string, prompt, motion):

    url_video_g = os.getenv("url_video_g")
    url_video_c = os.getenv("url_video_c")
    
    try:
        language = detect(prompt)
        if language == 'ru':
            prompt = GoogleTranslator(source='ru', target='en').translate(prompt)
            print(prompt)
    except:
        pass

    if motion == "Приближение →←":
        motion = 'zoom in'
    if motion == "Отдаление ←→":
        motion = 'zoom out'
    if motion == "Вверх ↑":
        motion = 'up'
    if motion == "Вниз ↓":
        motion = 'down'
    if motion == "Влево ←":
        motion = 'left'
    if motion == "Вправо →":
        motion = 'right'
    if motion == "По часовой стрелке ⟳":
        motion = 'rotate cw'
    if motion == "Против часовой стрелки ⟲":
        motion = 'rotate ccw'
 
    with open(encoded_string, "rb") as image_file:
        encoded_string2 = base64.b64encode(image_file.read())
        encoded_string2 = str(encoded_string2).replace("b'", '')

    data = {"prompt": f"{prompt}","image": f"{encoded_string2}","denoise":0.75,"motion": motion}
    r = requests.post(f"{url_video_g}", json=data)
    while True:
        data2 = {"task_id": f"{r.json()['task_id']}"}
        r2 = requests.post(f"{url_video_c}", json=data2)
        time.sleep(3)
        try:
            if r2.json()['status'] == "QUEUED":
                continue
            if r2.json()['status'] == "PROCESSING":
                continue
        except:
            try:
                n_im2 = f"{time.time()}"
                with tempfile.NamedTemporaryFile(prefix=f'aaafff{n_im2}', suffix='.mp4', delete=False) as file:
                    for chunk in r2.iter_content(chunk_size=1024):
                        if chunk:
                            file.write(chunk)
                    return file.name
            except Exception as e:
                print(e)
                break

                



css = """
#generate {
    width: 100%;
    background: #e253dd !important;
    border: none;
    border-radius: 50px;
    outline: none !important;
    color: white;
}
#generate:hover {
    background: #de6bda !important;
    outline: none !important;
    color: #fff;
    }
footer {visibility: hidden !important;}
"""

with gr.Blocks(css=css) as demo:

    with gr.Tab("Сгенерировать видео"):
        with gr.Column():
            prompt = gr.Textbox(placeholder="Введите описание видео...", show_label=True, label='Описание:', lines=3)
            # motion1 = gr.Dropdown(value="Приближение →←", interactive=True, show_label=True, label="Движение камеры:", choices=["Приближение →←", "Отдаление ←→", "Вверх ↑", "Вниз ↓", "Влево ←", "Вправо →", "По часовой стрелке ⟳", "Против часовой стрелки ⟲"])
            model = gr.Radio(interactive=True, value="Stable Video Diffusion", show_label=True, 
                             label="Модель нейросети:", choices=['Stable Video Diffusion', 'AnimateDiff'])
        with gr.Column():
            text_button = gr.Button("Сгенерировать видео", variant='primary', elem_id="generate")
        with gr.Column():
            video_output = gr.Video(show_label=True, label='Результат:', type="file")
            text_button.click(create_video, inputs=[prompt, model], outputs=video_output)
            
    with gr.Tab("Анимировать изображение"):
        with gr.Column():
            prompt2 = gr.Image(show_label=True, interactive=True, type='filepath', label='Исходное изображение:')
            # prompt12 = gr.Textbox(placeholder="Введите описание видео...", show_label=True, label='Описание видео (опционально):', lines=3)
            # motion2 = gr.Dropdown(value="Приближение →←", interactive=True, show_label=True, label="Движение камеры:", choices=["Приближение →←", "Отдаление ←→", "Вверх ↑", "Вниз ↓", "Влево ←", "Вправо →", "По часовой стрелке ⟳", "Против часовой стрелки ⟲"])
            model2 = gr.Radio(interactive=True, value="Stable Video Diffusion", show_label=True, 
                             label="Модель нейросети:", choices=['Stable Video Diffusion'])
        with gr.Column():
            text_button2 = gr.Button("Анимировать изображение", variant='primary', elem_id="generate")
        with gr.Column():
            video_output2 = gr.Video(show_label=True, label='Результат:', type="file")
            text_button2.click(animate_img, inputs=[prompt2, model2], outputs=video_output2)
    
demo.queue(concurrency_count=12)
demo.launch()