Spaces:
Runtime error
Runtime error
File size: 57,046 Bytes
8b274aa 15e8c2d bafc5cd 15e8c2d b8bd6c3 6bc8144 15e8c2d 6bc8144 744ab6c 9038d35 6bc8144 cdba26b fca757c cc24506 b8bd6c3 ef98f47 d058c4e b82e6a6 d058c4e ef98f47 d058c4e 1829fd6 1fa048a 744ab6c 1fa048a 744ab6c 1fa048a 744ab6c ef98f47 2b5730b d058c4e ef98f47 4c089c2 cc24506 ef98f47 d058c4e ef98f47 cc24506 d058c4e 43865d4 d058c4e ef98f47 d058c4e ef98f47 cc24506 d058c4e ef98f47 cc24506 d058c4e 52c5b8e ef98f47 d058c4e ef98f47 cc24506 d058c4e cdba26b 43865d4 ef98f47 43865d4 ef98f47 cdba26b fca757c ef98f47 cdba26b fca757c cdba26b cc24506 ef98f47 cc24506 ef98f47 cc24506 ef98f47 fca757c ef98f47 cc24506 ef98f47 cdba26b ef98f47 fca757c cdba26b d058c4e ef98f47 6bc8144 ef98f47 e9b7708 ef98f47 6bc8144 ef98f47 43865d4 cdba26b e9b7708 cc24506 cdba26b cc24506 cdba26b 43865d4 cc24506 cdba26b ef98f47 d058c4e ef98f47 744ab6c ef98f47 744ab6c ef98f47 744ab6c ef98f47 744ab6c ef98f47 744ab6c ef98f47 744ab6c ef98f47 744ab6c ef98f47 744ab6c ee6df46 744ab6c ef98f47 43865d4 744ab6c 43865d4 744ab6c 43865d4 ef98f47 cc24506 ef98f47 744ab6c cc24506 6bc8144 ef98f47 cc24506 6bc8144 744ab6c e098d46 ef98f47 43865d4 ef98f47 43865d4 ef98f47 6bc8144 ef98f47 cc24506 ef98f47 43865d4 ef98f47 43865d4 ef98f47 6bc8144 e9b7708 2b5730b 6bc8144 d058c4e 0b39b27 ef98f47 0b39b27 ef98f47 0b39b27 ef98f47 43865d4 cdba26b ef98f47 d058c4e 43865d4 cc24506 ef98f47 43865d4 ef98f47 43865d4 cc24506 43865d4 ef98f47 0b39b27 ef98f47 43865d4 0b39b27 ef98f47 db50614 b7e77cf 52c5b8e db50614 b7e77cf db50614 52c5b8e 43865d4 0b39b27 db50614 ef98f47 d058c4e ef98f47 43865d4 52c5b8e a889be2 ef98f47 db50614 a889be2 db50614 a889be2 db50614 a889be2 db50614 52c5b8e db50614 52c5b8e db50614 b7e77cf db50614 b7e77cf 0b39b27 cdba26b ef98f47 43865d4 ef98f47 cc24506 43865d4 cdba26b 0b39b27 ef98f47 cc24506 ef98f47 43865d4 ef98f47 43865d4 a889be2 43865d4 cc24506 43865d4 ef98f47 43865d4 fca757c ef98f47 43865d4 261f3dc 9038d35 ef98f47 43865d4 ef98f47 43865d4 ef98f47 fca757c ef98f47 43865d4 ef98f47 43865d4 ef98f47 43865d4 ef98f47 d058c4e 0b39b27 744ab6c ee6df46 d058c4e ef98f47 d058c4e 1fa048a ef98f47 d058c4e cc24506 ef98f47 52c5b8e 9038d35 52c5b8e a889be2 3a7d955 ef98f47 43865d4 cc24506 43865d4 ef98f47 43865d4 ef98f47 43865d4 ef98f47 cc24506 43865d4 744ab6c ef98f47 43865d4 4ad7ee5 744ab6c 4ad7ee5 744ab6c 0e14a87 4ad7ee5 ee6df46 744ab6c 4ad7ee5 744ab6c 0e14a87 744ab6c 4ad7ee5 0e14a87 744ab6c 4ad7ee5 e9b7708 744ab6c e9b7708 506f1df e9b7708 db50614 ef98f47 db50614 e9b7708 db50614 52c5b8e 4ad7ee5 e9b7708 db50614 e9b7708 ef98f47 43865d4 b7e77cf ef98f47 c8581d9 ef98f47 fca757c ef98f47 fca757c ef98f47 cc24506 43865d4 cc24506 43865d4 ef98f47 cdba26b cc24506 43865d4 cdba26b cc24506 fca757c 43865d4 fca757c ef98f47 fca757c ef98f47 43865d4 cc24506 ef98f47 cc24506 43865d4 cc24506 43865d4 ef98f47 43865d4 ef98f47 43865d4 fca757c ef98f47 cdba26b ef98f47 cdba26b fca757c ef98f47 fca757c ef98f47 fca757c 43865d4 fca757c cc24506 ef98f47 43865d4 ef98f47 43865d4 ef98f47 43865d4 fca757c ef98f47 43865d4 ef98f47 cdba26b ef98f47 0b39b27 a889be2 52c5b8e 43865d4 cc24506 ef98f47 cdba26b 43865d4 52c5b8e 0b39b27 ef98f47 0b39b27 52c5b8e cc24506 9038d35 cc24506 43865d4 cc24506 43865d4 cc24506 c8581d9 ef98f47 52c5b8e c8581d9 ef98f47 c8581d9 ef98f47 cc24506 ef98f47 cc24506 ef98f47 43865d4 ef98f47 43865d4 0b39b27 ef98f47 43865d4 ef98f47 cc24506 c8581d9 ef98f47 52c5b8e c8581d9 b7e77cf ef98f47 cc24506 b7e77cf ef98f47 c8581d9 ef98f47 b7e77cf 52c5b8e c8581d9 52c5b8e c8581d9 52c5b8e c8581d9 ef98f47 c8581d9 ef98f47 e9b7708 a889be2 c8581d9 b7e77cf ef98f47 b7e77cf ef98f47 b7e77cf a889be2 ef98f47 a889be2 ef98f47 52c5b8e c8581d9 ef98f47 b7e77cf ef98f47 c8581d9 db50614 ef98f47 c8581d9 ef98f47 b7e77cf db50614 e9b7708 db50614 c8581d9 ef98f47 52c5b8e c8581d9 b7e77cf ef98f47 c8581d9 db50614 c8581d9 ef98f47 b7e77cf 43865d4 b7e77cf ef98f47 43865d4 db50614 ef98f47 db50614 52c5b8e c8581d9 ef98f47 2b26186 db50614 52c5b8e db50614 cdba26b 52c5b8e cdba26b 43865d4 cdba26b cc24506 ef98f47 db50614 ef98f47 db50614 ef98f47 db50614 52c5b8e db50614 ef98f47 a889be2 db50614 ef98f47 db50614 52c5b8e a889be2 b7e77cf 52c5b8e 506f1df b7e77cf ef98f47 52c5b8e ef98f47 52c5b8e 2b26186 b7e77cf ef98f47 2b26186 506f1df a889be2 cdba26b ef98f47 db50614 52c5b8e ef98f47 43865d4 db50614 ef98f47 b7e77cf db50614 9038d35 ef98f47 db50614 52c5b8e db50614 52c5b8e ef98f47 b7e77cf ef98f47 cc24506 ef98f47 fca757c c8581d9 b7e77cf ef98f47 2b26186 43865d4 ef98f47 43865d4 0b39b27 2b5730b 0b39b27 cc24506 a889be2 6bc8144 ef98f47 d058c4e ef98f47 cc24506 ef98f47 43865d4 ef98f47 cc24506 163c0da ef98f47 cc24506 43865d4 ef98f47 c8581d9 2b26186 ef98f47 c8581d9 ef98f47 2b26186 ef98f47 2b26186 ef98f47 c8581d9 e098d46 9038d35 2b26186 9038d35 ef98f47 9038d35 ef98f47 9038d35 2b26186 9038d35 e9b7708 9038d35 2b26186 43865d4 ef98f47 43865d4 cc24506 ef98f47 43865d4 ef98f47 43865d4 ef98f47 43865d4 ef98f47 cdba26b ef98f47 744ab6c ee6df46 d058c4e ef98f47 0e14a87 43865d4 ef98f47 52c5b8e e9b7708 52c5b8e 43865d4 ef98f47 4c089c2 52c5b8e 43865d4 ee6df46 744ab6c ee6df46 ef98f47 43865d4 ef98f47 43865d4 ef98f47 744ab6c 43865d4 0b39b27 ef98f47 744ab6c ef98f47 43865d4 ef98f47 0e14a87 52c5b8e 43865d4 ef98f47 52c5b8e 43865d4 0b39b27 ef98f47 52c5b8e 0b39b27 ef98f47 52c5b8e 43865d4 ef98f47 52c5b8e 43865d4 b82e6a6 ef98f47 ee6df46 fca757c ef98f47 fca757c 0b39b27 ef98f47 cc24506 0b39b27 ef98f47 e098d46 ee6df46 e098d46 ee6df46 e098d46 506f1df e098d46 ee6df46 e098d46 ef98f47 fca757c ef98f47 fca757c 43865d4 cc24506 ee6df46 0b39b27 0e14a87 30e9b85 744ab6c 30e9b85 ee6df46 30e9b85 ef98f47 6bc8144 fca757c e9b7708 cc24506 ee6df46 fca757c 52c5b8e e9b7708 2b26186 744ab6c ee6df46 52c5b8e fca757c ef98f47 cc24506 ef98f47 ee6df46 fca757c 6bc8144 506f1df 0b39b27 ef98f47 cdba26b 0b39b27 ee6df46 0b39b27 e9b7708 fca757c 30e9b85 506f1df 52c5b8e 30e9b85 0b39b27 30e9b85 cdba26b ee6df46 30e9b85 e098d46 52c5b8e 30e9b85 506f1df e098d46 0b39b27 163c0da ee6df46 ef98f47 fca757c ef98f47 ee6df46 fca757c 43865d4 ef98f47 fca757c 15e8c2d ef98f47 43865d4 b7e77cf 52c5b8e b7e77cf ee6df46 b7e77cf ef98f47 b7e77cf 43865d4 ef98f47 43865d4 ef98f47 d058c4e 43865d4 d058c4e ef98f47 cc24506 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 |
import os
import asyncio
import logging
import tempfile
import requests
from datetime import datetime
import edge_tts
import gradio as gr
import torch
from transformers import GPT2Tokenizer, GPT2LMHeadModel
from keybert import KeyBERT
# Importación correcta
from moviepy.editor import VideoFileClip, concatenate_videoclips, AudioFileClip, CompositeAudioClip, concatenate_audioclips, AudioClip
import re
import math
import shutil
import json
from collections import Counter
# Configuración de logging
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler('video_generator_full.log', encoding='utf-8')
]
)
logger = logging.getLogger(__name__)
logger.info("="*80)
logger.info("INICIO DE EJECUCIÓN - GENERADOR DE VIDEOS")
logger.info("="*80)
# Diccionario de voces TTS disponibles organizadas por idioma
# Puedes expandir esta lista si conoces otros IDs de voz de Edge TTS
VOCES_DISPONIBLES = {
"Español (España)": {
"es-ES-JuanNeural": "Juan (España) - Masculino",
"es-ES-ElviraNeural": "Elvira (España) - Femenino",
"es-ES-AlvaroNeural": "Álvaro (España) - Masculino",
"es-ES-AbrilNeural": "Abril (España) - Femenino",
"es-ES-ArnauNeural": "Arnau (España) - Masculino",
"es-ES-DarioNeural": "Darío (España) - Masculino",
"es-ES-EliasNeural": "Elías (España) - Masculino",
"es-ES-EstrellaNeural": "Estrella (España) - Femenino",
"es-ES-IreneNeural": "Irene (España) - Femenino",
"es-ES-LaiaNeural": "Laia (España) - Femenino",
"es-ES-LiaNeural": "Lía (España) - Femenino",
"es-ES-NilNeural": "Nil (España) - Masculino",
"es-ES-SaulNeural": "Saúl (España) - Masculino",
"es-ES-TeoNeural": "Teo (España) - Masculino",
"es-ES-TrianaNeural": "Triana (España) - Femenino",
"es-ES-VeraNeural": "Vera (España) - Femenino"
},
"Español (México)": {
"es-MX-JorgeNeural": "Jorge (México) - Masculino",
"es-MX-DaliaNeural": "Dalia (México) - Femenino",
"es-MX-BeatrizNeural": "Beatriz (México) - Femenino",
"es-MX-CandelaNeural": "Candela (México) - Femenino",
"es-MX-CarlotaNeural": "Carlota (México) - Femenino",
"es-MX-CecilioNeural": "Cecilio (México) - Masculino",
"es-MX-GerardoNeural": "Gerardo (México) - Masculino",
"es-MX-LarissaNeural": "Larissa (México) - Femenino",
"es-MX-LibertoNeural": "Liberto (México) - Masculino",
"es-MX-LucianoNeural": "Luciano (México) - Masculino",
"es-MX-MarinaNeural": "Marina (México) - Femenino",
"es-MX-NuriaNeural": "Nuria (México) - Femenino",
"es-MX-PelayoNeural": "Pelayo (México) - Masculino",
"es-MX-RenataNeural": "Renata (México) - Femenino",
"es-MX-YagoNeural": "Yago (México) - Masculino"
},
"Español (Argentina)": {
"es-AR-TomasNeural": "Tomás (Argentina) - Masculino",
"es-AR-ElenaNeural": "Elena (Argentina) - Femenino"
},
"Español (Colombia)": {
"es-CO-GonzaloNeural": "Gonzalo (Colombia) - Masculino",
"es-CO-SalomeNeural": "Salomé (Colombia) - Femenino"
},
"Español (Chile)": {
"es-CL-LorenzoNeural": "Lorenzo (Chile) - Masculino",
"es-CL-CatalinaNeural": "Catalina (Chile) - Femenino"
},
"Español (Perú)": {
"es-PE-AlexNeural": "Alex (Perú) - Masculino",
"es-PE-CamilaNeural": "Camila (Perú) - Femenino"
},
"Español (Venezuela)": {
"es-VE-PaolaNeural": "Paola (Venezuela) - Femenino",
"es-VE-SebastianNeural": "Sebastián (Venezuela) - Masculino"
},
"Español (Estados Unidos)": {
"es-US-AlonsoNeural": "Alonso (Estados Unidos) - Masculino",
"es-US-PalomaNeural": "Paloma (Estados Unidos) - Femenino"
}
}
# Función para obtener lista plana de voces para el dropdown
def get_voice_choices():
choices = []
for region, voices in VOCES_DISPONIBLES.items():
for voice_id, voice_name in voices.items():
# Formato: (Texto a mostrar en el dropdown, Valor que se pasa)
choices.append((f"{voice_name} ({region})", voice_id))
return choices
# Obtener las voces al inicio del script
# Usamos la lista predefinida por ahora para evitar el error de inicio con la API
# Si deseas obtenerlas dinámicamente, descomenta la siguiente línea y comenta la que usa get_voice_choices()
# AVAILABLE_VOICES = asyncio.run(get_available_voices())
AVAILABLE_VOICES = get_voice_choices() # <-- Usamos la lista predefinida y aplanada
# Establecer una voz por defecto inicial
DEFAULT_VOICE_ID = "es-ES-JuanNeural" # ID de Juan
# Buscar el nombre amigable para la voz por defecto si existe
DEFAULT_VOICE_NAME = DEFAULT_VOICE_ID
for text, voice_id in AVAILABLE_VOICES:
if voice_id == DEFAULT_VOICE_ID:
DEFAULT_VOICE_NAME = text
break
# Si Juan no está en la lista (ej. lista de fallback), usar la primera voz disponible
if DEFAULT_VOICE_ID not in [v[1] for v in AVAILABLE_VOICES]:
DEFAULT_VOICE_ID = AVAILABLE_VOICES[0][1] if AVAILABLE_VOICES else "en-US-AriaNeural"
DEFAULT_VOICE_NAME = AVAILABLE_VOICES[0][0] if AVAILABLE_VOICES else "Aria (United States) - Female" # Fallback name
logger.info(f"Voz por defecto seleccionada (ID): {DEFAULT_VOICE_ID}")
# Clave API de Pexels
PEXELS_API_KEY = os.environ.get("PEXELS_API_KEY")
if not PEXELS_API_KEY:
logger.critical("NO SE ENCONTRÓ PEXELS_API_KEY EN VARIABLES DE ENTORNO")
# raise ValueError("API key de Pexels no configurada")
# Inicialización de modelos
MODEL_NAME = "datificate/gpt2-small-spanish"
logger.info(f"Inicializando modelo GPT-2: {MODEL_NAME}")
tokenizer = None
model = None
try:
tokenizer = GPT2Tokenizer.from_pretrained(MODEL_NAME)
model = GPT2LMHeadModel.from_pretrained(MODEL_NAME).eval()
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
logger.info(f"Modelo GPT-2 cargado | Vocabulario: {len(tokenizer)} tokens")
except Exception as e:
logger.error(f"FALLA CRÍTICA al cargar GPT-2: {str(e)}", exc_info=True)
tokenizer = model = None
logger.info("Cargando modelo KeyBERT...")
kw_model = None
try:
kw_model = KeyBERT('distilbert-base-multilingual-cased')
logger.info("KeyBERT inicializado correctamente")
except Exception as e:
logger.error(f"FALLA al cargar KeyBERT: {str(e)}", exc_info=True)
kw_model = None
def buscar_videos_pexels(query, api_key, per_page=5):
if not api_key:
logger.warning("No se puede buscar en Pexels: API Key no configurada.")
return []
logger.debug(f"Buscando en Pexels: '{query}' | Resultados: {per_page}")
headers = {"Authorization": api_key}
try:
params = {
"query": query,
"per_page": per_page,
"orientation": "landscape",
"size": "medium"
}
response = requests.get(
"https://api.pexels.com/videos/search",
headers=headers,
params=params,
timeout=20
)
response.raise_for_status()
data = response.json()
videos = data.get('videos', [])
logger.info(f"Pexels: {len(videos)} videos encontrados para '{query}'")
return videos
except requests.exceptions.RequestException as e:
logger.error(f"Error de conexión Pexels para '{query}': {str(e)}")
except json.JSONDecodeError:
logger.error(f"Pexels: JSON inválido recibido | Status: {response.status_code} | Respuesta: {response.text[:200]}...")
except Exception as e:
logger.error(f"Error inesperado Pexels para '{query}': {str(e)}", exc_info=True)
return []
def generate_script(prompt, max_length=150):
logger.info(f"Generando guión | Prompt: '{prompt[:50]}...' | Longitud máxima: {max_length}")
if not tokenizer or not model:
logger.warning("Modelos GPT-2 no disponibles - Usando prompt original como guion.")
return prompt.strip()
instruction_phrase_start = "Escribe un guion corto, interesante y coherente sobre:"
ai_prompt = f"{instruction_phrase_start} {prompt}"
try:
inputs = tokenizer(ai_prompt, return_tensors="pt", truncation=True, max_length=512)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
inputs = {k: v.to(device) for k, v in inputs.items()}
outputs = model.generate(
**inputs,
max_length=max_length + inputs[list(inputs.keys())[0]].size(1),
do_sample=True,
top_p=0.9,
top_k=40,
temperature=0.7,
repetition_penalty=1.2,
pad_token_id=tokenizer.pad_token_id,
eos_token_id=tokenizer.eos_token_id,
no_repeat_ngram_size=3
)
text = tokenizer.decode(outputs[0], skip_special_tokens=True)
cleaned_text = text.strip()
# Limpieza mejorada de la frase de instrucción
try:
# Buscar el índice de inicio del prompt original dentro del texto generado
prompt_in_output_idx = text.lower().find(prompt.lower())
if prompt_in_output_idx != -1:
# Tomar todo el texto DESPUÉS del prompt original
cleaned_text = text[prompt_in_output_idx + len(prompt):].strip()
logger.debug("Texto limpiado tomando parte después del prompt original.")
else:
# Fallback si el prompt original no está exacto en la salida: buscar la frase de instrucción base
instruction_start_idx = text.find(instruction_phrase_start)
if instruction_start_idx != -1:
# Tomar texto después de la frase base (puede incluir el prompt)
cleaned_text = text[instruction_start_idx + len(instruction_phrase_start):].strip()
logger.debug("Texto limpiado tomando parte después de la frase de instrucción base.")
else:
# Si ni la frase de instrucción ni el prompt se encuentran, usar el texto original
logger.warning("No se pudo identificar el inicio del guión generado. Usando texto generado completo.")
cleaned_text = text.strip() # Limpieza básica
except Exception as e:
logger.warning(f"Error durante la limpieza heurística del guión de IA: {e}. Usando texto generado sin limpieza adicional.")
cleaned_text = re.sub(r'<[^>]+>', '', text).strip() # Limpieza básica como fallback
# Asegurarse de que el texto resultante no sea solo la instrucción o vacío
if not cleaned_text or len(cleaned_text) < 10: # Umbral de longitud mínima
logger.warning("El guión generado parece muy corto o vacío después de la limpieza heurística. Usando el texto generado original (sin limpieza adicional).")
cleaned_text = re.sub(r'<[^>]+>', '', text).strip() # Fallback al texto original limpio
# Limpieza final de caracteres especiales y espacios sobrantes
cleaned_text = re.sub(r'<[^>]+>', '', cleaned_text).strip()
cleaned_text = cleaned_text.lstrip(':').strip() # Quitar posibles ':' al inicio
cleaned_text = cleaned_text.lstrip('.').strip() # Quitar posibles '.' al inicio
# Intentar obtener al menos una oración completa si es posible para un inicio más limpio
sentences = cleaned_text.split('.')
if sentences and sentences[0].strip():
final_text = sentences[0].strip() + '.'
# Añadir la segunda oración si existe y es razonable
if len(sentences) > 1 and sentences[1].strip() and len(final_text.split()) < max_length * 0.7: # Usar un 70% de max_length como umbral
final_text += " " + sentences[1].strip() + "."
final_text = final_text.replace("..", ".") # Limpiar doble punto
logger.info(f"Guion generado final (Truncado a 100 chars): '{final_text[:100]}...'")
return final_text.strip()
logger.info(f"Guion generado final (sin oraciones completas detectadas - Truncado): '{cleaned_text[:100]}...'")
return cleaned_text.strip() # Si no se puede formar una oración, devolver el texto limpio tal cual
except Exception as e:
logger.error(f"Error generando guion con GPT-2 (fuera del bloque de limpieza): {str(e)}", exc_info=True)
logger.warning("Usando prompt original como guion debido al error de generación.")
return prompt.strip()
# Función TTS ahora recibe la voz a usar
async def text_to_speech(text, output_path, voice):
logger.info(f"Convirtiendo texto a voz | Caracteres: {len(text)} | Voz: {voice} | Salida: {output_path}")
if not text or not text.strip():
logger.warning("Texto vacío para TTS")
return False
try:
communicate = edge_tts.Communicate(text, voice)
await communicate.save(output_path)
if os.path.exists(output_path) and os.path.getsize(output_path) > 100:
logger.info(f"Audio guardado exitosamente en: {output_path} | Tamaño: {os.path.getsize(output_path)} bytes")
return True
else:
logger.error(f"TTS guardó un archivo pequeño o vacío en: {output_path}")
return False
except Exception as e:
logger.error(f"Error en TTS con voz '{voice}': {str(e)}", exc_info=True)
return False
def download_video_file(url, temp_dir):
if not url:
logger.warning("URL de video no proporcionada para descargar")
return None
try:
logger.info(f"Descargando video desde: {url[:80]}...")
os.makedirs(temp_dir, exist_ok=True)
file_name = f"video_dl_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}.mp4"
output_path = os.path.join(temp_dir, file_name)
with requests.get(url, stream=True, timeout=60) as r:
r.raise_for_status()
with open(output_path, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
if os.path.exists(output_path) and os.path.getsize(output_path) > 1000:
logger.info(f"Video descargado exitosamente: {output_path} | Tamaño: {os.path.getsize(output_path)} bytes")
return output_path
else:
logger.warning(f"Descarga parece incompleta o vacía para {url[:80]}... Archivo: {output_path} Tamaño: {os.path.getsize(output_path) if os.path.exists(output_path) else 'N/A'} bytes")
if os.path.exists(output_path):
os.remove(output_path)
return None
except requests.exceptions.RequestException as e:
logger.error(f"Error de descarga para {url[:80]}... : {str(e)}")
except Exception as e:
logger.error(f"Error inesperado descargando {url[:80]}... : {str(e)}", exc_info=True)
return None
def loop_audio_to_length(audio_clip, target_duration):
logger.debug(f"Ajustando audio | Duración actual: {audio_clip.duration:.2f}s | Objetivo: {target_duration:.2f}s")
if audio_clip is None or audio_clip.duration is None or audio_clip.duration <= 0:
logger.warning("Input audio clip is invalid (None or zero duration), cannot loop.")
try:
sr = getattr(audio_clip, 'fps', 44100) if audio_clip else 44100
return AudioClip(lambda t: 0, duration=target_duration, sr=sr)
except Exception as e:
logger.error(f"Could not create silence clip: {e}", exc_info=True)
return AudioFileClip(filename="")
if audio_clip.duration >= target_duration:
logger.debug("Audio clip already longer or equal to target. Trimming.")
trimmed_clip = audio_clip.subclip(0, target_duration)
if trimmed_clip.duration is None or trimmed_clip.duration <= 0:
logger.error("Trimmed audio clip is invalid.")
try: trimmed_clip.close()
except: pass
return AudioFileClip(filename="")
return trimmed_clip
loops = math.ceil(target_duration / audio_clip.duration)
logger.debug(f"Creando {loops} loops de audio")
audio_segments = [audio_clip] * loops
looped_audio = None
final_looped_audio = None
try:
looped_audio = concatenate_audioclips(audio_segments)
if looped_audio.duration is None or looped_audio.duration <= 0:
logger.error("Concatenated audio clip is invalid (None or zero duration).")
raise ValueError("Invalid concatenated audio.")
final_looped_audio = looped_audio.subclip(0, target_duration)
if final_looped_audio.duration is None or final_looped_audio.duration <= 0:
logger.error("Final subclipped audio clip is invalid (None or zero duration).")
raise ValueError("Invalid final subclipped audio.")
return final_looped_audio
except Exception as e:
logger.error(f"Error concatenating/subclipping audio clips for looping: {str(e)}", exc_info=True)
try:
if audio_clip.duration is not None and audio_clip.duration > 0:
logger.warning("Returning original audio clip (may be too short).")
return audio_clip.subclip(0, min(audio_clip.duration, target_duration))
except:
pass
logger.error("Fallback to original audio clip failed.")
return AudioFileClip(filename="")
finally:
if looped_audio is not None and looped_audio is not final_looped_audio:
try: looped_audio.close()
except: pass
def extract_visual_keywords_from_script(script_text):
logger.info("Extrayendo palabras clave del guion")
if not script_text or not script_text.strip():
logger.warning("Guion vacío, no se pueden extraer palabras clave.")
return ["naturaleza", "ciudad", "paisaje"]
clean_text = re.sub(r'[^\w\sáéíóúñÁÉÍÓÚÑ]', '', script_text)
keywords_list = []
if kw_model:
try:
logger.debug("Intentando extracción con KeyBERT...")
keywords1 = kw_model.extract_keywords(clean_text, keyphrase_ngram_range=(1, 1), stop_words='spanish', top_n=5)
keywords2 = kw_model.extract_keywords(clean_text, keyphrase_ngram_range=(2, 2), stop_words='spanish', top_n=3)
all_keywords = keywords1 + keywords2
all_keywords.sort(key=lambda item: item[1], reverse=True)
seen_keywords = set()
for keyword, score in all_keywords:
formatted_keyword = keyword.lower().replace(" ", "+")
if formatted_keyword and formatted_keyword not in seen_keywords:
keywords_list.append(formatted_keyword)
seen_keywords.add(formatted_keyword)
if len(keywords_list) >= 5:
break
if keywords_list:
logger.debug(f"Palabras clave extraídas por KeyBERT: {keywords_list}")
return keywords_list
except Exception as e:
logger.warning(f"KeyBERT falló: {str(e)}. Intentando método simple.")
logger.debug("Extrayendo palabras clave con método simple...")
words = clean_text.lower().split()
stop_words = {"el", "la", "los", "las", "de", "en", "y", "a", "que", "es", "un", "una", "con", "para", "del", "al", "por", "su", "sus", "se", "lo", "le", "me", "te", "nos", "os", "les", "mi", "tu",
"nuestro", "vuestro", "este", "ese", "aquel", "esta", "esa", "aquella", "esto", "eso", "aquello", "mis", "tus",
"nuestros", "vuestros", "estas", "esas", "aquellas", "si", "no", "más", "menos", "sin", "sobre", "bajo", "entre", "hasta", "desde", "durante", "mediante", "según", "versus", "via", "cada", "todo", "todos", "toda", "todas", "poco", "pocos", "poca", "pocas", "mucho", "muchos", "mucha", "muchas", "varios", "varias", "otro", "otros", "otra", "otras", "mismo", "misma", "mismos", "mismas", "tan", "tanto", "tanta", "tantos", "tantas", "tal", "tales", "cual", "cuales", "cuyo", "cuya", "cuyos", "cuyas", "quien", "quienes", "cuan", "cuanto", "cuanta", "cuantos", "cuantas", "como", "donde", "cuando", "porque", "aunque", "mientras", "siempre", "nunca", "jamás", "muy", "casi", "solo", "solamente", "incluso", "apenas", "quizás", "tal vez", "acaso", "claro", "cierto", "obvio", "evidentemente", "realmente", "simplemente", "generalmente", "especialmente", "principalmente", "posiblemente", "probablemente", "difícilmente", "fácilmente", "rápidamente", "lentamente", "bien", "mal", "mejor", "peor", "arriba", "abajo", "adelante", "atrás", "cerca", "lejos", "dentro", "fuera", "encima", "debajo", "frente", "detrás", "antes", "después", "luego", "pronto", "tarde", "todavía", "ya", "aun", "aún", "quizá"}
valid_words = [word for word in words if len(word) > 3 and word not in stop_words]
if not valid_words:
logger.warning("No se encontraron palabras clave válidas con método simple. Usando palabras clave predeterminadas.")
return ["naturaleza", "ciudad", "paisaje"]
word_counts = Counter(valid_words)
top_keywords = [word.replace(" ", "+") for word, _ in word_counts.most_common(5)]
if not top_keywords:
logger.warning("El método simple no produjo keywords. Usando palabras clave predeterminadas.")
return ["naturaleza", "ciudad", "paisaje"]
logger.info(f"Palabras clave finales: {top_keywords}")
return top_keywords
# crear_video ahora recibe la voz seleccionada
def crear_video(prompt_type, input_text, selected_voice, musica_file=None):
logger.info("="*80)
logger.info(f"INICIANDO CREACIÓN DE VIDEO | Tipo: {prompt_type}")
logger.debug(f"Input: '{input_text[:100]}...'")
logger.info(f"Voz seleccionada: {selected_voice}")
start_time = datetime.now()
temp_dir_intermediate = None
audio_tts_original = None
musica_audio_original = None
audio_tts = None
musica_audio = None
video_base = None
video_final = None
source_clips = []
clips_to_concatenate = []
try:
# 1. Generar o usar guion
if prompt_type == "Generar Guion con IA":
guion = generate_script(input_text)
else:
guion = input_text.strip()
logger.info(f"Guion final ({len(guion)} chars): '{guion[:100]}...'")
if not guion.strip():
logger.error("El guion resultante está vacío o solo contiene espacios.")
raise ValueError("El guion está vacío.")
temp_dir_intermediate = tempfile.mkdtemp(prefix="video_gen_intermediate_")
logger.info(f"Directorio temporal intermedio creado: {temp_dir_intermediate}")
temp_intermediate_files = []
# 2. Generar audio de voz usando la voz seleccionada, con reintentos si falla
logger.info("Generando audio de voz...")
voz_path = os.path.join(temp_dir_intermediate, "voz.mp3")
tts_voices_to_try = [selected_voice]
fallback_juan = "es-ES-JuanNeural"
fallback_elvira = "es-ES-ElviraNeural"
if fallback_juan and fallback_juan != selected_voice and fallback_juan not in tts_voices_to_try:
tts_voices_to_try.append(fallback_juan)
if fallback_elvira and fallback_elvira != selected_voice and fallback_elvira not in tts_voices_to_try:
tts_voices_to_try.append(fallback_elvira)
tts_success = False
tried_voices = set()
for current_voice in tts_voices_to_try:
if not current_voice or current_voice in tried_voices: continue
tried_voices.add(current_voice)
logger.info(f"Intentando TTS con voz: {current_voice}...")
try:
tts_success = asyncio.run(text_to_speech(guion, voz_path, voice=current_voice))
if tts_success:
logger.info(f"TTS exitoso con voz '{current_voice}'.")
break
except Exception as e:
logger.warning(f"Fallo al generar TTS con voz '{current_voice}': {str(e)}", exc_info=True)
pass
if not tts_success or not os.path.exists(voz_path) or os.path.getsize(voz_path) <= 100:
logger.error("Fallo en la generación de voz después de todos los intentos. Archivo de audio no creado o es muy pequeño.")
raise ValueError("Error generando voz a partir del guion (fallo de TTS).")
temp_intermediate_files.append(voz_path)
audio_tts_original = AudioFileClip(voz_path)
if audio_tts_original.reader is None or audio_tts_original.duration is None or audio_tts_original.duration <= 0:
logger.critical("Clip de audio TTS inicial es inválido (reader is None o duración <= 0) *después* de crear AudioFileClip.")
try: audio_tts_original.close()
except: pass
audio_tts_original = None
if os.path.exists(voz_path):
try: os.remove(voz_path)
except: pass
if voz_path in temp_intermediate_files:
temp_intermediate_files.remove(voz_path)
raise ValueError("Audio de voz generado es inválido después de procesamiento inicial.")
audio_tts = audio_tts_original
audio_duration = audio_tts_original.duration
logger.info(f"Duración audio voz: {audio_duration:.2f} segundos")
if audio_duration < 1.0:
logger.error(f"Duración audio voz ({audio_duration:.2f}s) es muy corta.")
raise ValueError("Generated voice audio is too short (min 1 second required).")
# 3. Extraer palabras clave
logger.info("Extrayendo palabras clave...")
try:
keywords = extract_visual_keywords_from_script(guion)
logger.info(f"Palabras clave identificadas: {keywords}")
except Exception as e:
logger.error(f"Error extrayendo keywords: {str(e)}", exc_info=True)
keywords = ["naturaleza", "paisaje"]
if not keywords:
keywords = ["video", "background"]
# 4. Buscar y descargar videos
logger.info("Buscando videos en Pexels...")
videos_data = []
total_desired_videos = 10
per_page_per_keyword = max(1, total_desired_videos // len(keywords))
for keyword in keywords:
if len(videos_data) >= total_desired_videos: break
try:
videos = buscar_videos_pexels(keyword, PEXELS_API_KEY, per_page=per_page_per_keyword)
if videos:
videos_data.extend(videos)
logger.info(f"Encontrados {len(videos)} videos para '{keyword}'. Total data: {len(videos_data)}")
except Exception as e:
logger.warning(f"Error buscando videos para '{keyword}': {str(e)}")
if len(videos_data) < total_desired_videos / 2:
logger.warning(f"Pocos videos encontrados ({len(videos_data)}). Intentando con palabras clave genéricas.")
generic_keywords = ["nature", "city", "background", "abstract"]
for keyword in generic_keywords:
if len(videos_data) >= total_desired_videos: break
try:
videos = buscar_videos_pexels(keyword, PEXELS_API_KEY, per_page=2)
if videos:
videos_data.extend(videos)
logger.info(f"Encontrados {len(videos)} videos para '{keyword}' (genérico). Total data: {len(videos_data)}")
except Exception as e:
logger.warning(f"Error buscando videos genéricos para '{keyword}': {str(e)}")
if not videos_data:
logger.error("No se encontraron videos en Pexels para ninguna palabra clave.")
raise ValueError("No se encontraron videos adecuados en Pexels.")
video_paths = []
logger.info(f"Intentando descargar {len(videos_data)} videos encontrados...")
for video in videos_data:
if 'video_files' not in video or not video['video_files']:
logger.debug(f"Saltando video sin archivos de video: {video.get('id')}")
continue
try:
best_quality = None
for vf in sorted(video['video_files'], key=lambda x: x.get('width', 0) * x.get('height', 0), reverse=True):
if 'link' in vf:
best_quality = vf
break
if best_quality and 'link' in best_quality:
path = download_video_file(best_quality['link'], temp_dir_intermediate)
if path:
video_paths.append(path)
temp_intermediate_files.append(path)
logger.info(f"Video descargado OK desde {best_quality['link'][:50]}...")
else:
logger.warning(f"No se pudo descargar video desde {best_quality['link'][:50]}...")
else:
logger.warning(f"No se encontró enlace de descarga válido para video {video.get('id')}.")
except Exception as e:
logger.warning(f"Error procesando/descargando video {video.get('id')}: {str(e)}")
logger.info(f"Descargados {len(video_paths)} archivos de video utilizables.")
if not video_paths:
logger.error("No se pudo descargar ningún archivo de video utilizable.")
raise ValueError("No se pudo descargar ningún video utilizable de Pexels.")
# 5. Procesar y concatenar clips de video
logger.info("Procesando y concatenando videos descargados...")
current_duration = 0
min_clip_duration = 0.5
max_clip_segment = 10.0
for i, path in enumerate(video_paths):
if current_duration >= audio_duration + max_clip_segment:
logger.debug(f"Video base suficiente ({current_duration:.1f}s >= {audio_duration:.1f}s + {max_clip_segment:.1f}s buffer). Dejando de procesar clips fuente restantes.")
break
clip = None
try:
logger.debug(f"[{i+1}/{len(video_paths)}] Abriendo clip: {path}")
clip = VideoFileClip(path)
source_clips.append(clip)
if clip.reader is None or clip.duration is None or clip.duration <= 0:
logger.warning(f"[{i+1}/{len(video_paths)}] Clip fuente {path} parece inválido (reader is None o duración <= 0). Saltando.")
continue
remaining_needed = audio_duration - current_duration
potential_use_duration = min(clip.duration, max_clip_segment)
if remaining_needed > 0:
segment_duration = min(potential_use_duration, remaining_needed + min_clip_duration)
segment_duration = max(min_clip_duration, segment_duration)
segment_duration = min(segment_duration, clip.duration)
if segment_duration >= min_clip_duration:
try:
sub = clip.subclip(0, segment_duration)
if sub.reader is None or sub.duration is None or sub.duration <= 0:
logger.warning(f"[{i+1}/{len(video_paths)}] Subclip generado de {path} es inválido. Saltando.")
try: sub.close()
except: pass
continue
clips_to_concatenate.append(sub)
current_duration += sub.duration
logger.debug(f"[{i+1}/{len(video_paths)}] Segmento añadido: {sub.duration:.1f}s (total video: {current_duration:.1f}/{audio_duration:.1f}s)")
except Exception as sub_e:
logger.warning(f"[{i+1}/{len(video_paths)}] Error creando subclip de {path} ({segment_duration:.1f}s): {str(sub_e)}")
continue
else:
logger.debug(f"[{i+1}/{len(video_paths)}] Clip {path} ({clip.duration:.1f}s) no contribuye un segmento suficiente ({segment_duration:.1f}s necesario). Saltando.")
else:
logger.debug(f"[{i+1}/{len(video_paths)}] Duración de video base ya alcanzada. Saltando clip.")
except Exception as e:
logger.warning(f"[{i+1}/{len(video_paths)}] Error procesando video {path}: {str(e)}", exc_info=True)
continue
logger.info(f"Procesamiento de clips fuente finalizado. Se obtuvieron {len(clips_to_concatenate)} segmentos válidos.")
if not clips_to_concatenate:
logger.error("No hay segmentos de video válidos disponibles para crear la secuencia.")
raise ValueError("No hay segmentos de video válidos disponibles para crear el video.")
logger.info(f"Concatenando {len(clips_to_concatenate)} segmentos de video.")
concatenated_base = None
try:
concatenated_base = concatenate_videoclips(clips_to_concatenate, method="chain")
logger.info(f"Duración video base después de concatenación inicial: {concatenated_base.duration:.2f}s")
if concatenated_base is None or concatenated_base.duration is None or concatenated_base.duration <= 0:
logger.critical("Video base concatenado es inválido después de la primera concatenación (None o duración cero).")
raise ValueError("Fallo al crear video base válido a partir de segmentos.")
except Exception as e:
logger.critical(f"Error durante la concatenación inicial: {str(e)}", exc_info=True)
raise ValueError("Fallo durante la concatenación de video inicial.")
finally:
for clip_segment in clips_to_concatenate:
try: clip_segment.close()
except: pass
clips_to_concatenate = []
video_base = concatenated_base
final_video_base = video_base
if final_video_base.duration < audio_duration:
logger.info(f"Video base ({final_video_base.duration:.2f}s) es más corto que el audio ({audio_duration:.2f}s). Repitiendo...")
num_full_repeats = int(audio_duration // final_video_base.duration)
remaining_duration = audio_duration % final_video_base.duration
repeated_clips_list = [final_video_base] * num_full_repeats
if remaining_duration > 0:
try:
remaining_clip = final_video_base.subclip(0, remaining_duration)
if remaining_clip is None or remaining_clip.duration is None or remaining_clip.duration <= 0:
logger.warning(f"Subclip generado para duración restante {remaining_duration:.2f}s es inválido. Saltando.")
try: remaining_clip.close()
except: pass
else:
repeated_clips_list.append(remaining_clip)
logger.debug(f"Añadiendo segmento restante: {remaining_duration:.2f}s")
except Exception as e:
logger.warning(f"Error creando subclip para duración restante {remaining_duration:.2f}s: {str(e)}")
if repeated_clips_list:
logger.info(f"Concatenando {len(repeated_clips_list)} partes para repetición.")
video_base_repeated = None
try:
video_base_repeated = concatenate_videoclips(repeated_clips_list, method="chain")
logger.info(f"Duración del video base repetido: {video_base_repeated.duration:.2f}s")
if video_base_repeated is None or video_base_repeated.duration is None or video_base_repeated.duration <= 0:
logger.critical("Video base repetido concatenado es inválido.")
raise ValueError("Fallo al crear video base repetido válido.")
if final_video_base is not video_base_repeated:
try: final_video_base.close()
except: pass
final_video_base = video_base_repeated
except Exception as e:
logger.critical(f"Error durante la concatenación de repetición: {str(e)}", exc_info=True)
raise ValueError("Fallo durante la repetición de video.")
finally:
if 'repeated_clips_list' in locals():
for clip in repeated_clips_list:
if clip is not final_video_base:
try: clip.close()
except: pass
if final_video_base.duration > audio_duration:
logger.info(f"Recortando video base ({final_video_base.duration:.2f}s) para que coincida con la duración del audio ({audio_duration:.2f}s).")
trimmed_video_base = None
try:
trimmed_video_base = final_video_base.subclip(0, audio_duration)
if trimmed_video_base is None or trimmed_video_base.duration is None or trimmed_video_base.duration <= 0:
logger.critical("Video base recortado es inválido.")
raise ValueError("Fallo al crear video base recortado válido.")
if final_video_base is not trimmed_video_base:
try: final_video_base.close()
except: pass
final_video_base = trimmed_video_base
except Exception as e:
logger.critical(f"Error durante el recorte: {str(e)}", exc_info=True)
raise ValueError("Fallo durante el recorte de video.")
if final_video_base is None or final_video_base.duration is None or final_video_base.duration <= 0:
logger.critical("Video base final es inválido antes de audio/escritura (None o duración cero).")
raise ValueError("Video base final es inválido.")
if final_video_base.size is None or final_video_base.size[0] <= 0 or final_video_base.size[1] <= 0:
logger.critical(f"Video base final tiene tamaño inválido: {final_video_base.size}. No se puede escribir video.")
raise ValueError("Video base final tiene tamaño inválido antes de escribir.")
video_base = final_video_base
# 6. Manejar música de fondo
logger.info("Procesando audio...")
final_audio = audio_tts_original
musica_audio_looped = None
if musica_file:
musica_audio_original = None
try:
music_path = os.path.join(temp_dir_intermediate, "musica_bg.mp3")
shutil.copyfile(musica_file, music_path)
temp_intermediate_files.append(music_path)
logger.info(f"Música de fondo copiada a: {music_path}")
musica_audio_original = AudioFileClip(music_path)
if musica_audio_original.reader is None or musica_audio_original.duration is None or musica_audio_original.duration <= 0:
logger.warning("Clip de música de fondo parece inválido o tiene duración cero. Saltando música.")
try: musica_audio_original.close()
except: pass
musica_audio_original = None
else:
musica_audio_looped = loop_audio_to_length(musica_audio_original, video_base.duration)
logger.debug(f"Música ajustada a duración del video: {musica_audio_looped.duration:.2f}s")
if musica_audio_looped is None or musica_audio_looped.duration is None or musica_audio_looped.duration <= 0:
logger.warning("Clip de música de fondo loopeado es inválido. Saltando música.")
try: musica_audio_looped.close()
except: pass
musica_audio_looped = None
if musica_audio_looped:
composite_audio = CompositeAudioClip([
musica_audio_looped.volumex(0.2), # Volumen 20% para música
audio_tts_original.volumex(1.0) # Volumen 100% para voz
])
if composite_audio.duration is None or composite_audio.duration <= 0:
logger.warning("Clip de audio compuesto es inválido (None o duración cero). Usando solo audio de voz.")
try: composite_audio.close()
except: pass
final_audio = audio_tts_original
else:
logger.info("Mezcla de audio completada (voz + música).")
final_audio = composite_audio
musica_audio = musica_audio_looped # Asignar para limpieza
except Exception as e:
logger.warning(f"Error procesando música de fondo: {str(e)}", exc_info=True)
final_audio = audio_tts_original
musica_audio = None
logger.warning("Usando solo audio de voz debido a un error con la música.")
if final_audio.duration is not None and abs(final_audio.duration - video_base.duration) > 0.2:
logger.warning(f"Duración del audio final ({final_audio.duration:.2f}s) difiere significativamente del video base ({video_base.duration:.2f}s). Intentando recorte.")
try:
if final_audio.duration > video_base.duration:
trimmed_final_audio = final_audio.subclip(0, video_base.duration)
if trimmed_final_audio is None or trimmed_final_audio.duration <= 0:
logger.warning("Audio final recortado es inválido. Usando audio final original.")
try: trimmed_final_audio.close()
except: pass
else:
if final_audio is not trimmed_final_audio:
try: final_audio.close()
except: pass
final_audio = trimmed_final_audio
logger.warning("Audio final recortado para que coincida con la duración del video.")
except Exception as e:
logger.warning(f"Error ajustando duración del audio final: {str(e)}")
# 7. Crear video final
logger.info("Renderizando video final...")
video_final = video_base.set_audio(final_audio)
if video_final is None or video_final.duration is None or video_final.duration <= 0:
logger.critical("Clip de video final (con audio) es inválido antes de escribir (None o duración cero).")
raise ValueError("Clip de video final es inválido antes de escribir.")
output_filename = "final_video.mp4"
output_path = os.path.join(temp_dir_intermediate, output_filename)
logger.info(f"Escribiendo video final a: {output_path}")
video_final.write_videofile(
output_path,
fps=24,
threads=4,
codec="libx264",
audio_codec="aac",
preset="medium",
logger='bar'
)
total_time = (datetime.now() - start_time).total_seconds()
logger.info(f"PROCESO DE VIDEO FINALIZADO | Output: {output_path} | Tiempo total: {total_time:.2f}s")
return output_path
except ValueError as ve:
logger.error(f"ERROR CONTROLADO en crear_video: {str(ve)}")
raise ve
except Exception as e:
logger.critical(f"ERROR CRÍTICO NO CONTROLADO en crear_video: {str(e)}", exc_info=True)
raise e
finally:
logger.info("Iniciando limpieza de clips y archivos temporales intermedios...")
for clip in source_clips:
try:
clip.close()
except Exception as e:
logger.warning(f"Error cerrando clip de video fuente en finally: {str(e)}")
for clip_segment in clips_to_concatenate:
try:
clip_segment.close()
except Exception as e:
logger.warning(f"Error cerrando segmento de video en finally: {str(e)}")
if musica_audio is not None:
try:
musica_audio.close()
except Exception as e:
logger.warning(f"Error cerrando musica_audio (procesada) en finally: {str(e)}")
if musica_audio_original is not None and musica_audio_original is not musica_audio:
try:
musica_audio_original.close()
except Exception as e:
logger.warning(f"Error cerrando musica_audio_original en finally: {str(e)}")
if audio_tts is not None and audio_tts is not audio_tts_original:
try:
audio_tts.close()
except Exception as e:
logger.warning(f"Error cerrando audio_tts (procesada) en finally: {str(e)}")
if audio_tts_original is not None:
try:
audio_tts_original.close()
except Exception as e:
logger.warning(f"Error cerrando audio_tts_original en finally: {str(e)}")
if video_final is not None:
try:
video_final.close()
except Exception as e:
logger.warning(f"Error cerrando video_final en finally: {str(e)}")
elif video_base is not None and video_base is not video_final:
try:
video_base.close()
except Exception as e:
logger.warning(f"Error cerrando video_base en finally: {str(e)}")
if temp_dir_intermediate and os.path.exists(temp_dir_intermediate):
final_output_in_temp = os.path.join(temp_dir_intermediate, "final_video.mp4")
for path in temp_intermediate_files:
try:
if os.path.isfile(path) and path != final_output_in_temp:
logger.debug(f"Eliminando archivo temporal intermedio: {path}")
os.remove(path)
elif os.path.isfile(path) and path == final_output_in_temp:
logger.debug(f"Saltando eliminación del archivo de video final: {path}")
except Exception as e:
logger.warning(f"No se pudo eliminar archivo temporal intermedio {path}: {str(e)}")
logger.info(f"Directorio temporal intermedio {temp_dir_intermediate} persistirá para que Gradio lea el video final.")
# run_app ahora recibe todos los inputs, incluyendo la voz seleccionada
def run_app(prompt_type, prompt_ia, prompt_manual, musica_file, selected_voice): # <-- Recibe el valor del Dropdown
logger.info("="*80)
logger.info("SOLICITUD RECIBIDA EN INTERFAZ")
# Elegir el texto de entrada basado en el prompt_type
input_text = prompt_ia if prompt_type == "Generar Guion con IA" else prompt_manual
output_video = None
output_file = None
status_msg = gr.update(value="⏳ Procesando...", interactive=False)
if not input_text or not input_text.strip():
logger.warning("Texto de entrada vacío.")
# Retornar None para video y archivo, actualizar estado con mensaje de error
return None, None, gr.update(value="⚠️ Por favor, ingresa texto para el guion o el tema.", interactive=False)
# Validar la voz seleccionada. Si no es válida, usar la por defecto.
# AVAILABLE_VOICES se obtiene al inicio. Hay que buscar si el voice_id existe en la lista de pares (nombre, id)
voice_ids_disponibles = [v[1] for v in AVAILABLE_VOICES]
if selected_voice not in voice_ids_disponibles:
logger.warning(f"Voz seleccionada inválida o no encontrada en la lista: '{selected_voice}'. Usando voz por defecto: {DEFAULT_VOICE_ID}.")
selected_voice = DEFAULT_VOICE_ID # <-- Usar el ID de la voz por defecto
else:
logger.info(f"Voz seleccionada validada: {selected_voice}")
logger.info(f"Tipo de entrada: {prompt_type}")
logger.debug(f"Texto de entrada: '{input_text[:100]}...'")
if musica_file:
logger.info(f"Archivo de música recibido: {musica_file}")
else:
logger.info("No se proporcionó archivo de música.")
logger.info(f"Voz final a usar (ID): {selected_voice}") # Loguear el ID de la voz final
try:
logger.info("Llamando a crear_video...")
# Pasar el input_text elegido, la voz seleccionada (el ID) y el archivo de música a crear_video
video_path = crear_video(prompt_type, input_text, selected_voice, musica_file) # <-- PASAR selected_voice (ID) a crear_video
if video_path and os.path.exists(video_path):
logger.info(f"crear_video retornó path: {video_path}")
logger.info(f"Tamaño del archivo de video retornado: {os.path.getsize(video_path)} bytes")
output_video = video_path # Establecer valor del componente de video
output_file = video_path # Establecer valor del componente de archivo para descarga
status_msg = gr.update(value="✅ Video generado exitosamente.", interactive=False)
else:
logger.error(f"crear_video no retornó un path válido o el archivo no existe: {video_path}")
status_msg = gr.update(value="❌ Error: La generación del video falló o el archivo no se creó correctamente.", interactive=False)
except ValueError as ve:
logger.warning(f"Error de validación durante la creación del video: {str(ve)}")
status_msg = gr.update(value=f"⚠️ Error de validación: {str(ve)}", interactive=False)
except Exception as e:
logger.critical(f"Error crítico durante la creación del video: {str(e)}", exc_info=True)
status_msg = gr.update(value=f"❌ Error inesperado: {str(e)}", interactive=False)
finally:
logger.info("Fin del handler run_app.")
return output_video, output_file, status_msg
# Interfaz de Gradio
with gr.Blocks(title="Generador de Videos con IA", theme=gr.themes.Soft(), css="""
.gradio-container {max-width: 800px; margin: auto;}
h1 {text-align: center;}
""") as app:
gr.Markdown("# 🎬 Generador Automático de Videos con IA")
gr.Markdown("Genera videos cortos a partir de un tema o guion, usando imágenes de archivo de Pexels y voz generada.")
with gr.Row():
with gr.Column():
prompt_type = gr.Radio(
["Generar Guion con IA", "Usar Mi Guion"],
label="Método de Entrada",
value="Generar Guion con IA"
)
# Contenedores para los campos de texto para controlar la visibilidad
with gr.Column(visible=True) as ia_guion_column:
prompt_ia = gr.Textbox(
label="Tema para IA",
lines=2,
placeholder="Ej: Un paisaje natural con montañas y ríos al amanecer, mostrando la belleza de la naturaleza...",
max_lines=4,
value=""
# visible=... <-- ¡NO DEBE ESTAR AQUÍ!
)
with gr.Column(visible=False) as manual_guion_column:
prompt_manual = gr.Textbox(
label="Tu Guion Completo",
lines=5,
placeholder="Ej: En este video exploraremos los misterios del océano. Veremos la vida marina fascinante y los arrecifes de coral vibrantes. ¡Acompáñanos en esta aventura subacuática!",
max_lines=10,
value=""
# visible=... <-- ¡NO DEBE ESTAR AQUÍ!
)
musica_input = gr.Audio(
label="Música de fondo (opcional)",
type="filepath",
interactive=True,
value=None
# visible=... <-- ¡NO DEBE ESTAR AQUÍ!
)
# --- COMPONENTE: Selección de Voz ---
voice_dropdown = gr.Dropdown(
label="Seleccionar Voz para Guion",
choices=AVAILABLE_VOICES, # Usar la lista obtenida al inicio
value=DEFAULT_VOICE_ID, # Usar el ID de la voz por defecto calculada
interactive=True
# visible=... <-- ¡NO DEBE ESTAR AQUÍ!
)
# --- FIN COMPONENTE ---
generate_btn = gr.Button("✨ Generar Video", variant="primary")
with gr.Column():
video_output = gr.Video(
label="Previsualización del Video Generado",
interactive=False,
height=400
# visible=... <-- ¡NO DEBE ESTAR AQUÍ!
)
file_output = gr.File(
label="Descargar Archivo de Video",
interactive=False,
visible=False # <-- ESTÁ BIEN AQUÍ
# visible=... <-- ¡NO DEBE ESTAR AQUÍ si ya está visible=False arriba!
)
status_output = gr.Textbox(
label="Estado",
interactive=False,
show_label=False,
placeholder="Esperando acción...",
value="Esperando entrada..."
# visible=... <-- ¡NO DEBE ESTAR AQUÍ!
)
# Evento para mostrar/ocultar los campos de texto según el tipo de prompt
prompt_type.change(
lambda x: (gr.update(visible=x == "Generar Guion con IA"),
gr.update(visible=x == "Usar Mi Guion")),
inputs=prompt_type,
outputs=[ia_guion_column, manual_guion_column] # Apuntar a las Columnas contenedoras
)
# Evento click del botón de generar video
generate_btn.click(
# Acción 1 (síncrona): Resetear salidas y establecer estado
lambda: (None, None, gr.update(value="⏳ Procesando... Esto puede tomar varios minutos.", interactive=False)),
outputs=[video_output, file_output, status_output],
queue=True, # Usar la cola de Gradio
).then(
# Acción 2 (asíncrona): Llamar a la función principal
run_app,
# PASAR TODOS LOS INPUTS DE LA INTERFAZ que run_app espera
inputs=[prompt_type, prompt_ia, prompt_manual, musica_input, voice_dropdown], # <-- Pasar los 5 inputs a run_app
# run_app retornará los 3 outputs esperados
outputs=[video_output, file_output, status_output]
).then(
# Acción 3 (síncrona): Hacer visible el enlace de descarga
lambda video_path, file_path, status_msg: gr.update(visible=file_path is not None),
inputs=[video_output, file_output, status_output],
outputs=[file_output]
)
gr.Markdown("### Instrucciones:")
gr.Markdown("""
1. **Clave API de Pexels:** Asegúrate de haber configurado la variable de entorno `PEXELS_API_KEY` con tu clave.
2. **Selecciona el tipo de entrada**: "Generar Guion con IA" o "Usar Mi Guion".
3. **Sube música** (opcional): Selecciona un archivo de audio (MP3, WAV, etc.).
4. **Selecciona la voz** deseada del desplegable.
5. **Haz clic en "✨ Generar Video"**.
6. Espera a que se procese el video. Verás el estado.
7. La previsualización aparecerá si es posible, y siempre un enlace **Descargar Archivo de Video** se mostrará si la generación fue exitosa.
8. Revisa `video_generator_full.log` para detalles si hay errores.
""")
gr.Markdown("---")
gr.Markdown("Desarrollado por [Tu Nombre/Empresa/Alias - Opcional]")
if __name__ == "__main__":
logger.info("Verificando dependencias críticas...")
try:
from moviepy.editor import ColorClip
try:
temp_clip = ColorClip((100,100), color=(255,0,0), duration=0.1)
temp_clip.close()
logger.info("Clips base de MoviePy creados y cerrados exitosamente. FFmpeg parece accesible.")
except Exception as e:
logger.critical(f"Fallo al crear clip base de MoviePy. A menudo indica problemas con FFmpeg/ImageMagick. Error: {e}", exc_info=True)
except Exception as e:
logger.critical(f"Fallo al importar MoviePy. Asegúrate de que está instalado. Error: {e}", exc_info=True)
logger.info("Iniciando aplicación Gradio...")
try:
app.launch(server_name="0.0.0.0", server_port=7860, share=False)
except Exception as e:
logger.critical(f"No se pudo iniciar la app: {str(e)}", exc_info=True)
raise |