nmrprogs commited on
Commit
70b382b
verified
1 Parent(s): ec94d16

Upload 23 files

Browse files
Vidu/app.py ADDED
@@ -0,0 +1,562 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ from PIL import Image
4
+ import gradio as gr
5
+ import cv2
6
+
7
+ # Codigo creado por IA(Sistema de Interes) https://www.youtube.com/@IA.Sistema.de.Interes
8
+ # Funci贸n para ejecutar comandos y devolver el estado
9
+ def run_commands(description, aspect_ratio, enhance_check, model, style, upscale_check, task_type, img=None, is_extend=False, is_recreate=False):
10
+ try:
11
+ commands = []
12
+
13
+ if True:
14
+ # Comandos generales seg煤n el tipo de tarea
15
+ if upscale_check:
16
+ commands.append('python /content/Vidu_Studio/vidu_credit.py --credit 4')
17
+ else:
18
+ commands.append('python /content/Vidu_Studio/vidu_credit.py --credit 0')
19
+
20
+ if task_type == "video_to_video":
21
+ commands.append('python /content/Vidu_Studio/utils/video_fragment.py')
22
+ print("File Uploader...")
23
+ commands.append('python /content/Vidu_Studio/upload/file_uploader.py --file_info "file_info" --image "img_fragmento"')
24
+
25
+ if task_type == "extend":
26
+ print("Last frame...")
27
+ commands.append('python /content/Vidu_Studio/utils/fragment.py')
28
+
29
+ if task_type == "reference_to_video" or task_type == "image_to_video" or task_type == "extend":
30
+ print("File Uploader...")
31
+ commands.append('python /content/Vidu_Studio/upload/file_uploader.py --file_info "file_info" --image "img_fragmento"')
32
+
33
+ if task_type == "reference_to_video":
34
+ print("Generating video with reference...")
35
+ commands.append(
36
+ f'python /content/Vidu_Studio/create_video_reference.py --prompt "{description}" --enhance {str(enhance_check).lower()} --model "{model}"'
37
+ )
38
+ elif task_type == "text_to_video":
39
+ print("Generating video: Text to Video...")
40
+ commands.append(
41
+ f'python /content/Vidu_Studio/create_text_to_video.py --prompt "{description}" --enhance {str(enhance_check).lower()} --model "{model}" --style "{style}" --aspect_ratio "{aspect_ratio}"'
42
+ )
43
+ elif task_type == "image_to_video" or task_type == "extend":
44
+ print("Generating Video: Image to Video...")
45
+ commands.append(
46
+ f'python /content/Vidu_Studio/create_task.py --prompt "{description}" --enhance {str(enhance_check).lower()} --model "{model}"'
47
+ )
48
+ elif task_type == "video_to_video":
49
+ print("Generating Video: Video to Video...")
50
+ commands.append(
51
+ f'python /content/Vidu_Studio/create_task.py --prompt "{description}" --enhance {str(enhance_check).lower()} --model "{model}"'
52
+ )
53
+ else:
54
+ raise ValueError(f"Tipo de tarea no reconocido: {task_type}")
55
+ print("Video in progress...")
56
+ commands.append('python /content/Vidu_Studio/utils/process_task.py')
57
+
58
+ if upscale_check:
59
+ print("Generate Upscale...")
60
+ commands.append('python /content/Vidu_Studio/utils/upscale_task.py')
61
+ print("Upscale in progress...")
62
+ commands.append('python /content/Vidu_Studio/utils/process_task_upscale.py')
63
+ commands.append('python /content/Vidu_Studio/utils/delete_task.py')
64
+ commands.append('python /content/Vidu_Studio/utils/delete_task_upscale.py')
65
+ else:
66
+ commands.append('python /content/Vidu_Studio/utils/delete_task.py')
67
+
68
+ output = ""
69
+ for command in commands:
70
+ result = subprocess.run(command, shell=True, capture_output=True, text=True)
71
+ output += f"Exit:\n{result.stdout}\n"
72
+ print(result.stdout)
73
+
74
+ video_path = "/content/Vidu_Studio/video.mp4"
75
+ return output, video_path
76
+ except Exception as e:
77
+ return f"Excepci贸n: {str(e)}", None
78
+
79
+
80
+
81
+
82
+
83
+
84
+
85
+
86
+ def run_commands_dual(description, aspect_ratio, enhance_check, model, style, upscale_check, task_type, add_end_frame, img=None, is_extend=False, is_recreate=False):
87
+ try:
88
+ commands = []
89
+
90
+ if add_end_frame:
91
+ # Comandos generales seg煤n el tipo de tarea
92
+ if upscale_check:
93
+ commands.append('python /content/Vidu_Studio/vidu_credit.py --credit 4')
94
+ else:
95
+ commands.append('python /content/Vidu_Studio/vidu_credit.py --credit 0')
96
+
97
+ print("File Uploader...")
98
+ commands.append('python /content/Vidu_Studio/upload/file_uploader.py --file_info "file_info" --image "img_fragmento"')
99
+ commands.append('python /content/Vidu_Studio/upload/file_uploader.py --file_info "file_info2" --image "img_fragmento2"')
100
+
101
+ if task_type == "headtailimg2video":
102
+ print("Generating video with headtailimg2video...")
103
+ commands.append(
104
+ f'python /content/Vidu_Studio/headtailimg2video.py --prompt "{description}" --enhance {str(enhance_check).lower()} --model "{model}"'
105
+ )
106
+ print("Video in progress...")
107
+ commands.append('python /content/Vidu_Studio/utils/process_task.py')
108
+
109
+ if upscale_check:
110
+ print("Generate Upscale...")
111
+ commands.append('python /content/Vidu_Studio/utils/upscale_task.py')
112
+ print("Upscale in progress...")
113
+ commands.append('python /content/Vidu_Studio/utils/process_task_upscale.py')
114
+ commands.append('python /content/Vidu_Studio/utils/delete_task.py')
115
+ commands.append('python /content/Vidu_Studio/utils/delete_task_upscale.py')
116
+ else:
117
+ commands.append('python /content/Vidu_Studio/utils/delete_task.py')
118
+ else:
119
+ # Comandos generales seg煤n el tipo de tarea
120
+ if upscale_check:
121
+ commands.append('python /content/Vidu_Studio/vidu_credit.py --credit 4')
122
+ else:
123
+ commands.append('python /content/Vidu_Studio/vidu_credit.py --credit 0')
124
+
125
+ print("File Uploader...")
126
+ commands.append('python /content/Vidu_Studio/upload/file_uploader.py --file_info "file_info" --image "img_fragmento"')
127
+
128
+ if task_type == "headtailimg2video":
129
+ print("Generating video with Image to Video...")
130
+ commands.append(
131
+ f'python /content/Vidu_Studio/create_task.py --prompt "{description}" --enhance {str(enhance_check).lower()} --model "{model}"'
132
+ )
133
+
134
+ print("Video in progress...")
135
+ commands.append('python /content/Vidu_Studio/utils/process_task.py')
136
+
137
+ if upscale_check:
138
+ print("Generate Upscale...")
139
+ commands.append('python /content/Vidu_Studio/utils/upscale_task.py')
140
+ print("Upscale in progress...")
141
+ commands.append('python /content/Vidu_Studio/utils/process_task_upscale.py')
142
+ commands.append('python /content/Vidu_Studio/utils/delete_task.py')
143
+ commands.append('python /content/Vidu_Studio/utils/delete_task_upscale.py')
144
+ else:
145
+ commands.append('python /content/Vidu_Studio/utils/delete_task.py')
146
+
147
+
148
+ output = ""
149
+ for command in commands:
150
+ result = subprocess.run(command, shell=True, capture_output=True, text=True)
151
+ output += f"Exit:\n{result.stdout}\n"
152
+ print(result.stdout)
153
+
154
+ video_path = "/content/Vidu_Studio/video.mp4"
155
+ return output, video_path
156
+ except Exception as e:
157
+ return f"Excepci贸n: {str(e)}", None
158
+
159
+ # Funci贸n para procesar y guardar la imagen autom谩ticamente en formato JPG
160
+ def process_and_save_image(image, coordinates_file_path="/tmp/coordinates.txt"):
161
+ jpg_path = "/tmp/img_fragmento.jpg"
162
+
163
+ try:
164
+ if image.format != "JPEG":
165
+ image = image.convert("RGB")
166
+ image.save(jpg_path, "JPEG", quality=100)
167
+ if os.path.exists(jpg_path):
168
+ print(f"Imagen guardada correctamente")
169
+
170
+ # Obtener las dimensiones de la imagen
171
+ width, height = image.size
172
+
173
+ # Guardar las coordenadas en un archivo de texto
174
+ with open(coordinates_file_path, "w") as file:
175
+ file.write(f"X: {width}\n")
176
+ file.write(f"Y: {height}\n")
177
+
178
+ print(f"Coordenadas guardadas correctamente")
179
+
180
+ return None
181
+ except Exception as e:
182
+ print(f"Error al procesar la imagen: {str(e)}")
183
+ return None
184
+
185
+ # Funci贸n para procesar y guardar la imagen autom谩ticamente en formato JPG
186
+ def process_and_save_image1(image, coordinates_file_path="/tmp/coordinates.txt"):
187
+ jpg_path = "/tmp/img_fragmento.jpg"
188
+
189
+ try:
190
+ if image.format != "JPEG":
191
+ image = image.convert("RGB")
192
+ image.save(jpg_path, "JPEG", quality=100)
193
+ if os.path.exists(jpg_path):
194
+ print(f"Imagen guardada correctamente")
195
+
196
+ # Obtener las dimensiones de la imagen
197
+ width, height = image.size
198
+
199
+ # Guardar las coordenadas en un archivo de texto
200
+ with open(coordinates_file_path, "w") as file:
201
+ file.write(f"X: {width}\n")
202
+ file.write(f"Y: {height}\n")
203
+
204
+ print(f"Coordenadas guardadas correctamente")
205
+
206
+ return None
207
+ except Exception as e:
208
+ print(f"Error al procesar la imagen: {str(e)}")
209
+ return None
210
+
211
+ # Funci贸n para procesar y guardar la imagen autom谩ticamente en formato JPG
212
+ def process_and_save_image2(image, coordinates_file_path="/tmp/coordinates2.txt"):
213
+ jpg_path = "/tmp/img_fragmento2.jpg"
214
+
215
+ try:
216
+ if image.format != "JPEG":
217
+ image = image.convert("RGB")
218
+ image.save(jpg_path, "JPEG", quality=100)
219
+ if os.path.exists(jpg_path):
220
+ print(f"Imagen guardada correctamente")
221
+
222
+ # Obtener las dimensiones de la imagen
223
+ width, height = image.size
224
+
225
+ # Guardar las coordenadas en un archivo de texto
226
+ with open(coordinates_file_path, "w") as file:
227
+ file.write(f"X: {width}\n")
228
+ file.write(f"Y: {height}\n")
229
+
230
+ print(f"Coordenadas guardadas correctamente")
231
+
232
+ except Exception as e:
233
+ print(f"Error al procesar la imagen: {str(e)}")
234
+
235
+
236
+
237
+ # Funci贸n para obtener el 煤ltimo frame de un video
238
+ def get_last_frame(video_path):
239
+ try:
240
+ cap = cv2.VideoCapture(video_path)
241
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
242
+ cap.set(cv2.CAP_PROP_POS_FRAMES, frame_count - 1)
243
+ ret, frame = cap.read()
244
+ cap.release()
245
+
246
+ if ret:
247
+ return Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
248
+ else:
249
+ print(f"Error al leer el 煤ltimo frame del video: {video_path}")
250
+ return None
251
+ except Exception as e:
252
+ print(f"Excepci贸n al obtener el 煤ltimo frame: {str(e)}")
253
+ return None
254
+
255
+
256
+ # Funci贸n para ejecutar los comandos de guardado
257
+ def run_save_commands():
258
+ try:
259
+ print("Rendering video...")
260
+ commands = [
261
+ "python /content/Vidu_Studio/utils/fragment.py",
262
+ "python /content/Vidu_Studio/utils/union.py"
263
+ ]
264
+ output = ""
265
+ for command in commands:
266
+ result = subprocess.run(command, shell=True, capture_output=True, text=True)
267
+ output += f"Exit:\n{result.stdout}\n"
268
+ print(result.stdout)
269
+ video_path = "/content/Vidu_Studio/video.mp4"
270
+ return output, video_path
271
+ except Exception as e:
272
+ return f"Excepci贸n al guardar: {str(e)}", None
273
+
274
+ # Funci贸n para mostrar o ocultar el segundo cuadro de imagen
275
+ def activar_end_frame(activar):
276
+ return gr.update(visible=activar)
277
+
278
+ # Definir la interfaz
279
+ with gr.Blocks() as demo:
280
+ # Agregar un t铆tulo en grande al inicio de la interfaz
281
+ gr.HTML(f"<h1 style='text-align: center; font-size: 3em;'>VIDU STUDIO 3.0 - AUTOMATIC</p>Created by:<a href='https://www.youtube.com/@IA.Sistema.de.Interes' target='_blank'>IA(Sistema de Inter茅s)</a></p>")
282
+ with gr.Tabs():
283
+ # Primera pesta帽a: Image to Video
284
+ with gr.Tab("Image to Video"):
285
+ with gr.Row():
286
+ with gr.Column():
287
+ add_end_frame = gr.Checkbox(label="Add End Frame", value=False)
288
+
289
+ # Fila para mostrar ambas im谩genes cuando se activa
290
+ with gr.Row():
291
+ # Imagen de inicio (carga de archivo)
292
+ img1 = gr.Image(type="pil", label="Drag image here or select image", interactive=True,
293
+ elem_id="img1", width=200, height=200) # Ajustar tama帽o de la imagen
294
+
295
+ # Imagen de fin (se oculta inicialmente)
296
+ img2 = gr.Image(type="pil", label="Upload the last frame image", interactive=True,
297
+ elem_id="img2", visible=False, width=200, height=200) # Ajustar tama帽o de la imagen
298
+
299
+ description_input = gr.Textbox(label="Prompt",
300
+ placeholder="Aqu铆 va una caja de texto editable para el prompt",
301
+ elem_id="description_input")
302
+ enhance_checkbox = gr.Checkbox(label="Enhance prompt", value=False, elem_id="enhance_checkbox")
303
+ model_dropdown = gr.Dropdown(
304
+ choices=["vidu-1", "vidu-high-performance"],
305
+ label="Model",
306
+ value="vidu-1",
307
+ elem_id="model_dropdown"
308
+ )
309
+ upscale_checkbox = gr.Checkbox(label="Upscale", value=False, elem_id="upscale_checkbox")
310
+ create_button = gr.Button("Create", elem_id="create_button")
311
+ extend_button = gr.Button("Extend", elem_id="extend_button")
312
+ recreate_button = gr.Button("Re-create", elem_id="recreate_button") # Nuevo bot贸n "Re-create"
313
+ save_button = gr.Button("Save", elem_id="save_button") # Bot贸n de guardado
314
+
315
+ with gr.Column():
316
+ video_output = gr.Video(label="Video Output Image to Video", height=400, elem_id="video_output_image_to_video")
317
+ output_textbox = gr.Textbox(label="Output", interactive=False, elem_id="output_textbox") # Cambia el nombre del textbox
318
+
319
+
320
+ # L贸gica para mostrar el segundo cuadro de imagen al activar el checkbox
321
+ add_end_frame.change(activar_end_frame, add_end_frame, img2)
322
+
323
+ # Procesar la imagen autom谩ticamente cuando se carga
324
+ img1.change(
325
+ fn=process_and_save_image1,
326
+ inputs=img1,
327
+ outputs=[]
328
+ )
329
+
330
+ img2.change(
331
+ fn=process_and_save_image2,
332
+ inputs=img2,
333
+ outputs=[]
334
+ )
335
+
336
+ # Bot贸n "Create" y su salida
337
+ create_button.click(
338
+ fn=lambda desc, enhance, model, upscale, img, add_end: run_commands_dual(desc, "16:9", enhance, model, "general", upscale, task_type="headtailimg2video", img=img, add_end_frame=add_end),
339
+ inputs=[description_input, enhance_checkbox, model_dropdown, upscale_checkbox, img1, add_end_frame], # A帽ade el Checkbox aqu铆
340
+ outputs=[output_textbox, video_output] # Aseg煤rate de tener definidos estos componentes de salida
341
+ )
342
+
343
+ # Bot贸n "Extend" y su salida
344
+ extend_button.click(
345
+ fn=lambda desc, enhance, model, upscale, img: run_commands(desc, "16:9", enhance, model, "general", upscale, task_type="extend", img=img, is_extend=True), # Agrega img como argumento
346
+ inputs=[description_input, enhance_checkbox, model_dropdown, upscale_checkbox, img1], # Agrega image_input a la lista de inputs
347
+ outputs=[output_textbox, video_output]
348
+ )
349
+
350
+ # Bot贸n "Re-create" y su salida
351
+ recreate_button.click(
352
+ fn=lambda desc, enhance, model, upscale, img: run_commands(desc, "16:9", enhance, model, "general", upscale, task_type="image_to_video", img=img, is_recreate=True), # Agrega img como argumento
353
+ inputs=[description_input, enhance_checkbox, model_dropdown, upscale_checkbox, img1], # Agrega image_input a la lista de inputs
354
+ outputs=[output_textbox, video_output]
355
+ )
356
+
357
+ # Bot贸n "Save" y su salida
358
+ save_button.click(
359
+ fn=run_save_commands,
360
+ inputs=[],
361
+ outputs=[output_textbox, video_output]
362
+ )
363
+
364
+ # Segunda pesta帽a: Reference to Video
365
+ with gr.Tab("Reference to Video"):
366
+ with gr.Row():
367
+ with gr.Column():
368
+ image_input2 = gr.Image(type="pil", label="Drag image here or select image", interactive=True,
369
+ elem_id="image_input2")
370
+ description_input2 = gr.Textbox(label="Prompt",
371
+ placeholder="Enter text to begin creating a video that aligns with the subject of the image",
372
+ elem_id="description_input2")
373
+ enhance_checkbox2 = gr.Checkbox(label="Enhance prompt", value=False, elem_id="enhance_checkbox2")
374
+ model_dropdown2 = gr.Dropdown(
375
+ choices=["vidu-1", "vidu-high-performance"],
376
+ label="Model",
377
+ value="vidu-1",
378
+ elem_id="model_dropdown2"
379
+ )
380
+ upscale_checkbox2 = gr.Checkbox(label="Upscale", value=False, elem_id="upscale_checkbox2")
381
+ create_button2 = gr.Button("Create", elem_id="create_button2")
382
+ extend_button2 = gr.Button("Extend", elem_id="extend_button2")
383
+ recreate_button2 = gr.Button("Re-create", elem_id="recreate_button2") # Nuevo bot贸n "Re-create"
384
+ save_button2 = gr.Button("Save", elem_id="save_button2") # Bot贸n de guardado
385
+
386
+ with gr.Column():
387
+ video_output2 = gr.Video(label="Video Output Reference to Video", height=400, elem_id="video_output_reference_to_video")
388
+ output_textbox2 = gr.Textbox(label="Output", interactive=False, elem_id="output_textbox2") # Cambia el nombre del textbox
389
+
390
+ # Procesar la imagen autom谩ticamente cuando se carga
391
+ image_input2.change(
392
+ fn=process_and_save_image,
393
+ inputs=image_input2,
394
+ outputs=[]
395
+ )
396
+
397
+ # Bot贸n "Create" y su salida
398
+ create_button2.click(
399
+ fn=lambda desc, enhance, model, upscale, img: run_commands(desc, "16:9", enhance, model, "general", upscale, task_type="reference_to_video", img=img),
400
+ inputs=[description_input2, enhance_checkbox2, model_dropdown2, upscale_checkbox2, image_input2],
401
+ outputs=[output_textbox2, video_output2]
402
+ )
403
+
404
+ # Bot贸n "Extend" y su salida
405
+ extend_button2.click(
406
+ fn=lambda desc, enhance, model, upscale, img: run_commands(desc, "16:9", enhance, model, "general", upscale, task_type="extend", img=img, is_extend=True),
407
+ inputs=[description_input2, enhance_checkbox2, model_dropdown2, upscale_checkbox2, image_input2],
408
+ outputs=[output_textbox2, video_output2]
409
+ )
410
+
411
+ # Bot贸n "Re-create" y su salida
412
+ recreate_button2.click(
413
+ fn=lambda desc, enhance, model, upscale, img: run_commands(desc, "16:9", enhance, model, "general", upscale, task_type="reference_to_video", img=img, is_recreate=True),
414
+ inputs=[description_input2, enhance_checkbox2, model_dropdown2, upscale_checkbox2, image_input2],
415
+ outputs=[output_textbox2, video_output2]
416
+ )
417
+
418
+ # Bot贸n "Save" y su salida
419
+ save_button2.click(
420
+ fn=run_save_commands,
421
+ inputs=[],
422
+ outputs=[output_textbox2, video_output2]
423
+ )
424
+
425
+ # Tercera pesta帽a: Text to Video
426
+ with gr.Tab("Text to Video"):
427
+ with gr.Row():
428
+ with gr.Column():
429
+ description_input3 = gr.Textbox(label="Prompt",
430
+ placeholder="Enter text to begin creating a video",
431
+ elem_id="description_input3")
432
+ aspect_ratio_dropdown = gr.Dropdown(
433
+ choices=["16:9", "9:16", "4:3", "1:1"],
434
+ label="Aspect Ratio",
435
+ value="16:9",
436
+ elem_id="aspect_ratio_dropdown"
437
+ )
438
+ enhance_checkbox3 = gr.Checkbox(label="Enhance prompt", value=False, elem_id="enhance_checkbox3")
439
+ model_dropdown3 = gr.Dropdown(
440
+ choices=["vidu-1", "vidu-high-performance"],
441
+ label="Model",
442
+ value="vidu-1",
443
+ elem_id="model_dropdown3"
444
+ )
445
+ style_dropdown3 = gr.Dropdown(
446
+ choices=["general", "anime"],
447
+ label="Style",
448
+ value="general",
449
+ elem_id="style_dropdown3"
450
+ )
451
+ upscale_checkbox3 = gr.Checkbox(label="Upscale", value=False, elem_id="upscale_checkbox3")
452
+ create_button3 = gr.Button("Create", elem_id="create_button3")
453
+ extend_button3 = gr.Button("Extend", elem_id="extend_button3")
454
+ recreate_button3 = gr.Button("Re-create", elem_id="recreate_button3") # Nuevo bot贸n "Re-create"
455
+ save_button3 = gr.Button("Save", elem_id="save_button3") # Bot贸n de guardado
456
+
457
+ with gr.Column():
458
+ video_output3 = gr.Video(label="Video Output Text to Video", height=400, elem_id="video_output_text_to_video")
459
+ output_textbox3 = gr.Textbox(label="Output", interactive=False, elem_id="output_textbox3") # Cambia el nombre del textbox
460
+
461
+ # Bot贸n "Create" y su salida
462
+ create_button3.click(
463
+ fn=lambda desc, ratio, enhance, model, style, upscale: run_commands(desc, ratio, enhance, model, style,
464
+ upscale, task_type="text_to_video"),
465
+ inputs=[description_input3, aspect_ratio_dropdown, enhance_checkbox3, model_dropdown3, style_dropdown3,
466
+ upscale_checkbox3],
467
+ outputs=[output_textbox3, video_output3]
468
+ )
469
+
470
+ # Bot贸n "Extend" y su salida
471
+ extend_button3.click(
472
+ fn=lambda desc, enhance, model, upscale: run_commands(desc, "16:9", enhance, model, "general", upscale, task_type="extend", is_extend=True), # "general" como argumento
473
+ inputs=[description_input3, enhance_checkbox3, model_dropdown3, upscale_checkbox3], # Eliminado "general"
474
+ outputs=[output_textbox3, video_output3]
475
+ )
476
+
477
+ # Bot贸n "Re-create" y su salida
478
+ recreate_button3.click(
479
+ fn=lambda desc, ratio, enhance, model, style, upscale: run_commands(desc, ratio, enhance, model, style,
480
+ upscale, task_type="text_to_video", is_recreate=True),
481
+ inputs=[description_input3, aspect_ratio_dropdown, enhance_checkbox3, model_dropdown3, style_dropdown3,
482
+ upscale_checkbox3],
483
+ outputs=[output_textbox3, video_output3]
484
+ )
485
+
486
+ # Bot贸n "Save" y su salida
487
+ save_button3.click(
488
+ fn=run_save_commands,
489
+ inputs=[],
490
+ outputs=[output_textbox3, video_output3]
491
+ )
492
+
493
+ # Cuarta pesta帽a: Video to Video
494
+ with gr.Tab("Video to Video"):
495
+ with gr.Row():
496
+ with gr.Column():
497
+ video_input4 = gr.Video(label="Input Video", height=400, interactive=True) # Agregar entrada de video
498
+ description_input4 = gr.Textbox(label="Prompt",
499
+ placeholder="Enter text to begin creating a video",
500
+ elem_id="description_input4")
501
+ enhance_checkbox4 = gr.Checkbox(label="Enhance prompt", value=False, elem_id="enhance_checkbox4")
502
+ model_dropdown4 = gr.Dropdown(
503
+ choices=["vidu-1", "vidu-high-performance"],
504
+ label="Model",
505
+ value="vidu-1",
506
+ elem_id="model_dropdown4"
507
+ )
508
+ upscale_checkbox4 = gr.Checkbox(label="Upscale", value=False, elem_id="upscale_checkbox4")
509
+ create_button4 = gr.Button("Create", elem_id="create_button4")
510
+ extend_button4 = gr.Button("Extend", elem_id="extend_button4")
511
+ recreate_button4 = gr.Button("Re-create", elem_id="recreate_button4") # Nuevo bot贸n "Re-create"
512
+ save_button4 = gr.Button("Save", elem_id="save_button4") # Bot贸n de guardado
513
+
514
+ with gr.Column():
515
+ video_output4 = gr.Video(label="Video Output Video to Video", height=400, elem_id="video_output_video_to_video")
516
+ output_textbox4 = gr.Textbox(label="Output", interactive=False, elem_id="output_textbox4") # Cambia el nombre del textbox
517
+
518
+ # Guardar el video cargado en /content/Vidu_Studio/video.mp4
519
+ def save_uploaded_video(video):
520
+ if video is not None:
521
+ video_path = video
522
+ result = subprocess.run(f"cp '{video_path}' /content/Vidu_Studio/videotovideo.mp4", shell=True)
523
+ print(f"Video guardado en /content/Vidu_Studio/videotovideo.mp4")
524
+ print(result.stdout)
525
+
526
+ # Ejecutar save_uploaded_video cuando se carga un video
527
+ video_input4.upload(
528
+ fn=save_uploaded_video,
529
+ inputs=video_input4,
530
+ outputs=None
531
+ )
532
+
533
+ # Bot贸n "Create" y su salida
534
+ create_button4.click(
535
+ fn=lambda desc, enhance, model, upscale: run_commands(desc, "16:9", enhance, model, "general", upscale, task_type="video_to_video"), # "general" como argumento
536
+ inputs=[description_input4, enhance_checkbox4, model_dropdown4, upscale_checkbox4], # Eliminado "general"
537
+ outputs=[output_textbox4, video_output4]
538
+ )
539
+
540
+ # Bot贸n "Extend" y su salida
541
+ extend_button4.click(
542
+ fn=lambda desc, enhance, model, upscale: run_commands(desc, "16:9", enhance, model, "general", upscale, task_type="extend", is_extend=True), # "general" como argumento
543
+ inputs=[description_input4, enhance_checkbox4, model_dropdown4, upscale_checkbox4], # Eliminado "general"
544
+ outputs=[output_textbox4, video_output4]
545
+ )
546
+
547
+ # Bot贸n "Re-create" y su salida
548
+ recreate_button4.click(
549
+ fn=lambda desc, enhance, model, upscale: run_commands(desc, "16:9", enhance, model, "general", upscale, task_type="video_to_video", is_recreate=True), # "general" como argumento
550
+ inputs=[description_input4, enhance_checkbox4, model_dropdown4, upscale_checkbox4], # Eliminado "general"
551
+ outputs=[output_textbox4, video_output4]
552
+ )
553
+
554
+ # Bot贸n "Save" y su salida
555
+ save_button4.click(
556
+ fn=run_save_commands,
557
+ inputs=[],
558
+ outputs=[output_textbox4, video_output4]
559
+ )
560
+
561
+ # Ejecutar la interfaz
562
+ demo.launch(inline=False, debug=True, share=True)
Vidu/create_task.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import uuid
3
+ import json
4
+ import argparse # Para manejar los argumentos de la l铆nea de comandos
5
+
6
+ def create_task(promptx, content_id, jwt_token, enhance, model):
7
+ url = "https://api.vidu.studio/vidu/v1/tasks"
8
+
9
+ headers = {
10
+ "Connection": "keep-alive",
11
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
12
+ "Accept-Language": "en",
13
+ "sec-ch-ua-mobile": "?0",
14
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
15
+ "content-type": "application/json",
16
+ "X-Request-Id": str(uuid.uuid4()),
17
+ "sec-ch-ua-platform": '"Windows"',
18
+ "Accept": "*/*",
19
+ "Origin": "https://www.vidu.studio",
20
+ "Sec-Fetch-Site": "same-site",
21
+ "Sec-Fetch-Mode": "cors",
22
+ "Sec-Fetch-Dest": "empty",
23
+ "Referer": "https://www.vidu.studio/",
24
+ "Cookie": f"sajssdk_2015_cross_new_user=1; _ga=GA1.1.77204265.1725572952; amp_af43d4=61603120ab0445398cd1cb92fd88aef0...1i727srs7.1i727ujms.6.1.7; JWT={jwt_token}; Shunt=; sensorsdata2015jssdkcross=dfm-enc-%7B%22Va28a6y8_aV%22%3A%22sSEGIEItsRRRsHGE%22%2C%22gae28_aV%22%3A%22EGEySsGigsIHGA-AsSSHnIgEEySVVs-snAAEEHE-EsGnAAA-EGEySsGigsSisH%22%2C%22OemO2%22%3A%7B%22%24ki8r28_8eiggay_2mbeyr_8cOr%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24ki8r28_2rieyz_lrcMmeV%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24ki8r28_ergreere%22%3A%22%22%7D%2C%22aVr68a8ar2%22%3A%22rc3liZ7ku67OV5kgPsGCiskkDskl3qmawFlJPhNcpZTowqwEpF08wX3AQXKswsPJwZwAW9NcBF3swX0JwFKJBF1cpFPMwX08wFlJPhNcpZTowq7zwqKaBv3liZ7ku67OV5kgu9G6iZHgiZNapa3cQX1Hwh1hpX3IQhycQFlJ36A%3D%22%2C%22za28mec_kmfa6_aV%22%3A%7B%226ior%22%3A%22%24aVr68a8c_kmfa6_aV%22%2C%22Cikbr%22%3A%22sSEGIEItsRRRsHGE%22%7D%7D; _ga_ZJBV7VYP55=GS1.1.1725576214.2.1.1725578996.0.0.0",
25
+ "Accept-Encoding": "gzip, deflate"
26
+ }
27
+
28
+
29
+ payload = {
30
+ "input": {
31
+ "prompts": [
32
+ {"type": "text", "content": f"{promptx}"},
33
+ {"type": "image", "content": f"ssupload:?id={content_id}", "src_img": f"ssupload:?id={content_id}"}
34
+ ],
35
+ "enhance": enhance
36
+ },
37
+ "type": "img2video",
38
+ "settings": {
39
+ "duration": 4,
40
+ "model": model
41
+ }
42
+ }
43
+
44
+ response = requests.post(url, headers=headers, json=payload)
45
+ response_json = response.json()
46
+ task_id = response_json.get('id', 'ID no encontrado')
47
+
48
+ return task_id
49
+
50
+ def read_file_info(file_path):
51
+ try:
52
+ with open(file_path, "r") as file:
53
+ lines = file.readlines()
54
+ if len(lines) >= 1:
55
+ file_id = lines[0].strip().split(': ')[1]
56
+ return file_id
57
+ else:
58
+ print("File does not contain enough lines.")
59
+ except FileNotFoundError:
60
+ print(f"File not found: {file_path}")
61
+ except IOError as e:
62
+ print(f"Error reading file: {e}")
63
+
64
+ def read_jwt_token(file_path):
65
+ try:
66
+ with open(file_path, "r") as file:
67
+ token = file.readline().strip()
68
+ return token
69
+ except FileNotFoundError:
70
+ print(f"File not found: {file_path}")
71
+ except IOError as e:
72
+ print(f"Error reading file: {e}")
73
+
74
+ def save_task_id(file_path, task_id):
75
+ try:
76
+ with open(file_path, "w") as file:
77
+ file.write(f"task_id: {task_id}")
78
+ except IOError as e:
79
+ print(f"Error writing file: {e}")
80
+
81
+ def main():
82
+ parser = argparse.ArgumentParser(description='Script para crear una tarea con un prompt dado.')
83
+ parser.add_argument('--prompt', type=str, required=True, help='Prompt a utilizar')
84
+ parser.add_argument('--enhance', type=bool, default=True, help='Habilitar mejora (True o False)')
85
+ parser.add_argument('--model', type=str, required=True, help='Modelo a usar (vidu-1 o vidu-high-performance)')
86
+
87
+ args = parser.parse_args()
88
+
89
+ file_info_path = "/tmp/file_info.txt" # Ruta al archivo que contiene file_id
90
+ jwt_token_path = "/tmp/jwt_token.txt" # Ruta al archivo que contiene el jwt_token
91
+ task_id_path = "/tmp/task_id.txt" # Ruta al archivo donde se guardar谩 el task_id
92
+
93
+ file_id = read_file_info(file_info_path)
94
+ jwt_token = read_jwt_token(jwt_token_path)
95
+
96
+ if file_id and jwt_token:
97
+ try:
98
+ task_id = create_task(args.prompt, file_id, jwt_token, enhance=args.enhance, model=args.model)
99
+ #print(f"El ID de la tarea es: {task_id}")
100
+ save_task_id(task_id_path, task_id)
101
+ except Exception as e:
102
+ print(e)
103
+
104
+ if __name__ == "__main__":
105
+ main()
106
+
Vidu/create_text_to_video.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import argparse
3
+ import uuid
4
+
5
+ def create_video_task(jwt_token, prompt, aspect_ratio, enhance, model, style):
6
+ url = "https://api.vidu.studio/vidu/v1/tasks"
7
+
8
+ headers = {
9
+ "Host": "api.vidu.studio",
10
+ "Connection": "keep-alive",
11
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
12
+ "Accept-Language": "en",
13
+ "sec-ch-ua-mobile": "?0",
14
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
15
+ "content-type": "application/json",
16
+ "X-Request-Id": str(uuid.uuid4()),
17
+ "sec-ch-ua-platform": '"Windows"',
18
+ "Accept": "*/*",
19
+ "Origin": "https://www.vidu.studio",
20
+ "Sec-Fetch-Site": "same-site",
21
+ "Sec-Fetch-Mode": "cors",
22
+ "Sec-Fetch-Dest": "empty",
23
+ "Referer": "https://www.vidu.studio/",
24
+ "Cookie": f"sajssdk_2015_cross_new_user=1; _ga=GA1.1.77204265.1725572952; amp_af43d4=61603120ab0445398cd1cb92fd88aef0...1i727srs7.1i727ujms.6.1.7; JWT={jwt_token}; Shunt=; sensorsdata2015jssdkcross=dfm-enc-%7B%22Va28a6y8_aV%22%3A%22sSEGIEItsRRRsHGE%22%2C%22gae28_aV%22%3A%22EGEySsGigsIHGA-AsSSHnIgEEySVVs-snAAEEHE-EsGnAAA-EGEySsGigsSisH%22%2C%22OemO2%22%3A%7B%22%24ki8r28_8eiggay_2mbeyr_8cOr%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24ki8r28_2rieyz_lrcMmeV%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24ki8r28_ergreere%22%3A%22%22%7D%2C%22aVr68a8ar2%22%3A%22rc3liZ7ku67OV5kgPsGCiskkDskl3qmawFlJPhNcpZTowqwEpF08wX3AQXKswsPJwZwAW9NcBF3swX0JwFKJBF1cpFPMwX08wFlJPhNcpZTowq7zwqKaBv3liZ7ku67OV5kgu9G6iZHgiZNapa3cQX1Hwh1hpX3IQhycQFlJ36A%3D%22%2C%22za28mec_kmfa6_aV%22%3A%7B%226ior%22%3A%22%24aVr68a8c_kmfa6_aV%22%2C%22Cikbr%22%3A%22sSEGIEItsRRRsHGE%22%7D%7D; _ga_ZJBV7VYP55=GS1.1.1725576214.2.1.1725578996.0.0.0",
25
+ "Accept-Encoding": "gzip, deflate"
26
+ }
27
+
28
+ payload = {
29
+ "input": {
30
+ "prompts": [
31
+ {
32
+ "type": "text",
33
+ "content": prompt,
34
+ "enhance": enhance
35
+ }
36
+ ]
37
+ },
38
+ "type": "text2video",
39
+ "settings": {
40
+ "style": style,
41
+ "aspect_ratio": aspect_ratio, # Relaci贸n de aspecto editable
42
+ "duration": 4,
43
+ "model": model #"vidu-1"
44
+ }
45
+ }
46
+
47
+ response = requests.post(url, headers=headers, json=payload)
48
+ response_json = response.json()
49
+ task_id = response_json.get('id', 'ID no encontrado')
50
+
51
+ return task_id
52
+
53
+ def save_task_id(file_path, task_id):
54
+ try:
55
+ with open(file_path, "w") as file:
56
+ file.write(f"task_id: {task_id}")
57
+ except IOError as e:
58
+ print(f"Error writing file: {e}")
59
+
60
+ def main():
61
+ # Configurar el an谩lisis de argumentos
62
+ parser = argparse.ArgumentParser(description="Create a video task using the Vidu API.")
63
+ parser.add_argument('--prompt', type=str, required=True, help="The text prompt to generate the video.")
64
+ parser.add_argument('--aspect_ratio', type=str, default="16:9", help="The aspect ratio of the video (e.g., 16:9, 1:1, 4:3).")
65
+ parser.add_argument('--enhance', type=bool, default=True, help='Habilitar mejora (True o False)')
66
+ parser.add_argument('--model', type=str, required=True, help='vidu-1')
67
+ parser.add_argument('--style', type=str, required=True, help='general')
68
+
69
+ args = parser.parse_args()
70
+
71
+ # Leer el JWT token desde el archivo
72
+ with open('/tmp/jwt_token.txt', 'r') as file:
73
+ jwt_token = file.read().strip()
74
+
75
+ # Llamar a la funci贸n con el argumento del prompt y el aspect_ratio
76
+ task_id = create_video_task(jwt_token, args.prompt, args.aspect_ratio, enhance=args.enhance, model=args.model, style=args.style)
77
+ #print(f"El ID de la tarea es: {task_id}")
78
+
79
+ # Guardar el task_id en un archivo
80
+ save_task_id('/tmp/task_id.txt', task_id)
81
+
82
+ if __name__ == "__main__":
83
+ main()
84
+
Vidu/create_video_reference.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ import argparse
4
+ import uuid
5
+
6
+ def create_video_reference(jwt_token, prompt_text, image_id, enhance, x, y, model):
7
+ url = "https://api.vidu.studio/vidu/v1/tasks"
8
+
9
+ headers = {
10
+ "Connection": "keep-alive",
11
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
12
+ "Accept-Language": "en",
13
+ "sec-ch-ua-mobile": "?0",
14
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
15
+ "content-type": "application/json",
16
+ "X-Request-Id": str(uuid.uuid4()),
17
+ "sec-ch-ua-platform": '"Windows"',
18
+ "Accept": "*/*",
19
+ "Origin": "https://www.vidu.studio",
20
+ "Sec-Fetch-Site": "same-site",
21
+ "Sec-Fetch-Mode": "cors",
22
+ "Sec-Fetch-Dest": "empty",
23
+ "Referer": "https://www.vidu.studio/",
24
+ "Cookie": f"sajssdk_2015_cross_new_user=1; _ga=GA1.1.77204265.1725572952; amp_af43d4=61603120ab0445398cd1cb92fd88aef0...1i727srs7.1i727ujms.6.1.7; JWT={jwt_token}; Shunt=; sensorsdata2015jssdkcross=dfm-enc-%7B%22Va28a6y8_aV%22%3A%22sSEGIEItsRRRsHGE%22%2C%22gae28_aV%22%3A%22EGEySsGigsIHGA-AsSSHnIgEEySVVs-snAAEEHE-EsGnAAA-EGEySsGigsSisH%22%2C%22OemO2%22%3A%7B%22%24ki8r28_8eiggay_2mbeyr_8cOr%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24ki8r28_2rieyz_lrcMmeV%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24ki8r28_ergreere%22%3A%22%22%7D%2C%22aVr68a8ar2%22%3A%22rc3liZ7ku67OV5kgPsGCiskkDskl3qmawFlJPhNcpZTowqwEpF08wX3AQXKswsPJwZwAW9NcBF3swX0JwFKJBF1cpFPMwX08wFlJPhNcpZTowq7zwqKaBv3liZ7ku67OV5kgu9G6iZHgiZNapa3cQX1Hwh1hpX3IQhycQFlJ36A%3D%22%2C%22za28mec_kmfa6_aV%22%3A%7B%226ior%22%3A%22%24aVr68a8c_kmfa6_aV%22%2C%22Cikbr%22%3A%22sSEGIEItsRRRsHGE%22%7D%7D; _ga_ZJBV7VYP55=GS1.1.1725576214.2.1.1725578996.0.0.0",
25
+ "Accept-Encoding": "gzip, deflate"
26
+ }
27
+
28
+
29
+ payload = {
30
+ "input": {
31
+ "prompts": [
32
+ {
33
+ "type": "text",
34
+ "content": (f"{prompt_text}")
35
+ },
36
+ {
37
+ "type": "image",
38
+ "content": f"ssupload:?id={image_id}",
39
+ "src_img": f"ssupload:?id={image_id}",
40
+ "selected_region": {
41
+ "top_left": {"x": 0, "y": 0},
42
+ "bottom_right": {"x": x, "y": y}
43
+ }
44
+ }
45
+ ],
46
+ "enhance": enhance
47
+ },
48
+ "type": "character2video",
49
+ "settings": {
50
+ "duration": 4,
51
+ "model": f"{model}"
52
+ }
53
+ }
54
+
55
+ data = json.dumps(payload)
56
+ response = requests.post(url, headers=headers, data=data)
57
+ response_json = response.json()
58
+ task_id = response_json.get('id', 'ID no encontrado')
59
+
60
+ return task_id
61
+
62
+ def read_file_info(file_path):
63
+ try:
64
+ with open(file_path, "r") as file:
65
+ lines = file.readlines()
66
+ if len(lines) >= 1:
67
+ file_id = lines[0].strip().split(': ')[1]
68
+ return file_id
69
+ else:
70
+ print("File does not contain enough lines.")
71
+ except FileNotFoundError:
72
+ print(f"File not found: {file_path}")
73
+ except IOError as e:
74
+ print(f"Error reading file: {e}")
75
+
76
+ def read_jwt_token(file_path):
77
+ try:
78
+ with open(file_path, "r") as file:
79
+ token = file.readline().strip()
80
+ return token
81
+ except FileNotFoundError:
82
+ print(f"File not found: {file_path}")
83
+ except IOError as e:
84
+ print(f"Error reading file: {e}")
85
+
86
+ def read_coordinates(file_path):
87
+ try:
88
+ with open(file_path, "r") as file:
89
+ lines = file.readlines()
90
+ x = y = 512 # Default values
91
+ for line in lines:
92
+ if line.startswith("X: "):
93
+ x = int(line.strip().split(": ")[1])
94
+ elif line.startswith("Y: "):
95
+ y = int(line.strip().split(": ")[1])
96
+ return x, y
97
+ except FileNotFoundError:
98
+ print(f"File not found: {file_path}")
99
+ except IOError as e:
100
+ print(f"Error reading file: {e}")
101
+
102
+ def save_task_id(file_path, task_id):
103
+ try:
104
+ with open(file_path, "w") as file:
105
+ file.write(f"task_id: {task_id}")
106
+ except IOError as e:
107
+ print(f"Error writing file: {e}")
108
+
109
+ def main():
110
+ parser = argparse.ArgumentParser(description='Script para crear una tarea con un prompt dado.')
111
+ parser.add_argument('--prompt', type=str, required=True, help='Prompt a utilizar')
112
+ parser.add_argument('--enhance', type=bool, default=True, help='Habilitar mejora (True o False)')
113
+ parser.add_argument('--model', type=str, required=True, help='vidu-1')
114
+
115
+ args = parser.parse_args()
116
+
117
+ file_info_path = "/tmp/file_info.txt" # Ruta al archivo que contiene file_id
118
+ jwt_token_path = "/tmp/jwt_token.txt" # Ruta al archivo que contiene el jwt_token
119
+ task_id_path = "/tmp/task_id.txt" # Ruta al archivo donde se guardar谩 el task_id
120
+ coordinates_path = "/tmp/coordinates.txt" # Ruta al archivo que contiene las coordenadas
121
+
122
+ file_id = read_file_info(file_info_path)
123
+ jwt_token = read_jwt_token(jwt_token_path)
124
+ x, y = read_coordinates(coordinates_path)
125
+
126
+ if file_id and jwt_token:
127
+ try:
128
+ task_id = create_video_reference(jwt_token, args.prompt, file_id, enhance=args.enhance, x=x, y=y, model=args.model)
129
+ #print(f"El ID de la tarea es: {task_id}")
130
+ save_task_id(task_id_path, task_id)
131
+ except Exception as e:
132
+ print(e)
133
+
134
+ if __name__ == "__main__":
135
+ main()
Vidu/headtailimg2video.py ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ import argparse
4
+ import uuid
5
+
6
+ def create_video_reference(jwt_token, prompt_text, image_id, image_id2, enhance, x, y, x2, y2, model):
7
+
8
+ url = "https://api.vidu.studio/vidu/v1/tasks"
9
+
10
+ headers = {
11
+ "Connection": "keep-alive",
12
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
13
+ "Accept-Language": "en",
14
+ "sec-ch-ua-mobile": "?0",
15
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
16
+ "content-type": "application/json",
17
+ "X-Request-ID": str(uuid.uuid4()),
18
+ "sec-ch-ua-platform": '"Windows"',
19
+ "Accept": "*/*",
20
+ "Origin": "https://www.vidu.studio",
21
+ "Sec-Fetch-Site": "same-site",
22
+ "Sec-Fetch-Mode": "cors",
23
+ "Sec-Fetch-Dest": "empty",
24
+ "Referer": "https://www.vidu.studio/",
25
+ "Cookie": f"sajssdk_2015_cross_new_user=1; _ga=GA1.1.77204265.1725572952; amp_af43d4=61603120ab0445398cd1cb92fd88aef0...1i727srs7.1i727ujms.6.1.7; JWT={jwt_token}; Shunt=; sensorsdata2015jssdkcross=dfm-enc-%7B%22Va28a6y8_aV%22%3A%22sSEGIEItsRRRsHGE%22%2C%22gae28_aV%22%3A%22EGEySsGigsIHGA-AsSSHnIgEEySVVs-snAAEEHE-EsGnAAA-EGEySsGigsSisH%22%2C%22OemO2%22%3A%7B%22%24ki8r28_8eiggay_2mbeyr_8cOr%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24ki8r28_2rieyz_lrcMmeV%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24ki8r28_ergreere%22%3A%22%22%7D%2C%22aVr68a8ar2%22%3A%22rc3liZ7ku67OV5kgPsGCiskkDskl3qmawFlJPhNcpZTowqwEpF08wX3AQXKswsPJwZwAW9NcBF3swX0JwFKJBF1cpFPMwX08wFlJPhNcpZTowq7zwqKaBv3liZ7ku67OV5kgu9G6iZHgiZNapa3cQX1Hwh1hpX3IQhycQFlJ36A%3D%22%2C%22za28mec_kmfa6_aV%22%3A%7B%226ior%22%3A%22%24aVr68a8c_kmfa6_aV%22%2C%22Cikbr%22%3A%22sSEGIEItsRRRsHGE%22%7D%7D; _ga_ZJBV7VYP55=GS1.1.1725576214.2.1.1725578996.0.0.0",
26
+ "Accept-Encoding": "gzip, deflate"
27
+ }
28
+
29
+ payload = {
30
+ "input": {
31
+ "prompts": [
32
+ {"type": "text", "content": f"{prompt_text}"},
33
+ {
34
+ "type": "image",
35
+ "content": f"ssupload:?id={image_id}",
36
+ "src_img": f"ssupload:?id={image_id}",
37
+ "selected_region": {
38
+ "top_left": {"x": 0, "y": 0},
39
+ "bottom_right": {"x": x, "y": y}
40
+ }
41
+ },
42
+ {
43
+ "type": "image",
44
+ "content": f"ssupload:?id={image_id2}",
45
+ "src_img": f"ssupload:?id={image_id2}",
46
+ "selected_region": {
47
+ "top_left": {"x": 0, "y": 0},
48
+ "bottom_right": {"x": x2, "y": y2}
49
+ }
50
+ }
51
+ ],
52
+ "enhance": True
53
+ },
54
+ "type": "headtailimg2video",
55
+ "settings": {
56
+ "duration": 4,
57
+ "model": "vidu-high-performance"
58
+ }
59
+ }
60
+
61
+
62
+ data = json.dumps(payload)
63
+ response = requests.post(url, headers=headers, data=data)
64
+ response_json = response.json()
65
+ task_id = response_json.get('id', 'ID no encontrado')
66
+
67
+ return task_id
68
+
69
+ def read_file_info(file_path):
70
+ try:
71
+ with open(file_path, "r") as file:
72
+ lines = file.readlines()
73
+ if len(lines) >= 1:
74
+ file_id = lines[0].strip().split(': ')[1]
75
+ return file_id
76
+ else:
77
+ print("File does not contain enough lines.")
78
+ except FileNotFoundError:
79
+ print(f"File not found: {file_path}")
80
+ except IOError as e:
81
+ print(f"Error reading file: {e}")
82
+
83
+ def read_jwt_token(file_path):
84
+ try:
85
+ with open(file_path, "r") as file:
86
+ token = file.readline().strip()
87
+ return token
88
+ except FileNotFoundError:
89
+ print(f"File not found: {file_path}")
90
+ except IOError as e:
91
+ print(f"Error reading file: {e}")
92
+
93
+ def read_coordinates(file_path):
94
+ try:
95
+ with open(file_path, "r") as file:
96
+ lines = file.readlines()
97
+ x = y = 512 # Default values
98
+ for line in lines:
99
+ if line.startswith("X: "):
100
+ x = int(line.strip().split(": ")[1])
101
+ elif line.startswith("Y: "):
102
+ y = int(line.strip().split(": ")[1])
103
+ return x, y
104
+ except FileNotFoundError:
105
+ print(f"File not found: {file_path}")
106
+ except IOError as e:
107
+ print(f"Error reading file: {e}")
108
+
109
+ def save_task_id(file_path, task_id):
110
+ try:
111
+ with open(file_path, "w") as file:
112
+ file.write(f"task_id: {task_id}")
113
+ except IOError as e:
114
+ print(f"Error writing file: {e}")
115
+
116
+ def main():
117
+ parser = argparse.ArgumentParser(description='Script para crear una tarea con un prompt dado.')
118
+ parser.add_argument('--prompt', type=str, required=True, help='Prompt a utilizar')
119
+ parser.add_argument('--enhance', type=bool, default=True, help='Habilitar mejora (True o False)')
120
+ parser.add_argument('--model', type=str, required=True, help='vidu-1')
121
+
122
+ args = parser.parse_args()
123
+
124
+ file_info_path = "/tmp/file_info.txt" # Ruta al archivo que contiene file_id
125
+ file_info_path2 = "/tmp/file_info2.txt" # Ruta al archivo que contiene file_id
126
+ jwt_token_path = "/tmp/jwt_token.txt" # Ruta al archivo que contiene el jwt_token
127
+ task_id_path = "/tmp/task_id.txt" # Ruta al archivo donde se guardar谩 el task_id
128
+ coordinates_path = "/tmp/coordinates.txt" # Ruta al archivo que contiene las coordenadas
129
+ coordinates_path2 = "/tmp/coordinates2.txt" # Ruta al archivo que contiene las coordenadas
130
+
131
+ file_id = read_file_info(file_info_path)
132
+ file_id2 = read_file_info(file_info_path2)
133
+ jwt_token = read_jwt_token(jwt_token_path)
134
+ x, y = read_coordinates(coordinates_path)
135
+ x2, y2 = read_coordinates(coordinates_path2)
136
+
137
+ if file_id and jwt_token:
138
+ try:
139
+ task_id = create_video_reference(jwt_token, args.prompt, file_id, file_id2, enhance=args.enhance, x=x, y=y, x2=x2, y2=y2, model=args.model)
140
+ #print(f"El ID de la tarea es: {task_id}")
141
+ save_task_id(task_id_path, task_id)
142
+ except Exception as e:
143
+ print(e)
144
+
145
+ if __name__ == "__main__":
146
+ main()
Vidu/main.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from utils.utils import generar_contrasena, generar_nombre_completo, enviar_formulario, obtener_sitio_web_aleatorio
3
+ from utils.auth import send_auth_code, login_to_vidu
4
+ from utils.email_utils import get_verification_code, delete_temp_mail
5
+
6
+ # Ejemplo de uso
7
+ password_segura = generar_contrasena()
8
+ url = 'https://email-fake.com/'
9
+
10
+ # Supongamos que el formulario en el sitio web tiene un campo llamado 'campo_correo'
11
+ datos = {'campo_correo': 'ejemplo@dominio.com'}
12
+
13
+ # Enviar la solicitud POST al formulario
14
+ response = enviar_formulario(url, datos)
15
+
16
+ # Obtener un sitio web aleatorio de los dominios extra铆dos
17
+ sitio_domain = obtener_sitio_web_aleatorio(response.text)
18
+
19
+ # Generar y mostrar un nombre completo
20
+ nombre_completo = generar_nombre_completo()
21
+
22
+ #print(f'Email: {nombre_completo}@{sitio_domain}')
23
+ #print(f'Password: {password_segura}')
24
+
25
+ time.sleep(3)
26
+
27
+ email_reg = f"{nombre_completo}@{sitio_domain}"
28
+ # Enviar c贸digo de autenticaci贸n al correo
29
+ send_auth_code(email_reg)
30
+ print("60 seconds")
31
+ time.sleep(1)
32
+
33
+ # Intentar obtener el c贸digo de verificaci贸n durante 60 segundos (6 intentos con una pausa de 10 segundos)
34
+ verification_code = None
35
+ identifier = None
36
+ attempts = 6 # 6 intentos para un minuto (cada 10 segundos)
37
+ for attempt in range(attempts):
38
+ print(f"Attempt {attempt + 1} from {attempts}...")
39
+
40
+ # Obtener el c贸digo de verificaci贸n y el identificador
41
+ verification_code, identifier = get_verification_code(nombre_completo, sitio_domain)
42
+
43
+ if verification_code and identifier:
44
+ print(f"C贸digo de verificaci贸n encontrado: {verification_code}")
45
+ break # Salir del bucle si se encuentra el c贸digo
46
+
47
+ time.sleep(10) # Esperar 10 segundos antes de intentar nuevamente
48
+
49
+ if verification_code and identifier:
50
+ print(f"C贸digo de verificaci贸n: {verification_code}")
51
+ print(f"Identificador: {identifier}")
52
+ time.sleep(3)
53
+ print("Login...")
54
+
55
+ # Realizar el login y obtener el JWT Token
56
+ response, jwt_token = login_to_vidu(email_reg, verification_code)
57
+
58
+ if jwt_token:
59
+ print("Login exitoso. Token obtenido.")
60
+ # Guardar el JWT Token en un archivo
61
+ with open('/tmp/jwt_token.txt', 'w') as f:
62
+ f.write(jwt_token)
63
+ else:
64
+ print("No se pudieron encontrar los datos necesarios.")
65
+
66
+ time.sleep(3)
67
+
68
+ # Eliminar el correo temporal
69
+ delete_temp_mail(nombre_completo, sitio_domain, identifier)
Vidu/resident.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+
3
+ class A:
4
+ def __init__(self, shift=5): # Shift est谩 fijo en 5
5
+ self.shift = shift
6
+ self.chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
7
+
8
+ def c(self, data):
9
+ """
10
+ Codifica los datos usando Base64 y altera los caracteres.
11
+ """
12
+ encoded = base64.b64encode(data.encode()).decode()
13
+ return ''.join(self.chars[(self.chars.index(char) + self.shift) % len(self.chars)]
14
+ if char in self.chars else char for char in encoded)
15
+
16
+ def d(self, data):
17
+ """
18
+ Decodifica los datos modificados y los convierte nuevamente en Base64.
19
+ """
20
+ decoded = ''.join(self.chars[(self.chars.index(char) - self.shift) % len(self.chars)]
21
+ if char in self.chars else char for char in data)
22
+ return base64.b64decode(decoded).decode()
23
+
24
+ # Instancia fija con shift=5
25
+ resident = A(shift=5)
Vidu/upload/file_uploader.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import requests
3
+ import uuid
4
+ import subprocess
5
+
6
+ # Funci贸n para ejecutar el script con subprocess
7
+ def run_file_uploader(file_info_name, image_name):
8
+ print("ok")
9
+ try:
10
+ # Ejecuta el comando para ejecutar el script con el argumento file_info
11
+ result = subprocess.run(["python", "/content/Vidu_Studio/upload/file_uploader_with_etag.py", "--file_info", file_info_name, "--image", image_name],
12
+ capture_output=True, text=True)
13
+ print(result.stderr)
14
+ # Devuelve la salida del comando
15
+ if result.returncode == 0:
16
+ return f"Script ejecutado correctamente: {result.stdout}"
17
+ else:
18
+ return f"Error en la ejecuci贸n: {result.stderr}"
19
+
20
+ except Exception as e:
21
+ return f"Error al intentar ejecutar el script: {str(e)}"
22
+
23
+ def upload_file_to_vidu(jwt_token):
24
+ url = "https://api.vidu.studio/tools/v1/files/uploads"
25
+
26
+ headers = {
27
+ "Connection": "keep-alive",
28
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
29
+ "Accept-Language": "en",
30
+ "sec-ch-ua-mobile": "?0",
31
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
32
+ "content-type": "application/json",
33
+ "X-Request-Id": str(uuid.uuid4()),
34
+ "sec-ch-ua-platform": '"Windows"',
35
+ "Accept": "*/*",
36
+ "Origin": "https://www.vidu.studio",
37
+ "Sec-Fetch-Site": "same-site",
38
+ "Sec-Fetch-Mode": "cors",
39
+ "Sec-Fetch-Dest": "empty",
40
+ "Referer": "https://www.vidu.studio/",
41
+ "Cookie": f"sajssdk_2015_cross_new_user=1; _ga=GA1.1.77204265.1725572952; amp_af43d4=61603120ab0445398cd1cb92fd88aef0...1i727srs7.1i727ujms.6.1.7; JWT={jwt_token}; Shunt=; sensorsdata2015jssdkcross=dfm-enc-%7B%22Va28a6y8_aV%22%3A%22sSEGIEItsRRRsHGE%22%2C%22gae28_aV%22%3A%22EGEySsGigsIHGA-AsSSHnIgEEySVVs-snAAEEHE-EsGnAAA-EGEySsGigsSisH%22%2C%22OemO2%22%3A%7B%22%24ki8r28_8eiggay_2mbeyr_8cOr%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24ki8r28_2rieyz_lrcMmeV%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24ki8r28_ergreere%22%3A%22%22%7D%2C%22aVr68a8ar2%22%3A%22rc3liZ7ku67OV5kgPsGCiskkDskl3qmawFlJPhNcpZTowqwEpF08wX3AQXKswsPJwZwAW9NcBF3swX0JwFKJBF1cpFPMwX08wFlJPhNcpZTowq7zwqKaBv3liZ7ku67OV5kgu9G6iZHgiZNapa3cQX1Hwh1hpX3IQhycQFlJ36A%3D%22%2C%22za28mec_kmfa6_aV%22%3A%7B%226ior%22%3A%22%24aVr68a8c_kmfa6_aV%22%2C%22Cikbr%22%3A%22sSEGIEItsRRRsHGE%22%7D%7D; _ga_ZJBV7VYP55=GS1.1.1725576214.2.1.1725578996.0.0.0",
42
+ }
43
+
44
+ payload = {
45
+ "scene": "vidu"
46
+ }
47
+
48
+ try:
49
+ # Enviar la solicitud POST
50
+ response = requests.post(url, headers=headers, json=payload)
51
+
52
+ # Procesar la respuesta
53
+ response_json = response.json()
54
+ file_id = response_json.get("id")
55
+ put_url = response_json.get("put_url")
56
+
57
+ # Mostrar los valores extra铆dos
58
+ print(f"ID: {file_id}")
59
+ #print(f"PUT URL: {put_url}")
60
+
61
+ return file_id, put_url
62
+
63
+ except requests.exceptions.RequestException as e:
64
+ print(f"Request failed: {e}")
65
+ except ValueError as e:
66
+ print(f"Error decoding JSON: {e}")
67
+
68
+ def save_to_txt(file_id, put_url, filename):
69
+ with open(filename, "w") as file:
70
+ file.write(f"file_id: {file_id}\n")
71
+ file.write(f"put_url: {put_url}\n")
72
+ #print(f"Data saved to {filename}")
73
+
74
+ def read_jwt_from_file(file_path):
75
+ try:
76
+ with open(file_path, "r") as file:
77
+ jwt_token = file.read().strip()
78
+ return jwt_token
79
+ except FileNotFoundError:
80
+ print(f"File not found: jwtToken")
81
+ except IOError as e:
82
+ print(f"Error reading file: {e}")
83
+
84
+ def main():
85
+ # Configurar argparse dentro de la funci贸n main
86
+ parser = argparse.ArgumentParser(description="Subir archivos a Vidu Studio")
87
+ parser.add_argument("--file_info", type=str, required=True, help="Nombre del archivo de informaci贸n a guardar")
88
+ parser.add_argument("--image", type=str, required=True, help="Nombre base del archivo de imagen (sin extensi贸n)")
89
+
90
+ # Parsear los argumentos
91
+ args = parser.parse_args()
92
+ file_info_name = args.file_info
93
+ image_name = args.image
94
+
95
+ jwt_file_path = "/tmp/jwt_token.txt" # Ruta al archivo que contiene el JWT
96
+ jwt_token = read_jwt_from_file(jwt_file_path)
97
+
98
+ if jwt_token:
99
+ file_id, put_url = upload_file_to_vidu(jwt_token)
100
+ if file_id and put_url:
101
+ save_to_txt(file_id, put_url, filename=f"/tmp/{file_info_name}.txt")
102
+
103
+ run_file_uploader(file_info_name, image_name)
104
+
105
+ if __name__ == "__main__":
106
+ main()
Vidu/upload/file_uploader_with_etag.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import requests
3
+ import subprocess
4
+
5
+ # Funci贸n para ejecutar el script con subprocess
6
+ def run_finish_upload(file_info_name):
7
+ try:
8
+ # Ejecuta el comando para ejecutar el script con el argumento file_info
9
+ result = subprocess.run(["python", "/content/Vidu_Studio/upload/finish_upload.py", "--file_info", file_info_name],
10
+ capture_output=True, text=True)
11
+
12
+ # Devuelve la salida del comando
13
+ if result.returncode == 0:
14
+ return f"Script ejecutado correctamente: {result.stdout}"
15
+ else:
16
+ return f"Error en la ejecuci贸n: {result.stderr}"
17
+
18
+ except Exception as e:
19
+ return f"Error al intentar ejecutar el script: {str(e)}"
20
+
21
+ def upload_file_to_vidu(upload_url, file_path):
22
+ headers = {
23
+ "Connection": "keep-alive",
24
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
25
+ "Content-Type": "image/*", # Aseg煤rate de que el tipo de contenido coincida con el archivo que est谩s subiendo
26
+ "sec-ch-ua-mobile": "?0",
27
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
28
+ "sec-ch-ua-platform": '"Windows"',
29
+ "Accept": "*/*",
30
+ "Origin": "https://www.vidu.studio",
31
+ "Sec-Fetch-Site": "same-site",
32
+ "Sec-Fetch-Mode": "cors",
33
+ "Sec-Fetch-Dest": "empty",
34
+ "Referer": "https://www.vidu.studio/",
35
+ "Accept-Language": "es-ES,es;q=0.9",
36
+ "Accept-Encoding": "gzip, deflate"
37
+ }
38
+
39
+ with open(file_path, 'rb') as file:
40
+ response = requests.put(upload_url, headers=headers, data=file)
41
+
42
+ # Verificando el estado de la respuesta
43
+ if response.status_code == 200:
44
+ # Capturando los encabezados de la respuesta
45
+ response_headers = response.headers
46
+ # Extrayendo el valor del encabezado ETag
47
+ etag = response_headers.get('ETag', 'Encabezado ETag no encontrado')
48
+ return etag.replace('"', '')
49
+ else:
50
+ raise Exception(f"Error al subir el archivo: {response.status_code}")
51
+
52
+ def save_etag_to_txt(etag, filename="/tmp/etag_info.txt"):
53
+ with open(filename, "w") as file:
54
+ file.write(f"ETag: {etag}\n")
55
+ print(f"ETag saved to {etag}")
56
+
57
+ def read_file_info(file_path):
58
+ try:
59
+ with open(file_path, "r") as file:
60
+ lines = file.readlines()
61
+ if len(lines) >= 2:
62
+ file_id = lines[0].strip().split(': ')[1]
63
+ put_url = lines[1].strip().split(': ')[1]
64
+ return file_id, put_url
65
+ else:
66
+ print("File does not contain enough lines.")
67
+ except FileNotFoundError:
68
+ print(f"File not found: file_info or Image")
69
+ except IOError as e:
70
+ print(f"Error reading file: {e}")
71
+
72
+ def main():
73
+ print("uplaodr 2")
74
+ # Usamos argparse para obtener los nombres de los archivos
75
+ parser = argparse.ArgumentParser(description="Subir un archivo a Vidu Studio y obtener el ETag")
76
+ parser.add_argument("--file_info", type=str, required=True, help="Nombre base del archivo de informaci贸n (sin extensi贸n)")
77
+ parser.add_argument("--image", type=str, required=True, help="Nombre base del archivo de imagen (sin extensi贸n)")
78
+
79
+ # Parsear los argumentos de la l铆nea de comandos
80
+ args = parser.parse_args()
81
+
82
+ # Construir las rutas de archivo usando los nombres proporcionados
83
+ file_info_path = f"/tmp/{args.file_info}.txt" # Ruta al archivo de informaci贸n
84
+ image_path = f"/tmp/{args.image}.jpg" # Ruta al archivo de imagen
85
+
86
+ # Leer file_info.txt
87
+ file_id, put_url = read_file_info(file_info_path)
88
+
89
+ if put_url:
90
+ try:
91
+ # Subir el archivo y obtener el ETag
92
+ etag = upload_file_to_vidu(put_url, image_path)
93
+ # Guardar el ETag en un archivo
94
+ save_etag_to_txt(etag)
95
+ except Exception as e:
96
+ print(e)
97
+
98
+ run_finish_upload(args.file_info)
99
+
100
+ if __name__ == "__main__":
101
+ main()
Vidu/upload/finish_upload.py ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import requests
3
+
4
+ def finish_upload(upload_id, etag, jwt_token):
5
+ url = f"https://api.vidu.studio/tools/v1/files/uploads/{upload_id}/finish"
6
+ headers = {
7
+ "Connection": "keep-alive",
8
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
9
+ "sec-ch-ua-platform": '"Windows"',
10
+ "Accept-Language": "en",
11
+ "sec-ch-ua-mobile": "?0",
12
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
13
+ "content-type": "application/json",
14
+ "Accept": "*/*",
15
+ "Origin": "https://www.vidu.studio",
16
+ "Sec-Fetch-Site": "same-site",
17
+ "Sec-Fetch-Mode": "cors",
18
+ "Sec-Fetch-Dest": "empty",
19
+ "Referer": "https://www.vidu.studio/",
20
+ "Cookie": f"JWT={jwt_token}",
21
+ "Accept-Encoding": "gzip, deflate"
22
+ }
23
+ payload = {
24
+ "id": upload_id,
25
+ "etag": etag
26
+ }
27
+
28
+ response = requests.put(url, headers=headers, json=payload)
29
+ print(f"ETag: {etag}")
30
+
31
+ # Verificando el estado de la respuesta
32
+ return response.text
33
+
34
+ def read_file_info(file_path):
35
+ try:
36
+ with open(file_path, "r") as file:
37
+ lines = file.readlines()
38
+ if len(lines) >= 2:
39
+ file_id = lines[0].strip().split(': ')[1]
40
+ put_url = lines[1].strip().split(': ')[1]
41
+ return file_id, put_url
42
+ else:
43
+ print("File does not contain enough lines.")
44
+ except FileNotFoundError:
45
+ print(f"File not found: file_info or etag_info")
46
+ except IOError as e:
47
+ print(f"Error reading file: {e}")
48
+
49
+ def read_etag(file_path):
50
+ try:
51
+ with open(file_path, "r") as file:
52
+ line = file.readline().strip()
53
+ etag = line.split(': ')[1] if ': ' in line else None
54
+ return etag
55
+ except FileNotFoundError:
56
+ print(f"File not found: etag_info")
57
+ except IOError as e:
58
+ print(f"Error reading file: {e}")
59
+
60
+ def read_jwt_token(file_path):
61
+ try:
62
+ with open(file_path, "r") as file:
63
+ token = file.readline().strip()
64
+ return token
65
+ except FileNotFoundError:
66
+ print(f"File not found: jwtToken")
67
+ except IOError as e:
68
+ print(f"Error reading file: {e}")
69
+
70
+
71
+ def main():
72
+ # Usamos argparse para permitir la personalizaci贸n del nombre del archivo de informaci贸n
73
+ parser = argparse.ArgumentParser(description="Finalizar la subida de archivos a Vidu Studio")
74
+ parser.add_argument("--file_info", type=str, required=True, help="Nombre base del archivo de informaci贸n (sin extensi贸n)")
75
+
76
+ args = parser.parse_args()
77
+
78
+ # Crear las rutas de archivo usando los nombres proporcionados
79
+ file_info_path = f"/tmp/{args.file_info}.txt" # Ruta al archivo de informaci贸n (editable)
80
+ etag_info_path = "/tmp/etag_info.txt" # Ruta al archivo que contiene el etag
81
+ jwt_token_path = "/tmp/jwt_token.txt" # Ruta al archivo que contiene el jwt_token
82
+
83
+ file_id, put_url = read_file_info(file_info_path)
84
+ etag = read_etag(etag_info_path)
85
+ jwt_token = read_jwt_token(jwt_token_path)
86
+
87
+ if file_id and etag and jwt_token:
88
+ try:
89
+ result = finish_upload(file_id, etag, jwt_token)
90
+ #print(result) # Puedes descomentar si quieres ver la respuesta
91
+ except Exception as e:
92
+ print(e)
93
+
94
+ if __name__ == "__main__":
95
+ main()
Vidu/utils/auth.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import uuid
3
+
4
+ def extract_jwt_cookie(cookies):
5
+ """Extrae el valor de la cookie JWT."""
6
+ jwt_token = cookies.get('JWT')
7
+ return jwt_token
8
+
9
+ def login_to_vidu(correo, codes):
10
+ """Inicia sesi贸n en Vidu y devuelve la respuesta y el token JWT."""
11
+ url = "https://api.vidu.studio/iam/v1/users/login"
12
+
13
+ headers = {
14
+ "Host": "api.vidu.studio",
15
+ "Connection": "keep-alive",
16
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
17
+ "Accept-Language": "en",
18
+ "sec-ch-ua-mobile": "?0",
19
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
20
+ "Content-Type": "application/json",
21
+ "X-Request-Id": str(uuid.uuid4()), # Genera un UUID aleatorio
22
+ "sec-ch-ua-platform": "Windows",
23
+ "Accept": "*/*",
24
+ "Origin": "https://www.vidu.studio",
25
+ "Sec-Fetch-Site": "same-site",
26
+ "Sec-Fetch-Mode": "cors",
27
+ "Sec-Fetch-Dest": "empty",
28
+ "Referer": "https://www.vidu.studio/",
29
+ "Cookie": "sajssdk_2015_cross_new_user=1; _ga=GA1.1.77204265.1725572952; amp_af43d4=61603120ab0445398cd1cb92fd88aef0...1i727srs7.1i727ujms.6.1.7; sensorsdata2015jssdkcross=dfm-enc-%7B%22Va28a6y8_aV%22%3A%22EGEySsGigsIHGA-AsSSHnIgEEySVVs-snAAEEHE-EsGnAAA-EGEySsGigsSisH%22%2C%22gae28_aV%22%3A%22%22%2C%22OemO2%22%3A%7B%22%24ki8r28_8eiggay_2mbeyr_8cOr%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24ki8r28_2rieyz_lrcMmeV%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24ki8r28_ergreere%22%3A%22%22%7D%2C%22aVr68a8ar2%22%3A%22rc3liZ7ku67OV5kgPsGCiskkDskl3qmawFlJPhNcpZTowqwEpF08wX3AQXKswsPJwZwAW9NcBF3swX0JwFKJBF1cpFPMwX08wFlJPhNcpZTowq7zwqKagN%3D%3D%22%2C%22za28mec_kmfa6_aV%22%3A%7B%226ior%22%3A%22%22%2C%22Cikbr%22%3A%22%22%7D%7D; _ga_ZJBV7VYP55=GS1.1.1725576214.2.1.1725578971.0.0.0",
30
+ "Accept-Encoding": "gzip, deflate"
31
+ }
32
+
33
+ payload = {
34
+ "id_type": "email",
35
+ "identity": correo,
36
+ "auth_type": "authcode",
37
+ "credential": codes
38
+ }
39
+
40
+ response = requests.post(url, headers=headers, json=payload)
41
+ jwt_token = extract_jwt_cookie(response.cookies)
42
+ return response.json(), jwt_token
43
+
44
+ def send_auth_code(correo):
45
+ """Env铆a un c贸digo de autenticaci贸n al correo especificado."""
46
+ url = "https://api.vidu.studio/iam/v1/users/send-auth-code"
47
+ headers = {
48
+ "Host": "api.vidu.studio",
49
+ "Connection": "keep-alive",
50
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
51
+ "Accept-Language": "en",
52
+ "sec-ch-ua-mobile": "?0",
53
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
54
+ "content-type": "application/json",
55
+ "X-Request-Id": str(uuid.uuid4()), # Genera un UUID aleatorio
56
+ "sec-ch-ua-platform": '"Windows"',
57
+ "Accept": "*/*",
58
+ "Origin": "https://www.vidu.studio",
59
+ "Sec-Fetch-Site": "same-site",
60
+ "Sec-Fetch-Mode": "cors",
61
+ "Sec-Fetch-Dest": "empty",
62
+ "Referer": "https://www.vidu.studio/",
63
+ "Cookie": f"sajssdk_2015_cross_new_user=1; _ga=GA1.1.77204265.1725572952; amp_af43d4=61603120ab0445398cd1cb92fd88aef0...1i727srs7.1i727ujms.6.1.7; sensorsdata2015jssdkcross=dfm-enc-%7B%22Va28a6y8_aV%22%3A%22EGEySsGigsIHGA-AsSSHnIgEEySVVs-snAAEEHE-EsGnAAA-EGEySsGigsSisH%22%2C%22gae28_aV%22%3A%22%22%2C%22OemO2%22%3A%7B%22%24ki8r28_8eiggay_2mbeyr_8cOr%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24ki8r28_2rieyz_lrcMmeV%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24ki8r28_ergreere%22%3A%22%22%7D%2C%22aVr68a8ar2%22%3A%22rc3liZ7ku67OV5kgPsGCiskkDskl3qmawFlJPhNcpZTowqwEpF08wX3AQXKswsPJwZwAW9NcBF3swX0JwFKJBF1cpFPMwX08wFlJPhNcpZTowq7zwqKagN%3D%3D%22%2C%22za28mec_kmfa6_aV%22%3A%7B%226ior%22%3A%22%22%2C%22Cikbr%22%3A%22%22%7D%7D; _ga_ZJBV7VYP55=GS1.1.1725576214.2.1.1725578971.0.0.0",
64
+ "Accept-Encoding": "gzip, deflate"
65
+ }
66
+ payload = {
67
+ "channel": "email",
68
+ "receiver": f"{correo}",
69
+ "purpose": "login",
70
+ "locale": "en"
71
+ }
72
+
73
+ response = requests.post(url, headers=headers, json=payload)
74
+
75
+ if response.status_code == 200:
76
+ print("Request successful")
77
+
78
+ else:
79
+ print(f"Request failed with status code {response.status_code}")
Vidu/utils/delete_task.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import re
3
+
4
+ def read_task_id(file_path):
5
+ """
6
+ Leer el task_id desde un archivo, eliminando el texto extra y dejando solo el n煤mero.
7
+ """
8
+ try:
9
+ with open(file_path, "r") as file:
10
+ task_id_line = file.readline().strip()
11
+ # Usar una expresi贸n regular para extraer solo el n煤mero del task_id
12
+ match = re.search(r'\d+', task_id_line)
13
+ if match:
14
+ return match.group(0)
15
+ else:
16
+ print("No se encontr贸 un task_id v谩lido.")
17
+ return None
18
+ except FileNotFoundError:
19
+ print(f"Archivo no encontrado: {file_path}")
20
+ return None
21
+ except IOError as e:
22
+ print(f"Error leyendo el archivo: {e}")
23
+ return None
24
+
25
+ def read_jwt_token(file_path):
26
+ """
27
+ Leer el jwt_token desde un archivo.
28
+ """
29
+ try:
30
+ with open(file_path, "r") as file:
31
+ return file.readline().strip()
32
+ except FileNotFoundError:
33
+ print(f"Archivo no encontrado: {file_path}")
34
+ return None
35
+ except IOError as e:
36
+ print(f"Error leyendo el archivo: {e}")
37
+ return None
38
+
39
+ def delete_task(task_id, jwt_token):
40
+ """
41
+ Eliminar la tarea usando el task_id y el jwt_token.
42
+ """
43
+ url = f"https://api.vidu.studio/vidu/v1/tasks/{task_id}"
44
+
45
+ headers = {
46
+ "Connection": "keep-alive",
47
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
48
+ "Accept-Language": "en",
49
+ "sec-ch-ua-mobile": "?0",
50
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
51
+ "sec-ch-ua-platform": '"Windows"',
52
+ "Accept": "*/*",
53
+ "Origin": "https://www.vidu.studio",
54
+ "Sec-Fetch-Site": "same-site",
55
+ "Sec-Fetch-Mode": "cors",
56
+ "Sec-Fetch-Dest": "empty",
57
+ "Referer": "https://www.vidu.studio/",
58
+ "Cookie": f"sajssdk_2015_cross_new_user=1; _ga=GA1.1.77204265.1725572952; amp_af43d4=61603120ab0445398cd1cb92fd88aef0...1i727srs7.1i727ujms.6.1.7; JWT={jwt_token}; Shunt=; sensorsdata2015jssdkcross=dfm-enc-%7B%22Va28a6y8_aV%22%3A%22sSEGIEItsRRRsHGE%22%2C%22gae28_aV%22%3A%22EGEySsGigsIHGA-AsSSHnIgEEySVVs-snAAEEHE-EsGnAAA-EGEySsGigsSisH%22%2C%22OemO2%22%3A%7B%22%24ki8r28_8eiggay_2mbeyr_8cOr%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24ki8r28_2rieyz_lrcMmeV%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24ki8r28_ergreere%22%3A%22%22%7D%2C%22aVr68a8ar2%22%3A%22rc3liZ7ku67OV5kgPsGCiskkDskl3qmawFlJPhNcpZTowqwEpF08wX3AQXKswsPJwZwAW9NcBF3swX0JwFKJBF1cpFPMwX08wFlJPhNcpZTowq7zwqKaBv3liZ7ku67OV5kgu9G6iZHgiZNapa3cQX1Hwh1hpX3IQhycQFlJ36A%3D%22%2C%22za28mec_kmfa6_aV%22%3A%7B%226ior%22%3A%22%24aVr68a8c_kmfa6_aV%22%2C%22Cikbr%22%3A%22sSEGIEItsRRRsHGE%22%7D%7D; _ga_ZJBV7VYP55=GS1.1.1725576214.2.1.1725578996.0.0.0",
59
+ "Accept-Encoding": "gzip, deflate"
60
+ }
61
+
62
+ # Realizar la solicitud DELETE
63
+ response = requests.delete(url, headers=headers)
64
+
65
+ if response.status_code == 200:
66
+ print(f"Tarea {task_id} eliminada exitosamente.")
67
+ else:
68
+ print(f"Error al eliminar la tarea {task_id}. C贸digo de estado: {response.status_code}")
69
+
70
+ if __name__ == "__main__":
71
+ task_id_path = "/tmp/task_id.txt"
72
+ jwt_token_path = "/tmp/jwt_token.txt"
73
+
74
+ # Leer task_id y jwt_token desde los archivos correspondientes
75
+ task_id = read_task_id(task_id_path)
76
+ jwt_token = read_jwt_token(jwt_token_path)
77
+
78
+ if task_id and jwt_token:
79
+ delete_task(task_id, jwt_token)
80
+ else:
81
+ print("Error: No se pudo leer el task_id o el jwt_token.")
Vidu/utils/delete_task_upscale.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import re
3
+
4
+ def read_task_id(file_path):
5
+ """
6
+ Leer el task_id desde un archivo, eliminando el texto extra y dejando solo el n煤mero.
7
+ """
8
+ try:
9
+ with open(file_path, "r") as file:
10
+ task_id_line = file.readline().strip()
11
+ # Usar una expresi贸n regular para extraer solo el n煤mero del task_id
12
+ match = re.search(r'\d+', task_id_line)
13
+ if match:
14
+ return match.group(0)
15
+ else:
16
+ print("No se encontr贸 un task_id v谩lido.")
17
+ return None
18
+ except FileNotFoundError:
19
+ print(f"Archivo no encontrado: {file_path}")
20
+ return None
21
+ except IOError as e:
22
+ print(f"Error leyendo el archivo: {e}")
23
+ return None
24
+
25
+ def read_jwt_token(file_path):
26
+ """
27
+ Leer el jwt_token desde un archivo.
28
+ """
29
+ try:
30
+ with open(file_path, "r") as file:
31
+ return file.readline().strip()
32
+ except FileNotFoundError:
33
+ print(f"Archivo no encontrado: {file_path}")
34
+ return None
35
+ except IOError as e:
36
+ print(f"Error leyendo el archivo: {e}")
37
+ return None
38
+
39
+ def delete_task(task_id, jwt_token):
40
+ """
41
+ Eliminar la tarea usando el task_id y el jwt_token.
42
+ """
43
+ url = f"https://api.vidu.studio/vidu/v1/tasks/{task_id}"
44
+
45
+ headers = {
46
+ "Connection": "keep-alive",
47
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
48
+ "Accept-Language": "en",
49
+ "sec-ch-ua-mobile": "?0",
50
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
51
+ "sec-ch-ua-platform": '"Windows"',
52
+ "Accept": "*/*",
53
+ "Origin": "https://www.vidu.studio",
54
+ "Sec-Fetch-Site": "same-site",
55
+ "Sec-Fetch-Mode": "cors",
56
+ "Sec-Fetch-Dest": "empty",
57
+ "Referer": "https://www.vidu.studio/",
58
+ "Cookie": f"sajssdk_2015_cross_new_user=1; _ga=GA1.1.77204265.1725572952; amp_af43d4=61603120ab0445398cd1cb92fd88aef0...1i727srs7.1i727ujms.6.1.7; JWT={jwt_token}; Shunt=; sensorsdata2015jssdkcross=dfm-enc-%7B%22Va28a6y8_aV%22%3A%22sSEGIEItsRRRsHGE%22%2C%22gae28_aV%22%3A%22EGEySsGigsIHGA-AsSSHnIgEEySVVs-snAAEEHE-EsGnAAA-EGEySsGigsSisH%22%2C%22OemO2%22%3A%7B%22%24ki8r28_8eiggay_2mbeyr_8cOr%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24ki8r28_2rieyz_lrcMmeV%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24ki8r28_ergreere%22%3A%22%22%7D%2C%22aVr68a8ar2%22%3A%22rc3liZ7ku67OV5kgPsGCiskkDskl3qmawFlJPhNcpZTowqwEpF08wX3AQXKswsPJwZwAW9NcBF3swX0JwFKJBF1cpFPMwX08wFlJPhNcpZTowq7zwqKaBv3liZ7ku67OV5kgu9G6iZHgiZNapa3cQX1Hwh1hpX3IQhycQFlJ36A%3D%22%2C%22za28mec_kmfa6_aV%22%3A%7B%226ior%22%3A%22%24aVr68a8c_kmfa6_aV%22%2C%22Cikbr%22%3A%22sSEGIEItsRRRsHGE%22%7D%7D; _ga_ZJBV7VYP55=GS1.1.1725576214.2.1.1725578996.0.0.0",
59
+ "Accept-Encoding": "gzip, deflate"
60
+ }
61
+
62
+ # Realizar la solicitud DELETE
63
+ response = requests.delete(url, headers=headers)
64
+
65
+ if response.status_code == 200:
66
+ print(f"Tarea {task_id} eliminada exitosamente.")
67
+ else:
68
+ print(f"Error al eliminar la tarea {task_id}. C贸digo de estado: {response.status_code}")
69
+
70
+ if __name__ == "__main__":
71
+ task_id_path = "/tmp/task_id_upscale.txt"
72
+ jwt_token_path = "/tmp/jwt_token.txt"
73
+
74
+ # Leer task_id y jwt_token desde los archivos correspondientes
75
+ task_id = read_task_id(task_id_path)
76
+ jwt_token = read_jwt_token(jwt_token_path)
77
+
78
+ if task_id and jwt_token:
79
+ delete_task(task_id, jwt_token)
80
+ else:
81
+ print("Error: No se pudo leer el task_id o el jwt_token.")
Vidu/utils/email_utils.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import requests
3
+
4
+ COMMON_HEADERS = {
5
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
6
+ 'Accept-Language': 'es-ES,es;q=0.9',
7
+ 'Accept-Encoding': 'gzip, deflate'
8
+ }
9
+
10
+ def delete_temp_mail(username_email, dominios_dropdown, extracted_string):
11
+ """Borra el correo temporal especificado."""
12
+ EMAIL_FAKE_URL = 'https://email-fake.com/'
13
+ url = f"{EMAIL_FAKE_URL}/del_mail.php"
14
+
15
+ headers = {
16
+ 'Host': 'email-fake.com',
17
+ 'Connection': 'keep-alive',
18
+ 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
19
+ 'Accept': '*/*',
20
+ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
21
+ 'X-Requested-With': 'XMLHttpRequest',
22
+ 'sec-ch-ua-mobile': '?0',
23
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
24
+ 'sec-ch-ua-platform': '"Windows"',
25
+ 'Origin': 'https://email-fake.com',
26
+ 'Sec-Fetch-Site': 'same-origin',
27
+ 'Sec-Fetch-Mode': 'cors',
28
+ 'Sec-Fetch-Dest': 'empty',
29
+ 'Accept-Language': 'es-ES,es;q=0.9',
30
+ 'Cookie': f'embx=%5B%22{username_email}%40{dominios_dropdown}%22%2C',
31
+ }
32
+
33
+ data = f'delll={extracted_string}'
34
+
35
+ response = requests.post(url, headers=headers, data=data)
36
+
37
+ if "Message deleted successfully" in response.text:
38
+ print("Temporary mail deleted...")
39
+ return True
40
+ else:
41
+ print("Error deleting temporary email...")
42
+ return False
43
+
44
+ def get_verification_code(username_email, dominios_dropdown):
45
+ """Obtiene el c贸digo de verificaci贸n del correo y el identificador."""
46
+ EMAIL_FAKE_URL = 'https://email-fake.com/'
47
+ url = f"{EMAIL_FAKE_URL}/"
48
+
49
+ headers = {
50
+ 'Host': 'email-fake.com',
51
+ 'Connection': 'keep-alive',
52
+ 'Upgrade-Insecure-Requests': '1',
53
+ **COMMON_HEADERS,
54
+ 'Sec-Fetch-Site': 'none',
55
+ 'Sec-Fetch-Mode': 'navigate',
56
+ 'Sec-Fetch-User': '?1',
57
+ 'Sec-Fetch-Dest': 'document',
58
+ 'sec-ch-ua': '"Not_A Brand";v="8", "Chromium";v="120", "Google Chrome";v="120"',
59
+ 'sec-ch-ua-mobile': '?0',
60
+ 'sec-ch-ua-platform': 'Windows',
61
+ 'Cookie': f'surl={dominios_dropdown}%2F{username_email}',
62
+ }
63
+
64
+ response = requests.get(url, headers=headers)
65
+
66
+ # Utiliza una expresi贸n regular para encontrar el c贸digo de 6 d铆gitos
67
+ verification_code_match = re.search(r'<strong>(\d{6})</strong>', response.text)
68
+
69
+ # Utiliza una expresi贸n regular para encontrar el identificador largo
70
+ identifier_match = re.search(r'delll:\s*"([a-zA-Z0-9]+)"', response.text)
71
+
72
+ # Extrae y retorna los valores si fueron encontrados
73
+ if verification_code_match and identifier_match:
74
+ verification_code = verification_code_match.group(1)
75
+ identifier = identifier_match.group(1)
76
+ return verification_code, identifier
77
+ else:
78
+ return None, None
Vidu/utils/fragment.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import os
3
+ import shutil
4
+ import subprocess
5
+
6
+ def extraer_ultimo_fotograma(video_path, output_image_path):
7
+ """
8
+ Extrae el 煤ltimo fotograma de un video y lo guarda como una imagen JPG con calidad 100%.
9
+ Luego copia el video a la carpeta '/content/video_output' con numeraci贸n secuencial.
10
+
11
+ :param video_path: Ruta del archivo de video (ej. '/content/video.mp4')
12
+ :param output_image_path: Ruta donde se guardar谩 el fotograma como imagen (ej. '/content/img_fragmento.jpg')
13
+ """
14
+ # M茅todo 1: Usando OpenCV (si est谩 disponible)
15
+ try:
16
+ # Capturamos el video
17
+ video = cv2.VideoCapture(video_path)
18
+
19
+ # Obtenemos el n煤mero total de fotogramas
20
+ total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT))
21
+
22
+ # Nos desplazamos al 煤ltimo fotograma
23
+ video.set(cv2.CAP_PROP_POS_FRAMES, total_frames - 1)
24
+
25
+ # Leemos el 煤ltimo fotograma
26
+ ret, frame = video.read()
27
+
28
+ # Si el fotograma fue le铆do correctamente, lo guardamos como imagen con calidad 100%
29
+ if ret:
30
+ # Guardamos la imagen con calidad 100%
31
+ cv2.imwrite(output_image_path, frame, [int(cv2.IMWRITE_JPEG_QUALITY), 100])
32
+ print(f'脷ltimo fotograma guardado con calidad 100% (OpenCV)')
33
+ else:
34
+ print('Error al leer el 煤ltimo fotograma (OpenCV)')
35
+
36
+ # Liberamos el objeto video
37
+ video.release()
38
+
39
+ except Exception as e:
40
+ print(f"Error al usar OpenCV: {e}")
41
+
42
+ # M茅todo 2: Usando FFmpeg (si OpenCV falla)
43
+ # Obtiene la duraci贸n del video
44
+ duracion_cmd = [
45
+ "ffprobe",
46
+ "-v", "error",
47
+ "-show_entries", "format=duration",
48
+ "-of", "default=noprint_wrappers=1:nokey=1",
49
+ video_path
50
+ ]
51
+ duracion = float(subprocess.check_output(duracion_cmd))
52
+
53
+ # Calcula el tiempo para buscar cerca del final (0.1 segundos antes)
54
+ tiempo_busqueda = str(duracion - 0.1)
55
+
56
+ # Construye el comando FFmpeg para extraer el 煤ltimo fotograma
57
+ comando = [
58
+ "ffmpeg",
59
+ "-ss", tiempo_busqueda, # Busca cerca del final
60
+ "-i", video_path,
61
+ "-vframes", "1", # Extrae solo un fotograma
62
+ "-qscale:v", "2", # Ajusta la calidad si es necesario
63
+ output_image_path
64
+ ]
65
+
66
+ # Ejecuta el comando FFmpeg
67
+ subprocess.run(comando)
68
+ print(f'脷ltimo fotograma guardado con calidad 100% (FFmpeg)')
69
+
70
+ # Crear la carpeta '/content/video_output' si no existe
71
+ output_folder = '/content/Vidu_Studio/video_output'
72
+ if not os.path.exists(output_folder):
73
+ os.makedirs(output_folder)
74
+ print(f'Carpeta creada: {output_folder}')
75
+
76
+ # Verificar la numeraci贸n de los archivos en la carpeta
77
+ existing_videos = sorted([f for f in os.listdir(output_folder) if f.endswith('.mp4')])
78
+
79
+ if existing_videos:
80
+ # Obtener el 煤ltimo n煤mero de archivo y aumentar en 1
81
+ last_video = existing_videos[-1]
82
+ last_number = int(last_video.split('.')[0]) # Extraer n煤mero del formato '00001.mp4'
83
+ new_number = last_number + 1
84
+ else:
85
+ # Si no existen archivos, comenzar con '00001'
86
+ new_number = 1
87
+
88
+ # Formatear el nuevo nombre del archivo con ceros iniciales
89
+ new_video_name = f'{new_number:05}.mp4'
90
+ new_video_path = os.path.join(output_folder, new_video_name)
91
+
92
+ # Copiar el video original a la nueva ruta con numeraci贸n
93
+ shutil.copy(video_path, new_video_path)
94
+ print(f'Video copiado como {new_video_path}')
95
+
96
+
97
+ # Uso de la funci贸n
98
+ video_path = '/content/Vidu_Studio/video.mp4'
99
+ output_image_path = '/tmp/img_fragmento.jpg'
100
+
101
+ extraer_ultimo_fotograma(video_path, output_image_path)
Vidu/utils/jwt_reader.py ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ def read_jwt_from_file(file_path):
2
+ try:
3
+ with open(file_path, "r") as file:
4
+ jwt_token = file.read().strip()
5
+ return jwt_token
6
+ except FileNotFoundError:
7
+ print(f"File not found: {file_path}")
8
+ except IOError as e:
9
+ print(f"Error reading file: {e}")
Vidu/utils/process_task.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ import time
4
+ from tqdm import tqdm
5
+ import re # Importar m贸dulo de expresiones regulares
6
+
7
+ def get_task_details(task_id, jwt_token):
8
+ url = f"https://api.vidu.studio/vidu/v1/tasks/{task_id}"
9
+
10
+ headers = {
11
+ "Connection": "keep-alive",
12
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
13
+ "Accept-Language": "en",
14
+ "sec-ch-ua-mobile": "?0",
15
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
16
+ "sec-ch-ua-platform": '"Windows"',
17
+ "Accept": "*/*",
18
+ "Origin": "https://www.vidu.studio/",
19
+ "Referer": "https://www.vidu.studio/",
20
+ "Cache-Control": "no-cache",
21
+ "Cookie": f"sajssdk_2015_cross_new_user=1; _ga=GA1.1.77204265.1725572952; amp_af43d4=61603120ab0445398cd1cb92fd88aef0...1i727srs7.1i727ujms.6.1.7; JWT={jwt_token}; Shunt=; sensorsdata2015jssdkcross=dfm-enc-%7B%22Va28a6y8_aV%22%3A%22sSEGIEItsRRRsHGE%22%2C%22gae28_aV%22%3A%22EGEySsGigsIHGA-AsSSHnIgEEySVVs-snAAEEHE-EsGnAAA-EGEySsGigsSisH%22%2C%22OemO2%22%3A%7B%22%24ki8r28_8eiggay_2mbeyr_8cOr%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24ki8r28_2rieyz_lrcMmeV%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24ki8r28_ergreere%22%3A%22%22%7D%2C%22aVr68a8ar2%22%3A%22rc3liZ7ku67OV5kgPsGCiskkDskl3qmawFlJPhNcpZTowqwEpF08wX3AQXKswsPJwZwAW9NcBF3swX0JwFKJBF1cpFPMwX08wFlJPhNcpZTowq7zwqKaBv3liZ7ku67OV5kgu9G6iZHgiZNapa3cQX1Hwh1hpX3IQhycQFlJ36A%3D%22%2C%22za28mec_kmfa6_aV%22%3A%7B%226ior%22%3A%22%24aVr68a8c_kmfa6_aV%22%2C%22Cikbr%22%3A%22sSEGIEItsRRRsHGE%22%7D%7D; _ga_ZJBV7VYP55=GS1.1.1725576214.2.1.1725578996.0.0.0",
22
+ "Accept-Encoding": "gzip, deflate"
23
+ }
24
+
25
+ response = requests.get(url, headers=headers)
26
+ if response.status_code != 200:
27
+ print(f"Error fetching task details: {response.status_code}")
28
+ return 'ID no encontrado', 'URI no encontrado'
29
+
30
+ response_json = response.json()
31
+ creations = response_json.get('creations', [])
32
+ if creations and isinstance(creations, list) and len(creations) > 0:
33
+ creation_id = creations[0].get('id', 'ID no encontrado')
34
+ creation_uri = creations[0].get('uri', 'URI no encontrado')
35
+ else:
36
+ creation_id = 'ID no encontrado'
37
+ creation_uri = 'URI no encontrado'
38
+
39
+ return creation_id, creation_uri
40
+
41
+ def descargar_video(uri, nombre_archivo):
42
+ response = requests.get(uri, stream=True)
43
+
44
+ if response.status_code == 200:
45
+ with open(nombre_archivo, 'wb') as f:
46
+ for chunk in response.iter_content(chunk_size=1024):
47
+ if chunk:
48
+ f.write(chunk)
49
+ print(f"\nVideo descargado y guardado como {nombre_archivo}")
50
+ else:
51
+ print("\nError al descargar el video")
52
+
53
+ def read_file(file_path):
54
+ try:
55
+ with open(file_path, "r") as file:
56
+ content = file.readline().strip() # Leer el archivo y eliminar espacios
57
+ return content
58
+ except FileNotFoundError:
59
+ print(f"File not found: {file_path}")
60
+ return None
61
+ except IOError as e:
62
+ print(f"Error reading file: {e}")
63
+ return None
64
+
65
+ def write_file(file_path, content):
66
+ try:
67
+ with open(file_path, "w") as file:
68
+ file.write(content)
69
+ except IOError as e:
70
+ print(f"Error writing file: {e}")
71
+
72
+ def main():
73
+ task_id_path = "/tmp/task_id.txt"
74
+ jwt_token_path = "/tmp/jwt_token.txt"
75
+ creation_id_path = "/tmp/creation_id.txt"
76
+
77
+ task_id = read_file(task_id_path)
78
+ jwt_token = read_file(jwt_token_path)
79
+
80
+ if not task_id or not jwt_token:
81
+ print("No se pudo leer task_id o jwt_token. Aseg煤rate de que los archivos existan y contengan la informaci贸n correcta.")
82
+ return
83
+
84
+ # Usar expresi贸n regular para extraer solo el n煤mero del task_id en caso que est茅 en un formato especial
85
+ task_id = re.search(r'\d+', task_id).group() if task_id else None
86
+
87
+ while True:
88
+ with tqdm(total=10, desc="Esperando 10 segundos", ncols=80, leave=False) as pbar:
89
+ for _ in range(10):
90
+ time.sleep(1)
91
+ pbar.update(1)
92
+
93
+ creation_id, creation_uri = get_task_details(task_id, jwt_token)
94
+
95
+ if creation_id != 'ID no encontrado' and creation_uri != 'URI no encontrado':
96
+ #print(f"\nCreaci贸n encontrada: ID: {creation_id}, URI: {creation_uri}")
97
+ write_file(creation_id_path, creation_id) # Guardar el creation_id en un archivo
98
+ descargar_video(creation_uri, "/content/Vidu_Studio/video.mp4")
99
+ break
100
+ else:
101
+ # Imprimir el mensaje de error en la misma l铆nea
102
+ pbar.set_description("No se ha encontrado el ID o URI, intentando de nuevo...")
103
+ pbar.refresh()
104
+
105
+ if __name__ == "__main__":
106
+ main()
Vidu/utils/process_task_upscale.py ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ import time
4
+ from tqdm import tqdm
5
+ import re # Importar m贸dulo de expresiones regulares
6
+
7
+ def get_task_details(task_id, jwt_token):
8
+ url = f"https://api.vidu.studio/vidu/v1/tasks/{task_id}"
9
+
10
+ headers = {
11
+ "Connection": "keep-alive",
12
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
13
+ "Accept-Language": "en",
14
+ "sec-ch-ua-mobile": "?0",
15
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
16
+ "sec-ch-ua-platform": '"Windows"',
17
+ "Accept": "*/*",
18
+ "Origin": "https://www.vidu.studio/",
19
+ "Referer": "https://www.vidu.studio/",
20
+ "Cache-Control": "no-cache",
21
+ "Cookie": f"sajssdk_2015_cross_new_user=1; _ga=GA1.1.77204265.1725572952; amp_af43d4=61603120ab0445398cd1cb92fd88aef0...1i727srs7.1i727ujms.6.1.7; JWT={jwt_token}; Shunt=; sensorsdata2015jssdkcross=dfm-enc-%7B%22Va28a6y8_aV%22%3A%22sSEGIEItsRRRsHGE%22%2C%22gae28_aV%22%3A%22EGEySsGigsIHGA-AsSSHnIgEEySVVs-snAAEEHE-EsGnAAA-EGEySsGigsSisH%22%2C%22OemO2%22%3A%7B%22%24ki8r28_8eiggay_2mbeyr_8cOr%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24ki8r28_2rieyz_lrcMmeV%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24ki8r28_ergreere%22%3A%22%22%7D%2C%22aVr68a8ar2%22%3A%22rc3liZ7ku67OV5kgPsGCiskkDskl3qmawFlJPhNcpZTowqwEpF08wX3AQXKswsPJwZwAW9NcBF3swX0JwFKJBF1cpFPMwX08wFlJPhNcpZTowq7zwqKaBv3liZ7ku67OV5kgu9G6iZHgiZNapa3cQX1Hwh1hpX3IQhycQFlJ36A%3D%22%2C%22za28mec_kmfa6_aV%22%3A%7B%226ior%22%3A%22%24aVr68a8c_kmfa6_aV%22%2C%22Cikbr%22%3A%22sSEGIEItsRRRsHGE%22%7D%7D; _ga_ZJBV7VYP55=GS1.1.1725576214.2.1.1725578996.0.0.0",
22
+ "Accept-Encoding": "gzip, deflate"
23
+ }
24
+
25
+ response = requests.get(url, headers=headers)
26
+ if response.status_code != 200:
27
+ print(f"Error fetching task details: {response.status_code}")
28
+ return 'ID no encontrado', 'URI no encontrado'
29
+
30
+ response_json = response.json()
31
+ creations = response_json.get('creations', [])
32
+ if creations and isinstance(creations, list) and len(creations) > 0:
33
+ creation_id = creations[0].get('id', 'ID no encontrado')
34
+ creation_uri = creations[0].get('uri', 'URI no encontrado')
35
+ else:
36
+ creation_id = 'ID no encontrado'
37
+ creation_uri = 'URI no encontrado'
38
+
39
+ return creation_id, creation_uri
40
+
41
+ def descargar_video(uri, nombre_archivo):
42
+ response = requests.get(uri, stream=True)
43
+
44
+ if response.status_code == 200:
45
+ with open(nombre_archivo, 'wb') as f:
46
+ for chunk in response.iter_content(chunk_size=1024):
47
+ if chunk:
48
+ f.write(chunk)
49
+ print(f"\nVideo descargado y guardado como {nombre_archivo}")
50
+ else:
51
+ print("\nError al descargar el video")
52
+
53
+ def read_file(file_path):
54
+ try:
55
+ with open(file_path, "r") as file:
56
+ content = file.readline().strip() # Leer el archivo y eliminar espacios
57
+ return content
58
+ except FileNotFoundError:
59
+ print(f"File not found: {file_path}")
60
+ return None
61
+ except IOError as e:
62
+ print(f"Error reading file: {e}")
63
+ return None
64
+
65
+ def write_file(file_path, content):
66
+ try:
67
+ with open(file_path, "w") as file:
68
+ file.write(content)
69
+ except IOError as e:
70
+ print(f"Error writing file: {e}")
71
+
72
+ def main():
73
+ task_id_path = "/tmp/task_id_upscale.txt"
74
+ jwt_token_path = "/tmp/jwt_token.txt"
75
+ creation_id_path = "/tmp/creation_id.txt"
76
+
77
+ task_id = read_file(task_id_path)
78
+ jwt_token = read_file(jwt_token_path)
79
+ print(task_id)
80
+
81
+ if not task_id or not jwt_token:
82
+ print("No se pudo leer task_id o jwt_token. Aseg煤rate de que los archivos existan y contengan la informaci贸n correcta.")
83
+ return
84
+
85
+ # Usar expresi贸n regular para extraer solo el n煤mero del task_id en caso que est茅 en un formato especial
86
+ task_id = re.search(r'\d+', task_id).group() if task_id else None
87
+
88
+ while True:
89
+ with tqdm(total=10, desc="Esperando 10 segundos", ncols=80, leave=False) as pbar:
90
+ for _ in range(10):
91
+ time.sleep(1)
92
+ pbar.update(1)
93
+
94
+ creation_id, creation_uri = get_task_details(task_id, jwt_token)
95
+
96
+ if creation_id != 'ID no encontrado' and creation_uri != 'URI no encontrado':
97
+ #print(f"\nCreaci贸n encontrada: ID: {creation_id}, URI: {creation_uri}")
98
+ write_file(creation_id_path, creation_id) # Guardar el creation_id en un archivo
99
+ descargar_video(creation_uri, "/content/Vidu_Studio/video.mp4")
100
+ break
101
+ else:
102
+ # Imprimir el mensaje de error en la misma l铆nea
103
+ pbar.set_description("No se ha encontrado el ID o URI, intentando de nuevo...")
104
+ pbar.refresh()
105
+
106
+ if __name__ == "__main__":
107
+ main()
Vidu/utils/union.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+
4
+ def obtener_lista_videos(folder_path):
5
+ """
6
+ Obtiene una lista de archivos MP4 en el directorio especificado, ordenados por nombre.
7
+
8
+ :param folder_path: Ruta de la carpeta donde est谩n los videos
9
+ :return: Lista de rutas a los archivos de video
10
+ """
11
+ videos = [os.path.join(folder_path, filename) for filename in sorted(os.listdir(folder_path)) if filename.endswith(".mp4")]
12
+ return videos
13
+
14
+ def crear_lista_txt(folder_path, lista_txt_path):
15
+ """
16
+ Crea un archivo de lista de texto con las rutas a los archivos MP4 en el directorio especificado.
17
+
18
+ :param folder_path: Ruta de la carpeta donde est谩n los videos
19
+ :param lista_txt_path: Ruta del archivo de lista de texto
20
+ """
21
+ videos = obtener_lista_videos(folder_path)
22
+ with open(lista_txt_path, 'w') as f:
23
+ for video in videos:
24
+ f.write(f"file '{video}'\n")
25
+
26
+ def unir_videos_con_lista(lista_txt_path, output_video):
27
+ """
28
+ Une los videos MP4 usando un archivo de lista de texto.
29
+
30
+ :param lista_txt_path: Ruta del archivo de lista de texto
31
+ :param output_video: Ruta del archivo de video de salida
32
+ """
33
+ # Verifica si ffmpeg est谩 instalado
34
+ try:
35
+ subprocess.run(["ffmpeg", "-version"], check=True)
36
+ except subprocess.CalledProcessError:
37
+ print("ffmpeg no est谩 instalado. Debes instalarlo.")
38
+ return
39
+
40
+ # Ejecuta el comando ffmpeg para unir los videos
41
+ cmd = [
42
+ "ffmpeg", "-y", "-f", "concat", "-safe", "0",
43
+ "-i", lista_txt_path, "-c", "copy", output_video
44
+ ]
45
+ subprocess.run(cmd, check=True)
46
+ print(f"Video combinado guardado en {output_video}")
47
+
48
+ def eliminar_fragmentos(folder_path):
49
+ """
50
+ Elimina todos los archivos en el directorio especificado.
51
+
52
+ :param folder_path: Ruta de la carpeta donde est谩n los fragmentos
53
+ """
54
+ for archivo in os.listdir(folder_path):
55
+ ruta_archivo = os.path.join(folder_path, archivo)
56
+ if os.path.isfile(ruta_archivo):
57
+ os.remove(ruta_archivo)
58
+ print(f"Todos los fragmentos en {folder_path} han sido eliminados.")
59
+
60
+ # Define las rutas
61
+ folder_path = '/content/Vidu_Studio/video_output' # Carpeta donde est谩n los videos
62
+ lista_txt_path = '/tmp/video_list.txt' # Archivo de lista de texto
63
+ video_salida = '/content/Vidu_Studio/video.mp4' # Archivo de video combinado
64
+
65
+ # Crear el archivo de lista de texto
66
+ crear_lista_txt(folder_path, lista_txt_path)
67
+
68
+ # Unir los videos usando el archivo de lista de texto
69
+ unir_videos_con_lista(lista_txt_path, video_salida)
70
+
71
+ # Eliminar los fragmentos despu茅s de combinar los videos
72
+ eliminar_fragmentos(folder_path)
73
+
Vidu/utils/upscale_task.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json # Para trabajar con la respuesta JSON
3
+ import uuid
4
+
5
+ def ejecutar_post(creation_id, jwt_token):
6
+ url = 'https://api.vidu.studio/vidu/v1/tasks'
7
+
8
+ headers = {
9
+ 'Connection': 'keep-alive',
10
+ 'sec-ch-ua': '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
11
+ 'Accept-Language': 'en',
12
+ 'sec-ch-ua-mobile': '?0',
13
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36',
14
+ 'content-type': 'application/json',
15
+ 'X-Request-Id': str(uuid.uuid4()),
16
+ 'sec-ch-ua-platform': '"Windows"',
17
+ 'Accept': '*/*',
18
+ 'Origin': 'https://www.vidu.studio',
19
+ 'Sec-Fetch-Site': 'same-site',
20
+ 'Sec-Fetch-Mode': 'cors',
21
+ 'Sec-Fetch-Dest': 'empty',
22
+ 'Referer': 'https://www.vidu.studio/',
23
+ 'Cookie': f'JWT={jwt_token}', # Incluir solo el JWT
24
+ 'Cookie': f'sajssdk_2015_cross_new_user=1; _ga=GA1.1.77204265.1725572952; amp_af43d4=61603120ab0445398cd1cb92fd88aef0...1i727srs7.1i727ujms.6.1.7; JWT={jwt_token}; Shunt=; sensorsdata2015jssdkcross=dfm-enc-%7B%22Va28a6y8_aV%22%3A%22sSEGIEItsRRRsHGE%22%2C%22gae28_aV%22%3A%22EGEySsGigsIHGA-AsSSHnIgEEySVVs-snAAEEHE-EsGnAAA-EGEySsGigsSisH%22%2C%22OemO2%22%3A%7B%22%24ki8r28_8eiggay_2mbeyr_8cOr%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24ki8r28_2rieyz_lrcMmeV%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24ki8r28_ergreere%22%3A%22%22%7D%2C%22aVr68a8ar2%22%3A%22rc3liZ7ku67OV5kgPsGCiskkDskl3qmawFlJPhNcpZTowqwEpF08wX3AQXKswsPJwZwAW9NcBF3swX0JwFKJBF1cpFPMwX08wFlJPhNcpZTowq7zwqKaBv3liZ7ku67OV5kgu9G6iZHgiZNapa3cQX1Hwh1hpX3IQhycQFlJ36A%3D%22%2C%22za28mec_kmfa6_aV%22%3A%7B%226ior%22%3A%22%24aVr68a8c_kmfa6_aV%22%2C%22Cikbr%22%3A%22sSEGIEItsRRRsHGE%22%7D%7D; _ga_ZJBV7VYP55=GS1.1.1725576214.2.1.1725578996.0.0.0',
25
+ 'Accept-Encoding': 'gzip, deflate'
26
+ }
27
+
28
+ # Datos del cuerpo de la solicitud POST
29
+ data = {
30
+ "input": {
31
+ "creation_id": f"{creation_id}"
32
+ },
33
+ "type": "upscale",
34
+ "settings": {
35
+ "model": "stable",
36
+ "duration": 4
37
+ }
38
+ }
39
+
40
+ # Realizar la solicitud POST
41
+ response = requests.post(url, headers=headers, json=data)
42
+
43
+ # Convertir la respuesta a JSON
44
+ response_json = json.loads(response.text)
45
+
46
+ # Extraer el 'id' de la respuesta
47
+ task_id = response_json.get('id', 'ID no encontrado')
48
+
49
+ # Mostrar la respuesta
50
+ print(f"Status code: {response.status_code}")
51
+ #print(f"Response: {response.text}")
52
+
53
+ return task_id
54
+
55
+ # Funci贸n para guardar el task_id en el archivo en el formato deseado
56
+ def guardar_task_id(task_id):
57
+ task_id_formateado = f"task_id: {task_id}" # Formato deseado
58
+ file_path = '/tmp/task_id_upscale.txt' # Ruta del archivo actualizada
59
+
60
+ try:
61
+ with open(file_path, 'w') as file:
62
+ file.write(task_id_formateado)
63
+ print(f"task_id guardado")
64
+ except IOError as e:
65
+ print(f"Error al escribir el archivo: {e}")
66
+
67
+ def read_file(file_path):
68
+ try:
69
+ with open(file_path, "r") as file:
70
+ return file.readline().strip()
71
+ except FileNotFoundError:
72
+ print(f"Archivo no encontrado: {file_path}")
73
+ return None
74
+ except IOError as e:
75
+ print(f"Error al leer el archivo: {e}")
76
+ return None
77
+
78
+ def main():
79
+ creation_id_path = "/tmp/creation_id.txt"
80
+ jwt_token_path = "/tmp/jwt_token.txt"
81
+
82
+ # Leer creation_id y jwt_token desde los archivos
83
+ creation_id = read_file(creation_id_path)
84
+ jwt_token = read_file(jwt_token_path)
85
+
86
+ if not creation_id or not jwt_token:
87
+ print("No se pudo leer el creation_id o jwt_token. Aseg煤rate de que los archivos existan y contengan la informaci贸n correcta.")
88
+ return
89
+
90
+ # Llamar a la funci贸n para realizar el POST y obtener el task_id
91
+ task_id = ejecutar_post(creation_id, jwt_token)
92
+
93
+ if task_id != 'ID no encontrado':
94
+ # Guardar el task_id en el archivo de texto
95
+ guardar_task_id(task_id)
96
+ else:
97
+ print("No se pudo obtener el task_id.")
98
+
99
+ if __name__ == "__main__":
100
+ main()
Vidu/utils/utils.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import random
3
+ import string
4
+ import requests
5
+
6
+ def generar_nombre_completo():
7
+ """Genera un nombre completo triplicando el nombre y apellido, junto con un n煤mero aleatorio de 3 d铆gitos."""
8
+ nombres = ["Juan", "Pedro", "Maria", "Ana", "Luis", "Sofia", "Diego", "Laura", "Javier", "Isabel",
9
+ "Pablo", "Marta", "David", "Elena", "Sergio", "Irene", "Daniel", "Alicia", "Carlos", "Sandra",
10
+ "Antonio", "Lucia", "Miguel", "Sara", "Jose", "Cristina", "Alberto", "Blanca", "Alejandro", "Marta",
11
+ "Francisco", "Esther", "Roberto", "Silvia", "Manuel", "Patricia", "Marcos", "Victoria", "Fernando", "Rosa",
12
+ # Nombres comunes de EE.UU.
13
+ "James", "John", "Robert", "Michael", "William", "David", "Richard", "Joseph", "Charles", "Thomas",
14
+ "Christopher", "Daniel", "Matthew", "Anthony", "Mark", "Donald", "Steven", "Paul", "Andrew", "Joshua",
15
+ "Kenneth", "Kevin", "Brian", "George", "Edward", "Ronald", "Timothy", "Jason", "Jeffrey", "Ryan",
16
+ "Jacob", "Gary", "Nicholas", "Eric", "Jonathan", "Stephen", "Larry", "Justin", "Scott", "Brandon",
17
+ "Benjamin", "Samuel", "Frank", "Gregory", "Raymond", "Alexander", "Patrick", "Jack", "Dennis", "Jerry",
18
+ "Tyler", "Aaron", "Henry", "Douglas", "Jose", "Peter", "Adam", "Zachary", "Nathan", "Walter",
19
+ "Kyle", "Harold", "Carl", "Arthur", "Gerald", "Roger", "Keith", "Jeremy", "Terry", "Lawrence",
20
+ "Sean", "Christian", "Ethan", "Austin", "Joe", "Jordan", "Albert", "Jesse", "Willie", "Billy"]
21
+
22
+ apellidos = ["Garcia", "Rodriguez", "Gonzalez", "Fernandez", "Lopez", "Martinez", "Sanchez", "Perez", "Alonso", "Diaz",
23
+ "Martin", "Ruiz", "Hernandez", "Jimenez", "Torres", "Moreno", "Gomez", "Romero", "Alvarez", "Vazquez",
24
+ "Gil", "Lopez", "Ramirez", "Santos", "Castro", "Suarez", "Munoz", "Gomez", "Gonzalez", "Navarro",
25
+ "Dominguez", "Lopez", "Rodriguez", "Sanchez", "Perez", "Garcia", "Gonzalez", "Martinez", "Fernandez", "Lopez",
26
+ # Apellidos comunes de EE.UU.
27
+ "Smith", "Johnson", "Williams", "Brown", "Jones", "Garcia", "Miller", "Davis", "Rodriguez", "Martinez",
28
+ "Hernandez", "Lopez", "Gonzalez", "Wilson", "Anderson", "Thomas", "Taylor", "Moore", "Jackson", "Martin",
29
+ "Lee", "Perez", "Thompson", "White", "Harris", "Sanchez", "Clark", "Ramirez", "Lewis", "Robinson",
30
+ "Walker", "Young", "Allen", "King", "Wright", "Scott", "Torres", "Nguyen", "Hill", "Flores",
31
+ "Green", "Adams", "Nelson", "Baker", "Hall", "Rivera", "Campbell", "Mitchell", "Carter", "Roberts",
32
+ "Gomez", "Phillips", "Evans", "Turner", "Diaz", "Parker", "Cruz", "Edwards", "Collins", "Reyes",
33
+ "Stewart", "Morris", "Morales", "Murphy", "Cook", "Rogers", "Gutierrez", "Ortiz", "Morgan", "Cooper",
34
+ "Peterson", "Bailey", "Reed", "Kelly", "Howard", "Ward", "Cox", "Diaz", "Richardson", "Wood"]
35
+
36
+
37
+ nombre = random.choice(nombres)
38
+ apellido = random.choice(apellidos)
39
+ numero = random.randint(100, 999)
40
+
41
+ nombre_completo = f"{nombre}_{apellido}_{numero}"
42
+ return nombre_completo
43
+
44
+ def generar_contrasena():
45
+ """Genera una contrase帽a aleatoria."""
46
+ caracteres = string.ascii_letters + "0123456789" + "#$%&/()@_-*+[]"
47
+ longitud = 10
48
+ contrase帽a = ''.join(random.choice(caracteres) for _ in range(longitud))
49
+ return contrase帽a
50
+
51
+ def enviar_formulario(url, datos):
52
+ """Env铆a una solicitud POST a un formulario web."""
53
+ response = requests.post(url, data=datos)
54
+ return response
55
+
56
+ def extraer_dominios(response_text):
57
+ """Extrae dominios de un texto utilizando expresiones regulares."""
58
+ dominios = re.findall(r'id="([^"]+\.[^"]+)"', response_text)
59
+ return dominios
60
+
61
+ def obtener_sitio_web_aleatorio(response_text):
62
+ """Obtiene un sitio web aleatorio de los dominios extra铆dos."""
63
+ dominios = extraer_dominios(response_text)
64
+ sitio_web_aleatorio = random.choice(dominios)
65
+ return sitio_web_aleatorio
Vidu/utils/video_fragment.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import os
3
+
4
+ def extraer_ultimo_fotograma_ffmpeg(ruta_video, ruta_imagen):
5
+ """
6
+ Extrae el 煤ltimo fotograma de un video usando FFmpeg y lo guarda
7
+ en la ruta especificada, reemplazando el archivo si ya existe.
8
+
9
+ Args:
10
+ ruta_video: Ruta al archivo de video.
11
+ ruta_imagen: Ruta donde se guardar谩 la imagen (incluyendo extensi贸n).
12
+ """
13
+ # Verifica si el archivo ya existe y lo elimina si es necesario
14
+ if os.path.exists(ruta_imagen):
15
+ os.remove(ruta_imagen)
16
+
17
+ # Obtiene la duraci贸n del video
18
+ duracion_cmd = [
19
+ "ffprobe",
20
+ "-v", "error",
21
+ "-show_entries", "format=duration",
22
+ "-of", "default=noprint_wrappers=1:nokey=1",
23
+ ruta_video
24
+ ]
25
+ duracion = float(subprocess.check_output(duracion_cmd))
26
+
27
+ # Calcula el tiempo para buscar cerca del final (0.1 segundos antes)
28
+ tiempo_busqueda = str(duracion - 0.1)
29
+
30
+ # Construye el comando FFmpeg para extraer el 煤ltimo fotograma
31
+ comando = [
32
+ "ffmpeg",
33
+ "-ss", tiempo_busqueda, # Busca cerca del final
34
+ "-i", ruta_video,
35
+ "-vframes", "1", # Extrae solo un fotograma
36
+ "-qscale:v", "2", # Ajusta la calidad si es necesario
37
+ ruta_imagen
38
+ ]
39
+
40
+ # Ejecuta el comando FFmpeg
41
+ subprocess.run(comando)
42
+
43
+ # Ejemplo de uso
44
+ video_path = '/content/Vidu_Studio/videotovideo.mp4'
45
+ output_image_path = '/tmp/img_fragmento.jpg'
46
+ extraer_ultimo_fotograma_ffmpeg(video_path, output_image_path)
Vidu/vidu_credit.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import urllib.request
2
+ import json
3
+ import subprocess
4
+ import argparse
5
+
6
+ # Funci贸n para cargar el JWT token desde un archivo
7
+ def cargar_jwt_token(ruta='/tmp/jwt_token.txt'):
8
+ try:
9
+ with open(ruta, 'r') as archivo:
10
+ jwt_token = archivo.read().strip()
11
+ return jwt_token
12
+ except FileNotFoundError:
13
+ print("Error: El archivo no fue encontrado.")
14
+ subprocess.run(["python", "/content/Vidu_Studio/main.py"], check=True)
15
+ return None
16
+
17
+ # Funci贸n para obtener los cr茅ditos utilizando el JWT token
18
+ def obtener_credits(jwt_token, credit_comparar):
19
+ url = "https://api.vidu.studio/vidu/v1/tasks/credits?type=img2video&settings.duration=4&settings.model=vidu-1"
20
+ headers = {
21
+ "Host": "api.vidu.studio",
22
+ "Connection": "keep-alive",
23
+ "sec-ch-ua": '"Chromium";v="128", "Not;A=Brand";v="24", "Google Chrome";v="128"',
24
+ "Accept-Language": "en",
25
+ "sec-ch-ua-mobile": "?0",
26
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
27
+ "sec-ch-ua-platform": '"Windows"',
28
+ "Accept": "*/*",
29
+ "Origin": "https://www.vidu.studio",
30
+ "Sec-Fetch-Site": "same-site",
31
+ "Sec-Fetch-Mode": "cors",
32
+ "Sec-Fetch-Dest": "empty",
33
+ "Referer": "https://www.vidu.studio/",
34
+ "Cookie": f"sajssdk_2015_cross_new_user=1; _ga=GA1.1.77204265.1725572952; amp_af43d4=61603120ab0445398cd1cb92fd88aef0...1i727srs7.1i727ujms.6.1.7; JWT={jwt_token}; Shunt=; sensorsdata2015jssdkcross=dfm-enc-%7B%22Va28a6y8_aV%22%3A%22sSEGIEItsRRRsHGE%22%2C%22gae28_aV%22%3A%22EGEySsGigsIHGA-AsSSHnIgEEySVVs-snAAEEHE-EsGnAAA-EGEySsGigsSisH%22%2C%22OemO2%22%3A%7B%22%24ki8r28_8eiggay_2mbeyr_8cOr%22%3A%22%E7%9B%B4%E6%8E%A5%E6%B5%81%E9%87%8F%22%2C%22%24ki8r28_2rieyz_lrcMmeV%22%3A%22%E6%9C%AA%E5%8F%96%E5%88%B0%E5%80%BC_%E7%9B%B4%E6%8E%A5%E6%89%93%E5%BC%80%22%2C%22%24ki8r28_ergreere%22%3A%22%22%7D%2C%22aVr68a8ar2%22%3A%22rc3liZ7ku67OV5kgPsGCiskkDskl3qmawFlJPhNcpZTowqwEpF08wX3AQXKswsPJwZwAW9NcBF3swX0JwFKJBF1cpFPMwX08wFlJPhNcpZTowq7zwqKaBv3liZ7ku67OV5kgu9G6iZHgiZNapa3cQX1Hwh1hpX3IQhycQFlJ36A%3D%22%2C%22za28mec_kmfa6_aV%22%3A%7B%226ior%22%3A%22%24aVr68a8c_kmfa6_aV%22%2C%22Cikbr%22%3A%22sSEGIEItsRRRsHGE%22%7D%7D; _ga_ZJBV7VYP55=GS1.1.1725576214.2.1.1725578996.0.0.0",
35
+ "Accept-Encoding": "gzip, deflate"
36
+ }
37
+
38
+ request = urllib.request.Request(url, headers=headers, method='GET')
39
+
40
+ try:
41
+ # Realizar la solicitud y obtener la respuesta
42
+ with urllib.request.urlopen(request) as response:
43
+ response_body = response.read().decode('utf-8')
44
+ #print("Response:", response_body)
45
+ data = json.loads(response_body)
46
+
47
+ # Extraer 'current_credits' de la respuesta
48
+ current_credits = data.get('current_credits')
49
+ if current_credits is not None:
50
+ print(f"Current Credits: {current_credits}")
51
+ # Comparar los cr茅ditos y ejecutar el comando si es igual al valor proporcionado
52
+ if current_credits == credit_comparar or current_credits == 0:
53
+ print(f"Cr茅ditos iguales a {credit_comparar}. Ejecutando /content/main.py...")
54
+ subprocess.run(["python", "/content/Vidu_Studio/main.py"], check=True)
55
+ else:
56
+ print(f"Los cr茅ditos no son {credit_comparar}.")
57
+ else:
58
+ print("No se encontr贸 'current_credits' en la respuesta.")
59
+ except urllib.error.HTTPError as e:
60
+ print(f"Error HTTP: {e.code}")
61
+ print(f"Detalles del error: {e.read().decode('utf-8')}")
62
+ except urllib.error.URLError as e:
63
+ print(f"Error de conexi贸n: {e.reason}")
64
+
65
+ # Ejecutar el script principal
66
+ if __name__ == "__main__":
67
+ # Configurar el parser de argumentos
68
+ parser = argparse.ArgumentParser(description='Verificar cr茅ditos y ejecutar un script basado en el valor de cr茅ditos.')
69
+ parser.add_argument('--credit', type=int, default=4, help='El valor de cr茅ditos para comparar (predeterminado es 4).')
70
+ args = parser.parse_args()
71
+
72
+ jwt_token = cargar_jwt_token()
73
+ if jwt_token:
74
+ obtener_credits(jwt_token, args.credit)